乐于分享
好东西不私藏

盘点Claude Code源码中的提示词系统工程

盘点Claude Code源码中的提示词系统工程

提示词系统工程

本章概要

Claude Code 不仅仅是一个 CLI 工具,它的每一个交互都依赖于提示词——这些文本指令告诉 Claude 应该如何工作、如何使用工具、如何理解上下文。提示词就像血液一样,流淌在 Claude Code 的每一个模块中,连接所有组件,为 Claude 提供养分。

本章是全书的枢纽章节,揭示前面所有模块(Context、内存、权限、工具、Agent 等)如何向提示词注入内容,最终形成 Claude Code 的完整系统提示词。

前置知识:第1-11章(所有模块的基础知识)后续章节:第13章 Feature Flags阅读时长:60-80分钟代码参考src/constants/prompts.tssrc/constants/systemPromptSections.tssrc/utils/systemPrompt.ts


12.1 提示词系统定位

12.1.1 “血液”的含义

Claude Code 的提示词系统之所以被称为”血液”,是因为它具有以下特征:

特征
说明
连接所有模块
Context、内存、权限、工具、Agent 都向提示词注入内容
持续循环更新
每一轮对话都会重新构建提示词
提供养分
为 Claude 提供上下文、指令、约束
流淌在每一个交互中
每次 API 调用都包含完整的系统提示词
用户输入 ──→ 构建提示词 ──→ 发送给 Claude API
              ↑
              │
      ┌───────┼───────┐
      │       │       │
   Memory   Tools   Context
      │       │       │
   Agent   MCP   Permissions

12.1.2 提示词连接所有模块

模块
向提示词注入的内容
Context
压缩后的上下文摘要
Memory
用户偏好、项目知识、外部引用
Tools
工具描述、使用指南
Permissions
Hook/Rules 指令、安全约束
Agents
Agent 定义、行为准则
MCP
MCP 服务器指令
Env Info
cwd、git 状态、平台信息

12.1.3 本章目标

本章目标:

1. 理解提示词系统的三层架构
2. 掌握 SystemPromptSection 缓存机制
3. 理解主提示词的 6 步构建流程
4. 掌握有效提示词的 6 层优先级链
5. 了解各类提示词的构建方式
6. 看懂提示词如何在各模块间流转

12.2 提示词架构全景

12.2.1 三层架构总览

Claude Code 的提示词系统分为三个层次:

┌─────────────────────────────────────────────────────────────┐
│                    应用层(buildEffectiveSystemPrompt)          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  overrideSystemPrompt ──────┐                       │   │
│  │  Coordinator System Prompt ─┤ → 直接替换或追加       │   │
│  │  Agent System Prompt ───────┤   到最终提示词          │   │
│  │  Custom System Prompt ──────┤                       │   │
│  │  Default System Prompt ─────┘                       │   │
│  │              + appendSystemPrompt(始终追加)          │   │
│  └─────────────────────────────────────────────────────┘   │
│                            │                                 │
└────────────────────────────┼─────────────────────────────────┘
                             │
                             ▼
┌─────────────────────────────────────────────────────────────┐
│                    构建层(getSystemPrompt)                      │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌───────────────────────┐  ┌────────────────────────────┐ │
│  │  静态内容              │  │  SYSTEM_PROMPT_DYNAMIC_   │ │
│  │  (可全局缓存)          │  │  BOUNDARY                 │ │
│  │                       │  │                            │ │
│  │  - Intro             │  │  ┌──────────────────────┐ │ │
│  │  - System            │  │  │ 动态 Sections        │ │ │
│  │  - Tasks             │  │  │                      │ │ │
│  │  - Actions           │  │  │ systemPromptSection()│ │ │
│  │  - Tools             │  │  │ (带缓存)            │ │ │
│  │  - Tone              │  │  │                      │ │ │
│  │  - Output            │  │  │ DANGEROUS_uncached..│ │ │
│  │                       │  │  │ (每次重算)          │ │ │
│  └───────────────────────┘  │  └──────────────────────┘ │ │
│                             └────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
                             │
                             ▼
┌─────────────────────────────────────────────────────────────┐
│                    Section 解析层                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  resolveSystemPromptSections()                               │
│       │                                                     │
│       ├── systemPromptSectionCache: Map<string, string|null> │
│       │    (src/bootstrap/state.ts)                         │
│       │                                                     │
│       └── 返回解析后的 string[]                              │
└─────────────────────────────────────────────────────────────┘

12.2.2 三层职责

层次
组件
职责
应用层 buildEffectiveSystemPrompt()
根据优先级选择最终提示词
构建层 getSystemPrompt()
组装静态和动态内容
解析层 resolveSystemPromptSections()
计算并缓存动态 Sections

12.2.3 提示词流转全景图

┌─────────────────────────────────────────────────────────────┐
│                   提示词流转全景图                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  【模块注入层】                                               │
│                                                             │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐      │
│  │   Memory    │  │   Tools     │  │    MCP     │      │
│  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘      │
│         │                 │                 │                 │
│         ▼                 ▼                 ▼                 │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  动态 Sections (systemPromptSection /              │   │
│  │              DANGEROUS_uncachedSystemPromptSection)│   │
│  └─────────────────────────────────────────────────────┘   │
│                            │                               │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐      │
│  │   Context   │  │ Permissions │  │   Agents    │      │
│  │  (Compact) │  │  (Hooks)   │  │(Definition) │      │
│  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘      │
│         │                 │                 │                 │
│         └─────────────────┼─────────────────┘                 │
│                           │                                   │
│                           ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  buildEffectiveSystemPrompt()                        │   │
│  │  优先级链: override → Coordinator → Agent →          │   │
│  │           Custom → Default + append                  │   │
│  └─────────────────────────────────────────────────────┘   │
│                           │                               │
│                           ▼                               │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  getSystemPrompt()                                  │   │
│  │  静态内容 (Intro/System/Tasks/Actions/Tools/       │   │
│  │         Tone/Output)                                │   │
│  │  + DYNAMIC_BOUNDARY                                 │   │
│  │  + 动态 Sections (memory + env + MCP + ...)       │   │
│  └─────────────────────────────────────────────────────┘   │
│                           │                               │
│                           ▼                               │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  resolveSystemPromptSections()                       │   │
│  │  systemPromptSectionCache (按 name 缓存)            │   │
│  └─────────────────────────────────────────────────────┘   │
│                           │                               │
│                           ▼                               │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  最终 System Prompt (string[])                      │   │
│  │  → 发送给 Claude API                                 │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

