Claude Code 产品设计与提示词分析报告 Claude Code 产品设计与提示词分析报告 源码版本:Claude Code v2.1.88(~51万行 TypeScript) 分析日期:2026-03-31 基于源码 `` 的逆向分析。写给两类人:想知道"Claude Code 到底怎么做到的"的产品人,以及想抄提示词工程细节的工程师。 一、架构总览 Claude Code 本质上是一个 有状态的 Agent 框架 ,核心循环很朴素: 用户输入 → 系统提示词 + 工具定义 → LLM → 工具调用 → 执行 → 结果回填 → 循环 但魔鬼在细节里。它围绕这个循环做了几件事: 系统提示词的分层缓存 — 静态内容和动态内容用 SYSTEM_PROMPT_DYNAMIC_BOUNDARY 隔开,静态部分跨会话复用 prompt cache 工具权限的渐进式管控 — 不是简单的 allow/deny,而是按 permission mode 分级(详见技术分析篇第 8 章) 子 Agent 体系 — Coordinator 模式、fork 模式、专用 Agent 三层架构 上下文生命周期管理 — Compact、Microcompact、Dream 三级压缩(详见技术分析篇第 7 章) 命令系统 — 斜杠命令不仅是快捷方式,每个命令实质上是一个 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-push 、 git 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 </ wrapper, no