Claude Code 不只是一个“在终端里聊天的 AI”。把它用顺手之后,它更像一个可配置、可约束、可编排的本地开发代理:能读写仓库、执行命令、调用 MCP 工具、运行子代理、触发 Hooks,也能在 CI 或脚本里以 JSON 输出工作结果。

这篇不是入门教程。安装、登录、第一次提问这些内容只保留最低限度;重点放在日常高强度使用时真正影响效率和稳定性的东西:上下文、权限、配置、自动化、并行工作流和排障。

一页速查

会话入口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 交互式会话
claude

# 单次任务,适合脚本或 CI
claude -p "summarize this project"

# 继续最近会话
claude --continue

# 选择历史会话恢复
claude --resume

# 额外授权相邻目录
claude --add-dir ../shared ../infra

# 先进入计划模式
claude --permission-mode plan

# 打开后台 agent 看板
claude agents

常用会话命令

命令用途
/init为仓库生成起始 CLAUDE.md
/memory查看、编辑、开关记忆与 CLAUDE.md
/permissions管理工具权限与审批规则
/plan先规划,确认后再改文件
/goal设置完成条件,让 Claude 跨 turn 工作到条件满足
/loop按间隔重复执行提示,适合轮询 CI、部署、PR 状态
/context查看上下文窗口消耗
/compact压缩长会话,保留关键状态
/model切换模型
/effort调整推理强度
/mcp管理 MCP 服务器
/agents管理子代理
/workflows查看和管理 Dynamic workflow 运行
/schedule创建云端或桌面计划任务
/bg把当前会话放到后台 Agent View
/tasks查看后台任务
/diff查看当前改动
/code-review本地审查当前 diff
/rewind回退到检查点
/clear开启新任务,保留项目记忆

常用 CLI 标志

参数用途
-p, --prompt非交互式执行一次提示
--output-format json输出结构化 JSON
--output-format stream-json输出流式 JSON 事件
--json-schema要求结构化输出符合 JSON Schema
--add-dir允许 Claude 访问额外目录
--allowedTools预批准部分工具调用
--disallowedTools禁止部分工具调用
--permission-mode设置权限模式
--agent使用指定子代理作为主会话代理
--agents临时用 JSON 定义子代理
--safe-mode禁用自定义配置启动,适合排障
--append-system-prompt在默认系统提示后追加指令
--system-prompt替换默认系统提示

推荐心智模型

Claude Code 的能力可以拆成五层:

  1. 模型层:选择 Sonnet、Opus、Haiku 等模型别名,控制成本、速度和推理能力。
  2. 上下文层:通过 CLAUDE.md、自动记忆、文件读取、MCP 工具描述和历史会话构造上下文。
  3. 工具层:读写文件、搜索代码、执行 Bash、调用 MCP、运行子代理。
  4. 权限层:决定哪些工具能自动执行、哪些必须审批、哪些永远禁止。
  5. 自动化层:用 Skills、Hooks、Subagents、/goal/loop、Dynamic workflows、headless CLI、CI 脚本把重复流程固化下来。

高阶用法的关键不是“写更长的 Prompt”,而是把这五层分清楚:事实放记忆,流程放 Skills,外部系统接 MCP,安全边界放权限,机械动作交给 Hooks。

配置作用域

Claude Code 的配置有作用域。不要把所有东西都塞进一个文件。

作用域位置适合放什么是否应提交
User~/.claude/个人偏好、常用工具、全局指令
Project.claude/团队共享规则、项目 Skills、项目权限基线看内容
Local.claude/settings.local.json个人在当前仓库的覆盖配置
MCP project.mcp.json团队共享 MCP 服务器
MCP user/local~/.claude.json私有 MCP、授权状态、本机缓存

建议:

  • 团队约定放 CLAUDE.md.claude/settings.json
  • 个人习惯放 ~/.claude/CLAUDE.md~/.claude/settings.json
  • 私人密钥、本机路径、临时 allow 规则放 .claude/settings.local.json
  • 不要手写 ~/.claude.json,除非你正在排障。