12.3 SystemPromptSection 机制

12.3.1 Section 定义结构

// src/constants/systemPromptSections.ts

type ComputeFn = () =>string | null | Promise<string | null>

interface SystemPromptSection {
  name: string// 唯一标识符
  compute: ComputeFn // 计算函数
  cacheBreak: boolean// 是否破坏缓存
}

12.3.2 两种 Section 工厂

// 普通缓存 Section
functionsystemPromptSection(
  name: string,
  compute: ComputeFn,
  options?: { cacheBreak?: boolean }
): SystemPromptSection

// 危险的不缓存 Section(每次重算)
functionDANGEROUS_uncachedSystemPromptSection(
  name: string,
  compute: ComputeFn,
  reason: string// 必须提供原因,用于日志记录
): SystemPromptSection

12.3.3 缓存管理机制

// src/bootstrap/state.ts
const systemPromptSectionCache = new Map<stringstring | null>()

// src/constants/systemPromptSections.ts
asyncfunctionresolveSystemPromptSections(
  sections: SystemPromptSection[]
): Promise<(string | null)[]> 
{
return sections.map(s => {
// 命中缓存且无 cacheBreak → 返回缓存值
if (!s.cacheBreak && systemPromptSectionCache.has(s.name)) {
return systemPromptSectionCache.get(s.name)
    }

// 计算新值
const value = await s.compute()

// 存入缓存
    systemPromptSectionCache.set(s.name, value)

return value
  })
}

12.3.4 缓存清除时机

// 以下情况会清除缓存:
// 1. /clear 命令
// 2. /compact 命令后
// 3. 工作树进入/退出时
// 4. cacheBreak = true 时

functionclearSystemPromptCache(): void{
  systemPromptSectionCache.clear()
}

12.3.5 内置 Sections 一览

Section 名称
缓存
内容概要
memory
内存系统提示词
env_info
cwd/git/平台/模型信息
language
语言设置
output_style
输出风格
session_guidance
会话指导
ant_model_override
模型覆盖配置
scratchpad
草稿板指令
mcp_instructions
MCP 服务器指令
session_memory
Session 内存
summarize_tool_results
工具结果摘要
numeric_length_anchors
数字长度锚点
token_budget
Token 预算
brief
KAIROS Brief
frc
函数结果清除

12.4 主提示词构建流程

12.4.1 getSystemPrompt() 函数签名

// src/constants/prompts.ts:444-577

exportasyncfunctiongetSystemPrompt(
  tools: Tools,
  model: string,
  additionalWorkingDirectories?: string[],
  mcpClients?: MCPServerConnection[]
): Promise<string[]>

12.4.2 六步构建流程

getSystemPrompt() 执行流程
              │
              ▼
┌─────────────────────────────────────┐
│ Step 1: Simple 模式检查            │
│ if (CLAUDE_CODE_SIMPLE)            │
│   → return getSimpleSystemPrompt()  │
│      (极简版,约 200 行)            │
└─────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────┐
│ Step 2: Proactive 模式检查          │
│ if (feature('PROACTIVE') ||         │
│     feature('KAIROS'))              │
│   → 返回简化版提示词                │
│      (跳过某些静态 Section)        │
└─────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────┐
│ Step 3: 构建静态 Sections           │
│                                     │
│ const staticSections = [             │
│   getSimpleIntroSection(),         │
│   getSimpleSystemSection(),         │
│   getSimpleDoingTasksSection(),     │
│   getActionsSection(),             │
│   getUsingYourToolsSection(),       │
│   getSimpleToneAndStyleSection(),  │
│   getOutputEfficiencySection(),     │
│ ]                                  │
└─────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────┐
│ Step 4: 构建动态 Sections           │
│                                     │
│ const dynamicSections = [            │
│   systemPromptSection(               │
│     'session_guidance',              │
│     computeSessionGuidance          │
│   ),                                │
│   systemPromptSection(               │
│     'memory',                       │
│     computeMemory                   │
│   ),                                │
│   systemPromptSection(               │
│     'ant_model_override',           │
│     computeAntModelOverride          │
│   ),                                │
│   systemPromptSection(               │
│     'env_info',                     │
│     computeEnvInfo                  │
│   ),                                │
│   systemPromptSection(               │
│     'language',                     │
│     computeLanguage                 │
│   ),                                │
│   systemPromptSection(               │
│     'output_style',                 │
│     computeOutputStyle              │
│   ),                                │
│   DANGEROUS_uncachedSystemPromptSection(
│     'mcp_instructions',              │
│     computeMcpInstructions,          │
│     'MCP connections can change'    │
│   ),                                │
│   systemPromptSection(               │
│     'scratchpad',                  │
│     computeScratchpad               │
│   ),                                │
│ ]                                   │
└─────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────┐
│ Step 5: 解析动态 Sections           │
│                                     │
│ const resolvedDynamic = await         │
│   resolveSystemPromptSections(       │
│     dynamicSections                 │
│   )                                │
└─────────────────────────────────────┘
              │
              ▼
┌─────────────────────────────────────┐
│ Step 6: 组装最终数组               │
│                                     │
│ return [                            │
│   ...staticSections,                │
│   SYSTEM_PROMPT_DYNAMIC_BOUNDARY,   │
│   ...resolvedDynamic,              │
│ ]                                  │
└─────────────────────────────────────┘

12.4.3 SYSTEM_PROMPT_DYNAMIC_BOUNDARY 标记

// 标记静态内容和动态内容的分界
// 帮助调试和日志分析

exportconst SYSTEM_PROMPT_DYNAMIC_BOUNDARY = 
'\n─── DYNAMIC SECTIONS BELOW ───\n'

