Skip to main content

Claude Code 产品设计与提示词分析报告

Claude Code 产品设计与提示词分析报告

源码版本:Claude Code v2.1.88(~51万行 TypeScript) 分析日期:2026-03-31

基于源码 `` 的逆向分析。写给两类人:想知道"Claude Code 到底怎么做到的"的产品人,以及想抄提示词工程细节的工程师。


一、架构总览

Claude Code 本质上是一个有状态的 Agent 框架,核心循环很朴素:

用户输入 → 系统提示词 + 工具定义 → LLM → 工具调用 → 执行 → 结果回填 → 循环

但魔鬼在细节里。它围绕这个循环做了几件事:

  1. 系统提示词的分层缓存 — 静态内容和动态内容用 SYSTEM_PROMPT_DYNAMIC_BOUNDARY 隔开,静态部分跨会话复用 prompt cache
  2. 工具权限的渐进式管控 — 不是简单的 allow/deny,而是按 permission mode 分级(详见技术分析篇第 8 章)
  3. 子 Agent 体系 — Coordinator 模式、fork 模式、专用 Agent 三层架构
  4. 上下文生命周期管理 — Compact、Microcompact、Dream 三级压缩(详见技术分析篇第 7 章)
  5. 命令系统 — 斜杠命令不仅是快捷方式,每个命令实质上是一个 prompt 模板

二、系统提示词深度拆解

2.1 提示词的整体结构

getSystemPrompt() 返回一个 string[],按顺序拼接。关键设计:用一个 boundary marker 把提示词切成两半

// constants/prompts.ts
export const SYSTEM_PROMPT_DYNAMIC_BOUNDARY =
  '__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__'

Boundary 之前的内容(静态):

  • Intro section(身份声明)
  • System section(基本规则)
  • Doing tasks section(行为准则)
  • Actions section(风险管控)
  • Using your tools section(工具偏好)
  • Tone and style section(输出风格)
  • Output efficiency section(效率指令)

Boundary 之后的内容(动态,每个 session 不同):

  • Session-specific guidance(根据启用的工具动态生成)
  • Memory(从文件加载)
  • Environment info(OS、shell、git 状态)
  • Language preference
  • Output style(用户自定义输出风格)
  • MCP server instructions
  • Scratchpad 路径

设计意图:静态部分可以跨用户、跨会话共享 prompt cache(Claude API 的 cacheScope: 'global'),大幅降低 token 成本和延迟。动态部分放在后面,即使变化也不会破坏前面的缓存。

这个分层缓存策略是 Claude Code 在成本控制上最关键的设计决策之一。每次请求只需要为动态部分付费,静态提示词几千 token 的成本被摊薄到几乎为零。

2.2 核心提示词原文摘录

身份声明

You are an interactive agent that helps users with software engineering tasks.

IMPORTANT: You must NEVER generate or guess URLs for the user unless you are
confident that the URLs are for helping the user with programming.

简洁。没有角色扮演,没有"你是一个友好的…",直接进入工作模式。

行为准则(Doing Tasks)

这是提示词里最长、信息密度最高的部分。摘几个关键指令:

禁止过度工程化(这段很值得所有 AI 编码工具抄):

Don't add features, refactor code, or make "improvements" beyond what was asked.
A bug fix doesn't need surrounding code cleaned up. A simple feature doesn't
need extra configurability. Don't add docstrings, comments, or type annotations
to code you didn't changed. Only add comments where the logic isn't self-evident.
Don't add error handling, fallbacks, or validation for scenarios that can't
happen. Trust internal code and framework guarantees. Only validate at system
boundaries (user input, external APIs).
Don't create helpers, utilities, or abstractions for one-time operations.
Don't design for hypothetical future requirements. The right amount of
complexity is what the task actually requires—no speculative abstractions,
but no half-finished implementations either. Three similar lines of code
is better than a premature abstraction.

Ant 内部版本的注释策略(更激进):

Default to writing no comments. Only add one when the WHY is non-obvious:
a hidden constraint, a subtle invariant, a workaround for a specific bug,
behavior that would surprise a reader.

Don't explain WHAT the code does, since well-named identifiers already do that.
Don't reference the current task, fix, or callers ("used by X", "added for
the Y flow"), since those belong in the PR description and rot as the codebase
evolves.

失败处理(避免无脑重试):

If an approach fails, diagnose why before switching tactics—read the error,
check your assumptions, try a focused fix. Don't retry the identical action
blindly, but don't abandon a viable approach after a single failure either.
Escalate to the user with AskUserQuestion only when you're genuinely stuck
after investigation, not as a first response to friction.

风险动作管控(Actions Section)

这段的核心思想是可逆性分级

Carefully consider the reversibility and blast radius of actions. Generally
you can freely take local, reversible actions like editing files or running
tests. But for actions that are hard to reverse, affect shared systems beyond
your local environment, or could otherwise be risky or destructive, check
with the user before proceeding.

具体例子:

  • 破坏性操作:删文件/分支、drop 表、rm -rf
  • 不可逆操作:force-pushgit reset --hard、amend 已发布的 commit
  • 影响他人的操作:push 代码、创建 PR、发消息
  • 上传到第三方工具的内容

工具偏好指令(Using Your Tools)

Do NOT use the Bash tool to run commands when a relevant dedicated tool is
provided. Using dedicated tools allows the user to better understand and
review your work.

具体映射:

  • 读文件 → Read(不是 cat/head/tail)
  • 编辑文件 → Edit(不是 sed/awk)
  • 创建文件 → Write(不是 cat heredoc)
  • 搜文件 → Glob(不是 find)
  • 搜内容 → Grep(不是 grep/rg)
  • Bash 只用于"没有专用工具能做"的操作

输出效率(两个版本)

外部版(简洁至上):

Go straight to the point. Try the simplest approach first without going
in circles. Do not overdo it. Be extra concise.

If you can say it in one sentence, don't use three.

Ant 内部版(更注重可读性):

When sending user-facing text, you're writing for a person, not logging
to a console. Assume users can't see most tool calls or thinking - only
your text output. Before your first tool call, briefly state what you're
about to do.

Write user-facing text in flowing prose while eschewing fragments, excessive
em dashes, symbols and notation. Avoid semantic backtracking: structure each
sentence so a person can read it linearly, building up meaning without having
to re-parse what came before.

What's most important is the reader understanding your output without mental
overhead or follow-ups, not how terse you are.

这个内外版本差异反映了 Anthropic 的一个判断:外部用户要效率,内部用户要可读性。

2.3 环境信息注入

// constants/prompts.ts → computeSimpleEnvInfo()

`Primary working directory: ${cwd}`
`Is a git repository: ${isGit}`
`Platform: ${env.platform}`
`Shell: ${shellName}`
`OS Version: ${unameSR}`
`You are powered by the model named ${marketingName}.`
`Assistant knowledge cutoff is ${cutoff}.`
`Claude Code is available as a CLI in the terminal, desktop app (Mac/Windows),
web app (claude.ai/code), and IDE extensions (VS Code, JetBrains).`
`Fast mode for Claude Code uses the same ${FRONTIER_MODEL_NAME} model with
faster output. It does NOT switch to a different model.`

环境信息不只是告诉模型"你在哪",还包含了模型自我认知产品能力边界

2.4 系统提示词的缓存架构

// constants/prompts.ts
// Boundary marker separating static (cross-org cacheable) content from
// dynamic content. Everything BEFORE this marker in the system prompt array
// can use scope: 'global'. Everything AFTER contains user/session-specific
// content and should not be cached.

代码里还有一个 systemPromptSection() 函数,用标签(如 'session_guidance''memory''language')管理动态 section,支持按需计算和缓存失效追踪。


三、工具设计分析

3.1 Tool 接口定义

Tool.ts 定义了工具的核心接口(类型定义文件,~100 行内主要是 type 声明)。关键字段包括:

  • name — 工具名
  • description — 给模型看的描述
  • inputSchema — JSON Schema 参数定义
  • isAvailable — 运行时可用性检查
  • permissions — 权限要求

3.2 BashTool — 最复杂的安全边界

BashTool 的提示词是所有工具里最长的,因为它承担了"万能工具"的角色,同时需要强约束。

工具偏好复述(在工具级提示词里再强化一遍,和系统提示词形成双重约束):

File search: Use Glob (NOT find or ls)
Content search: Use Grep (NOT grep or rg)
Read files: Use Read (NOT cat/head/tail)
Edit files: Use Edit (NOT sed/awk)
Write files: Use Write (NOT echo >/cat <<EOF)
Communication: Output text directly (NOT echo/printf)

Sleep 命令管控(防止 token 浪费):

