Claude Code 0331 系统报告

第6章 · 上下文系统

第6章 · 上下文系统

6.1 context.ts

context.ts(189行入口)提供两类上下文:

系统上下文(getSystemContext)

  • 当前Git分支名和HEAD SHA(通过 gitFilesystem.ts 的纯文件系统读取,不调用git子进程)
  • 最近的Git日志(最后5条提交)
  • 未提交的变更(git diff摘要)
  • 操作系统和平台信息

用户上下文(getUserContext)

  • CLAUDE.md文件内容(层级合并:项目级 > 用户级 > 全局级)
  • Memory文件内容(从 ~/.claude/projects/<path>/memory/ 加载)
  • Dream产出的记忆(如果存在)

6.2 Git文件系统读取

一个值得注意的工程决策:Claude Code读取Git状态时,不调用 git 命令行工具utils/git/gitFilesystem.ts(700行)直接读取 .git/ 目录的文件系统:

  • readGitHead():解析 .git/HEAD 文件
  • resolveRef():递归解析ref到SHA(先松散文件,再packed-refs)
  • getCommonDir():处理Git Worktree(工作树指向主仓库的commonDir)

为什么这样做?因为启动 git 子进程有不可忽视的开销(~10-50ms),而文件系统读取只需<1ms。在启动路径上,这个优化很有价值。

此外,GitFileWatcher 类使用 fs.watchFile() 监视 .git/HEAD 和分支ref文件的变化,通过脏标记(dirty flag)机制实现低开销的缓存失效。

6.3 系统提示构建

constants/prompts.ts 实现了动态的系统提示构建。系统提示由多个Section组成,每个Section是一个惰性求值的函数:

const sections = [
  systemPromptSection('base', () => getBasePrompt()),
  systemPromptSection('tools', () => getToolDescriptions(tools)),
  systemPromptSection('context', () => getUserContext()),
  systemPromptSection('proactive', () => getProactiveSection()),
  systemPromptSection('brief', () => getBriefSection()),
  // ...
]

Section的求值是延迟的——只在实际需要时才计算。不同模式(交互 vs KAIROS vs Coordinator)使用不同的Section组合。

KAIROS模式的系统提示包含一段关键指令:

"You are an autonomous agent. Use the available tools to do useful work.
You will receive <tick> prompts that keep you alive between turns —
just treat them as 'you're awake, what now?'
The time in each <tick> is the user's current local time."

第三部分:工具系统全解

On this page