12.5 有效提示词优先级链

12.5.1 buildEffectiveSystemPrompt() 函数

// src/utils/systemPrompt.ts:41-123

exportfunctionbuildEffectiveSystemPrompt(
  customSystemPrompt: string | undefined,
  agentDefinition: AgentDefinition | undefined,
  appendSystemPrompt: string | undefined
): string[] 
{

// 优先级 0: overrideSystemPrompt(loop 模式专用)
if (overrideSystemPrompt) {
return overrideSystemPrompt
  }

// 优先级 1: Coordinator Mode
if (feature('COORDINATOR_MODE')) {
const coordPrompt = getCoordinatorSystemPrompt()
if (agentDefinition?.systemPrompt) {
return [...coordPrompt, ...agentDefinition.systemPrompt]
    }
return coordPrompt
  }

// 优先级 2: Agent Definition
if (agentDefinition?.systemPrompt) {
// KAIROS 模式:追加到默认提示词
if (feature('KAIROS') || feature('PROACTIVE')) {
return [...getSystemPrompt(...), ...agentDefinition.systemPrompt]
    }
// 普通模式:直接替换
return agentDefinition.systemPrompt
  }

// 优先级 3: Custom System Prompt (--system-prompt)
if (customSystemPrompt) {
return [customSystemPrompt]
  }

// 优先级 4: Default
const defaultPrompt = getSystemPrompt(...)

// 优先级 5: appendSystemPrompt(始终追加)
if (appendSystemPrompt) {
return [...defaultPrompt, ...appendSystemPrompt]
  }

return defaultPrompt
}

12.5.2 优先级流程图

overrideSystemPrompt? ──── Yes ───→ 直接返回 override
        │
        No
        │
        ▼
Coordinator Mode? ─────── Yes ───→ getCoordinatorSystemPrompt()
        │                            │
        │                            ├─── Agent Definition? ── Yes ─→ 追加到末尾
        │                            │
        │                            └─── 无 Agent ──────────────→ 仅 Coordinator
        │
        ▼
Agent Definition? ────── Yes ───→ agent.systemPrompt
        │                            │
        │                            ├─── KAIROS/PROACTIVE? ── 追加到默认
        │                            │
        │                            └─── 普通模式 ────────────── 直接替换
        │
        ▼
Custom System Prompt? ─── Yes ───→ [customSystemPrompt]
        │
        ▼
Default ──────────────────────→ getSystemPrompt(...)
                                    │
                                    └─── + appendSystemPrompt(始终追加)

12.5.3 各优先级对比

优先级
来源
行为
典型用途
0
loop 模式
直接返回
调试模式
1
Coordinator Mode
追加 Agent prompt
多 Agent 协调
2
Agent Definition
替换/追加
自定义 Agent
3
–system-prompt
直接替换
用户自定义
4
Default
调用 getSystemPrompt()
标准提示词
5
appendSystemPrompt
追加到末尾
KAIROS 额外指令

12.6 静态 Section 详解

12.6.1 静态内容概述

静态内容在 Simple 模式和 Proactive 模式都会使用,可以全局缓存。

12.6.2 七大静态 Section

Section
来源函数
行数
内容概要
Intro
getSimpleIntroSection()
~15
“You are an interactive agent…”
System
getSimpleSystemSection()
~30
“The Working Directory is…”
Tasks
getSimpleDoingTasksSection()
~25
“You are encouraged to…”
Actions
getActionsSection()
~20
“Be thoughtful about…”
Tools
getUsingYourToolsSection()
~30
“You have tools…”
Tone
getSimpleToneAndStyleSection()
~15
语气风格指导
Output
getOutputEfficiencySection()
~15
“Be efficient…”

12.6.3 Intro Section 示例

// getSimpleIntroSection() 典型输出

exportconst INTRO_SECTION = `You are an interactive agent...

TypeScript/JavaScript developer tool.
...

You are helpful, harmless, and honest.`

12.6.4 System Section 示例

// getSimpleSystemSection() 典型输出

exportconst SYSTEM_SECTION = `The Working Directory is: {cwd}

Do not speculate about file contents or structure.
Always verify before making assumptions.
If you are unsure, ask clarifying questions.`

12.6.5 Tools Section 示例

// getUsingYourToolsSection() 典型输出

exportconst TOOLS_SECTION = `You have tools available:

- Read: Read file contents
- Edit: Make targeted edits
- Bash: Run shell commands
- Grep: Search file contents
- Glob: Find files by pattern

Be thoughtful about when to use each tool.
Prefer targeted tools over general commands.`


12.7 动态 Sections 详解

12.7.1 动态 Sections 完整列表

Section 名称
缓存
compute 函数
内容
memory
computeMemory
内存系统提示词
env_info
computeEnvInfo
cwd/git/平台信息
language
computeLanguage
语言设置
output_style
computeOutputStyle
输出风格
session_guidance
computeSessionGuidance
会话指导
ant_model_override
computeAntModelOverride
模型覆盖
scratchpad
computeScratchpad
草稿板指令
mcp_instructions computeMcpInstructions
MCP 服务器指令
session_memory
computeSessionMemory
Session 内存
summarize_tool_results
computeSummarizeToolResults
工具结果摘要
numeric_length_anchors
computeNumericLengthAnchors
数字长度锚点
token_budget
computeTokenBudget
Token 预算
brief
computeBrief
KAIROS Brief
frc
computeFrc
函数结果清除

12.7.2 env_info Section 详解

// src/constants/prompts.ts:651-710

exportasyncfunctioncomputeSimpleEnvInfo(
  modelId: string,
  additionalWorkingDirectories?: string[]
): Promise<string | null
{
// 返回包含以下信息的字符串:
// - 当前工作目录 (cwd)
// - Git 状态 (branch, status)
// - 操作系统平台
// - Shell 类型
// - 模型信息
// - 额外工作目录 (如果有)
}

示例输出

Current directory: /path/to/project
Git branch: main
Git status: clean (no uncommitted changes)
Platform: macOS (arm64)
Shell: zsh 5.9
Model: claude-opus-4-5 (max tokens: 4096)