记忆系统

CLAUDE.md 放规则,不放流水账

CLAUDE.md 是项目级记忆。适合放稳定、可复用、能改变行为的规则:

1
2
3
4
5
6
7
# Project Instructions

- Use pnpm for package management.
- Run `pnpm test` before claiming a change is complete.
- Do not edit generated files under `src/generated/`.
- API handlers live in `apps/api/src/routes/`.
- Prefer existing repository patterns over new abstractions.

不适合放:

  • 某次任务的临时背景。
  • 大段架构文档复制粘贴。
  • “一定不能做危险操作”这种空泛安全提醒。
  • 密钥、token、内网密码。

CLAUDE.md 可以用 @path/to/file 导入其他文件:

1
2
3
See @README.md for project overview.
See @docs/testing.md for test conventions.
See @docs/release.md for release workflow.

导入要克制。CLAUDE.md 太长时,Claude 会更容易漏掉具体规则。

分层 CLAUDE.md

大仓库适合分层:

1
2
3
4
5
repo/
CLAUDE.md
apps/api/CLAUDE.md
apps/web/CLAUDE.md
packages/db/CLAUDE.md

根文件写全局规则,子目录文件写局部规则。Claude 读到子目录文件时,会按需加载对应规则。这样比在根部维护一个巨大说明文件更稳。

自动记忆

Claude Code 还有本机自动记忆。你可以在会话里说:

1
remember that this repo uses Testcontainers for integration tests

它会把信息写进本机 memory 目录。这个目录通常在 ~/.claude/projects/<project>/memory/,入口文件是 MEMORY.md。它适合放个人长期偏好和项目经验,但它不是团队共享机制。

/memory 审计记忆。发现 Claude 总犯同一个错时,先看规则是否真的被加载,再看规则是否太模糊。

权限设计

权限是 Claude Code 的安全边界;CLAUDE.md 只是行为指导,不是安全机制。

基本原则

  • 自动允许只读命令,比如 git statusgit diffrg
  • 自动允许确定性的格式化命令,比如 prettier --write,但只限项目内。
  • rmchmod、迁移、部署、网络写操作保持审批。
  • 对密钥文件、生成产物、供应商目录使用 deny 规则。
  • 不要长期使用跳过权限的模式,除非在隔离工作区里做批量机械任务。

典型本地设置

.claude/settings.local.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"permissions": {
"allow": [
"Read",
"Edit",
"Bash(git status*)",
"Bash(git diff*)",
"Bash(git log*)",
"Bash(rg *)",
"Bash(npm test*)",
"Bash(npm run lint*)"
],
"deny": [
"Read(.env*)",
"Read(**/secrets/**)",
"Edit(public/**)",
"Bash(rm -rf *)",
"Bash(git push*)",
"Bash(npm publish*)",
"Bash(kubectl apply*)"
]
}
}

这只是示例。真实项目里应该按仓库技术栈收紧,比如 Go 项目允许 go test ./...,Node 项目允许 pnpm test,Java 项目允许 mvn test

大仓库读权限控制

不要只靠“请不要读 dist”。用 deny 规则挡住无意义上下文:

1
2
3
4
5
6
7
8
9
10
11
12
{
"permissions": {
"deny": [
"Read(node_modules/**)",
"Read(dist/**)",
"Read(build/**)",
"Read(coverage/**)",
"Read(**/*.min.js)",
"Read(**/generated/**)"
]
}
}

这样能同时降低 token 消耗和误读风险。

模型与推理强度

模型选择建议按任务分层:

任务建议
小改动、解释、简单脚本haiku 或低 effort
日常编码、测试、重构sonnet
复杂架构、疑难 bug、跨模块推理opus 或更高 effort
长上下文分析使用带长上下文能力的模型别名

常用:

1
2
3
/model sonnet
/model opus
/effort high

一次性深度推理可以直接在提示里写 ultrathink,但不要滥用。它适合“先推理再动手”的问题,例如并发 bug、协议设计、复杂迁移方案。

如果通过网关或第三方模型路由,要区分两个概念:

  • ANTHROPIC_BASE_URL 改的是请求发往哪里。
  • 模型名或模型别名决定实际使用哪个模型。

上下文控制

让 Claude 先画地图

不要一上来让它大改。先让它建立局部地图:

1
2
3
4
5
先不要修改文件。请阅读这个支付模块相关代码,回答:
1. 入口 handler 在哪里
2. 核心状态流转在哪里
3. 哪些测试覆盖了退款流程
4. 如果要加 partial refund,最小改动面是什么

用计划模式挡住冲动编辑

复杂任务先进入 /plan

1
2
/plan
实现订单取消后的库存回补。先列出你会改哪些文件、为什么改、如何验证。不要写代码。

确认计划后再让它执行:

1
按这个计划执行。每完成一个阶段跑对应测试。

控制上下文膨胀

长会话里定期检查:

1
/context

如果上下文快满:

1
/compact

压缩前可以先要求 Claude 生成“可恢复状态”:

1
2
3
4
5
6
在 compact 前,整理当前任务状态:
- 已确认事实
- 已修改文件
- 剩余 TODO
- 必须保留的设计约束
- 下一步验证命令

快速旁路问题用 /btw

不想污染主会话历史时,用 /btw 问临时问题。适合确认一个命令、解释一个错误码、让它帮你想变量名。

无人值守:Loop、Goal 与 Workflow

Claude Code 新一代自动化能力的核心不是“让它一直跑”,而是把结束条件说清楚,让它能自己判断下一步要不要继续。可以按这条链路理解:

1
verification loop -> /goal -> /loop -> scheduled tasks -> dynamic workflows

Verification loop 是前提

不要只说“把功能做好”。要给 Claude 一个能运行、能读结果、能反复迭代的检查:

1
2
3
4
5
6
7
实现 token refresh rotation。

完成条件:
- npm test -- auth/refresh exits 0
- npm run lint exits 0
- 没有修改 public API
- git diff 里包含测试覆盖

这就是 verification loop:Claude 改代码、运行检查、读失败、再改,直到检查通过。没有这个闭环时,Claude 只能靠“看起来完成了”来停。

适合做检查信号的东西:

  • 单元测试、集成测试、构建退出码。
  • lint、typecheck、格式检查。
  • CLI 输出和 fixture diff。
  • UI 截图对比。
  • issue 队列、文件计数、待办清单为空。

/goal:一直做,直到完成条件满足

/goal 适合有明确终点的长任务。它会设置一个 session 级完成条件;每个 turn 结束后,Claude Code 用一个小模型评估条件是否已经满足。如果没有满足,就自动开始下一轮。

1
/goal all tests in test/auth pass, npm run lint exits 0, and the current diff includes tests for refresh rotation

实战写法:

1
/goal migrate all usages of LegacyClient to NewClient under src/payments, keep public behavior unchanged, run npm test -- payments successfully, and stop after 20 turns if still failing

好的 goal 条件要包含三件事:

要素示例
可测终点npm test -- payments exits 0
证明方式“在最终回复中贴出测试命令和退出结果”
约束边界“不要修改数据库 schema,不要改公共 API”

管理命令:

1
2
/goal
/goal clear

注意:

  • 同一个 session 同时只能有一个 active goal。
  • /clear 会清掉 active goal。
  • --resume--continue 恢复会话时,未完成的 goal 会恢复,但计时和 token 基线会重新开始。
  • claude -p "/goal ..." 可以在非交互模式里跑到条件满足。
  • evaluator 不会自己读文件或跑命令,它只能判断对话里已经出现的证据。所以要让 Claude 把验证输出带回 transcript。