Do not sleep between commands that can run immediately — just run them.
If your command is long running and you would like to be notified when
it finishes — use `run_in_background`. No sleep needed.
Do not retry failing commands in a sleep loop — diagnose the root cause.
`sleep N` as the first command with N ≥ 2 is blocked.

你可能没注意到的设计细节sleep N as the first command with N ≥ 2 is blocked——这不是提示词约束,是代码层硬限制。模型可以用 sleep 做第二条命令,但不能做第一条。这个设计精准打击了一种特定的 token 浪费模式:模型在每轮对话开头都 sleep 5 "等一等",消耗 5 秒的 API 时间但什么都没做。同时 run_in_background 提供了正规的后台执行路径——不是简单地禁止等待,而是给了更好的替代方案。这种"禁止坏模式 + 提供好替代"的配对设计在 BashTool 里反复出现。

Git 安全协议

NEVER update the git config
NEVER run destructive commands (push --force, reset --hard, checkout .,
  restore ., clean -f, branch -D) unless the user explicitly requests
NEVER skip hooks (--no-verify, --no-gpg-sign, etc)
NEVER run force push to main/master

Sandbox 模式:BashTool 支持沙箱运行,限制文件系统和网络访问。提示词里包含了沙箱配置的完整 JSON 描述,让模型知道边界在哪。

3.3 FileEditTool — 精确编辑

Performs exact string replacements in files.

- You must use your Read tool at least once in the conversation before editing.
  This tool will error if you attempt an edit without reading the file.
- When editing text from Read tool output, ensure you preserve the exact
  indentation (tabs/spaces) as it appears AFTER the line number prefix.
- The edit will FAIL if old_string is not unique in the file. Either provide
  a larger string with surrounding context to make it unique or use replace_all

关键设计:强制先读后写。不允许模型凭记忆或猜测编辑文件,必须先 Read 获取真实内容。

3.4 WebFetchTool — 二级模型处理

export function makeSecondaryModelPrompt(
  markdownContent: string,
  prompt: string,
  isPreapprovedDomain: boolean,
): string {
  // 预批准域名:允许引用原文
  // 非预批准域名:严格限制引用长度(125 字符),禁止逐字复制
}

抓取的网页内容先用一个小模型(fast model)处理,再把摘要返回给主模型。非预批准域名还有版权保护限制。

3.5 TodoWriteTool — 任务管理的提示词工程

TodoWriteTool 的提示词长达数百行,包含大量 few-shot examples。核心设计:

明确的使用场景(3+ 步骤才用):

1. Complex multi-step tasks - 3 or more distinct steps
2. Non-trivial and complex tasks
3. User explicitly requests todo list
4. User provides multiple tasks
5. After receiving new instructions

明确的不使用场景

1. Only a single, straightforward task
2. Task is trivial
3. Less than 3 trivial steps
4. Purely conversational or informational

任务状态管理

- pending: Task not yet started
- in_progress: Currently working on (limit to ONE task at a time)
- completed: Task finished successfully

IMPORTANT: Task descriptions must have two forms:
- content: imperative form ("Run tests")
- activeForm: present continuous ("Running tests")

提示词里包含 8 个正例和 4 个反例,通过 few-shot 明确边界。

3.6 工具提示词原文摘录

以下三个工具的提示词展示了 Claude Code 如何通过工具描述层做行为约束。这些描述不是给用户看的文档,而是给模型看的即时指令——模型在决定是否调用某工具时会重新阅读这些描述。

GrepTool — 搜索工具

// tools/GrepTool/prompt.ts
export function getDescription(): string {
  return `A powerful search tool built on ripgrep

  Usage:
  - ALWAYS use Grep for search tasks. NEVER invoke \`grep\` or \`rg\` as
    a Bash command. The Grep tool has been optimized for correct permissions
    and access.
  - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
  - Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type
    parameter (e.g., "js", "py", "rust")
  - Output modes: "content" shows matching lines, "files_with_matches"
    shows only file paths (default), "count" shows match counts
  - Use Agent tool for open-ended searches requiring multiple rounds
  - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping
    (use \`interface\\{\\}\` to find \`interface{}\` in Go code)
  - Multiline matching: By default patterns match within single lines only.
    For cross-line patterns like \`struct \\{[\\s\\S]*?field\`,
    use \`multiline: true\`
`
}

产品意图:第一条指令就用 ALWAYS... NEVER 的强约束格式,把模型从 Bash 的 grep/rg 路径上拉回来。这和系统提示词里的 "Do NOT use the Bash tool to run commands when a relevant dedicated tool is provided" 形成双重约束。模型在工具选择阶段看到这段话,相当于一个即时决策锚点。

GlobTool — 文件匹配工具

// tools/GlobTool/prompt.ts
export const DESCRIPTION =
  `- Fast file pattern matching tool that works with any codebase size
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
- Returns matching file paths sorted by modification time
- Use this tool when you need to find files by name patterns
- When you are doing an open ended search that may require multiple rounds
  of globbing and grepping, use the Agent tool instead`

产品意图:最后一行是关键——把"多次搜索"的需求分流到 Agent tool,避免模型在主对话里做 5-6 轮 glob/grep 轮询撑爆上下文。这是工具编排层面的上下文保护策略。

AskUserQuestionTool — 用户交互工具

// tools/AskUserQuestionTool/prompt.ts
export const DESCRIPTION =
  'Asks the user multiple choice questions to gather information, clarify
   ambiguity, understand preferences, make decisions or offer them choices.'

export const ASK_USER_QUESTION_TOOL_PROMPT = `Use this tool when you need
to ask the user questions during execution. This allows you to:
1. Gather user preferences or requirements
2. Clarify ambiguous instructions
3. Get decisions on implementation choices as you work
4. Offer choices to the user about what direction to take.

Usage notes:
- Users will always be able to select "Other" to provide custom text input
- Use multiSelect: true to allow multiple answers to be selected
- If you recommend a specific option, make that the first option in the
  list and add "(Recommended)" at the end of the label

Plan mode note: In plan mode, use this tool to clarify requirements or
choose between approaches BEFORE finalizing your plan. Do NOT use this
tool to ask "Is my plan ready?" or "Should I proceed?" - use
ExitPlanMode for plan approval. IMPORTANT: Do not reference "the plan"
in your questions because the user cannot see the plan in the UI until
you call ExitPlanMode.
`

还支持 preview 功能——选项可以附带 HTML 或 Markdown 预览,UI 会自动切换到左右分栏布局:

export const PREVIEW_FEATURE_PROMPT = {
  markdown: `Use the optional preview field on options when presenting
concrete artifacts that users need to visually compare:
- ASCII mockups of UI layouts or components
- Code snippets showing different implementations`,
  html: `Preview content must be a self-contained HTML fragment
(no <html>/<body> wrapper, no <script> or <style> tags)`,
}

产品意图:这个工具解决了一个真实的产品问题——LLM 默认的"问用户"方式是输出一段自然语言问题,用户得打字回复。多选 + 推荐项 + "Other"出口的设计,把交互成本从"打字"降到"点击"。Plan mode 的特殊约束更值得注意:禁止问"计划好了吗",因为用户在 UI 上看不到计划内容——这是一个UI/工具联动的设计决策。

BashTool 提示词中的 Git Safety Protocol

BashTool 的完整提示词很长(~300 行),但其中的 Git 安全协议值得单独摘出来:

- DO NOT use git commands: --force, --hard, --prune, or branch -D
  unless the user explicitly asked you to. Rewrite questions (like
  "can you squash my commits?") are OK to proceed.
- Interactive rebase (git rebase -i) is NOT supported in non-interactive
  mode. Use git log to identify commits, then use git reset or other
  non-interactive commands.
- If the user asked you to do something that requires --force (like
  rewriting history), check with the user first.

产品意图:不是禁用 force push,而是要求"用户明确要求才行"。这是可逆性分级管控在工具层的落地——系统提示词定义原则(Actions section),工具描述给出具体规则(哪些 flag 需要确认)。

EnterPlanModeTool — 计划模式的完整提示词

EnterPlanModeTool 的提示词不只是"进入计划模式"这么简单,它定义了 Agent 在计划模式下的完整行为边界:

// tools/EnterPlanModeTool/prompt.ts(摘要)

Enter plan mode. In this mode, you can:
- Read files and search the codebase freely
- Run read-only commands (git log, git diff, tests in read-only mode)
- Ask the user clarifying questions using AskUserQuestionTool

You CANNOT:
- Edit, create, or delete files
- Run commands that mutate state (git commit, npm install, etc.)
- Make HTTP requests that have side effects

You MUST:
- Understand the current state of the code relevant to the task
- Identify all files that need to change
- Write a clear plan with specific file paths, line numbers, and
  descriptions of each change
- Call ExitPlanModeTool when your plan is ready