12.7.3 mcp_instructions Section 详解

// src/constants/prompts.ts:579-604

functioncomputeMcpInstructions(
  mcpClients: MCPServerConnection[]
): string | null
{
if (!mcpClients || mcpClients.length === 0) {
returnnull
  }

return mcpClients
    .map(client => {
const serverName = client.name
const instructions = client.server.instructions
return`[${serverName}]\n${instructions}`
    })
    .join('\n\n')
}

为什么需要 DANGEROUS_uncachedSystemPromptSection?

原因
说明
MCP 连接会变
服务器可能随时连接/断开
每次需要最新状态
不能使用过时的缓存
日志记录
必须提供 reason 用于调试

12.7.4 scratchpad Section 详解

// KAIROS 模式下的后台思考笔记

exportconst SCRATCHPAD_PROMPT = `
// You have a scratchpad for internal notes.
// Use it to track progress on long-running tasks.
// Keep it concise — this is not user-visible.

// Guidelines:
// - Write brief notes on ongoing work
// - Track partial results
// - Note decisions made
// - Don't write user-facing content here
`

12.7.5 token_budget Section 详解

// Token 预算警告

exportconst TOKEN_BUDGET_SECTION = `
// Token Budget Warning
// Context is approaching capacity.
// Consider:
// - Using /compact to compress context
// - Finishing current task before starting new one
// - Removing unnecessary details
`


12.8 appendSystemPrompt 机制

12.8.1 机制详解

// appendSystemPrompt 始终追加到最终提示词
// 优先级最低(优先级 5)

functionbuildEffectiveSystemPrompt(...): string[] {
// ... 优先级链 ...

// 第4优先级:Default
const defaultPrompt = getSystemPrompt(...)

// 第5优先级:appendSystemPrompt(始终追加)
if (appendSystemPrompt) {
return [...defaultPrompt, ...appendSystemPrompt]
  }

return defaultPrompt
}

12.8.2 使用场景

场景
用途
KAIROS 模式
添加自主代理的额外指令
调试模式
添加调试信息
自定义集成
SDK 调用者注入自定义指令

12.8.3 与 agent.systemPrompt 的区别

特性
agent.systemPrompt
appendSystemPrompt
位置
替换默认提示词
追加到默认提示词
优先级
高(优先级2)
低(优先级5)
用途
完全替换
追加补充内容
典型场景
自定义 Agent
KAIROS 额外指令

12.8.4 appendSystemPrompt 使用示例

// KAIROS 模式下的 appendSystemPrompt

const kairosAppendPrompt = `
// KAIROS Mode Additional Instructions
// - Monitor for new user messages
// - Write memories proactively
// - Use BriefTool for status updates
// - Keep scratchpad updated
`


// 在 buildEffectiveSystemPrompt 中
const effectivePrompt = buildEffectiveSystemPrompt(
undefined,  // customSystemPrompt
  agentDefinition,  // 可能是 KAIROS agent
  kairosAppendPrompt  // appendSystemPrompt
)

12.9 工具提示词

12.9.1 工具提示词三层结构

┌─────────────────────────────────────────────────────────────┐
│                    工具提示词三层结构                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Layer 1: 工具注册时的描述(Tool.description)                │
│           └─→ 工具名称、参数 schema                         │
│           └─→ 自动生成,不包含使用指南                       │
│                                                             │
│  Layer 2: 工具使用指南(Tool prompt.ts)                   │
│           └─→ 何时使用、如何构造参数、示例                   │
│           └─→ 各工具独立文件                                 │
│                                                             │
│  Layer 3: 动态提示(工具执行结果、错误等)                   │
│           └─→ 注入到当前轮的 user message                  │
│           └─→ 运行时生成                                    │
│                                                             │
└─────────────────────────────────────────────────────────────┘

12.9.2 工具 prompt.ts 完整列表

工具
文件路径
内容概要
行数
AgentTool
src/tools/AgentTool/prompt.ts
Agent 使用时机、block 格式
~150
BashTool
src/tools/BashTool/prompt.ts
命令执行、安全提示
~100
ReadTool
src/tools/FileReadTool/prompt.ts
文件读取、编码处理
~80
EditTool
src/tools/EditTool/prompt.ts
编辑规则、原子性
~120
GrepTool
src/tools/GrepTool/prompt.ts
搜索语法、输出格式
~80
GlobTool
src/tools/GlobTool/prompt.ts
glob 模式匹配
~60
WriteTool
src/tools/FileWriteTool/prompt.ts
写入规则、目录创建
~80
BriefTool
src/tools/BriefTool/prompt.ts
KAIROS brief 格式
~100
NotebookTool
src/tools/NotebookTool/prompt.ts
Jupyter 笔记本操作
~70
WebSearchTool
src/tools/WebSearchTool/prompt.ts
搜索使用指南
~80
WebFetchTool
src/tools/WebFetchTool/prompt.ts
网页获取使用
~70

12.9.3 AgentTool prompt.ts 详解

// src/tools/AgentTool/prompt.ts

exportconst AGENT_TOOL_PROMPT = `
// Agent tool usage instructions

When to use the Agent tool:
- For tasks that require deep focus and extended reasoning
- When you need to delegate subtasks to a focused sub-agent
- For exploration and research tasks that might benefit from dedicated context

How to write the agent block:

<agent>
  <role>expert programmer specializing in security</role>
  <goal>implement authentication system with OAuth 2.0</goal>
  <backstory>You are a security expert with 10 years of experience 
  in authentication systems. You've implemented OAuth for major tech companies
  and understand the latest security best practices.</backstory>
  <tools>Read,Edit,Bash,Grep</tools>
</agent>

Common mistakes to avoid:
1. Don't use Agent for simple, quick tasks (less than 5 minutes)
2. Don't create too many sub-agents (prefer sequential delegation)
3. Always provide clear, specific goals
4. Don't give conflicting instructions to different agents

Examples:

Good: <goal>Add unit tests for the auth module</goal>
Bad:  <goal>Work on the code</goal>

Anti-patterns:
- Nesting agents too deeply (>3 levels)
- Not providing enough context in the goal
- Giving vague role descriptions
`