/loop:按间隔重复检查

/loop 适合“等外部状态变化”的场景,比如 CI、部署、PR review、长任务日志。它不是完成条件驱动,而是时间驱动。

固定间隔:

1
/loop 5m check if the deployment finished and summarize the latest status

让 Claude 自己决定下一次检查间隔:

1
/loop check whether CI passed and address any review comments

只输入 /loop 时,Claude 会运行内置维护提示:继续未完成工作、照看当前分支 PR、处理失败 CI 或 review comments;如果项目里有自定义 loop.md,会用它替代默认维护提示。

循环里也可以调用 Skill:

1
/loop 20m /review-pr 1234

使用边界:

  • /loop 是 session-scoped,适合开着当前终端做轮询。
  • 最小有效间隔按 cron 粒度约等于 1 分钟。
  • 动态间隔通常会在 1 分钟到 1 小时之间调整。
  • 如果要“直到某个条件满足”,优先用 /goal
  • 如果外部系统能主动通知,优先用 Channels,不要轮询。

/goal/loop、Stop hook 怎么选

机制下一轮何时开始何时停止适合
/goal上一轮结束后立即评估完成条件被模型确认有明确验收条件的长任务
/loop到达时间间隔你取消,或 Claude 判断无需继续轮询 CI、部署、PR 状态
Stop hook上一轮结束后执行 hook脚本或提示判断可结束团队级硬门禁、强制测试

我的经验:个人临时任务用 /goal,等待外部系统用 /loop,团队强约束用 Stop hook。它们可以组合,但不要一开始就叠满,否则排障会很烦。

Scheduled tasks、Routines 与 Channels

/loop 只是 session 内计划任务。Claude Code 还有更长生命周期的自动化:

能力运行位置是否需要机器开着适合
/loop当前 CLI session临时轮询
Desktop scheduled task本机桌面端需要本地文件和工具的定时任务
Cloud routineAnthropic 管理环境稳定、长期、跨设备的定时任务
GitHub ActionsGitHubCI 驱动的批处理
Channels当前 open sessionCI、聊天、监控主动推事件

/schedule 更适合创建独立计划任务;Channels 更适合事件驱动,例如 CI 失败时把日志推入当前会话,让 Claude 立即反应,而不是每 5 分钟轮询一次。

Dynamic workflows:把编排写成脚本

Dynamic workflow 是最新一层的“多代理编排”。它不是普通 prompt,也不是一个 subagent,而是 Claude 为任务生成一段 JavaScript workflow script,由 runtime 在后台执行。脚本负责循环、分支、聚合中间结果;主会话只接收最终报告或关键进度。

适合:

  • 全仓库 bug sweep。
  • 500 个文件级别的迁移。
  • 多角度研究和交叉验证。
  • 大设计方案的多路线评估。
  • 需要几十到上百个 agent 分片处理的任务。

不适合:

  • 小改动。
  • 同一个文件里的细腻重构。
  • 需要频繁人工确认的流程。
  • 成本敏感但没有明确切片边界的任务。

触发方式:

1
ultracode: audit every API endpoint under src/routes for missing auth checks

也可以自然语言要求:

1
Use a workflow to inspect all packages for deprecated Logger usage. Run agents by package, aggregate findings, and have verifier agents challenge the results before reporting.

查看和管理:

1
/workflows

保存复用:

  • 运行 /workflows
  • 选择一次成功的 run。
  • s 保存。
  • 保存到 .claude/workflows/ 供项目共享,或 ~/.claude/workflows/ 个人复用。
  • 之后像 slash command 一样调用:/triage-issues

可以把输入传给已保存 workflow:

1
Run /triage-issues on issues 1024, 1025, and 1030

