从配置环境到扩展并行会话,本文介绍充分发挥 Claude Code 能力的技巧与模式。
Tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions.
Claude Code 是一个具备自主执行能力的编程环境。与回答问题后就等待下一条消息的聊天机器人不同,Claude Code 可以读取文件、运行命令、进行修改并自主解决问题;在此期间,你可以旁观、调整方向,也可以完全离开。
Claude Code is an agentic coding environment. Unlike a chatbot that answers questions and waits, Claude Code can read your files, run commands, make changes, and autonomously work through problems while you watch, redirect, or step away entirely.
这改变了你的工作方式。你不再自己编写代码再让 Claude 审查,而是描述想要的结果,由 Claude 想清楚如何实现。Claude 会探索、规划并实施。
This changes how you work. Instead of writing code yourself and asking Claude to review it, you describe what you want and Claude figures out how to build it. Claude explores, plans, and implements.
不过,这种自主性仍然需要一个学习过程。Claude 的工作受到某些约束,你需要理解这些约束。
But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand.
本指南介绍的模式,已经在 Anthropic 内部团队,以及使用 Claude Code 处理各种代码库、语言和环境的工程师中被证明有效。有关 Agent 循环的工作方式,请参阅《Claude Code 如何工作》。
This guide covers patterns that have proven effective across Anthropic’s internal teams and for engineers using Claude Code across various codebases, languages, and environments. For how the agentic loop works, see How Claude Code works.
大多数最佳实践都基于一个约束:Claude 的上下文窗口很快就会填满,而且随着内容增多,其表现会下降。
Most best practices are based on one constraint: Claude’s context window fills up fast, and performance degrades as it fills.
Claude 的上下文窗口容纳整个对话,包括每一条消息、Claude 读取的每个文件,以及每条命令的输出。然而,它很快就可能被填满。单次调试会话或代码库探索,就可能生成并消耗数万 token。
Claude’s context window holds your entire conversation, including every message, every file Claude reads, and every command output. However, this can fill up fast. A single debugging session or codebase exploration might generate and consume tens of thousands of tokens.
这很关键,因为随着上下文被填满,大语言模型的表现会下降。当上下文窗口接近满载时,Claude 可能开始“忘记”早先的指令,或犯更多错误。上下文窗口是最需要管理的资源。要了解一次会话实际如何逐渐填满,请观看交互式演示,了解启动时加载了什么,以及每次文件读取的开销。使用自定义状态栏持续跟踪上下文使用量,并参阅《减少 token 使用量》了解相关策略。
This matters since LLM performance degrades as context fills. When the context window is getting full, Claude may start “forgetting” earlier instructions or making more mistakes. The context window is the most important resource to manage. To see how a session fills up in practice, watch an interactive walkthrough of what loads at startup and what each file read costs. Track context usage continuously with a custom status line, and see Reduce token usage for strategies on reducing token usage.
让 Claude 有办法验证自己的工作
Give Claude a way to verify its work
给 Claude 一项能够运行的检查:测试、构建,或者可供对比的截图。这决定了你是必须守着会话,还是可以放心离开。
Give Claude a check it can run: tests, a build, a screenshot to compare. It’s the difference between a session you watch and one you walk away from.
当工作看起来完成时,Claude 就会停下来。如果没有可以运行的检查,“看起来完成”就是唯一可用的信号,而你就成了验证循环:每个错误都要等你发现。给 Claude 一个能产出通过或失败结果的检查,这个循环便能自行闭合。Claude 完成工作、运行检查、读取结果,并不断迭代,直到检查通过。
Claude stops when the work looks done. Without a check it can run, “looks done” is the only signal available, and you become the verification loop: every mistake waits for you to notice it. Give Claude something that produces a pass or fail, and the loop closes on its own. Claude does the work, runs the check, reads the result, and iterates until the check passes.
检查可以是任何能够返回信号、并让 Claude 在对话中读取的东西:测试套件、构建退出码、代码检查器、将输出与固定测试样本进行差异比较的脚本,或者与设计稿对照的浏览器截图。Claude 的检查通过后,你再亲自运行 /verify,在正在运行的应用中确认这些改动。
The check is anything that returns a signal Claude can read in the conversation: a test suite, a build exit code, a linter, a script that diffs output against a fixture, or a browser screenshot compared against a design. Run /verify yourself after Claude’s check passes to confirm the change against the running app.
有了检查之后,再决定它要在多大程度上控制任务能否停止:
Once the check exists, decide how hard it gates the stop:
- 在单条提示词中:像上表一样,在同一条消息中要求 Claude 运行检查并迭代。
- 贯穿整个会话:将检查设为
/goal条件。独立的评估器会在每轮之后重新检查,Claude 则持续工作,直到目标得到解决。如果 Claude 停滞不前,Claude Code 最终会停止运行,但仍保留已设置的目标;请参阅 /goal 评估的工作方式。 - 作为确定性关卡:Stop hook 以脚本形式运行检查,在通过之前阻止本轮结束。Stop input 说明了连续阻止的次数上限。
- 引入第二意见:使用验证子 Agent,或会检查自身发现的动态工作流,让一个拥有新上下文的模型尝试反驳结果,使执行任务的 Agent 不再同时负责给自己打分。
- In one prompt: ask Claude to run the check and iterate in the same message, as in the table above.
- Across a session: set the check as a
/goalcondition. A separate evaluator re-checks it after every turn and Claude keeps working until the goal resolves. If Claude stalls, Claude Code eventually stops the run with the goal still set — see how /goal evaluation works. - As a deterministic gate: a Stop hook runs your check as a script and blocks the turn from ending until it passes. Stop input covers the cap on consecutive blocks.
- By a second opinion: a verification subagent or a dynamic workflow that checks its own findings has a fresh model try to refute the result, so the agent doing the work isn’t the one grading it.
每种做法都是用前期配置换取更少的持续关注。提示词方式现在就适用于任何任务。/goal 和 Stop hook 方式则能让无人值守的运行在你不在场时正确完成。
Each step trades setup for attention. The prompt version works on any task today. The /goal and Stop hook versions are what let an unattended run finish correctly without you.
让 Claude 展示证据,而不只是宣称成功:例如测试输出、它运行的命令及返回结果,或结果截图。查看证据比自己重新验证更快,也适用于你没有全程旁观的会话。
Have Claude show evidence rather than asserting success: the test output, the command it ran and what it returned, or a screenshot of the result. Reviewing evidence is faster than re-running the verification yourself, and it works for sessions you weren’t watching.
先探索,再规划,最后编写代码
Explore first, then plan, then code
将研究和规划与实施分开,避免解决了错误的问题。
Separate research and planning from implementation to avoid solving the wrong problem.
让 Claude 直接开始写代码,可能产出解决错误问题的实现。使用规划模式,将探索与执行分开。
Letting Claude jump straight to coding can produce code that solves the wrong problem. Use plan mode to separate exploration from execution.
推荐的工作流分为四个阶段:
The recommended workflow has four phases:
1
1
探索
Explore
反复按 Shift+Tab,直到状态栏显示 ⏸ plan mode on,即可进入规划模式;也可以用 claude --permission-mode plan 启动会话。Claude 会读取文件并回答问题,但不会进行修改。
Enter plan mode by pressing Shift+Tab until the status bar shows ⏸ plan mode on, or start the session with claude --permission-mode plan. Claude reads files and answers questions without making changes.
claude(规划模式)
claude (plan mode)
2
2
规划
Plan
让 Claude 创建详细的实施计划。
Ask Claude to create a detailed implementation plan.
claude(规划模式)
claude (plan mode)
按 Ctrl+G,在文本编辑器中打开计划,以便在 Claude 继续之前直接编辑。
Press Ctrl+G to open the plan in your text editor for direct editing before Claude proceeds.
3
3
实施
Implement
通过批准计划或按 Shift+Tab 退出规划模式,然后让 Claude 编写代码,并依据计划进行验证。
Switch out of plan mode by approving the plan or pressing Shift+Tab, then let Claude code, verifying against its plan.
claude
claude
4
4
提交
Commit
让 Claude 使用能清楚描述改动的提交说明提交代码,并创建 PR。
Ask Claude to commit with a descriptive message and create a PR.
claude
claude
规划模式很有用,但也会增加额外开销。
Plan mode is useful, but also adds overhead.
对于范围明确、改动很小的任务,例如修正拼写、添加一行日志或重命名变量,直接让 Claude 执行即可。
For tasks where the scope is clear and the fix is small (like fixing a typo, adding a log line, or renaming a variable) ask Claude to do it directly.
当你不确定采用什么方案、改动涉及多个文件,或不熟悉将要修改的代码时,规划最有价值。如果你能用一句话描述整个 diff,就跳过规划。
Planning is most useful when you’re uncertain about the approach, when the change modifies multiple files, or when you’re unfamiliar with the code being modified. If you could describe the diff in one sentence, skip the plan.
在提示词中提供具体上下文
Provide specific context in your prompts
指令越精确,之后需要纠正的次数就越少。
The more precise your instructions, the fewer corrections you’ll need.
Claude 可以推断意图,但不会读心。引用具体文件、说明约束,并指出可参考的示例模式。
Claude can infer intent, but it can’t read your mind. Reference specific files, mention constraints, and point to example patterns.
当你正在探索,并且能够接受之后再调整方向时,模糊的提示词也有用。像 "what would you improve in this file?" 这样的提示词,可能会让你发现原本没有想到要问的事情。
Vague prompts can be useful when you’re exploring and can afford to course-correct. A prompt like "what would you improve in this file?" can surface things you wouldn’t have thought to ask about.
提供丰富的内容
Provide rich content
使用 @ 引用文件,粘贴截图或图片,或通过管道直接输入数据。
Use @ to reference files, paste screenshots/images, or pipe data directly.
你可以通过多种方式向 Claude 提供丰富的数据:
You can provide rich data to Claude in several ways:
- 使用
@引用文件,而不是描述代码位于哪里。Claude 会先读取文件,再作答。 - 直接粘贴图片。将图片复制粘贴或拖放到提示词中。
- 提供 URL,用于引用文档和 API 参考资料。用
/permissions将常用域名加入允许列表。 - 通过管道输入数据:运行
cat error.log | claude -p "explain this error",直接发送文件内容。 - 让 Claude 自行获取所需信息。告诉 Claude 使用 Bash 命令、MCP 工具或读取文件的方式,自行取得上下文。
- Reference files with
@instead of describing where code lives. Claude reads the file before responding. - Paste images directly. Copy/paste or drag and drop images into the prompt.
- Give URLs for documentation and API references. Use
/permissionsto allowlist frequently-used domains. - Pipe in data by running
cat error.log | claude -p "explain this error"to send file contents directly. - Let Claude fetch what it needs. Tell Claude to pull context itself using Bash commands, MCP tools, or by reading files.
配置环境
Configure your environment
几个配置步骤,就能显著提升 Claude Code 在所有会话中的效果。有关扩展功能的完整概览,以及何时使用各项功能,请参阅《扩展 Claude Code》。
A few setup steps make Claude Code significantly more effective across all your sessions. For a full overview of extension features and when to use each one, see Extend Claude Code.
编写有效的 CLAUDE.md
Write an effective CLAUDE.md
运行 /init,根据当前项目结构生成初始 CLAUDE.md 文件,再逐步完善。
Run /init to generate a starter CLAUDE.md file based on your current project structure, then refine over time.
CLAUDE.md 是一个特殊文件,Claude 会在每次对话开始时读取它。将 Bash 命令、代码风格和工作流规则写在其中,为 Claude 提供仅靠代码无法推断的持久上下文。
CLAUDE.md is a special file that Claude reads at the start of every conversation. Include Bash commands, code style, and workflow rules. This gives Claude persistent context it can’t infer from code alone.
CLAUDE.md 文件没有固定格式要求,但应保持简短,方便人类阅读。例如:
There’s no required format for CLAUDE.md files, but keep it short and human-readable. For example:
CLAUDE.md
CLAUDE.md
运行 /context,确认 Claude 已加载该文件。每次会话都会加载 CLAUDE.md,因此只放入普遍适用的内容。对于只在部分情况下相关的领域知识或工作流,改用 Skills。Claude 会按需加载它们,避免让每次对话都膨胀。
Run /context to confirm Claude loaded the file. CLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use skills instead. Claude loads them on demand without bloating every conversation.
保持简洁。对每一行都问自己:“删掉它,会导致 Claude 犯错吗?”如果不会,就删掉。臃肿的 CLAUDE.md 会让 Claude 忽略你真正的指令!
Keep it concise. For each line, ask: “Would removing this cause Claude to make mistakes?” If not, cut it. Bloated CLAUDE.md files cause Claude to ignore your actual instructions!
如果明明已有禁止规则,Claude 仍不断做你不希望它做的事,可能是文件太长,规则被淹没了。如果 Claude 问的问题在 CLAUDE.md 中已有答案,可能是措辞存在歧义。把 CLAUDE.md 当作代码来对待:出问题时检查它,定期精简,并通过观察 Claude 的行为是否真正改变来验证修改。对于已提交到仓库的 CLAUDE.md,运行 /doctor,Claude 就会建议删减那些能够从代码库推导出来的内容。
If Claude keeps doing something you don’t want despite having a rule against it, the file is probably too long and the rule is getting lost. If Claude asks you questions that are answered in CLAUDE.md, the phrasing might be ambiguous. Treat CLAUDE.md like code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude’s behavior actually shifts. For a checked-in CLAUDE.md, run /doctor and Claude proposes cuts for content it can derive from the codebase.
如果 Claude 总是跳过某一条指令,只在那一行加上“IMPORTANT”之类的强调。如果强调很多行,就没有哪一行能突出出来。将 CLAUDE.md 提交到 git,让团队也能参与维护。这个文件的价值会随时间累积。
If Claude keeps skipping one instruction, add emphasis such as “IMPORTANT” to that line alone. If you emphasize many lines, none of them stands out. Check CLAUDE.md into git so your team can contribute. The file compounds in value over time.
CLAUDE.md 可以使用 @path/to/import 语法导入其他文件。有关导入规则和 CLAUDE.md 可以放在哪些位置,请参阅《CLAUDE.md 文件》。
CLAUDE.md files can import additional files using @path/to/import syntax. For import rules and where CLAUDE.md files can live, see CLAUDE.md files.
配置权限
Configure permissions
要在保留控制权的同时减少提示,可以用 /permissions 预先批准可信工具,并用 /sandbox 允许沙箱中的命令不经询问直接运行。如果想亲自批准编辑和命令,则切换到 Manual 模式。
To get fewer prompts without giving up control, pre-approve the tools you trust with /permissions and let sandboxed commands run without asking with /sandbox. Switch to Manual mode when you want to approve edits and commands yourself.
从 Claude Code v2.1.283 开始,auto 模式是交互式终端和 VS Code 会话的内置初始权限模式:一个独立的分类器模型会替你审查大多数操作,仅阻止看起来存在风险的操作,例如扩大任务范围、操作未知基础设施,或受恶意内容驱使的操作。在更早的版本中,只有 Pro、Max 和 Team 套餐默认以 auto 模式作为内置初始权限模式。
With Claude Code v2.1.283 or later, auto mode is the built-in starting permission mode for interactive terminal and VS Code sessions: a separate classifier model reviews most actions instead of you and blocks only what looks risky, such as scope escalation, unknown infrastructure, or hostile-content-driven actions. On earlier versions, auto mode is the built-in starting permission mode only on Pro, Max, and Team plans.
在 Manual 模式下,Claude Code 会在执行可能修改系统的操作之前询问,例如写入文件、运行 Bash 命令和使用 MCP 工具。这很安全,但也很繁琐。批准到第十次时,你可能已经只是在机械地点确认,而不是认真审查。有两种工具可以减少 Manual 模式中的打断,而且同样适用于 auto 模式:
In Manual mode, Claude Code asks before actions that might modify your system: file writes, Bash commands, MCP tools. That’s safe but tedious. After the tenth approval you’re clicking through rather than reviewing. Two tools cut those interruptions in Manual mode and apply in auto mode as well:
- 权限允许列表:允许你知道安全的特定工具操作,例如
npm run lint或git commit。 - 沙箱:启用操作系统级隔离,限制文件系统和网络访问,让 Claude 在明确的边界内更自由地工作。
- Permission allowlists: permit specific tools you know are safe, like
npm run lintorgit commit - Sandboxing: enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries
Read more about permission modes, permission rules, and sandboxing.
使用 CLI 工具
Use CLI tools
与外部服务交互时,告诉 Claude Code 使用 gh、aws、gcloud 和 sentry-cli 等 CLI 工具。
Tell Claude Code to use CLI tools like gh, aws, gcloud, and sentry-cli when interacting with external services.
CLI 工具是与外部服务交互时最节省上下文的方式。如果你使用 GitHub,就安装 gh CLI。Claude 知道如何用它创建 issue、发起拉取请求和读取评论。没有 gh,Claude 仍可以使用 GitHub API,但未经认证的请求经常会触发速率限制。
CLI tools are the most context-efficient way to interact with external services. If you use GitHub, install the gh CLI. Claude knows how to use it for creating issues, opening pull requests, and reading comments. Without gh, Claude can still use the GitHub API, but unauthenticated requests often hit rate limits.
Claude 也很擅长学习自己还不熟悉的 CLI 工具。可以尝试这样的提示词:Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.
Claude is also effective at learning CLI tools it doesn’t already know. Try prompts like Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.
连接 MCP 服务器
Connect MCP servers
运行 claude mcp add,并提供服务器名称及 URL 或命令,即可连接 Notion、Figma 或数据库等外部工具。例如:claude mcp add --transport http notion https://mcp.notion.com/mcp。
Run claude mcp add with a server name and URL or command to connect external tools like Notion, Figma, or your database. For example: claude mcp add --transport http notion https://mcp.notion.com/mcp.
借助 MCP 服务器,你可以让 Claude 根据问题跟踪系统中的条目实现功能、查询数据库、分析监控数据、集成 Figma 设计,以及自动执行工作流。
With MCP servers, you can ask Claude to implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows.
设置 Hooks
Set up hooks
对于每次都必须执行、不能有任何例外的操作,使用 Hooks。
Use hooks for actions that must happen every time with zero exceptions.
Hooks 会在 Claude 工作流的特定节点自动运行脚本。CLAUDE.md 中的指令属于建议性要求,而 Hooks 是确定性的,可以保证操作执行。
Hooks run scripts automatically at specific points in Claude’s workflow. Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.
Claude 可以帮你编写 Hooks。试试这样的提示词:“编写一个 Hook,在每次文件编辑后运行 eslint”,或“编写一个 Hook,阻止对 migrations 文件夹的写入。”若要手动配置 Hooks,直接编辑 .claude/settings.json,并运行 /hooks 浏览现有配置。
Claude can write hooks for you. Try prompts like “Write a hook that runs eslint after every file edit” or “Write a hook that blocks writes to the migrations folder.” Edit .claude/settings.json directly to configure hooks by hand, and run /hooks to browse what’s configured.
创建 Skills
Create skills
在 .claude/skills/ 中创建 SKILL.md 文件,为 Claude 提供领域知识和可复用工作流。
Create SKILL.md files in .claude/skills/ to give Claude domain knowledge and reusable workflows.
Skills 使用与你的项目、团队或领域相关的特定信息扩展 Claude 的知识。Claude 会在相关时自动应用它们,你也可以通过 /skill-name 直接调用。
Skills extend Claude’s knowledge with information specific to your project, team, or domain. Claude applies them automatically when relevant, or you can invoke them directly with /skill-name.
在 .claude/skills/ 中添加一个包含 SKILL.md 的目录,即可创建 Skill:
Create a skill by adding a directory with a SKILL.md to .claude/skills/:
.claude/skills/api-conventions/SKILL.md
.claude/skills/api-conventions/SKILL.md
Skills 也可以定义由你直接调用的可重复工作流:
Skills can also define repeatable workflows you invoke directly:
.claude/skills/fix-issue/SKILL.md
.claude/skills/fix-issue/SKILL.md
运行 /fix-issue 1234 即可调用它。对于具有副作用、且希望手动触发的工作流,使用 disable-model-invocation: true。
Run /fix-issue 1234 to invoke it. Use disable-model-invocation: true for workflows with side effects that you want to trigger manually.
创建自定义子 Agent
Create custom subagents
在 .claude/agents/ 中定义专门的助手,让 Claude 可以将独立任务委派给它们。
Define specialized assistants in .claude/agents/ that Claude can delegate to for isolated tasks.
子 Agent 在各自的上下文中运行,并有各自允许使用的工具集。它们适合需要读取大量文件或专注于特定领域的任务,同时不会把主对话塞满。
Subagents run in their own context with their own set of allowed tools. They’re useful for tasks that read many files or need specialized focus without cluttering your main conversation.
.claude/agents/security-reviewer.md
.claude/agents/security-reviewer.md
明确告诉 Claude 使用子 Agent:“使用一个子 Agent,审查这段代码中的安全问题。”
Tell Claude to use subagents explicitly: “Use a subagent to review this code for security issues.”
安装插件
Install plugins
运行 /plugin 浏览插件市场。插件可以添加 Skills、工具和集成,无须配置。
Run /plugin to browse the marketplace. Plugins add skills, tools, and integrations without configuration.
插件将 Skills、Hooks、子 Agent 和 MCP 服务器打包成一个可安装单元,由社区和 Anthropic 提供。如果你使用有类型系统的编程语言,安装一个代码智能插件,让 Claude 能够精确导航到符号,并在编辑后自动检测错误。
Plugins bundle skills, hooks, subagents, and MCP servers into a single installable unit from the community and Anthropic. If you work with a typed language, install a code intelligence plugin to give Claude precise symbol navigation and automatic error detection after edits.
有关如何在 Skills、子 Agent、Hooks 和 MCP 之间选择,请参阅《扩展 Claude Code》。
For guidance on choosing between skills, subagents, hooks, and MCP, see Extend Claude Code.
有效沟通
Communicate effectively
把你会问其他工程师的问题拿来问 Claude;对于规模较大的功能,在开始实现之前,先让 Claude 向你提问并写出规格说明。
Ask Claude the questions you’d ask another engineer, and for larger features have Claude interview you and write a spec before you start implementing.
询问代码库相关问题
Ask codebase questions
向 Claude 提出你会问资深工程师的问题。
Ask Claude questions you’d ask a senior engineer.
熟悉新代码库时,可以使用 Claude Code 进行学习和探索。你可以像向其他工程师请教一样提问:
When onboarding to a new codebase, use Claude Code for learning and exploration. You can ask Claude the same sorts of questions you would ask another engineer:
- 日志机制如何工作?
- 怎样创建一个新的 API 端点?
foo.rs第 134 行的async move { ... }是做什么的?CustomerOnboardingFlowImpl处理了哪些边界情况?- 为什么这段代码在第 333 行调用
foo(),而不是bar()?
- How does logging work?
- How do I make a new API endpoint?
- What does
async move { ... }do on line 134 offoo.rs? - What edge cases does
CustomerOnboardingFlowImplhandle? - Why does this code call
foo()instead ofbar()on line 333?
这样使用 Claude Code,是一种有效的上手工作流,能够缩短熟悉项目的时间,并减轻其他工程师的负担。不需要特殊的提示技巧,直接提问即可。
Using Claude Code this way is an effective onboarding workflow, improving ramp-up time and reducing load on other engineers. No special prompting required: ask questions directly.
让 Claude 向你提问
Let Claude interview you
对于规模较大的功能,先让 Claude 对你进行访谈。用一个最简提示词开始,并要求 Claude 使用 AskUserQuestion 工具向你提问。
For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the AskUserQuestion tool.
Claude 会询问你可能还没有考虑到的事情,包括技术实现、UI/UX、边界情况和取舍。发送提示词之前,将 [brief description] 替换为你的功能描述。
Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs. Replace [brief description] with your feature before sending the prompt.
规格说明完成后,启动一个新会话来实施。新会话拥有干净的上下文,可以完全聚焦实现,而你也有一份书面规格说明可供参考。
Once the spec is complete, start a fresh session to execute it. The new session has clean context focused entirely on implementation, and you have a written spec to reference.
最有用的规格说明是自包含的:明确涉及哪些文件和接口,说明哪些内容不在范围内,并以一个能证明功能有效的端到端验证步骤收尾。花时间把规格说明写准确,比花时间盯着实现过程更有回报。
The most useful specs are self-contained: they name the files and interfaces involved, state what is out of scope, and end with an end-to-end verification step that proves the feature works. Time spent making the spec precise pays off more than time spent watching the implementation.
管理会话
Manage your session
对话可以持久保存,也可以回退。充分利用这一点!
Conversations are persistent and reversible. Use this to your advantage!
尽早、频繁地纠正方向
Course-correct early and often
一旦发现 Claude 偏离方向,就立即纠正。
Correct Claude as soon as you notice it going off track.
紧密的反馈循环能带来最好的结果。虽然 Claude 偶尔能在第一次尝试时就完美解决问题,但快速纠正它,通常能更快得到更好的方案。
The best results come from tight feedback loops. Though Claude occasionally solves problems perfectly on the first attempt, correcting it quickly generally produces better solutions faster.
Esc:按Esc在操作中途停止 Claude。上下文会保留,因此你可以调整方向。Esc + Esc或/rewind:连按两次Esc,或运行/rewind,打开回退菜单,恢复之前的对话与代码状态,或从选定消息处开始总结。"Undo that":让 Claude 撤销它的修改。/clear:在不相关的任务之间重置上下文。包含无关上下文的长会话会降低表现。
Esc: stop Claude mid-action with theEsckey. Context is preserved, so you can redirect.Esc + Escor/rewind: pressEsctwice or run/rewindto open the rewind menu and restore previous conversation and code state, or summarize from a selected message."Undo that": have Claude revert its changes./clear: reset context between unrelated tasks. Long sessions with irrelevant context can reduce performance.
如果在同一会话中,你已经针对同一问题纠正 Claude 超过两次,上下文里就充斥着失败方案了。运行 /clear,用一个更具体、融入了已学到经验的提示词重新开始。一个使用更好提示词的干净会话,几乎总比不断累积纠正信息的长会话表现更好。
If you’ve corrected Claude more than twice on the same issue in one session, the context is cluttered with failed approaches. Run /clear and start fresh with a more specific prompt that incorporates what you learned. A clean session with a better prompt almost always outperforms a long session with accumulated corrections.
积极管理上下文
Manage context aggressively
在不相关的任务之间运行 /clear,重置上下文。
Run /clear between unrelated tasks to reset context.
当接近上下文上限时,Claude Code 会自动压缩对话历史,保留重要代码和决策,同时释放空间。
Claude Code automatically compacts conversation history when you approach context limits, which preserves important code and decisions while freeing space.
在长会话中,Claude 的上下文窗口可能被无关对话、文件内容和命令填满。这会降低表现,有时还会分散 Claude 的注意力。
During long sessions, Claude’s context window can fill with irrelevant conversation, file contents, and commands. This can reduce performance and sometimes distract Claude.
- 在任务之间经常使用
/clear,彻底重置上下文窗口。 - 自动压缩触发时,Claude 会总结最重要的内容,包括代码模式、文件状态和关键决策。
- 若要更精细地控制,运行
/compact <instructions>,例如/compact Focus on the API changes。 - 若只想压缩部分对话,使用
Esc + Esc或/rewind,选择一个消息检查点,然后选择 Summarize from here(从此处开始总结)或 Summarize up to here(总结到此处)。前者压缩从该位置开始的后续消息,保留之前的上下文;后者压缩较早的消息,完整保留最近的消息。参阅回退菜单的总结选项。 - 在 CLAUDE.md 中用诸如
"When compacting, always preserve the full list of modified files and any test commands"的指令定制压缩行为,确保关键信息在总结之后仍被保留。 - 对于无须保留在上下文中的问题,使用
/btw。答案不会进入对话历史,因此你可以确认细节,而不增加上下文。
- Use
/clearfrequently between tasks to reset the context window entirely - When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions
- For more control, run
/compact <instructions>, like/compact Focus on the API changes - To compact only part of the conversation, use
Esc + Escor/rewind, select a message checkpoint, and choose Summarize from here or Summarize up to here. The first condenses messages from that point forward while keeping earlier context intact; the second condenses earlier messages while keeping recent ones in full. See the rewind menu’s summarize options. - Customize compaction behavior in CLAUDE.md with instructions like
"When compacting, always preserve the full list of modified files and any test commands"to ensure critical context survives summarization - For questions that don’t need to stay in context, use
/btw. The answer never enters conversation history, so you can check a detail without growing context.
使用子 Agent 开展调查
Use subagents for investigation
通过 "use subagents to investigate X" 委派研究。子 Agent 在独立上下文中探索,让主对话保持干净,专注实施。
Delegate research with "use subagents to investigate X". They explore in a separate context, keeping your main conversation clean for implementation.
既然上下文是根本约束,就用子 Agent 将研究过程移出主上下文。Claude 研究代码库时会读取大量文件,这些都会消耗上下文。子 Agent 在独立的上下文窗口中运行,并汇报摘要:
Since context is your fundamental constraint, use subagents to keep research out of it. When Claude researches a codebase it reads lots of files, all of which consume your context. Subagents run in separate context windows and report back summaries:
你也可以在 Claude 完成实现后,使用子 Agent 进行验证。参阅《添加对抗式审查步骤》。
You can also use subagents for verification after Claude implements something. See Add an adversarial review step.
利用检查点回退
Rewind with checkpoints
你发送的每条开启新一轮交互的提示词,都会创建一个检查点。你可以将对话、代码或二者一起恢复到之前任意检查点。
Every prompt you send that starts a turn creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.
每次修改之前,Claude 都会自动为文件创建快照,让检查点能够恢复文件。连按两次 Escape 或运行 /rewind,即可打开回退菜单。你可以仅恢复对话、仅恢复代码、同时恢复二者,或从选定消息处开始总结。详情请参阅《检查点》。
Claude automatically snapshots files before each change so a checkpoint can restore them. Double-tap Escape or run /rewind to open the rewind menu. You can restore conversation only, restore code only, restore both, or summarize from a selected message. See Checkpointing for details.
你不必小心规划每一步,也可以让 Claude 尝试有风险的方案。如果不奏效,就回退并换一种方法。检查点会随对话一起保存,因此你可以关闭终端,之后恢复会话,仍然能够回退。
Instead of carefully planning every move, you can tell Claude to try something risky. If it doesn’t work, rewind and try a different approach. Checkpoints are saved with the conversation, so you can close your terminal, resume the session later, and still rewind.
检查点只跟踪通过 Claude 文件编辑工具做出的修改。通过 Bash 命令或外部进程产生的改动不会被记录。它不能替代 git。
Checkpoints only track changes made through Claude’s file editing tools. Changes made through Bash commands or external processes are not captured. This isn’t a replacement for git.
恢复对话
Resume conversations
使用 /rename 为会话命名,并像对待分支一样管理它们:每条工作线都有自己的持久上下文。
Name sessions with /rename and treat them like branches: each workstream gets its own persistent context.
Claude Code 会在本地保存对话,因此当一个任务需要分多次完成时,你不必重新解释上下文。运行 claude --continue 从上次停止的地方继续,或用 claude --resume 从列表中选择。给会话起一个有描述性的名称,例如 oauth-migration,方便之后查找。完整的恢复、分支和命名控制,请参阅《管理会话》。
Claude Code saves conversations locally, so when a task spans multiple sittings you don’t have to re-explain the context. Run claude --continue to pick up where you left off, or claude --resume to choose from a list. Give sessions descriptive names like oauth-migration so you can find them later. See Manage sessions for the full set of resume, branch, and naming controls.
自动化与规模扩展
Automate and scale
当你能高效使用一个 Claude 之后,就可以通过并行会话、非交互模式和扇出模式成倍提升产出。
Once you’re effective with one Claude, multiply your output with parallel sessions, non-interactive mode, and fan-out patterns.
运行非交互模式
Run non-interactive mode
在 CI、pre-commit 钩子或脚本中使用 claude -p "prompt"。添加 --output-format stream-json --verbose,即可获得流式 JSON 输出。
Use claude -p "prompt" in CI, pre-commit hooks, or scripts. Add --output-format stream-json --verbose for streaming JSON output.
通过 claude -p "your prompt",你可以以非交互方式运行 Claude,不出现交互式输入提示。除非传入 --no-session-persistence,否则该次运行仍会创建可恢复的会话。非交互模式是将 Claude 集成到 CI 流水线、pre-commit 钩子或任何自动化工作流的方式。输出格式包括纯文本、JSON 和流式 JSON,便于程序化解析结果。
With claude -p "your prompt", you can run Claude non-interactively, without an interactive prompt. The run still creates a resumable session unless you pass --no-session-persistence. Non-interactive mode is how you integrate Claude into CI pipelines, pre-commit hooks, or any automated workflow. The output formats let you parse results programmatically: plain text, JSON, or streaming JSON.
第一条命令输出纯文本。json 格式返回一个含有 result 字段的 JSON 对象。stream-json 格式每行输出一个 JSON 对象,从 init 事件开始。
The first command prints plain text. The json format returns a single JSON object with a result field. The stream-json format prints one JSON object per line, starting with an init event.
运行多个 Claude 会话
Run multiple Claude sessions
并行运行多个 Claude 会话,可以加快开发、进行相互隔离的实验,或启动复杂工作流。
Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows.
根据你愿意亲自承担多少协调工作,选择合适的并行方式;当会话之间需要交换发现时,再加入消息通信:
Pick the parallel approach that fits how much coordination you want to do yourself, and add messaging when the sessions need to pass findings between them:
- Worktrees:在相互隔离的 git 检出目录中运行独立的 CLI 会话,避免编辑冲突。
- 跨会话消息:让你自行运行的会话相互传递发现。
- 桌面应用:以可视化方式管理多个本地会话,也可以让每个会话拥有独立的 worktree。
- 在云端使用 Claude Code:默认在 Anthropic 管理的基础设施上运行会话。
- Agent 视图:研究预览功能。运行
claude agents,派发能够在后台持续运行的会话,并在同一屏幕上查看它们。 - Agent 团队:实验性功能,默认关闭。通过共享任务、消息通信和团队负责人,自动协调多个会话。
- Worktrees: run separate CLI sessions in isolated git checkouts so edits don’t collide
- Cross-session messaging: let the sessions you run yourself pass findings to each other
- Desktop app: manage multiple local sessions visually, optionally each in its own worktree
- Use Claude Code in the cloud: run sessions on Anthropic-managed infrastructure by default
- Agent view: research preview. Run
claude agentsto dispatch sessions that keep running in the background and watch them from one screen - Agent teams: experimental and disabled by default. Automated coordination of multiple sessions with shared tasks, messaging, and a team lead
除了并行处理工作,多会话也支持以质量为重点的工作流。全新的上下文能改善代码审查,因为 Claude 不会偏向自己刚写出的代码。
Beyond parallelizing work, multiple sessions enable quality-focused workflows. A fresh context improves code review since Claude won’t be biased toward code it just wrote.
例如,使用“编写者/审查者”模式:
For example, use a Writer/Reviewer pattern:
测试也可以采用类似做法:让一个 Claude 编写测试,再让另一个 Claude 编写能够通过测试的代码。
You can do something similar with tests: have one Claude write tests, then another write code to pass them.
跨文件扇出任务
Fan out across files
循环遍历任务,为每个任务调用 claude -p。使用 --allowedTools 限定批量操作的权限范围。
Loop through tasks calling claude -p for each. Use --allowedTools to scope permissions for batch operations.
对于大规模迁移或分析,你可以将工作分配给多个并行的 Claude 调用。运行 /batch <instruction>,让 Claude 将改动拆分给 5 到 30 个子 Agent;每个子 Agent 都在自己的 worktree 中工作。如果希望改为用自己的脚本驱动扇出,则循环调用 claude -p:
For large migrations or analyses, you can distribute work across many parallel Claude invocations. Run /batch <instruction> to have Claude split the change across 5 to 30 subagents. Each subagent works in its own worktree. To drive the fan-out from your own script instead, loop over claude -p:
1
1
生成任务列表
Generate a task list
让 Claude 将需要迁移的文件列表写入一个文件,以供下一步的循环读取,例如使用提示词 list all 2,000 Python files that need migrating and save the list to files.txt。
Have Claude write the list of files that need migrating to a file, so the loop in the next step can read it, with a prompt like list all 2,000 Python files that need migrating and save the list to files.txt
2
2
编写脚本,循环遍历列表
Write a script to loop through the list
3
3
先在少量文件上测试,再运行全部文件
Test on a few files, then run on all of them
根据前 2–3 个文件上遇到的问题完善提示词,然后再处理完整集合。--allowedTools 参数限制 Claude 能执行的操作,在无人值守运行时尤为重要。
Refine your prompt based on what goes wrong with the first 2-3 files, then run on the full set. The --allowedTools flag restricts what Claude can do, which matters when you’re running unattended.
你也可以将 Claude 集成到现有的数据或处理流水线中:
You can also integrate Claude into existing data/processing pipelines:
使用 auto 模式自主运行
Run autonomously with auto mode
若希望不中断地执行,同时在后台进行安全检查,使用 auto 模式。分类器模型会在命令执行前审查,阻止扩大任务范围、操作未知基础设施,以及受恶意内容驱使的操作,同时允许常规工作不经提示继续进行。
For uninterrupted execution with background safety checks, use auto mode. A classifier model reviews commands before they run, blocking scope escalation, unknown infrastructure, and hostile-content-driven actions while letting routine work proceed without prompts.
在带有 -p 参数的非交互运行中,即使分类器反复阻止操作,Claude Code 也不会停止运行。有关此时会发生什么以及相关阈值,请参阅《auto 模式何时回退》。
When the classifier repeatedly blocks actions in a non-interactive run with the -p flag, Claude Code doesn’t stop the run. See when auto mode falls back for what happens instead and for the thresholds.
添加对抗式审查步骤
Add an adversarial review step
在认定任务完成之前,让一个子 Agent 在全新的上下文中审查 diff,并报告遗漏或不足。
Before treating a task as done, have a subagent review the diff in a fresh context and report gaps.
Claude 无人值守工作的时间越长,在认定工作完成之前进行独立检查就越重要。运行在全新子 Agent 上下文中的审查者,只能看到 diff 和你提供的标准,看不到产生改动的推理过程,因此会独立评估结果。
The longer Claude works unattended, the more an independent check matters before you count the work as done. A reviewer running in a fresh subagent context sees only the diff and the criteria you give it, not the reasoning that produced the change, so it evaluates the result on its own terms.
如果要检查正确性,运行内置的 /code-review Skill。它会在一个新的子 Agent 中检查当前 diff 的缺陷,并将发现返回到会话中。如果想根据计划检查 diff,则自己编写审查提示词,明确要检查的工作、作为依据的计划,以及什么才算需要报告的问题:
For a correctness check, run the bundled /code-review skill, which reviews the current diff for bugs in a fresh subagent and returns findings to the session. To check the diff against your plan instead, write the review prompt yourself. Name the work to check, the plan to check it against, and what counts as a finding:
由于审查者作为子 Agent 运行,负责实现的会话会直接收到问题,能够修复后再次审查,无须你在窗口之间复制审查结果。
Because the reviewer runs as a subagent, the implementing session receives the gaps directly and can fix them and re-review without you copying findings between windows.
一个被要求寻找缺口的审查者,通常总会报告一些问题,即使工作本身没有问题,因为你给它的任务就是找缺口。追逐每一条发现会导致过度设计:增加抽象层、防御性代码,以及针对不可能发生的情况编写测试。告诉审查者只标记影响正确性或明确需求的问题,其余都视为可选建议。
A reviewer prompted to find gaps will usually report some, even when the work is sound, because that is what it was asked to do. Chasing every finding leads to over-engineering: extra abstraction layers, defensive code, and tests for cases that can’t happen. Tell the reviewer to flag only gaps that affect correctness or the stated requirements, and treat the rest as optional.
避免常见的失败模式
Avoid common failure patterns
下面这些错误很常见。尽早识别它们可以节省时间:
These are common mistakes. Recognizing them early saves time:
- 什么都往里塞的会话。你先开始一项任务,又问 Claude 一个不相关的问题,然后回到最初的任务。上下文因此充满无关信息。
解决办法:在不相关的任务之间使用
/clear。 - 反复纠正。Claude 做错了,你纠正它;仍然错,你再纠正。失败方案污染了上下文。
解决办法:两次纠正失败后,使用
/clear,把已经学到的经验融入一个更好的初始提示词。 - 规定过多的 CLAUDE.md。如果 CLAUDE.md 太长,Claude 会忽略其中一半,因为重要规则被噪声淹没了。
解决办法:果断精简。如果没有某条指令,Claude 也已经能正确完成相应操作,就删掉它,或者改成 Hook。
- 信任与验证之间的落差。Claude 产出了看起来合理的实现,却没有处理边界情况。
解决办法:始终提供验证方式,包括测试、脚本、截图。如果无法验证,就不要交付。
- 无止境的探索。你让 Claude“调查”某件事,却没有限定范围。Claude 读取了数百个文件,填满上下文。
解决办法:严格限定调查范围,或使用子 Agent,避免探索消耗主上下文。
- The kitchen sink session. You start with one task, then ask Claude something unrelated, then go back to the first task. Context is full of irrelevant information.
Fix:
/clearbetween unrelated tasks. - Correcting over and over. Claude does something wrong, you correct it, it’s still wrong, you correct again. Context is polluted with failed approaches.
Fix: After two failed corrections,
/clearand write a better initial prompt incorporating what you learned. - The over-specified CLAUDE.md. If your CLAUDE.md is too long, Claude ignores half of it because important rules get lost in the noise.
Fix: Ruthlessly prune. If Claude already does something correctly without the instruction, delete it or convert it to a hook.
- The trust-then-verify gap. Claude produces a plausible-looking implementation that doesn’t handle edge cases.
Fix: Always provide verification (tests, scripts, screenshots). If you can’t verify it, don’t ship it.
- The infinite exploration. You ask Claude to “investigate” something without scoping it. Claude reads hundreds of files, filling the context.
Fix: Scope investigations narrowly or use subagents so the exploration doesn’t consume your main context.
培养你的直觉
Develop your intuition
本指南中的模式并非一成不变。它们是通常有效的起点,但未必适用于每一种情况。
The patterns in this guide aren’t set in stone. They’re starting points that work well in general, but might not be optimal for every situation.
有时你应该让上下文持续累积,因为你正深入解决一个复杂问题,历史信息很有价值。有时应该跳过规划,让 Claude 自己摸索,因为任务本身具有探索性。有时模糊的提示词恰到好处,因为你想在施加约束之前,先看看 Claude 如何理解问题。
Sometimes you should let context accumulate because you’re deep in one complex problem and the history is valuable. Sometimes you should skip planning and let Claude figure it out because the task is exploratory. Sometimes a vague prompt is exactly right because you want to see how Claude interprets the problem before constraining it.
关注哪些做法有效。当 Claude 产出出色结果时,留意你做了什么:提示词结构、提供的上下文,以及所处的模式。当 Claude 表现吃力时,追问原因。是上下文噪声太多?提示词太模糊?还是任务太大,无法一次完成?
Pay attention to what works. When Claude produces great output, notice what you did: the prompt structure, the context you provided, the mode you were in. When Claude struggles, ask why. Was the context too noisy? The prompt too vague? The task too big for one pass?
随着时间推移,你会形成任何指南都无法完整涵盖的直觉。你会知道何时应该具体明确,何时可以开放探索;何时规划,何时探索;何时清空上下文,何时让它继续累积。
Over time, you’ll develop intuition that no guide can capture. You’ll know when to be specific and when to be open-ended, when to plan and when to explore, when to clear context and when to let it accumulate.
相关资源
Related resources
- Claude Code 如何工作:Agent 循环、工具和上下文管理。
- 扩展 Claude Code:Skills、Hooks、MCP、子 Agent 和插件。
- 常见工作流:调试、测试、PR 等任务的分步操作方法。
- CLAUDE.md:保存项目约定和持久上下文。
- How Claude Code works: the agentic loop, tools, and context management
- Extend Claude Code: skills, hooks, MCP, subagents, and plugins
- Common workflows: step-by-step recipes for debugging, testing, PRs, and more
- CLAUDE.md: store project conventions and persistent context
— 全文完 —
原文来自 Anthropic,中文为非官方学习译文。
查看原始出处 ↗