exportconst AGENT_TOOL_WRONG_USAGE = `
// Common mistakes:
1. Nesting agents too deeply (>3 levels)
2. Not providing enough context in the goal
3. Giving conflicting instructions to multiple agents
4. Using Agent for tasks that could be done directly
`

12.9.4 BashTool prompt.ts 详解

// src/tools/BashTool/prompt.ts

exportconst BASH_TOOL_PROMPT = `
// Bash tool usage instructions

When to use Bash:
- Running shell commands (npm, git, docker, etc.)
- Running build scripts
- Executing code in a REPL
- Running tests

Security guidelines:
- Never run commands that modify .git history (force push, etc.)
- Always confirm destructive commands (rm -rf, etc.)
- Don't run commands you don't understand

Output formatting:
- Short commands (< 1 min): output directly
- Long commands: show progress indicator
- Failed commands: show error and suggest fixes

Examples:

git status --short
npm run build
docker-compose up -d
pytest tests/ -v
`


exportconst BASH_TOOL_DANGEROUS = `
// Commands that require extra caution:
- rm -rf (especially with glob patterns)
- git push --force
- drop database
- systemctl restart (may interrupt services)
- chmod 777 (security risk)
`

12.9.5 EditTool prompt.ts 详解

// src/tools/EditTool/prompt.ts

exportconst EDIT_TOOL_PROMPT = `
// Edit tool usage instructions

Atomic edits:
- Each EditTool call should be a single, focused change
- If a change requires multiple edits, use multiple EditTool calls
- Prefer EditTool over WriteTool when possible (less destructive)

Edit types:
1. Replacement: Replace exact content
2. Insert: Insert at line number
3. Create: Write new content

Common patterns:

// Pattern 1: Replace exact content
<edit>
  <file>src/app.ts</file>
  <old>const old = 'text'</old>
  <new>const new = 'updated text'</new>
</edit>

// Pattern 2: Insert after line
<edit>
  <file>src/app.ts</file>
  <line>10</line>
  <insert>new line content</insert>
</edit>

Avoid:
- Large rewrites (>50 lines at once)
- Editing multiple unrelated sections
- Making architectural changes without user confirmation
`


exportconst EDIT_TOOL_ATOMICITY = `
// Atomicity principle:
// Each edit should be self-contained and focused.
// If an edit has multiple parts, split it into multiple edits.
`


12.10 内存提示词

12.10.1 loadMemoryPrompt() 完整逻辑

// src/memdir/memdir.ts:419-507

exportasyncfunctionloadMemoryPrompt(): Promise<string | null{
const autoEnabled = isAutoMemoryEnabled()

// 是否跳过索引更新(KAIROS 日志模式)
const skipIndex = getFeatureValue_CACHED_MAY_BE_STALE(
'tengu_moth_copse',
false,
  )

// KAIROS 模式 → 每日日志
if (feature('KAIROS') && autoEnabled && getKairosActive()) {
return buildAssistantDailyLogPrompt(skipIndex)
  }

// Cowork 额外指南(从环境变量注入)
const coworkExtraGuidelines = process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES

// TEAMMEM 模式 → 组合提示词
if (feature('TEAMMEM')) {
if (teamMemPaths!.isTeamMemoryEnabled()) {
const autoDir = getAutoMemPath()
const teamDir = teamMemPaths!.getTeamMemPath()

// 确保目录存在
await ensureMemoryDirExists(teamDir)

// 记录遥测
      logMemoryDirCounts(autoDir, { memory_type: 'auto' })
      logMemoryDirCounts(teamDir, { memory_type: 'team' })

// 构建组合提示词
return teamMemPrompts!.buildCombinedMemoryPrompt(
        coworkExtraGuidelines ? [coworkExtraGuidelines] : undefined,
        skipIndex,
      )
    }
  }

// 普通模式 → 标准内存
if (autoEnabled) {
const autoDir = getAutoMemPath()
await ensureMemoryDirExists(autoDir)
    logMemoryDirCounts(autoDir, { memory_type: 'auto' })

return buildMemoryLines(
'auto memory',
      autoDir,
      coworkExtraGuidelines ? [coworkExtraGuidelines] : undefined,
      skipIndex,
    ).join('\n')
  }

// 遥测:记录禁用状态
  logEvent('tengu_memdir_disabled', {
    disabled_by_env_var: isEnvTruthy(
      process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY,
    ),
    disabled_by_setting:
      !isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY) &&
      getInitialSettings().autoMemoryEnabled === false,
  })

returnnull
}

12.10.2 buildMemoryLines() 完整内容

// src/memdir/memdir.ts:199-266

exportfunctionbuildMemoryLines(
  displayName: string,
  memoryDir: string,
  extraGuidelines?: string[],
  skipIndex = false,
): string[] 
{

const howToSave = skipIndex
    ? [
'## How to save memories',
'',
'Write each memory to its own file using this frontmatter format:',
'',
        ...MEMORY_FRONTMATTER_EXAMPLE,
'',
'- Keep the name, description, and type fields up-to-date',
'- Organize memory semantically by topic, not chronologically',
'- Update or remove memories that turn out to be wrong or outdated',
      ]
    : [
'## How to save memories',
'',
'Saving a memory is a two-step process:',
'',
'**Step 1** — write the memory to its own file:',
'',
        ...MEMORY_FRONTMATTER_EXAMPLE,
'',
'**Step 2** — add a pointer to that file in `MEMORY.md`:',
'MEMORY.md is an index, not a memory — each entry should be one line.',
'',
'- Keep index entries concise (under ~150 chars)',
'- Keep the name, description, and type fields up-to-date',
'- Organize memory semantically, not chronologically',
      ]

return [
`# ${displayName}`,
'',
`You have a persistent, file-based memory system at \`${memoryDir}\`.`,
'This directory already exists — write to it directly with the Write tool.',
'',
"You should build up this memory system over time so that future conversations",
"can have a complete picture of who the user is, how they'd like to collaborate,",
'what behaviors to avoid or repeat, and the context behind the work.',
'',
'If the user explicitly asks you to remember something, save it immediately.',
'If they ask you to forget something, find and remove the relevant entry.',
'',
    ...TYPES_SECTION_INDIVIDUAL,      // 四类记忆类型说明
    ...WHAT_NOT_TO_SAVE_SECTION,       // 什么不该存
    ...howToSave,                     // 如何保存(两步)
    ...WHEN_TO_ACCESS_SECTION,          // 何时访问
    ...TRUSTING_RECALL_SECTION,       // 信任记忆的注意事项
'',
    ...(extraGuidelines ?? []),
'',
    ...buildSearchingPastContextSection(memoryDir),
  ]
}