成本和限制要记住:

  • workflow 可以并发很多 agent,token 花费会明显高。
  • workflow script 本身不直接读写文件或跑 shell,真正执行由 agent 完成。
  • 官方限制里单次 run 有并发和总 agent 数上限,用来防 runaway。
  • 先在一个目录或少量文件上试跑,再扩到全仓。
  • 如果公司不允许这类编排,可以在配置里禁用 Dynamic workflows。

组合工作流模板

PR 守护

1
2
3
/goal current branch PR has passing CI, all actionable review comments addressed, npm test exits 0, and final response includes the commands run

/loop 10m check PR CI and review comments; if new actionable comments appear, address them within the goal constraints

这个组合适合你去开会:/goal 负责终点,/loop 负责外部状态变化。

大迁移

1
2
3
4
5
6
7
8
ultracode: migrate all packages from LegacyLogger to StructuredLogger.

Plan:
- split work by package
- have each worker update usages and local tests
- run verifier agents to sample migrated packages
- aggregate failures into a fix list
- stop before committing or pushing

如果 migration 很机械,但范围大,用 Dynamic workflow 比在单会话里塞满上下文更稳。

失败 CI 响应

1
/loop check CI status for this branch. When a failure appears, read the failing job log, identify the smallest reproducible command, fix the root cause, and run the narrowest verification.

如果 CI 系统支持 Channels,把“失败事件 + 日志链接”直接推给 Claude,比 /loop 更省 token。

自治但有边界的修复

1
/goal fix the flaky test in auth-refresh.spec.ts, prove it by running the test 20 times locally, do not modify production code unless the root cause is production behavior, and stop after 15 turns if not solved

/goal 加 turn 或时间上限很重要。无人值守不是无限授权。

Skills

Skills 适合固化可复用流程。把“每次都要粘贴的一段工作方式”做成 Skill,而不是塞进 CLAUDE.md

什么时候用 Skill

用 Skill:

  • 代码审查 checklist。
  • 发布流程。
  • 数据库迁移流程。
  • 文档生成格式。
  • 项目专用排障步骤。

不用 Skill:

  • 稳定事实,比如项目使用 PostgreSQL。
  • 安全边界,比如不能读取 .env
  • 外部系统访问,比如查 Sentry 或 Linear。

示例:迁移审查 Skill

.claude/skills/migration-review/SKILL.md

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
---
name: migration-review
description: Review database migrations for safety, rollback, and production impact
---

Review the migration with this checklist:

1. Identify every schema and data change.
2. Check whether the migration is backward compatible.
3. Check whether long locks or full table scans may happen.
4. Verify rollback strategy.
5. Verify application code can run during rolling deploy.
6. Report findings as P0/P1/P2 with file references.

Do not edit files unless explicitly asked.

使用:

1
/migration-review review the current diff

