导语金句:你每天手动重复的那些任务,其实都可以交给一个子 Agent 自动完成——它不需要复杂配置,只需要一个 markdown 文件和 5 分钟。
一、为什么你的 Claude Code 会越用越慢
用 Claude Code 一段时间后,很多人会遇到一个问题:
刚开始对话很流畅,代码生成快、修改准、解释也清晰。
但聊到第 20 条消息以后,它开始变得“迟钝”了。
你让它改一行代码,它说要先读懂上下文;
你让它生成新功能,它说不确定当前状态;
你让它做代码审查,它开始给出模糊建议。
这不是 Claude 变笨了,而是上下文窗口被填满了。
一个 session 里,如果同时堆着:
- 项目文件列表
- 代码审查逻辑
- 测试运行过程
- Bug 修复记录
- 新功能生成内容
上下文会快速膨胀到几十万 tokens,模型开始 autocompact(自动压缩),之前的关键信息就会被“遗忘”。
这个问题的解法,就是子 Agent(Subagent)。
二、什么是子 Agent?
一个子 Agent,就是一个独立运行的 Claude 实例。
它有自己独立的上下文窗口,做一件聚焦的任务,然后把总结结果返回给主 session。
没有子 Agent 时:
你让 Claude 做代码审查,它需要:
- 读 40 个文件
- 搜索问题模式
- 生成修复代码
- 自己 review 自己的结果
- 运行测试
所有这些都在同一个 context 里进行。到了第 20 条消息,它已经记不住你最初的需求是什么了。
有子 Agent 时:
你把“代码审查”这件事委托给一个 reviewer 子 Agent。
这个 reviewer 在自己独立的 context 里工作,读文件、找问题、给结论。
它只返回一句总结:"发现 3 个问题,1 个严重,2 个建议修复。"
主 session 继续处理其他事情,context 始终保持精简。
三、子 Agent 文件的存放位置
在哪里放这些文件,决定了谁能用到它们。
个人通用(所有项目可用):
~/.claude/agents/
项目专用(团队共享,通过 git 管理):
.claude/agents/
两者的区别是,前者在你的本地所有项目都生效,后者可以提交到仓库和团队共享。
四、一个子 Agent 文件的完整结构
每个子 Agent 就是一个 markdown 文件,由两部分组成:YAML frontmatter(顶部配置)+ 系统提示词(主体内容)。
---
name: reviewer
description: 何时使用这个 Agent。写具体一点。
model: claude-sonnet-4-5
tools:
- Read
- Grep
- Glob
- Bash
---
你是一个[角色]。你的工作是[具体任务]。
调用时:
1. 执行[步骤 1]
2. 执行[步骤 2]
3. 返回[具体输出格式]
逐个字段解释:
- name:调用时用的名字,用 @reviewer 这样的方式
- description:Claude 用来判断何时自动委托的触发条件描述,要写得像“当用户要求代码审查时使用”
- model:路由到 Sonnet 做具体任务(比 Opus 便宜约 5 倍)
- tools:限制 Agent 能访问的操作。审查类用只读工具,写作类可以加写入权限
- markdown 主体:系统提示词,定义 Agent 的具体行为
五、模板一:代码审查子 Agent(5 分钟)
适用场景:检查代码质量、找 Bug、做上线前的安全审查。
创建文件:
.claude/agents/reviewer.md
完整模板:
---
name: reviewer
description: 专家级代码审查。当用户要求审查代码、检查 Bug 或对修改有疑问时使用。
model: claude-sonnet-4-5
tools:
- Read
- Grep
- Glob
- Bash
---
你是一位资深代码审查员。你的工作是找出 Bug、安全问题和代码质量问题。
调用时:
1. 运行 `git diff HEAD~1` 查看最近改动
2. 完整阅读修改的文件
3. 检查以下内容:
- 逻辑错误和边界值问题
- 缺失的 null/undefined 检查
- 安全问题(硬编码密钥、注入、XSS)
- 性能问题(N+1 查询、阻塞调用)
- 命名规范和可读性问题
输出格式:
## 审查总结
[1-2 句话的概述]
## 发现的问题
**严重:** [会导致生产环境出 Bug 的问题]
**警告:** [合并前应该修复的问题]
**建议:** [代码风格和可读性建议]
如果没有发现问题,说"代码质量良好"并解释原因。
不要提出不必要的修改建议。
使用方法:
check the last commit@reviewer
或者让 Claude 根据 description 自动委托,你说“review this code”,它就会自动调用 reviewer。
六、模板二:测试生成子 Agent(5 分钟)
适用场景:快速生成单元测试、提升测试覆盖率、为新功能补充测试用例。
创建文件:
.claude/agents/test-writer.md
完整模板:
---
name: test-writer
description: 为代码编写测试。当用户要求添加测试、提升覆盖率或编写单元/集成测试时使用。
model: claude-sonnet-4-5
tools:
- Read
- Grep
- Glob
- Write
- Bash
---
你是一位测试工程师。你的工作是为项目编写符合现有风格的测试用例。
调用时:
1. 找到项目中已有的测试文件,了解测试框架、导入方式和断言风格
2. 阅读需要测试的文件或模块
3. 编写覆盖以下场景的测试:
- 正常路径:预期输入的正常处理
- 边界情况:空值、null、零值、最大值
- 错误情况:无效输入、超时、数据缺失
- 异步行为(如适用)
4. 运行测试:npm test 或对应命令
5. 在返回前修复任何失败
只输出测试文件路径和覆盖范围说明。
不要修改源代码,只写测试。
使用方法:
@test-writer 为 src/lib/auth/session.ts 写测试@test-writer
七、模板三:文档生成子 Agent(5 分钟)
适用场景:生成函数文档、补充 JSDoc、编写 README 章节、输出 API 文档。
创建文件:
.claude/agents/doc-writer.md
完整模板:
---
name: doc-writer
description: 生成文档。当用户要求为代码添加文档、JSDoc、README 段落或 API 文档时使用。
model: claude-sonnet-4-5
tools:
- Read
- Grep
- Glob
- Write
---
你是一位文档专家。你的工作是为项目撰写清晰、简洁的文档,保持与项目现有风格一致。
调用时:
1. 阅读需要添加文档的文件或模块
2. 查看项目中现有文档风格
3. 函数类:添加描述、参数类型、返回值、用法示例
4. 复杂逻辑:添加注释解释"为什么",而不是"做了什么"
5. API 类:记录方法、路径、请求/响应结构、认证要求
规则:
- 严格匹配项目现有文档风格
- 简洁为主,代码自解释的部分跳过
- 不改变任何功能,只添加文档
- 如果代码本身难以理解,文档要注明并标记重构建议
使用方法:
@doc-writer 为 src/api/ 目录生成完整文档@doc
八、模板四:安全扫描子 Agent(5 分钟)
适用场景:上线前安全审计、检测密钥泄露、排查依赖漏洞。
创建文件:
.claude/agents/security.md
完整模板:
---
name: security
description: 安全审计。当用户要求检查漏洞、扫描密钥泄露或进行安全审计时使用。
model: claude-sonnet-4-5
tools:
- Read
- Grep
- Glob
- Bash
---
你是一位安全工程师。你的工作是在代码库中查找安全漏洞。
调用时:
1. 扫描硬编码密钥:
`grep -rn "sk-\|api_key\|password\|secret\|token" --include="*.ts" --include="*.js" --include="*.py" . | grep -v node_modules | grep -v ".env.example"`
2. 检查 SQL 注入(字符串拼接的查询语句)
3. 检查 XSS(未经过滤的用户输入进入 HTML)
4. 检查受保护路由是否缺少认证
5. 运行 npm audit 或等效命令检查依赖漏洞
6. 检查 .env 文件和密钥是否在 .gitignore 中
输出格式:
## 安全报告
**严重:** [可被利用的漏洞]
**高危:** [上线前必须修复的问题]
**中危:** [近期应该处理的问题]
**低危:** [未遵循最佳实践的地方]
每个问题注明:文件位置、行号、问题说明、修复建议。
只报告问题,不要自行修复。
使用方法:
@security 扫描整个代码库@security
九、模板五:PR 描述生成子 Agent(5 分钟)
适用场景:快速生成规范的 PR 描述、总结分支改动、准备 Code Review 材料。
创建文件:
.claude/agents/pr-writer.md
完整模板:
---
name: pr-writer
description: 撰写 PR 描述。当用户要求创建 Pull Request 描述、总结改动或准备 PR 时使用。
model: claude-sonnet-4-5
tools:
- Read
- Grep
- Glob
- Bash
---
你是一位 PR 描述专家。你的工作是撰写清晰、结构化的 Pull Request 描述,可以直接粘贴到 GitHub。
调用时:
1. 运行 `git log main..HEAD --oneline` 获取提交列表
2. 运行 `git diff main...HEAD --stat` 获取文件改动统计
3. 阅读关键改动文件,理解上下文
严格按以下格式输出:
## 做了什么
[一段话:描述这个 PR 做了什么]
## 为什么做
[一段话:解释这次改动的背景和原因]
## 主要改动
[按模块分组的改动列表]
## 测试方式
[这个 PR 是如何被测试的]
不需要额外内容。输出后可直接粘贴到 GitHub。
使用方法:
@pr-writer 总结这个分支的所有改动@pr
十、三种调用子 Agent 的方式
方式一:@ 提及(最可靠)
@reviewer check the last commit
@test-writer 为 auth.ts 写测试
@security 扫描 src/ 目录
方式二:自动委托
Claude 会读取每个子 Agent 的 description 字段,决定是否自动委托。
当你说出"review this code"时,Claude 看到 reviewer 的 description 包含"代码审查",就会自动调用它。
要让自动委托生效,description 必须写得具体。
✅ "Use this agent when the user asks for code review"
❌ "Code stuff"
方式三:/agents 命令
Claude Code 自带的子 Agent 管理命令:
/agents → 打开 Agent 管理界面
Running → 查看当前活跃的子 Agent
Library → 浏览、创建、编辑 Agent
十一、成本真相:子 Agent 真的省钱吗?
子 Agent 会在独立 context 里运行,这意味着会消耗 tokens。
但真正的收益不是省 token,而是保持主 session 精简。
不用子 Agent:
- 一个 session 处理所有事情
- 到第 20 条消息时 context 膨胀到 20 万 tokens
- 后续每条消息成本增加
- Autocompact 丢失重要上下文
用子 Agent:
- 主 session 保持在 3 万 tokens 左右
- 每个子 Agent 独立消耗 1.5-2 万 tokens
- 返回给主 session 的只是 500 字总结
- 总 token 量相近,但质量更高
还有一个关键技巧:
子 Agent 路由到 Sonnet,主 session 用 Opus。
在环境变量里加一行:
export CLAUDE_CODE_SUBAGENT_MODEL="claude-sonnet-4-5-20250929"
这样子 Agent 用 Sonnet(比 Opus 便宜约 5 倍),你的主 session 保持用 Opus 的推理能力。
十二、从哪个模板开始?
Copy 任意一个。
只需要 5 分钟创建文件,立刻就能用。
如果只选一个,推荐从 reviewer(代码审查) 开始。
在你的下一次代码提交之后,直接在 Claude Code 里输入:
@reviewer check the last commit
你会立刻看到结果。
一旦体验过让 Agent 替你审查代码这件事,你大概再也不会回到“自己 review 自己代码”的状态了。
结语:你的工作流,从今天开始不一样
子 Agent 不是高深的技术,也不是需要重度配置的工程系统。
它只是一个 markdown 文件。
你每天手动重复做的那些事——审查代码、写测试、补文档、扫描安全漏洞、写 PR 描述——都可以变成一句 @agent 命令。
15 分钟搭好一个,用一辈子。
当你有了 3-5 个常用的子 Agent,你的工作流会变成这样:
- 提交代码 →
@reviewer自动审查 - 写完功能 →
@test-writer自动补测试 - 准备上线 →
@security自动扫描 - 发起合并 →
@pr-writer自动生成描述
而你只需要做一件事:定义清楚你希望每个 Agent 做什么。
结尾金句:AI 编程的下半场,不是让一个模型干所有事,而是让多个专注的 Agent 各司其职,共同构建一个真正高效的工作流。
Lead-in sentence: The tasks you manually repeat every day can actually be automated by a sub-agent — it doesn’t need complex configuration, just a markdown file and 5 minutes.
I. Why Your Claude Code Slows Down Over Time
After using Claude Code for a while, many people encounter this problem:
At first, conversations are smooth — code generation is fast, edits are accurate, and explanations are clear.
But around message 20, it starts to feel sluggish.
You ask it to change a line of code, and it says it needs to read the context first; you ask for a new feature, and it’s unsure about the current state; you request a code review, and it gives vague advice.
This isn’t because Claude has gotten dumber — it’s because the context window is filling up.
In a single session, if you’ve accumulated:
Project file lists
Code review logic
Test run histories
Bug-fix records
New feature generation
The context can swell to hundreds of thousands of tokens. When that happens, the model starts autocompacting (compressing context), and key information from earlier becomes “forgotten.”
The solution to this problem is: Sub-agents.
II. What Are Sub-agents?
A sub-agent is an independent instance of Claude running separately.
It has its own context window, performs a focused task, and returns only the summary to the main session.
Without sub-agents:
When you ask Claude to review code, it needs to:
Read 40 files
Search for error patterns
Generate fixes
Review its own results
Run tests
All in one context. By message 20, it may not even remember what your original request was.
With sub-agents:
You delegate the “code review” task to a dedicated reviewer sub-agent.
That agent works in its own context, reads files, finds issues, and produces a conclusion.
It then returns a single summary line: “Found 3 issues: 1 critical, 2 suggested.”
The main session continues handling other tasks, while the context remains concise.
III. Where to Store Sub-Agent Files
The location of these files determines who can use them.
Personal Universal (Available for All Projects):
Project-Specific (Team Sharing via Git):
The difference between the two is that the former is active for all your local projects, while the latter can be committed to a repository for team sharing.
IV. The Complete Structure of a Sub-Agent File
Each sub-agent is a markdown file consisting of two parts: YAML frontmatter (top configuration) + System Prompt (main content).
Detailed Explanation of Fields:
name: The name used for invocation, such as @reviewer.
description: The trigger condition description that Claude uses to determine when to delegate automatically, phrased like "Use when the user requests code review".
model: Routes to Sonnet for the specific task (approx. 5 times cheaper than Opus).
tools: Limits the operations the agent can access. Read-only tools are used for reviews, while write permissions can be added for writing tasks.
markdown body: The system prompt defining the specific behavior of the agent.
V. Template One: Code Review Sub-Agent (5 minutes)
Use Case: Checking code quality, finding bugs, performing pre-deployment security reviews.
Create File:
Complete Template:
Usage:
Or let Claude automatically delegate based on the description — you say "review this code", and it will call the reviewer.
VI. Template Two: Test Generation Sub-Agent (5 minutes)
Use Case: Quickly generate unit tests, improve test coverage, and add test cases for new features.
Create File:
Complete Template:
Usage:
VII. Template Three: Documentation Generation Sub-Agent (5 minutes)
Use Case: Generate function documentation, supplement JSDoc, write README sections, and output API documentation.
Create File:
Complete Template:
Usage:
Eight, Template 4: Security Scan Sub-Agent (5 minutes)
Use case: Pre-launch security audit, detect key leakage, check for dependency vulnerabilities.
Create file:
Full template:
Usage:
Nine, Template 5: PR Description Generation Sub-Agent (5 minutes)
Use case: Quickly generate standard PR descriptions, summarize branch changes, prepare Code Review materials.
Create file:
Full template:
Usage:
Ten, Three Ways to Call Sub-Agents
Method 1: @ Mention (Most Reliable)
Method 2: Automatic Delegation
Claude reads the description field of each sub-agent to decide whether to delegate automatically.
When you say "review this code", Claude sees that the reviewer's description includes "code review" and will automatically call it.
For automatic delegation to work, the description must be written specifically.
Method 3: /agents Command
Claude Code's built-in sub-agent management command:
Eleven, Cost Truth: Do Sub-Agents Really Save Money?
Sub-agents run in independent contexts, meaning they consume tokens.
But the real benefit is not saving tokens, but keeping the main session streamlined.
Without sub-agents:
One session handles everything
By message 20, context inflates to 200,000 tokens
Cost of subsequent messages increases
Autocompact loses important context
With sub-agents:
Main session stays around 30,000 tokens
Each sub-agent independently consumes 15,000-20,000 tokens
Only a 500-word summary is returned to the main session
Total token usage is similar, but quality is higher.
There's a key trick:
Route sub-agents to Sonnet, use Opus for the main session.
Add this line to your environment variables:
This allows sub-agents to use Sonnet (cheaper by ~5x than Opus) while maintaining Opus-level reasoning in your main session.
XII. Where to start?
Copy any template.
It takes only 5 minutes to create a file and start using it.
If you must choose one, start with the reviewer (code review).
After your next code commit, simply type in Claude Code:
You'll see results immediately.
Once you experience an agent reviewing your code for you, you likely won't go back to reviewing your own code manually.
Conclusion: Your workflow changes today
Sub-agents aren't complex engineering or heavy-duty configuration.
They're just markdown files.
The repetitive tasks you do daily — reviewing code, writing tests, updating docs, scanning security, writing PR descriptions — can all become @agent commands.
Set up one in 15 minutes, use it for a lifetime.
With 3-5 common sub-agents, your workflow will look like this:
Commit code → @reviewer auto-reviews
Finish feature → @test-writer auto-writes tests
Ready to deploy → @security auto-scans
Initiate merge → @pr-writer auto-generates description
Your only task: Clearly define what each agent should do.
Final thought: The next phase of AI programming isn't one model doing everything, but multiple specialized agents working together to build a truly efficient workflow.