12.10.3 四类记忆类型完整定义

// src/memdir/memoryTypes.ts

const MEMORY_TYPES = ['user''feedback''project''reference'asconst
type MemoryType = (typeof MEMORY_TYPES)[number]

// user — 用户画像
// "Contain information about the user's role, goals, 
//  responsibilities, and knowledge."
//
// When to save:
// - Any detail about the user's role
// - User's experience level
// - Communication preferences
//
// Examples:
// "user: I'm a data scientist"
// "user: 10 years Go experience, new to React"
// "user: Prefers brief responses, no summaries"
//

// feedback — 反馈记忆
// "Guidance the user has given you about how to approach work."
//
// Include BOTH corrections AND confirmations:
// - Corrections: "don't do X"
// - Confirmations: "yes exactly, keep doing that"
//
// Structure:
// Rule
// **Why:** (reason - past incident or preference)
// **How to apply:** (when/where)
//
// Examples:
// "don't mock the database" → Why: past incident, How: integration tests only
// "单PR优于多小PR" → Why: confirmed approach, How: refactors
//

// project — 项目上下文
// "Information about ongoing work, goals, initiatives, bugs, incidents."
// NOT derivable from code.
//
// When to save:
// - Goals and deadlines
// - Decisions with rationale
// - Ongoing issues
//
// Always convert relative dates to absolute dates:
// "Thursday" → "2026-03-05"
//
// Examples:
// "merge freeze begins 2026-03-05"
// "auth rewrite driven by compliance requirements"
// "mobile team cutting release branch next week"
//

// reference — 外部系统指针
// "Pointers to where information can be found in external systems."
//
// When to save:
// - Linear/Asana project names
// - Slack channels
// - Grafana dashboards
// - Documentation links
//
// Examples:
// "Linear project INGEST: pipeline bugs"
// "Grafana: oncall latency dashboard"
// "Slack: #incidents channel"
//

12.10.4 MEMORY.md 索引格式

# auto memory

## How to save memories

Saving a memory is a two-step process:

**Step 1** — write the memory to its own file (e.g., `user_role.md`)

**Step 2** — add a pointer to that file in `MEMORY.md`

## Types of memory

...

## MEMORY.md

[user_go_expertise.md](user_go_expertise.md) — 10年Go专家,首次React
[feedback_no_mocks.md](feedback_no_mocks.md) — 测试不用mock
[project_auth_compliance.md](project_auth_compliance.md) — Auth合规驱动
[reference_linear_ingest.md](reference_linear_ingest.md) — Linear INGEST项目
[feedback_pr_style.md](feedback_pr_style.md) — 单PR优于多小PR

12.11 压缩提示词

12.11.1 压缩提示词模板

// src/services/compact/prompt.ts

exportconst COMPACT_SYSTEM_PROMPT = `
// Context Compaction Instructions
//
// Claude Code is about to compress the conversation context.
// The following guidelines help decide what to keep and what to discard.

## 保留 (Keep)

- 正在进行的任务 (ongoing tasks)
- 用户偏好和反馈 (user preferences and feedback)
- 重要决策及其理由 (decisions and rationale)
- 外部系统引用 (external system references)
- 未解决的问题 (unresolved issues)
- 项目特定上下文 (project-specific context)

## 丢弃 (Discard)

- 已完成任务的详情 (completed task details)
- 过时的错误信息 (outdated errors)
- 可从代码推导的信息 (code-derivable info)
- 已经被解决的问题 (resolved problems)
- 冗长的日志输出 (verbose log output)
- 中间过程的调试信息 (intermediate debug info)

## 摘要格式

请生成简洁的摘要,包含:

1. **当前任务状态**
   - 正在做什么
   - 进展如何

2. **关键上下文**
   - 用户偏好(如有)
   - 项目约束(如有)

3. **下一步计划**
   - 待完成的任务
   - 需要用户确认的事项

## 示例

输入:
[300 行对话,包含多次 git 操作、文件编辑、测试运行]

输出:
## Session Summary

**Task**: Implement user authentication
**Progress**: 80% complete, OAuth flow working, tests passing
**Pending**: Final security review, documentation
**User Prefs**: Brief responses preferred
**Context**: Auth rewrite driven by compliance requirements
`


exportconst MICRO_COMPACT_PROMPT = `
// Micro-compaction Instructions
//
// For removing specific tool results from context
// when they are no longer needed

When to micro-compact:
- Tool result was used and is no longer needed
- Error message that was already addressed
- Outdated version information

Keep:
- Final results and conclusions
- User-relevant outputs
`

12.11.2 压缩触发条件

压缩类型
触发条件
影响范围
autoCompact
Token 超过 80%
整个 Context
microCompact
单个工具结果过大
特定消息
contextCollapse
手动触发 /compact
用户指定范围

12.12 Agent 提示词

12.12.1 内置 Agent 完整列表

Agent
文件
用途
systemPrompt 特点
generalPurposeAgent
built-in/generalPurposeAgent.ts
通用任务
默认提示词,平衡所有能力
exploreAgent
built-in/exploreAgent.ts
只读搜索
强调 Read/Grep/Glob,不编辑
planAgent
built-in/planAgent.ts
计划制定
结构化输出,分步骤
verificationAgent
built-in/verificationAgent.ts
验证任务
强调测试,批判性思维

12.12.2 exploreAgent 详解

// src/tools/AgentTool/built-in/exploreAgent.ts

exportconst EXPLORE_AGENT_PROMPT = `
// You are a research agent specializing in code exploration.
// You have READ-ONLY access to the codebase.

## Your Role

- Understand code structure and architecture
- Find relevant files and code patterns
- Research without making changes
- Report findings clearly and concisely

## Guidelines

- Use Read, Grep, Glob tools extensively
- Analyze file relationships and dependencies
- Identify patterns and conventions
- Don't edit or write any files
- Don't run build or test commands unless specifically asked

## Output Format

Provide a structured report:

### Research Summary
Brief description of what you investigated

### Relevant Files
List of files with their purposes

### Key Findings
- Architecture patterns
- Important patterns found
- Dependencies and relationships

### Potential Issues
- Code smells
- Security concerns
- Performance considerations
`


exportconst EXPLORE_AGENT_TOOLS = ['Read''Grep''Glob']

12.12.3 planAgent 详解

// src/tools/AgentTool/built-in/planAgent.ts

exportconst PLAN_AGENT_PROMPT = `
// You are a planning agent that creates structured implementation plans.

## Your Role

- Break down complex tasks into steps
- Identify dependencies
- Estimate effort and risks
- Create actionable plans

## Plan Format

### Task Overview
Brief description of what needs to be done

### Steps
1. **Step Name**: Description
   - Files to modify
   - Tests to add
   - Potential blockers

2. **Step Name**: Description
   ...

### Dependencies
- What needs to be done first
- External dependencies

### Risks
- Potential issues
- Mitigation strategies

### Effort Estimate
- Time estimate
- Complexity level
`


exportconst PLAN_AGENT_TOOLS = ['Read''Edit''Bash''Glob']

12.12.4 自定义 Agent 加载流程

// src/tools/AgentTool/loadAgentsDir.ts

interface AgentDefinition {
  name: string// Agent 名称
  description: string// Agent 描述
  systemPrompt: string[]           // Agent 专用系统提示词
  tools: string[]                // Agent 可用的工具列表
  temperature?: number// 温度参数
  maxTokens?: number// 最大 token 数
  model?: string// 使用的模型
}

// agent.md frontmatter 格式:
// ---
// name: code-reviewer
// description: Expert code reviewer for security
// tools: [Read, Grep, Bash]
// model: claude-opus-4-5
// ---
//
// # Code Reviewer Agent
//
// You specialize in reviewing code for security vulnerabilities...

asyncfunctionloadAgentsDir(): Promise<AgentDefinition[]> {
const agentsDir = path.join(projectRoot, 'agents')

// 1. 检查目录是否存在
if (!await fs.pathExists(agentsDir)) {
return []
  }

// 2. 扫描所有 .md 文件
const agentFiles = await glob('**/*.md', { cwd: agentsDir })

// 3. 解析每个文件
const agents = awaitPromise.all(
    agentFiles.map(async file => {
const content = await readFile(file)
return parseAgentDefinition(content)
    })
  )

// 4. 过滤无效定义
return agents.filter(Booleanas AgentDefinition[]
}

12.13 Coordinator Mode 提示词

12.13.1 coordinatorMode.ts 详解

// src/coordinator/coordinatorMode.ts

exportfunctiongetCoordinatorSystemPrompt(): string[] {
return [
'# Coordinator Mode',
'',
'You are coordinating multiple agents to complete a complex task.',
'Your role is to orchestrate, not to execute directly.',
'',
'## Your Responsibilities',
'',
'### Task Decomposition',
'- Break down complex tasks into subtasks',
'- Assign subtasks to appropriate agents',
'- Ensure agents have clear, non-overlapping responsibilities',
'',
'### Coordination',
'- Monitor agent progress',
'- Handle agent failures and timeouts',
'- Reassign tasks if needed',
'- Synthesize results from multiple agents',
'',
'### Quality Control',
'- Verify agent outputs',
'- Ensure consistency across agents',
'- Resolve conflicts between agent recommendations',
'',
'## Agent Assignment',
'',
'Choose the right agent for each subtask:',
'- exploreAgent: Research and analysis',
'- planAgent: Planning and estimation',
'- verificationAgent: Testing and validation',
'- generalPurposeAgent: General implementation',
'',
'## Communication',
'',
'When assigning tasks:',
'1. Provide clear, specific instructions',
'2. Set appropriate expectations',
'3. Define success criteria',
'4. Establish timeline if relevant',
  ]
}

12.13.2 Coordinator vs 普通 Agent

特性
Coordinator
普通 Agent
职责
协调多个 Agent
执行单一任务
提示词重点
协调指令、任务分配
任务执行、工具使用
工具
AgentTool(委托子任务)
Read/Edit/Bash(直接操作)
输出
任务分解 + 结果整合
单一任务结果
优先级
高(优先级 1)
中(优先级 2)

12.14 systemPromptType 类型定义

12.14.1 SystemPrompt 品牌类型

// src/utils/systemPromptType.ts

// SystemPrompt 品牌类型
// 用于在编译时区分 string[] 和 SystemPrompt
exporttype SystemPrompt = readonly string[] & {
  readonly __brand: 'SystemPrompt'
}

// 转换为 SystemPrompt 类型
exportfunctionasSystemPrompt(prompt: string[]): SystemPrompt{
return prompt as SystemPrompt
}

// 类型守卫
exportfunctionisSystemPrompt(prompt: unknown): promptisSystemPrompt{
return (
Array.isArray(prompt) &&
typeof prompt[0] === 'string' &&
'__brand'in prompt &&
    (prompt asany).__brand === 'SystemPrompt'
  )
}

12.14.2 类型守卫使用示例

// 错误处理中的类型守卫

functionprocessSystemPrompt(prompt: unknown): string[] {
if (isSystemPrompt(prompt)) {
// prompt 是 SystemPrompt 类型
return [...prompt, '\n---\nAppended content']
  }

// prompt 是 string[]
return prompt
}

12.15 提示词流转总图

┌─────────────────────────────────────────────────────────────┐
│                   提示词流转总图(完整版)                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  【模块注入层】                                               │
│                                                             │
│  ┌───────────┐  ┌───────────┐  ┌───────────┐             │
│  │  Memory   │  │  Tools    │  │    MCP     │             │
│  │ loadMemory │  │ tool.desc │  │ mcp_inst. │             │
│  └─────┬─────┘  └─────┬─────┘  └─────┬─────┘             │
│        │                │                │                   │
│        ▼                ▼                ▼                   │
│  ┌─────────────────────────────────────────┐             │
│  │  systemPromptSection() /                │             │
│  │  DANGEROUS_uncachedSystemPromptSection()│             │
│  │  (memory/env_info/mcp/scratchpad/...)  │             │
│  └─────────────────────────────────────────┘             │
│                        │                                  │
│  ┌───────────┐  ┌───────────┐  ┌───────────┐             │
│  │  Context   │  │ Permissions│  │   Agents  │             │
│  │  Compact   │  │   Hooks   │  │ Definition │             │
│  └─────┬─────┘  └─────┬─────┘  └─────┬─────┘             │
│        │                │                │                   │
│        └────────────────┼────────────────┘                   │
│                         ▼                                      │
│  ┌─────────────────────────────────────────┐                 │
│  │  buildEffectiveSystemPrompt()          │                 │
│  │                                         │                 │
│  │  优先级链:                              │                 │
│  │  0. overrideSystemPrompt               │                 │
│  │  1. Coordinator → Agent                │                 │
│  │  2. Agent Definition                  │                 │
│  │  3. Custom System Prompt              │                 │
│  │  4. Default System Prompt             │                 │
│  │  5. + appendSystemPrompt             │                 │
│  └─────────────────────────────────────────┘                 │
│                         │                                      │
│                         ▼                                      │
│  ┌─────────────────────────────────────────┐                 │
│  │  getSystemPrompt()                      │                 │
│  │                                         │                 │
│  │  ┌─────────────────────────────────┐  │                 │
│  │  │ 静态内容 (Intro/System/Tasks/  │  │                 │
│  │  │ Actions/Tools/Tone/Output)      │  │                 │
│  │  └─────────────────────────────────┘  │                 │
│  │  + SYSTEM_PROMPT_DYNAMIC_BOUNDARY    │                 │
│  │  + 动态 Sections                      │                 │
│  │    (memory + env_info + MCP + ...)  │                 │
│  │                                         │                 │
│  └─────────────────────────────────────────┘                 │
│                         │                                      │
│                         ▼                                      │
│  ┌─────────────────────────────────────────┐                 │
│  │  resolveSystemPromptSections()          │                 │
│  │                                         │                 │
│  │  systemPromptSectionCache              │                 │
│  │  (按 name 缓存, cacheBreak 破坏)       │                 │
│  │                                         │                 │
│  └─────────────────────────────────────────┘                 │
│                         │                                      │
│                         ▼                                      │
│  ┌─────────────────────────────────────────┐                 │
│  │  最终 System Prompt (string[])         │                 │
│  │                                         │                 │
│  │  → 发送给 Claude API                   │                 │
│  │  → 模型返回 Assistant Message          │                 │
│  │  → 工具调用 → 结果 → 下一轮...      │                 │
│  │                                         │                 │
│  └─────────────────────────────────────────┘                 │
└─────────────────────────────────────────────────────────────┘

12.16 小结

  1. 提示词是血液:连接所有模块,为 Claude 提供上下文、指令、约束

  2. 三层架构:应用层(优先级选择)→ 构建层(静态+动态组装)→ 解析层(缓存)

  3. SystemPromptSection 机制:通过 systemPromptSection() 和 DANGEROUS_uncachedSystemPromptSection() 创建可组合的提示词模块

  4. 主提示词构建 6 步:Simple 检查 → Proactive 检查 → 静态 Sections → 动态 Sections → 解析 → 组装

  5. 优先级链 6 层:override → Coordinator → Agent → Custom → Default → append

  6. 动态 Sections 14 个:memory、env_info、language、mcp_instructions 等

  7. appendSystemPrompt:始终追加,用于 KAIROS 等场景

  8. 工具提示词三层:Tool.description → Tool prompt.ts → 动态结果

  9. 内存提示词:四类记忆类型(user/feedback/project/reference)

  10. 压缩提示词:保留/丢弃规则,摘要格式


源码位置

核心文件

文件
职责
src/constants/prompts.ts
主提示词构建(getSystemPrompt)
src/constants/systemPromptSections.ts
Section 定义和缓存管理
src/utils/systemPrompt.ts
有效提示词优先级(buildEffectiveSystemPrompt)
src/utils/systemPromptType.ts
SystemPrompt 类型定义
src/bootstrap/state.ts
systemPromptSectionCache

工具提示词

文件
职责
src/tools/AgentTool/prompt.ts
Agent 工具提示词
src/tools/BashTool/prompt.ts
Bash 工具提示词
src/tools/ReadTool/prompt.ts
Read 工具提示词
src/tools/EditTool/prompt.ts
Edit 工具提示词
src/tools/GrepTool/prompt.ts
Grep 工具提示词
src/tools/GlobTool/prompt.ts
Glob 工具提示词
src/tools/WriteTool/prompt.ts
Write 工具提示词
src/tools/BriefTool/prompt.ts
Brief 工具提示词
src/tools/NotebookTool/prompt.ts
Notebook 工具提示词

内存提示词

文件
职责
src/memdir/memdir.ts
loadMemoryPrompt, buildMemoryLines
src/memdir/memoryTypes.ts
四类记忆类型定义
src/memdir/findRelevantMemories.ts
记忆检索

其他提示词

文件
职责
src/services/compact/prompt.ts
压缩提示词模板
src/tools/AgentTool/built-in/*.ts
内置 Agent 提示词
src/coordinator/coordinatorMode.ts
Coordinator 提示词

延伸阅读

  • System Prompt Engineering — 提示词工程指南
  • Anthropic API Documentation — Claude API 提示词参数
  • Prompt Engineering Handbook — 提示词工程手册