When asking clarifying questions in plan mode:
- Do NOT ask "Is my plan ready?" or "Should I proceed?" — use
  ExitPlanMode for plan approval
- Do NOT reference "the plan" in questions — the user cannot see
  the plan until you call ExitPlanMode
- Use AskUserQuestionTool to clarify requirements or choose between
  approaches BEFORE finalizing your plan

产品意图:这段提示词的值得注意的之处在于三件事的联动——

  1. 工具层硬约束:写权限工具在 plan mode 下不可用(不是提示词说"别改",是真的调不了)
  2. 输出结构化:计划不是一段自然语言,而是包含文件路径和行号的结构化输出
  3. UI 联动:ExitPlanMode 把计划传给 UI 的专门审批界面,用户看到的是可展开的变更列表而不是聊天记录里的文本

Do NOT reference "the plan" 这条约束尤其值得注意——它说明工具设计者预判到了模型会犯的错误:在计划还没展示给用户时就假设用户已经看到了。这种"预判模型的预判"在 Claude Code 的提示词里反复出现。

BashTool 的安全沙箱描述

BashTool 还支持沙箱模式,提示词中包含了完整的沙箱配置描述:

When sandbox mode is enabled, your commands run in an isolated environment
with restricted filesystem and network access. The sandbox configuration
specifies:
- allowedRoots: directories you can read and write
- networkAllowlist: hosts you can connect to
- readPaths: additional read-only paths
- blockedCommands: commands that are always blocked (rm -rf /, etc.)

产品意图:沙箱配置被完整注入到工具描述里,让模型知道边界在哪。这比"你在沙箱里运行"更有用——模型看到 allowedRoots: ["/workspace"],就知道只能操作 /workspace 下的文件,不会尝试去读 /etc/passwd。类比:你告诉工人"这里施工"和给他一张标注了禁区的平面图,后者的行为约束力强得多。


四、子 Agent 体系

4.1 内置 Agent 类型

源码中有 6 个内置 Agent:

Agent 用途 模型 可写文件
Explore 代码搜索 haiku(外部)/ inherit(内部) ❌ 只读
Plan 架构规划 inherit ❌ 只读
general-purpose 通用任务 默认子 Agent 模型
verification 验证实现 inherit ❌ 只读(tmp 允许)
statusline-setup 状态栏配置 待确认 待确认
claude-code-guide 使用指南 待确认 待确认

4.2 Explore Agent

最精细的只读 Agent 设计:

=== CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
This is a READ-ONLY exploration task. You are STRICTLY PROHIBITED from:
- Creating new files
- Modifying existing files
- Deleting files
- Creating temporary files anywhere, including /tmp
- Using redirect operators (>, >>, |) or heredocs to write to files

通过 disallowedTools 从工具层面硬限制,不只靠提示词。

4.3 Verification Agent — 最精彩的 Agent 设计

Verification Agent 的提示词是整个代码库里信息密度最高的段落之一。

对抗自身的自欺倾向

You have two documented failure patterns. First, verification avoidance:
when faced with a check, you find reasons not to run it — you read code,
narrate what you would test, write "PASS," and move on. Second, being
seduced by the first 80%: you see a polished UI or a passing test suite
and feel inclined to pass it, not noticing half the buttons do nothing.

识别自己的合理化借口

You will feel the urge to skip checks. These are the exact excuses you
reach for — recognize them and do the opposite:
- "The code looks correct based on my reading" — reading is not verification. Run it.
- "The implementer's tests already pass" — the implementer is an LLM. Verify independently.
- "This is probably fine" — probably is not verified. Run it.
- "Let me start the server and check the code" — no. Start the server and hit the endpoint.
- "I don't have a browser" — did you actually check for mcp__claude-in-chrome__*?

输出格式强制:每个 PASS 必须包含实际执行的命令和输出,纯代码阅读不算验证。

Bad:
### Check: POST /api/register validation
**Result: PASS**
Evidence: Reviewed the route handler. The logic correctly validates...

Good:
### Check: POST /api/register rejects short password
**Command run:**
  curl -s -X POST localhost:8000/api/register ...
**Output observed:**
  {"error": "password must be at least 8 characters"}
**Result: PASS**

最终判决格式

VERDICT: PASS
or
VERDICT: FAIL
or
VERDICT: PARTIAL

PARTIAL 只用于环境限制(缺工具、起不来服务),不能用于"我不确定这是不是 bug"。

4.4 Fork 子 Agent 模式

Fork 是一种轻量级子 Agent,与父 Agent 共享 prompt cache:

Calling Agent without a subagent_type creates a fork, which runs in the
background and keeps its tool output out of your context.

Forks are cheap because they share your prompt cache. Don't set model on
a fork — a different model can't reuse the parent's cache.

关键行为约束:

  • Don't peek — 不要读 fork 的 output_file,等通知
  • Don't race — 不要伪造或预测 fork 的结果
  • Prompt 是指令 — fork 继承上下文,prompt 只写"做什么",不写背景

五、Coordinator 模式 — 多 Agent 编排

5.1 角色定义

Coordinator 是一个编排器,不直接执行代码操作:

You are a coordinator. Your job is to:
- Help the user achieve their goal
- Direct workers to research, implement and verify code changes
- Synthesize results and communicate with the user
- Answer questions directly when possible — don't delegate work that
  you can handle without tools

5.2 工作流阶段

阶段 执行者 目的
Research Workers(并行) 调研代码、找文件、理解问题
Synthesis Coordinator 读结果、理解问题、写实现规格
Implementation Workers 按规格修改代码
Verification Workers 测试变更

Synthesis 阶段是 Coordinator 的核心价值。提示词明确要求:

When workers report research findings, you must understand them before
directing follow-up work. Read the findings. Identify the approach. Then
write a prompt that proves you understood by including specific file paths,
line numbers, and exactly what to change.

Never write "based on your findings" or "based on the research." These
phrases delegate understanding to the worker instead of doing it yourself.

5.3 Continue vs Spawn 决策

| Situation | Mechanism | Why |
|-----------|-----------|-----|
| Research explored exactly the files that need editing | Continue | Worker already has files in context |
| Research was broad but implementation is narrow | Spawn fresh | Avoid exploration noise |
| Correcting a failure | Continue | Worker has error context |
| Verifying code a different worker wrote | Spawn fresh | Fresh eyes |
| First attempt used wrong approach | Spawn fresh | Clean slate |

5.4 Worker 通知机制

Worker 结果以 <task-notification> XML 的形式作为 user-role message 回传给 Coordinator:

<task-notification>
<task-id>{agentId}</task-id>
<status>completed|failed|killed</status>
<summary>{human-readable status summary}</summary>
<result>{agent's final text response}</result>
<usage>
  <total_tokens>N</total_tokens>
  <tool_uses>N</tool_uses>
  <duration_ms>N</duration_ms>
</usage>
</task-notification>

六、上下文生命周期管理

6.1 三级压缩体系

  1. Microcompact — 后台自动清理旧的工具结果,保留最近 N 条
  2. Compact — 将对话历史压缩为摘要,由专门的 summarization prompt 驱动
  3. Dream — 离线记忆整理,将近期学习综合为持久化记忆

6.2 Function Result Clearing

// Microcompact 提示词
`Old tool results will be automatically cleared from context to free up
space. The ${config.keepRecent} most recent results are always kept.`

模型收到的指令是:"把重要信息写在回复里,因为原始工具结果可能被清除。"

6.3 Dream — 记忆整理

Dream 的提示词分四个阶段:

Phase 1 — Orientls 记忆目录,读入口文件,浏览已有主题文件

Phase 2 — Gather recent signal:按优先级从日志、现有记忆、transcript 中找新信息

Phase 3 — Consolidate

  • 合并新信号到现有主题文件(不重复建)
  • 把相对日期转绝对日期
  • 删除被证伪的事实

Phase 4 — Prune and index

  • 入口文件保持 ≤25KB
  • 每条目一行 ≤150 字符
  • 删除过时指针,缩短过长条目

七、命令系统

commands.ts 注册了大量斜杠命令。按功能分类:

开发工作流

  • /commit — 创建 git commit
  • /commit-push-pr — commit + push + 创建 PR
  • /review / /ultrareview — 代码审查
  • /security-review — 安全审查
  • /diff — 查看差异
  • /branch — 分支管理

上下文管理

  • /compact — 压缩对话历史
  • /clear — 清除对话/缓存
  • /context — 查看上下文使用情况
  • /rewind — 回退对话

配置与工具

  • /config — 配置管理
  • /mcp — MCP 服务器管理
  • /model — 模型切换
  • /fast — 快速模式切换
  • /permissions — 权限模式
  • /hooks — 钩子配置
  • /sandbox — 沙箱管理

Agent 与 Skill

  • /agents — Agent 管理
  • /skills — Skill 管理
  • /plan — 进入计划模式
  • /init — 初始化项目

产品功能

  • /cost / /usage — 费用/用量
  • /doctor — 诊断
  • /help — 帮助
  • /theme / /color — 主题
  • /vim — Vim 模式
  • /status — 状态

实验性功能(feature-flagged)

  • /proactive — 自主工作模式
  • /brief — 简报模式
  • /bridge — 远程桥接
  • /voice — 语音模式
  • /buddy — Buddy 助手
  • /fork — Fork 子 Agent

命令系统的设计哲学:斜杠命令 = prompt 模板 + 上下文注入。不是简单的宏,而是带参数的 prompt 构造器。

7.1 全量命令分类表

COMMANDS 数组注册 71 个命令(含 feature-flagged),另有 25 个内部命令。按产品意图分五类:

核心工作流命令(对话生命周期)

命令 说明 类型
/compact 压缩对话历史为摘要,保留上下文同时释放 token local
/clear 清除对话历史和缓存,重新开始 local
/resume 恢复之前的对话会话(别名 /continue prompt
/session 显示远程会话 URL 和 QR 码,支持移动端接入 local
/exit 退出 REPL local
/rename 重命名当前对话 local
/tag 给会话加可搜索标签 local
/export 将对话导出为文件或剪贴板 local
/rewind 将代码和对话恢复到之前的某个时间点 local
/branch 在当前对话的某个节点创建分支(别名 /fork local
/context 以彩色网格可视化当前上下文使用情况 local-jsx
/files 列出当前上下文中追踪的所有文件 local
/memory 编辑 Claude 记忆文件(用户级/项目级) local
/init 初始化项目,扫描代码库生成 CLAUDE.md prompt
/plan 启用计划模式或查看当前计划 local

代码分析与审查命令

命令 说明 类型
/diff 查看未提交变更和每轮对话的 diff local
/review 审查 Pull Request,生成代码审查报告 prompt
/ultrareview 深度代码审查(多维度) prompt
/security-review 对当前分支变更做安全审查 prompt
/pr-comments 获取 GitHub PR 的评论 prompt
/advisor 配置 advisor 模型(辅助分析) local

扩展与集成管理命令

命令 说明 类型
/mcp 管理 MCP 服务器(启用/禁用/配置) local
/plugin 管理插件 local
/reload-plugins 在当前会话中激活待处理的插件变更 local
/skills 列出可用的 Skills local
/agents 管理 Agent 配置 local
/hooks 查看工具事件的钩子配置 local
/permissions 管理工具权限的 allow/deny 规则 local
/sandbox 管理沙箱设置(沙箱隔离、自动允许等) local
/install-github-app 为仓库设置 Claude GitHub Actions local
/install-slack-app 安装 Claude Slack 应用 local
/ide 管理 IDE 集成和显示状态 local
/chrome Claude in Chrome (Beta) 设置 local
/desktop 将当前会话转到 Claude Desktop local
/mobile 显示下载 Claude 移动应用的 QR 码 local
/add-dir 添加新的工作目录 local

调试与诊断命令

命令 说明 类型
/doctor 诊断和验证 Claude Code 安装与设置 local-jsx
/status 显示版本、模型、账号、API 连通性和工具状态 local
/cost 显示当前会话的总费用和时长 local
/usage 显示计划用量限制 local
/stats 显示 Claude Code 使用统计和活动 local
/extra-usage 配置超额使用,用量到顶后继续工作 local
/rate-limit-options 显示遇到速率限制时的可选项 local
/heapdump 将 JS 堆导出到 ~/Desktop(隐藏命令) local
/terminal-setup 配置终端快捷键(如 Option+Enter 换行) local

体验与配置命令

命令 说明 类型
/config 打开配置面板 local
/model 切换 AI 模型 local-jsx
/fast 切换快速模式(仅限特定模型) local
/effort 设置模型的 effort 级别 local
/theme 更改终端主题 local-jsx
/color 设置当前会话的提示栏颜色 local
/vim 在 Vim 和普通编辑模式间切换 local
/keybindings 打开或创建快捷键配置文件 local
/statusline 切换状态栏显示 local
/output-style 更改输出风格(已废弃,用 /config local-jsx
/help 显示帮助和可用命令 local
/copy 复制最后一条回复到剪贴板 local
/feedback 提交 Claude Code 反馈 local
/stickers 订购 Claude Code 贴纸 local
/btw 不打断主对话的前提下快速提问 prompt
/release-notes 显示更新日志 local
/upgrade 升级到 Max 获取更高用量限制 local
/passes 分享 Claude Code 免费周给朋友 local
/privacy-settings 查看和更新隐私设置 local
/thinkback 2025 Claude Code 年度回顾 local
/thinkback-play 年度回顾播放模式 local
/remote-env 配置 teleport 会话的默认远程环境 local

Feature-Flagged 命令(按条件加载)

命令 Feature Flag 说明
/proactive PROACTIVE / KAIROS 自主工作模式,Agent 自主决定何时行动
/brief KAIROS / KAIROS_BRIEF 简报模式
/assistant KAIROS 助手命令
/bridge BRIDGE_MODE 远程桥接模式
/remote-control-server DAEMON + BRIDGE_MODE 远程控制服务端
/voice VOICE_MODE 语音交互模式
/buddy BUDDY Buddy 协作助手
/fork FORK_SUBAGENT Fork 子 Agent
/peers UDS_INBOX 同伴消息
/workflows WORKFLOW_SCRIPTS 工作流脚本
/torch TORCH 实验性功能
/web (remote-setup) CCR_REMOTE_SETUP 远程设置
/logout / /login 非 3P 服务时 登录/登出

内部命令(仅 Anthropic 内部)

命令 说明
/commit 创建 git commit
/commit-push-pr commit + push + 创建 PR(一条龙)
/issue 处理 GitHub issue
/share 分享会话
/summary 生成会话摘要
/teleport 远程 teleport
/bughunter Bug 猎人模式
/autofix-pr 自动修复 PR
/onboarding 新用户引导
/env 环境管理
/version 版本信息
/good-claude 内部好评
/break-cache 打破 prompt cache
/backfill-sessions 回填会话
/init-verifiers 初始化验证器
/mock-limits 模拟限制
/bridge-kick 踢出桥接
/reset-limits 重置限制
/ant-trace 内部追踪
/perf-issue 性能问题
/oauth-refresh OAuth 刷新
/debug-tool-call 调试工具调用
/agents-platform Agent 平台管理
/ctx-viz 上下文可视化
/force-snip 强制剪裁(history snip)
/ultraplan 超级规划
/subscribe-pr 订阅 PR 变更

产品意图总结:命令系统不只是快捷键集合,而是一个意图分发层。每个命令实际上是三件事的组合:

  1. Prompt 模板:预置的指令上下文(如 /review 注入审查专家提示词)
  2. 上下文注入:自动收集相关数据(如 /diff 注入当前 diff)
  3. UI 模式切换:有些命令切到 JSX 渲染(如 /model 的选择器、/doctor 的诊断面板)

远程安全命令集(REMOTE_SAFE_COMMANDS,17 个)和桥接安全命令集(BRIDGE_SAFE_COMMANDS,6 个)的划分,说明团队在移动端/远程场景下做了最小权限暴露——只开放不影响终端状态的命令。


八、8 个设计亮点详细分析

亮点 1:系统提示词的 Cache-Aware 分层

问题:Claude API 的 prompt cache 按前缀匹配。如果系统提示词包含任何动态内容(如当前日期、工作目录),每次请求都会 cache miss。

方案:用 SYSTEM_PROMPT_DYNAMIC_BOUNDARY 把提示词切成 static 和 dynamic 两部分。Static 部分跨用户、跨会话共享 cacheScope: 'global'

代码证据

return [
  getSimpleIntroSection(outputStyleConfig),     // ← static
  getSimpleSystemSection(),                       // ← static
  getSimpleDoingTasksSection(),                   // ← static
  getActionsSection(),                            // ← static
  getUsingYourToolsSection(enabledTools),         // ← static
  getSimpleToneAndStyleSection(),                 // ← static
  getOutputEfficiencySection(),                   // ← static
  ...(shouldUseGlobalCacheScope()
    ? [SYSTEM_PROMPT_DYNAMIC_BOUNDARY]            // ← boundary
    : []),
  ...resolvedDynamicSections,                     // ← dynamic
]

效果:代码注释提到 Agent listing 的动态部分曾占 fleet cache_creation tokens 的 ~10.2%,通过改为 attachment 注入修复。

竞品对比:Cursor 的系统提示词硬编码在客户端,每次请求都付全额 token 成本——它靠本地模型推理省钱,但在云端 API 场景下这个设计就吃亏了。GitHub Copilot 的缓存优化发生在 IDE 层(重复代码块复用),但没法做到跨会话的全局缓存共享。Claude Code 的做法是把"省钱"从客户端工程问题变成了 API 协议层问题——让 Anthropic 自己的 cache 机制来解决,产品侧只需要做好 static/dynamic 分离。

产品判断:cache-aware 分层不只是技术优化,它决定了产品能不能在不亏本的情况下提供长上下文能力。如果每次请求都为几千 token 的系统提示词付费,长对话的成本会指数级上升。这个设计让 Claude Code 可以放心塞更多信息进系统提示词(详细的工具指令、复杂的行为约束),而不担心成本爆炸。其他 AI 编码工具因为没做这个优化,系统提示词普遍更短、更保守——这不是产品选择,是成本倒逼。

亮点 2:Verification Agent 的对抗性设计

问题:LLM 验证代码实现时有系统性偏差——倾向于看代码"看起来对不对"而不是跑起来验。两个已记录的失败模式:verification avoidance(找理由不跑测试)和 first-80% seduction(被好看的 UI 说服通过)。

方案:Verification Agent 的提示词用"元认知"对抗这些偏差:

  1. 事先列出自己的合理化借口清单
  2. 每个 PASS 必须附带命令和输出
  3. 强制至少一个 adversarial probe
  4. 输出格式机器可解析(VERDICT: PASS/FAIL/PARTIAL

代码证据built-in/verificationAgent.ts 中 ~150 行的 VERIFICATION_SYSTEM_PROMPT,几乎全是"如何不被自己骗"的指令。

效果:Caller(主 Agent)会 spot-check Verifier 的命令输出,形成验证链条。

竞品对比:GitHub Copilot 的 /test 命令让模型自己跑测试——同一个模型既写代码又验证代码,自欺偏差无解。Cursor 的 Agent mode 更粗暴:直接把 test output 回填对话,让主模型自己判断通过没通过,没有独立的验证流程。Devin 虽然有独立的验证步骤,但它的验证 prompt 缺少对抗性设计——没有列出自己的合理化借口,没有强制输出实际命令,很容易退化成"代码看起来没问题,PASS"。

[推测] 产品判断:验证必须和实现分离,这是工程常识,但大部分 AI 编码工具做不到——因为多一个 Agent 意味着多一轮 LLM 调用、多几千 token。Claude Code 愿意为验证付出这个成本,说明 Anthropic 内部测试过:没有独立验证的 Agent,代码正确率会显著低于有验证的版本。Verification Agent 的 PARTIAL verdict 只允许用于环境限制,不允许用于"我不确定"——堵死了模型偷懒的最后出口。

亮点 3:工具偏好 = 提示词 + 工具描述双重约束

问题:模型喜欢用 Bash 做一切(因为它"万能"),但 Bash 的输出不利于用户理解和权限管控。

方案:在两个层级同时约束:

  1. 系统提示词Using your tools section):宏观指导
  2. BashTool 描述getSimplePrompt()):微观再强化
// 系统提示词层
"Do NOT use the Bash tool to run commands when a relevant dedicated tool
is provided."

// BashTool 描述层(模型在决定调用 Bash 时会看到)
"Avoid using this tool to run find, grep, cat, head, tail, sed, awk, or
echo commands, unless explicitly instructed."

设计意图:双重约束防止在上下文变长后模型"忘记"系统提示词的指令。工具描述是模型每次做工具选择时的即时提醒。

竞品对比:大部分 AI 编码工具只在系统提示词里写"用专用工具",然后就指望模型记一辈子。Copilot CLI 的系统提示词有类似约束,但工具描述层没有再强化——模型在 30 轮对话后大概率开始偷用 Bash。Cursor 干脆不约束工具选择,它的 Agent 可以随意用 Bash 做一切,输出格式不受控。Replit Agent 也是同样的问题——万能 Bash 导致用户看到的是一堆 raw terminal output,而不是结构化的搜索结果或编辑 diff。

代码证据:双重约束的具体落点——

// 系统提示词(getUsingYourToolsSection)
"Do NOT use the Bash tool to run commands when a relevant dedicated tool
is provided. Using dedicated tools allows the user to better understand
and review your work."

// BashTool 描述(getSimplePrompt)——模型每次选择 Bash 时会重新阅读
"File search: Use Glob (NOT find or ls)
Content search: Use Grep (NOT grep or rg)
Read files: Use Read (NOT cat/head/tail)
Edit files: Use Edit (NOT sed/awk)
Write files: Use Write (NOT echo >/cat <<EOF)
Communication: Output text directly (NOT echo/printf)"

注意 BashTool 描述用的是 NOT + 具体命令名,而系统提示词用的是抽象的"relevant dedicated tool"。工具层的描述更具体、更有可操作性——模型看到 NOT find 比看到"请使用专用工具"更容易做出正确判断。

产品判断:这个设计的精髓是"在决策点嵌入约束"。类比人类管理:你在员工手册里写"注意安全"没用,得在冲压机上贴"操作前必须戴手套"的标牌。模型每次做工具选择时都会重新阅读工具描述,所以这里的约束比系统提示词开头的约束更"新鲜"。上下文越长,这个优势越明显。

亮点 4:Coordinator 的 Synthesis-First 工作流

问题:多 Agent 协作时,Coordinator 容易变成简单的"传话筒"——把 worker 的结果转发给下一个 worker,自己不做理解。

方案:提示词明确禁止"lazy delegation":

Never write "based on your findings" or "based on the research." These
phrases delegate understanding to the worker instead of doing it yourself.

并给出了正反例:

// Anti-pattern
Agent({ prompt: "Based on your findings, fix the auth bug", ... })

// Good
Agent({ prompt: "Fix the null pointer in src/auth/validate.ts:42. The user
field on Session (src/auth/types.ts:15) is undefined when sessions expire
but the token remains cached. Add a null check before user.id access..." })

设计意图:强制 Coordinator 做一轮"理解-综合-规格化",把模糊的研究结果变成精确的实现指令。这实质上是把 Coordinator 当作人类 Tech Lead 来使用——Tech Lead 的价值不是传话,是理解后给出具体指令。

竞品对比:Copilot Workspace 有类似的"先调研再实施"流程,但它的调研结果直接变成 PR diff,中间没有一个 Coordinator 做综合——多个文件的调研结果被平等地对待,没有主次之分。Cursor 的 Composer 模式更简单:模型边看代码边改,研究和实施混在一起,遇到复杂问题容易在一个文件里打转而忽略跨文件影响。Devin 有类似 Coordinator 的角色,但它的"综合"更偏向项目管理(追踪进度),而不是技术综合(理解代码关系后给出精确指令)。

代码证据:禁止 lazy delegation 的具体约束——

// Anti-pattern(Coordinator 假装理解了)
Agent({ prompt: "Based on your findings, fix the auth bug", ... })

// Good(Coordinator 证明自己理解了)
Agent({ prompt: "Fix the null pointer in src/auth/validate.ts:42.
The user field on Session (src/auth/types.ts:15) is undefined when
sessions expire but the token remains cached. Add a null check
before user.id access..." })

正例里的具体细节(文件路径、行号、字段名、根因分析)证明 Coordinator 真的读了 Worker 的结果,而不只是转发。这个约束的底层逻辑是:如果你不能给出具体的文件路径和行号,说明你没真正理解问题。

[推测] 产品判断:多加一轮 Coordinator 的综合,意味着多花一轮 LLM 调用的 token 和延迟。大部分多 Agent 产品不敢这么做,因为用户等不起。Claude Code 愿意付这个代价,说明它的目标用户(专业开发者)对正确性的容忍延迟高于对速度的追求。这和"快速出 demo"的 AI 编码工具形成了产品定位上的根本差异。

亮点 5:可逆性分级的风险管控

问题:Agent 自主执行时,一个错误的 rm -rfforce push 可能造成不可挽回的损失。

方案:不搞一刀切的"所有操作都要确认",而是按可逆性分级:

Generally you can freely take local, reversible actions like editing files
or running tests. But for actions that are hard to reverse, affect shared
systems beyond your local environment, check with the user before proceeding.

分级逻辑

  • 自由执行:编辑文件(可 git revert)、跑测试(只读)、查代码
  • 需要确认:删除文件、force push、发消息、改 CI/CD
  • 显式授权覆盖:用户说"更自主地操作"后可以跳过确认,但仍需 attend to risks

代码证据:系统提示词里 ~150 字的 Actions section + BashTool 里的 Git Safety Protocol。

设计意图:在自主性和安全性之间找到平衡点。太多确认 = 烦人,太少确认 = 危险。可逆性是一个好用的判断标准。

竞品对比:Cursor 的 Agent mode 只有"允许"和"拒绝"两档——要么全部确认(烦死),要么 auto-apply 全放开(危险)。Copilot 的权限模型更细,但它的判断依据是"工具类型"而不是"可逆性"——比如 Bash 始终需要确认,即使你只是跑个 ls。Windsurf 的 Cascade 有类似可逆性判断,但它的安全边界更窄,只覆盖了 git 操作,没有扩展到发消息、改 CI 等非代码场景。

代码证据:BashTool 里 Git Safety Protocol 的具体约束——

NEVER update the git config
NEVER run destructive commands (push --force, reset --hard, checkout .,
  restore ., clean -f, branch -D) unless the user explicitly requests
NEVER skip hooks (--no-verify, --no-gpg-sign, etc)
NEVER run force push to main/master

四个 NEVER 把最高风险操作锁死,同时用 "unless the user explicitly requests" 保留了逃生口——用户明确要求时可以做,但不能自作主张。注意 NEVER skip hooks 这一条:它不只是防破坏性操作,还在防模型绕过代码审查流程(hooks 通常包含 lint、test、sign)。

[推测] 产品判断:可逆性分级的落地有个根本困难:它依赖模型对"hard to reverse"的理解力。模型有时候会误判——比如认为 git stash pop 是可逆的(其实可能产生冲突)。更好的做法是用代码层硬限制(直接 block force push),但 Claude Code 选择用提示词软约束,说明他们认为灵活性比绝对安全更重要。这是产品取舍,不是技术缺陷。另外,"显式授权覆盖"这个逃生口很有意思——用户说"更自主地操作"后,模型的判断标准会降低,但仍需"attend to risks"。这相当于把安全阈值的选择权交给了用户。

亮点 6:Plan Mode — "先想后做"的权限沙箱

问题:Agent 收到任务后默认直接动手改代码。但很多场景下,用户真正需要的是"先告诉我你打算怎么改"——尤其是涉及架构决策、多文件重构、或者用户自己还没想清楚需求的时候。

方案EnterPlanModeTool 让 Agent 进入一个只读沙箱。核心约束:

Plan mode constraints:
- You CANNOT edit files
- You CANNOT run mutating commands  
- You CAN read files, search code, run read-only commands
- You MUST produce a written plan before exiting

用户端的交互流程:

用户: "重构这个模块的认证逻辑"
  → Agent 调用 EnterPlanModeTool
  → 进入只读模式
  → Agent 阅读代码、搜索依赖、理解现状
  → 输出计划(文件路径、行号、改动描述)
  → 调用 ExitPlanModeTool,附带计划内容
  → 用户在 UI 上看到计划,选择批准/拒绝/修改
  → 批准后 Agent 退出 plan mode,开始执行

代码证据AskUserQuestionTool 的描述中明确写了 plan mode 的特殊行为:

Plan mode note: In plan mode, use this tool to clarify requirements or
choose between approaches BEFORE finalizing your plan. Do NOT use this
tool to ask "Is my plan ready?" or "Should I proceed?" - use
ExitPlanMode for plan approval. IMPORTANT: Do NOT reference "the plan"
in your questions because the user cannot see the plan in the UI until
you call ExitPlanMode.

给产品人的启示:Plan Mode 不只是一个"只读开关",它是一个信任建立机制。用户看到 Agent 的完整计划后,批准执行的心理门槛大幅降低。类比人类工作流:没人会直接让实习生去改生产代码,先让他写个方案,review 通过再动手。

给工程师的启示:Plan Mode 的约束是在工具层实现的——不是在提示词里说"别改文件",而是直接禁用写权限的工具。这是"约束优于引导"原则的又一次落地。ExitPlanModeTool 把计划内容结构化地传回 UI,而不是让 Agent 在对话里用自然语言描述,保证了 UI 和逻辑的一致性。

竞品对比:Copilot Workspace 强制先出 plan 再实施,但它的 plan 是自动生成的 PR diff——用户看到的是代码变更而不是思路,这降低了 plan 的"沟通价值"。Cursor 的 Ask 模式可以看代码但不改,类似只读模式,但没有结构化的计划输出和批准机制——用户只能在对话里打字说"OK 开始改吧",UI 体验粗糙。Windsurf 的 Plan 模式接近 Claude Code 的设计,但缺少 AskUserQuestionTool 的 UI 联动(多选、预览),计划审批的交互颗粒度更粗。

你可能没注意到的细节AskUserQuestionTool 在 plan mode 下有特殊行为约束——禁止问"Is my plan ready?"或"Should I proceed?",因为用户在 UI 上看不到计划内容(必须先调 ExitPlanMode)。还禁止在问题中引用"the plan",因为用户根本不知道你在说什么。这说明工具设计和 UI 设计是联动的——不是每个组件各管各的,而是整个交互流程端到端设计。大部分 AI 产品做不到这一点,因为它们的工具层和 UI 层是分开开发的。

亮点 7:Worktree 隔离 — Agent 在沙箱里搞破坏

问题:Agent 执行代码修改时,可能引入破坏性变更。如果直接在用户的工作目录操作,一次错误的批量替换或者删错文件,整个项目状态就乱了。

方案EnterWorktreeTool / ExitWorktreeTool 基于 git worktree 创建隔离环境:

// Agent 定义中可以声明隔离级别
isolation: z.enum(['worktree', 'remote']).optional()

Worktree 的工作机制:

主分支 (main)
  ↓ EnterWorktreeTool
  → git worktree add .claude-worktrees/task-abc
  → Agent 在 worktree 中操作
  → 修改文件、运行测试、验证结果
  ↓ ExitWorktreeTool
  → 将 worktree 中的变更合并/PR 回主分支
  → 清理 worktree

关键产品决策bypassPermissions 模式仅在 worktree/remote 隔离下可用。代码证据:

- bypassPermissions 模式:全部自动通过(仅 worktree/remote 隔离下可用)

设计意图:这是一个值得注意的的安全对冲——你想让 Agent 完全自主(bypass permissions)?可以,但必须在隔离环境里。破坏力和隔离度成正比。类比:你给建筑工人完全的施工权限没问题,但得是在脚手架围起来的施工区里,不是在你住着的客厅里。

给产品人的启示:Worktree 隔离解决了"信任"和"自主性"之间的死结。不隔离就不能给高权限,不给高权限 Agent 就束手束脚。Worktree 让这两个矛盾的需求同时满足——Agent 可以随便造,但造完的东西需要用户 approve 才能合并回主分支。

竞品对比:Copilot Workspace 天然在 branch 上操作,但 branch 不等于 worktree——branch 共享工作目录和索引,一个 rm -rf 或者错误的全局搜索替换就能把整个工作区搞乱。Cursor 的 Agent mode 完全没有隔离机制,直接在用户项目目录操作,出错了只能靠 undo。Devin 用容器做隔离,安全性更好但启动成本高(每次要初始化一个完整的开发环境),而且容器和本地项目的文件同步是个大问题。git worktree 是个聪明的折中——共享 git 历史和依赖,但文件系统隔离,启动成本几乎为零(git worktree add 秒级完成)。

更深层的设计细节:worktree 隔离还支持远程执行模式(isolation: 'remote'),意味着 Agent 可以在远程机器上运行——和本地工作目录物理隔离。这是面向未来的架构:当 Agent 的操作越来越激进(自动重构、自动升级依赖),本地 worktree 可能不够用,远程隔离 + 容器化才是终局。Agent 定义的 isolation 字段是一个 enum 而不是 boolean,暗示未来还会有更多隔离级别。

亮点 8:输出风格系统 — Agent 的"人设"可配置

问题:不同用户、不同场景需要不同的 Agent 输出风格。写代码时想要简洁的技术风格,写文档时想要详细的解释风格,调试时想要有条理的排查风格。

方案outputStyles 系统让 Agent 的系统提示词中 Tone and style section 可替换:

// 系统提示词构建时
getSimpleIntroSection(outputStyleConfig),  // ← outputStyleConfig 控制风格
getSimpleToneAndStyleSection(),            // ← 默认风格(可被覆盖)

输出风格通过 /config 命令配置(/output-style 命令已废弃)。风格配置注入到系统提示词的静态层,意味着它参与 prompt cache——切换风格会有 cache miss,但同风格的多次请求享受 cache 命中。

代码证据:系统提示词中明确把 "Output style" 列为动态 section 的一个组成部分:

- Output style(用户自定义输出风格)

给产品人的启示:这是把"提示词工程"从产品内部的事变成了用户可配置的事。大多数 AI 产品把输出风格写死在系统提示词里,用户只能接受。Claude Code 把它做成可配置项,实质上是在说:"你比我更知道你需要什么风格的输出。"

给工程师的启示:outputStyle 的设计巧妙之处在于它没有搞一个复杂的风格 DSL,而是直接替换系统提示词的某个 section。简单粗暴但有效——任何能写 markdown 的人都能定义一个新的输出风格。

竞品对比:Cursor 没有输出风格系统,模型按系统提示词里的固定风格输出,用户没法调。Copilot 有 "detailed/terse" 的简单开关,但只有两档,且不支持自定义。ChatGPT 的 Custom Instructions 只能改"关于你"和"回复风格"两个文本框,颗粒度太粗。Claude Code 的 outputStyle 直接替换系统提示词的一个完整 section,用户可以用 Markdown 写任意复杂的风格指令——包括行为约束、格式要求、特定场景的输出模板。

你可能没注意到的细节:outputStyle 注入到系统提示词的静态层getSimpleIntroSection(outputStyleConfig)),意味着它参与 prompt cache。但这里有个矛盾——如果用户频繁切换风格,每次都会 cache miss,反而增加延迟和成本。所以 Claude Code 把 /output-style 命令废弃了,改为通过 /config 配置——暗示他们期望用户设一个风格后长期使用,而不是频繁切换。这是用产品设计引导用户行为的例子:技术上支持频繁切换,但产品上鼓励稳定性。

亮点 8 的补充:TodoWriteTool 的 few-shot 工程

TodoWriteTool 的提示词值得单独说一下,因为它是整个代码库里 few-shot examples 最密集的工具描述。

代码证据

Task descriptions must have two forms:
- content: imperative form ("Run tests")
- activeForm: present continuous ("Running tests")

这个双态设计直接对接 TUI 渲染——任务列表在前端展示时用 content,当前活跃任务在状态栏用 activeForm。如果模型只输出一种形式,UI 就得做 fallback(要么截断要么猜测),体验差。

使用边界的 few-shot:8 个正例 + 4 个反例,通过具体场景划清"该用 TodoWrite"和"不该用"的边界。3+ 步骤是硬阈值——2 步的任务即使复杂也不该用,因为 TodoWrite 的管理开销(创建、更新状态、标记完成)大于收益。

竞品对比:Copilot 没有独立的任务管理工具,多步骤任务靠模型在对话里用 markdown 列表追踪——容易丢失、没有状态管理、用户不知道"进行到哪了"。Cursor 的 Agent 用内置的 todo list,但它的提示词远没有 Claude Code 的精细——没有双态描述、没有 few-shot 边界、没有 3 步阈值。结果是模型经常在不该用 todo 的场景创建 todo list,浪费上下文。


九、Agent 定义规范

9.1 AgentDefinition 类型

// tools/AgentTool/loadAgentsDir.ts (Zod schema 摘要)
z.object({
  description: z.string().min(1),
  tools: z.array(z.string()).optional(),        // 允许的工具(allowlist)
  disallowedTools: z.array(z.string()).optional(), // 禁用的工具(denylist)
  prompt: z.string().min(1),
  model: z.string().optional(),                  // 'inherit' 继承父模型
  effort: z.union([z.enum(EFFORT_LEVELS), z.number()]).optional(),
  permissionMode: z.enum(PERMISSION_MODES).optional(),
  mcpServers: z.array(AgentMcpServerSpecSchema()).optional(),
  hooks: HooksSchema().optional(),
  maxTurns: z.number().int().positive().optional(),
  skills: z.array(z.string()).optional(),
  initialPrompt: z.string().optional(),
  memory: z.enum(['user', 'project', 'local']).optional(),
  background: z.boolean().optional(),
  isolation: z.enum(['worktree', 'remote']).optional(),
})

Agent 可以从 Markdown frontmatter 或 JSON 文件加载。支持:

  • 工具白名单/黑名单
  • 指定模型或继承
  • 权限模式覆盖
  • MCP 服务器绑定
  • 独立记忆作用域
  • Worktree 隔离

十、Proactive 模式 — 自主 Agent

PROACTIVE feature flag 启用时,Claude Code 进入自主工作模式:

You are running autonomously. You will receive <tick> prompts that keep
you alive between turns — just treat them as "you're awake, what now?"

关键行为指令:

  • 用 Sleep 控制节奏If you have nothing useful to do on a tick, you MUST call Sleep.
  • Bias toward actionRead files, search code, explore the project, run tests — all without asking.
  • 终端焦点感知terminalFocus 字段决定自主程度
    • Unfocused → 用户不在,大胆行动
    • Focused → 用户在看,保持协作

十一、用户旅程分析

从用户视角走一遍完整流程,看每个节点的产品设计决策。

11.1 安装与首次启动

npm install -g @anthropic-ai/claude-code
claude

安装后首次启动触发 onboarding 流程(源码中有专门的 /onboarding 命令,虽然对外隐藏)。首次启动做几件事:

  1. 认证引导:弹出 OAuth 流程或 API Key 输入。产品决策——默认走 OAuth(降低门槛),API Key 是 fallback(面向高级用户)
  2. 终端能力检测terminalSetup 命令检测终端类型(Apple Terminal / iTerm / etc),自动配置 Option+Enter 换行等快捷键
  3. IDE 检测/ide 命令检测 VS Code / JetBrains 等 IDE,提示安装扩展
  4. CLAUDE.md 扫描:如果项目根目录有 CLAUDE.md,自动加载为项目级记忆

给产品人的启示:首次体验不是"教你用",而是"帮你配好环境"。认证、终端、IDE、项目记忆四个维度的自动检测,把 onboarding 摩擦降到最低。

11.2 第一次对话

用户输入第一句话后,Claude Code 做的事情:

用户输入
  → buildSystemPrompt() 构建系统提示词
    → 静态部分(身份、规则、工具偏好、输出风格)
    → boundary marker
    → 动态部分(环境信息、git 状态、语言偏好)
  → 工具定义注入(每个工具的 getDescription())
  → LLM 调用
  → 工具调用循环

关键细节:

  • 系统提示词是 lazy 构建的getSystemPrompt() 返回 string[],不是拼好的大字符串。每个 section 是独立函数,支持按需组合
  • 工具描述是动态的:BashTool 的 getSimplePrompt() 根据 OS 类型返回不同内容(Windows vs Unix)
  • 环境信息每次刷新getEnvironmentDetails() 包含当前时间、工作目录、git 分支、OS 信息——这些是动态部分,不走 prompt cache

给工程师的启示:静态/动态分离不只是省钱。动态部分包含会话状态(git branch、文件变更),这些信息如果混进静态部分会导致 cache 失效,反而增加延迟。

11.3 工具调用链

模型决定调用工具后,执行流程:

模型返回 tool_use block
  → 权限检查(permissionMode 分级)
    → allowPermissionSafetyLevel 判断
      → 自动执行 or 询问用户
  → 工具执行
  → 结果截断(防止输出撑爆上下文)
  → tool_result 回填对话

权限分级的产品逻辑:

  • readOnly 模式:只允许读操作(Grep、Glob、Read、WebSearch)
  • default 模式:允许大部分操作,Bash/写文件需确认
  • acceptEdits 模式:文件编辑自动通过,Bash 需确认
  • bypassPermissions 模式:全部自动通过(仅 worktree/remote 隔离下可用)

工具输出截断是另一个容易忽略的细节——BashTool 的输出有上限,超过部分截断并提示"输出被截断,用 offset/limit 参数查看更多"。这不是 bug,是上下文保护。

11.4 会话恢复

/resume 命令恢复之前的对话。背后的产品设计:

  1. 会话存储:每次对话的完整记录(用户输入、模型输出、工具调用和结果)持久化存储
  2. 恢复时的上下文重建
    • 加载历史对话记录
    • 重新构建系统提示词(因为环境可能变了——新的 git branch、新的文件)
    • 重新注入工具定义
  3. 分支恢复/branch 在某个历史节点创建新分支,保留之前的上下文但允许走不同路径

给产品人的启示:会话恢复不是简单的"加载历史记录"。系统提示词里的动态部分(环境信息、git 状态)必须重新生成——用户切了分支后恢复对话,如果还用旧的 git 信息,工具调用会出错。

11.5 上下文压力与压缩

当对话变长,上下文管理三级介入:

上下文快满
  → Microcompact(自动,~87.5% 阈值)
    → 清理旧的 tool_result(Function Result Clearing)
    → 保留最近的工具调用结果
  → Compact(手动或自动,~95% 阈值)
    → 将整个对话压缩为摘要
    → 摘要作为系统消息注入新上下文
  → Dream(Agent 模式下的记忆整理)
    → 将有价值的发现写入记忆文件
    → 清理临时状态

Function Result Clearing 的策略值得注意——不是简单地删除旧结果,而是用 isContentlessToolResult() 判断:如果工具结果只有元数据没有实际内容(如空的文件读取结果),直接清除;如果有内容但很旧,保留摘要。这个判断直接影响 token 消耗。

11.6 错误处理

Claude Code 的错误处理分三层:

  1. 工具级错误:工具执行失败 → 错误信息作为 tool_result 回填 → 模型看到错误后自行调整策略(换工具或换参数)
  2. 模型级错误:API 调用失败(rate limit、网络错误)→ 重试逻辑 + 用户提示。/rate-limit-options 命令在遇到限制时显示可选项
  3. 会话级错误:上下文溢出 → 触发 compact。模型输出异常 → 解析失败时安全降级

最值得学的错误处理模式:让模型自己处理工具错误。不是在框架层写一堆 if/else,而是把错误信息原样返回给模型,让它判断下一步。模型的错误恢复能力比硬编码的重试逻辑灵活得多——它可以换一种方式重试(比如文件不存在时换路径搜索),也可以放弃当前策略改用其他工具。

给工程师的启示:工具结果里的错误信息格式很重要。如果错误信息太技术化(stack trace),模型可能理解不了;如果太笼统("something went wrong"),模型无法做出正确决策。Claude Code 的做法是保留有意义的错误信息,同时截断 stack trace。

11.7 用户旅程产品矩阵

阶段 用户目标 Claude Code 的响应 产品设计原则
安装 快速跑起来 自动检测终端/IDE,OAuth 优先 零配置优先
首次对话 完成第一个任务 系统提示词 + 工具集自动就位 隐形引导
工具调用 看到实际结果 权限分级 + 输出截断 安全但不烦人
会话变长 继续工作不中断 三级压缩自动介入 上下文透明管理
恢复会话 接上次的活 重建上下文(动态部分刷新) 状态一致性
出错 知道发生了什么、怎么修 错误回填模型,让模型自己恢复 自愈优先于硬编码

设计反模式:三个可以做得更好的地方

以上夸了不少,但源码里也有让人皱眉的设计。以下是三个"如果是我会怎么改"的分析。

反模式 1:TodoWrite 的 3 步阈值太机械

TodoWriteTool 的提示词写死了 "3 or more distinct steps" 才该用 todo list。但现实中,2 步任务也可能很复杂——比如"重构认证模块"只有两步(改代码、跑测试),但每一步都涉及 10+ 个文件。

问题在哪:用步骤数衡量复杂度是偷懒。一个 5 步的 trivial 任务(改 5 个文件的 import 路径)比一个 2 步的复杂任务(重构核心模块)更适合用 todo list 吗?显然不是。

怎么改:把判断标准从"步骤数"改成"预估工作量"或"涉及文件数"。提示词已经写了 "Non-trivial and complex tasks" 应该用 todo list,但和 3 步阈值并列后,模型大概率优先数步骤而不是判断复杂度。更好的做法是删掉硬阈值,只保留复杂度判断 + few-shot examples。

为什么没改:可能是因为"3 步"这个规则简单、可验证、few-shot 容易写。复杂度判断更主观,few-shot 边界模糊,模型执行的一致性会下降。这是"可预测性 vs 精确性"的取舍,Claude Code 选了前者。

反模式 2:错误处理完全依赖模型自愈

Claude Code 的错误处理哲学是"把错误原样返回给模型,让它自己想办法"。这很优雅,但也意味着框架层没有兜底逻辑。

问题在哪:模型的错误恢复能力不稳定。同一个错误,第 1 轮可能正确处理(换个路径重试),第 5 轮上下文变长后可能开始瞎猜(随便换个参数再试一次)。特别是 rate limit 错误——模型可能不理解 "429 Too Many Requests" 的含义,继续疯狂重试。

代码证据:工具执行失败后,错误信息作为 tool_result 回填,格式大致是:

Error: ENOENT: no such file or directory, open '/path/to/file.ts'

这个错误信息对人类来说很清晰,但对模型来说信息量有限——它知道文件不存在,但不知道该去找哪个替代路径。如果错误信息里包含"你可能想找 /path/to/file.js(注意后缀是 js 不是 ts)",模型的恢复成功率会高很多。

怎么改:在工具层加一层"error enrichment"——不只是返回原始错误,还附带可能的原因和建议操作。比如 ENOENT 错误附带 "did you mean: [glob 搜索结果]",rate limit 附带 "retry after N seconds"。这不会替代模型的判断,但能提高判断质量。

为什么没改:错误 enrichment 需要每个工具单独实现,工程量大。而且"给模型太多建议"可能反过来限制它的创造力——有时候模型需要的是"试试完全不同的方法",而不是"在同一条路上修修补补"。

反模式 3:Explore Agent 的输出截断缺乏智能分页

Explore Agent 是只读的代码搜索 Agent,很精巧。但它有个问题:当搜索结果很长时,输出会被截断,而 Agent 的 prompt 没有教它如何主动分页来避免信息丢失。

问题在哪:假设用户问"找到所有调用 authenticate() 的地方",在大型代码库里可能有 200 个匹配。GrepTool 的输出会被截断(可能只返回前 50 个),Explore Agent 报告"找到了多个调用"但实际只覆盖了 25%。用户以为搜索完整了,其实漏了大部分。

代码证据:GrepTool 支持 offsetlimit 参数,但 Explore Agent 的 prompt 没有明确要求它"在截断时主动用 offset 翻页"。它只是说 "Search thoroughly"——但"thoroughly"对模型来说太模糊了。

// GrepTool 参数
offset: z.number().optional(),  // Start at this match number
limit: z.number().optional(),   // Return at most this many matches

怎么改:在 Explore Agent 的 prompt 里加一条明确指令——"如果搜索结果被截断(输出提示 'output truncated'),必须用 offset 参数继续翻页,直到确认没有更多结果。不要在截断时报告'找到了所有结果'。" 简单一句话,解决大半问题。

为什么没改:可能是为了避免 Explore Agent 在大代码库里做太多轮搜索撑爆上下文。翻页搜索的 token 成本不低——每一轮 GrepTool 调用都是一次完整的工具执行 + 结果回填。在"完整性"和"成本"之间,Claude Code 选择了控制成本。


十二、总结

Claude Code 的设计哲学可以概括为三句话:

  1. 提示词是产品。系统提示词不是"给模型的说明",而是产品的核心用户体验层。每一行都在做边界划定、行为塑造、风险管控。

  2. 约束优于引导。不用"请不要",用"这样做会失败"。FileEditTool 强制先读后写,Verification Agent 强制输出命令,Explore Agent 从工具层禁用写权限。软约束和硬约束并用。

  3. 层级化复杂度管理。简单任务走单 Agent,复杂任务走 Coordinator + Workers,极端复杂走 fork 并行。上下文管理从 Microcompact 到 Compact 到 Dream 三级递进。不是"一个模型搞定一切",而是按任务复杂度匹配执行架构。

如果要做一个类似的 AI 编码产品,最值得抄的三样东西:

  • 系统提示词的 cache-aware 分层(省钱、降延迟)
  • Verification Agent 的对抗性设计(解决 LLM 验证的系统性偏差)
  • 工具偏好的双重约束(系统提示词 + 工具描述,防止上下文漂移)

分析基于 `` 源码,部分 feature-flagged 功能的行为以代码中的条件分支为准。标注"待确认"的部分需要进一步验证。

十三、竞品对比

维度 Claude Code Cursor GitHub Copilot Windsurf
架构 CLI + Agent Loop IDE 集成 IDE 插件 IDE 集成
工具数量 40+ 20+ 10+ 15+
子 Agent Fork + Coordinator 有限
权限 6 层 AST 分析 基础 基础 中等
MCP 原生支持 支持 不支持 支持
记忆系统 Memdir + Dream 项目规则 Rules
语音 有(实验)
价格 $20/月 $20/月 $10/月 $15/月

以上对比基于公开信息分析,具体功能以各产品最新版本为准。

十四、Buddy Pet 系统

终端里的虚拟宠物——18 个物种(鸭子、鹅、猫、恐龙、章鱼、猫头鹰、乌龟、蜗牛、兔子、蘑菇、胖胖等),5 个稀有度(common 60%、uncommon 25%、rare 10%、epic 4%、legendary 1%)。

Bones(骨架)由用户 ID hash 确定性生成——同一用户永远孵出同一只。Soul(灵魂)由模型首次生成后存入配置。稀有度独立于物种,legendary 有 50+ 属性下限。

交互:/buddy pet 触发爱心飘浮,/buddy rename 改名,/buddy hat 换帽子(8 种)。

代码里 Buddy 作为独立的"观察者"参与对话——它的提示词明确说"你不是 Claude,你是一个旁边看着的小家伙"。这不是恶搞,是认真做过的产品设计:终端工具冷冰冰的问题,用一个虚拟宠物解决了。