新的 Claude Code 已经把旧的 custom commands 思路并入 Skills。.claude/commands/*.md 仍可用,但新建流程优先用 .claude/skills/<name>/SKILL.md

Subagents、Agent View 与 Agent Teams

Subagent 适合隔离探索

探索大仓库很容易污染主上下文。把探索交给子代理:

1
2
3
4
5
Use a subagent to investigate how token refresh works. Return only:
1. relevant files
2. call flow
3. edge cases
4. tests that cover it

子代理有自己的上下文,主会话只收到总结。

自定义子代理

.claude/agents/security-reviewer.md

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
---
name: security-reviewer
description: Review code for auth, injection, secret leakage, and unsafe defaults
tools: Read, Grep, Bash
model: opus
---

You are a security-focused code reviewer.

Focus on:
- authentication and authorization bypass
- injection risks
- secret handling
- unsafe deserialization
- SSRF and path traversal
- dangerous shell execution

Return findings with severity, file path, and concrete fix guidance.
Do not modify files.

调用:

1
Ask @security-reviewer to review the current diff

也可以让它成为主会话代理:

1
claude --agent security-reviewer

Forks 适合并行思考

/fork 会继承当前会话上下文,适合在不打断主线的情况下并行生成方案:

1
/fork draft unit tests for the parser changes so far

区别:

机制上下文适合
Subagent独立定义、独立上下文专业角色、隔离探索
Fork继承当前会话同一任务的并行分支

Agent View:后台会话看板

claude agents 是新的后台 agent 看板,适合同时派发多个彼此独立的任务:

1
claude agents

典型用法:

  • 一个 agent 查 flaky test。
  • 一个 agent 审 PR diff。
  • 一个 agent 做文档更新。
  • 你在看板里观察谁还在工作、谁需要输入、谁完成了。

在普通会话里可以把当前 session 放到后台:

1
/bg

然后回到 claude agents 看板。需要深入某个后台会话时,再 attach 进去继续对话。

Agent View 和 subagent 的关键区别:

机制你能否直接进入 worker 对话是否共享主会话上下文适合
Subagent否,通常只回传总结否,结果回到主会话隔离研究、专业角色
Agent View是,可以 attach各 session 独立多个独立任务并行

Agent Teams:多个 Claude 会话协作

Agent teams 是实验性能力,需要显式打开:

1
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1

它让一个 lead session 协调多个 Claude Code session:有共享任务列表、agent 间消息和独立上下文。它比 subagent 更重,适合“任务可以拆块,而且 worker 之间需要沟通”的场景。

适合:

  • 前端、后端、测试各自推进一个跨层 feature。
  • 多个假设并行调试,再互相挑战证据。
  • 研究和 review,让多个 agent 从不同角度找问题。
  • 新模块拆成多个相对独立的子任务。

不适合:

  • 多个 agent 同时改同一个文件。
  • 顺序依赖很强的迁移。
  • 成本敏感的小任务。
  • 需要你频繁做产品判断的设计过程。

并行能力选择表

能力粒度谁负责协调中间结果在哪里最适合
Subagent单 session 内 worker主 Claude子上下文,回传总结隔离探索、专项审查
Fork当前会话分支分支会话同一上下文下试不同方案
Agent View多个后台 session各自 session多个独立任务并行
Agent Teams多个协作 sessionLead agent共享任务列表和消息跨模块协作
Worktrees文件系统隔离你或 Claude独立 git checkout并行编辑不互相踩
Dynamic workflows脚本化 agent 编排Workflow script脚本变量和 runtime大规模分片、可复用编排

MCP

MCP 用来接外部工具和数据源。比如浏览器、GitHub、Sentry、Linear、数据库只读查询、内部知识库。

作用域

作用域命令存储位置适合
localclaude mcp add ...~/.claude.json 当前项目条目私人项目配置
userclaude mcp add --scope user ...~/.claude.json 顶层所有项目通用
projectclaude mcp add --scope project ....mcp.json团队共享

添加本地 stdio MCP

1
2
claude mcp add playwright -- npx -y @playwright/mcp@latest
claude mcp list

添加 HTTP MCP

1
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

需要 OAuth 的服务通常要进入会话后运行:

1
/mcp

MCP 排障

1
2
3
claude mcp list
claude mcp get <name>
claude mcp remove <name>

常见问题:

  • Pending approval:项目级 MCP 还没批准,进 /mcp 处理。
  • tools fetch failed:服务器连上了,但工具列表拉取失败,看 claude mcp get <name>
  • 启动超时:本地 stdio server 首次 npx 下载太慢,临时加大 MCP_TIMEOUT
  • .mcp.json 修改不生效:Claude Code 会话启动时读取,重启会话。

Hooks

Hooks 适合自动执行确定性的边界动作。它们可以在工具调用前后、通知、停止、子代理开始/结束等事件上触发。

典型用途:

  • 编辑后自动格式化。
  • Bash 执行前拦截危险命令。
  • Claude 等待输入时发系统通知。
  • 会话启动时注入动态上下文。
  • 子代理结束后跑审查脚本。

示例:编辑后自动格式化

.claude/settings.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npm run format -- --write"
}
]
}
]
}
}

真实项目里最好写成脚本,只格式化被修改文件,避免每次改一行都格式化全仓库。

示例:拦截危险 Bash

.claude/settings.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "./scripts/claude-guard-bash.sh"
}
]
}
]
}
}

scripts/claude-guard-bash.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env bash
set -euo pipefail

input="$(cat)"
command="$(printf '%s' "$input" | jq -r '.tool_input.command // empty')"

if printf '%s' "$command" | grep -Eq '(^|[;&|[:space:]])rm[[:space:]]+-rf[[:space:]]+/'; then
echo "Blocked dangerous rm -rf / command" >&2
exit 2
fi

if printf '%s' "$command" | grep -Eq 'git[[:space:]]+push|npm[[:space:]]+publish|kubectl[[:space:]]+apply'; then
echo "Blocked release/deploy command; ask the human explicitly." >&2
exit 2
fi

退出码 2 表示阻止该工具调用,并把错误信息反馈给 Claude。

Headless 与脚本化

非交互模式是高级玩家的分水岭。它让 Claude Code 变成 Unix pipeline 的一环。

普通管道

1
2
git diff main...HEAD | claude -p \
"Review this diff. Return only correctness bugs and missing tests."

JSON 输出

1
claude -p "Summarize this project" --output-format json | jq -r '.result'

JSON Schema 输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
claude -p "Extract risky files from this diff" \
--output-format json \
--json-schema '{
"type": "object",
"properties": {
"files": {
"type": "array",
"items": {
"type": "object",
"properties": {
"path": { "type": "string" },
"risk": { "type": "string" },
"reason": { "type": "string" }
},
"required": ["path", "risk", "reason"]
}
}
},
"required": ["files"]
}' | jq '.structured_output.files'

流式 JSON

1
2
3
4
claude -p "Explain this failing build" \
--output-format stream-json \
--verbose \
--include-partial-messages

适合接到自定义 UI、日志系统或长任务监控里。

CI 里的建议

  • 尽量把输入通过 stdin 或文件路径传入,减少 Claude 自己探索的自由度。
  • --output-format json,不要解析自然语言。
  • --allowedTools--disallowedTools 明确工具边界。
  • 对“只读审查”任务禁用编辑和写命令。
  • 记录 session_id、成本、模型信息,方便追踪。

大仓库工作流

从启动位置控制范围

在 monorepo 里,不要总在根目录启动:

1
2
cd apps/payments
claude

需要跨包时再加目录:

1
claude --add-dir ../../packages/db ../../packages/shared

稀疏工作树

跨模块大改时,让 Claude 在 worktree 里隔离执行,避免污染主工作区。可以配合仓库的 sparse checkout 策略,只签出必要目录。

先让它列改动面

1
2
3
4
5
6
Do not edit files yet. Find the minimal set of packages involved in adding OAuth refresh rotation.
Return:
- package list
- relevant entrypoints
- likely tests
- files you would not touch

让探索和实现分离

1
Use a subagent to map the billing module. Keep the main context clean. After that, propose the implementation plan.

代码审查模式

本地 diff 审查

1
/code-review

或:

1
2
git diff main...HEAD | claude -p \
"Review this diff. Prioritize correctness bugs, security issues, and missing tests. Return findings only."

好的审查提示

1
2
3
4
5
6
7
8
9
10
11
Review the current diff as a senior backend engineer.

Focus on:
1. correctness regressions
2. concurrency and transaction boundaries
3. authorization checks
4. migration safety
5. missing tests

Do not comment on style unless it affects behavior.
For every finding, include file path, exact code reference, impact, and a concrete fix.

审查要分两轮

第一轮只读找问题:

1
Do not edit files. Review the diff and list only actionable findings.

第二轮再修:

1
Fix P0 and P1 findings only. Leave P2 suggestions untouched.

调试模式

高效调试不要让 Claude “猜”。让它走证据链:

1
2
3
4
5
6
7
8
This test fails. Do not edit code yet.

Please:
1. run the smallest failing test
2. read the failure output
3. identify the first wrong assumption
4. inspect only the relevant code path
5. propose a fix with verification command

如果是间歇性问题:

1
2
3
4
5
6
7
This is flaky. Build a hypothesis table:
- hypothesis
- evidence for
- evidence against
- command to confirm or reject

Run only the cheapest confirmation first.

提示词模板

架构探索

1
2
3
4
5
6
7
8
9
Do not edit files.
Map the request lifecycle for <feature>.
Return a compact report with:
- entrypoints
- core domain objects
- external dependencies
- persistence layer
- tests
- risks for changing this area

小步实现

1
2
3
4
5
6
7
8
9
10
Implement <change>.

Constraints:
- preserve public API compatibility
- follow existing patterns
- keep the diff minimal
- add or update tests
- run the narrowest relevant test first

Stop and ask before changing database schema or public contracts.

重构

1
2
3
4
5
6
7
8
Refactor <component> without changing behavior.

Process:
1. characterize current behavior with tests or snapshots
2. make one mechanical change at a time
3. run tests after each meaningful step
4. keep public interfaces stable
5. summarize behavior-preserving evidence at the end

迁移

1
2
3
4
5
6
7
8
9
Plan this migration before editing:
- compatibility during rolling deploy
- data backfill strategy
- rollback strategy
- lock and runtime risk
- observability
- tests

Do not write migration files until the plan is approved.

常见故障排查

Claude 不遵守 CLAUDE.md

检查:

  • /memory 里是否加载了正确文件。
  • 规则是否太长、太泛、互相冲突。
  • 子目录是否有更具体的 CLAUDE.md
  • 规则是否应该改成权限 deny、Hook 或 Skill。

MCP 不出现

检查:

1
2
claude mcp list
claude mcp get <name>

如果是项目级 .mcp.json,进入会话跑 /mcp 看是否待批准。

会话越来越笨

通常是上下文污染:

  • /context 看消耗。
  • /compact 压缩。
  • 把探索交给 subagent。
  • 把稳定规则沉淀到 CLAUDE.md
  • 把重复流程沉淀到 Skill。
  • 用 deny 规则阻止读取无关目录。

它想改太多文件

打断并收窄:

1
2
3
Stop. Re-plan with the smallest possible diff.
List files that are truly necessary, and explain why each one must change.
Do not edit until I approve.

它反复跑昂贵命令

给验证策略:

1
2
3
4
Use this verification order:
1. run the single failing test
2. run the package test
3. run the full suite only after the package test passes

必要时用权限限制 full suite 或部署类命令。

我的推荐默认配置

CLAUDE.md

1
2
3
4
5
6
7
8
# Instructions

- Prefer minimal, behavior-preserving changes.
- Read existing patterns before adding abstractions.
- Do not edit generated files.
- Run the narrowest relevant test after each meaningful change.
- When uncertain, state the uncertainty and gather evidence before editing.
- For reviews, report correctness, security, and missing-test issues before style comments.

.claude/settings.local.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
"permissions": {
"allow": [
"Read",
"Edit",
"Bash(git status*)",
"Bash(git diff*)",
"Bash(git log*)",
"Bash(rg *)"
],
"deny": [
"Read(.env*)",
"Read(**/secrets/**)",
"Read(node_modules/**)",
"Read(dist/**)",
"Read(build/**)",
"Bash(rm -rf *)",
"Bash(git push*)",
"Bash(npm publish*)"
]
}
}

日常节奏

1
2
3
4
5
6
1. 让 Claude 先读局部代码,不改文件。
2. 要求它给最小改动计划。
3. 计划确认后执行。
4. 每个阶段跑窄测试。
5. 用 /diff 和 /code-review 做收尾。
6. 把新学到的稳定规则写回 CLAUDE.md 或 Skill。

参考资料