sub-agent-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Sub-Agents in Claude Code

Claude Code中的子代理

Status: Production Ready ✅ Last Updated: 2026-02-02 Source: https://code.claude.com/docs/en/sub-agents
Sub-agents are specialized AI assistants that Claude Code can delegate tasks to. Each sub-agent has its own context window, configurable tools, and custom system prompt.

状态:已就绪可投入生产 ✅ 最后更新:2026-02-02 来源https://code.claude.com/docs/en/sub-agents
子代理是Claude Code可以将任务委托给的专业AI助手。每个子代理都有自己的上下文窗口、可配置工具和自定义系统提示。

Why Use Sub-Agents: Context Hygiene

为何使用子代理:上下文整洁性

The primary value of sub-agents isn't specialization—it's keeping your main context clean.
Without agent (context bloat):
Main context accumulates:
├─ git status output (50 lines)
├─ npm run build output (200 lines)
├─ tsc --noEmit output (100 lines)
├─ wrangler deploy output (100 lines)
├─ curl health check responses
├─ All reasoning about what to do next
└─ Context: 📈 500+ lines consumed
With agent (context hygiene):
Main context:
├─ "Deploy to cloudflare"
├─ [agent summary - 30 lines]
└─ Context: 📊 ~50 lines consumed

Agent context (isolated):
├─ All verbose tool outputs
├─ All intermediate reasoning
└─ Discarded after returning summary
The math: A deploy workflow runs ~10 tool calls. That's 500+ lines in main context vs 30-line summary with an agent. Over a session, this compounds dramatically.
When this matters most:
  • Repeatable workflows (deploy, migrate, audit, review)
  • Verbose tool outputs (build logs, test results, API responses)
  • Multi-step operations where only the final result matters
  • Long sessions where context pressure builds up
Key insight: Use agents for workflows you repeat, not just for specialization. The context savings compound over time.

子代理的核心价值并非专业化——而是保持主对话上下文的整洁
不使用代理时(上下文膨胀):
主上下文累积内容:
├─ git status 输出(50行)
├─ npm run build 输出(200行)
├─ tsc --noEmit 输出(100行)
├─ wrangler deploy 输出(100行)
├─ curl 健康检查响应
├─ 关于下一步操作的所有推理过程
└─ 上下文占用:📈 500+行
使用代理时(上下文整洁):
主上下文:
├─ "部署至Cloudflare"
├─ [代理摘要 - 30行]
└─ 上下文占用:📊 ~50行

代理独立上下文:
├─ 所有冗长的工具输出
├─ 所有中间推理过程
└─ 返回摘要后即被丢弃
数据对比:一个部署工作流约执行10次工具调用。不使用代理时主上下文占用500+行,使用代理时仅需30行摘要。在整个会话过程中,这种上下文节省会显著累积。
最能体现价值的场景
  • 可重复工作流(部署、迁移、审计、评审)
  • 冗长的工具输出(构建日志、测试结果、API响应)
  • 仅最终结果重要的多步骤操作
  • 上下文压力逐渐增大的长会话
核心见解:将代理用于你重复执行的工作流,而不仅仅是专业化场景。上下文节省会随着时间推移持续累积。

Built-in Sub-Agents

内置子代理

Claude Code includes three built-in sub-agents available out of the box:
Claude Code包含三个开箱即用的内置子代理:

Explore Agent

Explore Agent

Fast, lightweight agent optimized for read-only codebase exploration.
PropertyValue
ModelHaiku (fast, low-latency)
ModeStrictly read-only
ToolsGlob, Grep, Read, Bash (read-only: ls, git status, git log, git diff, find, cat, head, tail)
Thoroughness levels (specify when invoking):
  • quick
    - Fast searches, targeted lookups
  • medium
    - Balanced speed and thoroughness
  • very thorough
    - Comprehensive analysis across multiple locations
When Claude uses it: Searching/understanding codebase without making changes. Findings don't bloat the main conversation.
User: Where are errors from the client handled?
Claude: [Invokes Explore with "medium" thoroughness]
       → Returns: src/services/process.ts:712
快速、轻量型代理,针对只读代码库探索进行优化。
属性
模型Haiku(快速、低延迟)
模式严格只读
工具Glob、Grep、Read、Bash(只读命令:ls、git status、git log、git diff、find、cat、head、tail)
细致度级别(调用时可指定):
  • quick
    - 快速搜索、定向查找
  • medium
    - 速度与细致度平衡
  • very thorough
    - 跨多位置的全面分析
Claude的使用场景:无需修改代码即可搜索/理解代码库。发现结果不会使主对话上下文膨胀。
用户:客户端错误在哪里处理?
Claude:[以"medium"细致度调用Explore代理]
       → 返回结果:src/services/process.ts:712

Plan Agent

Plan Agent

Specialized for plan mode research and information gathering.
PropertyValue
ModelSonnet
ModeRead-only research
ToolsRead, Glob, Grep, Bash
InvocationAutomatic in plan mode
When Claude uses it: In plan mode when researching codebase to create a plan. Prevents infinite nesting (sub-agents cannot spawn sub-agents).
专门针对计划模式研究和信息收集的代理。
属性
模型Sonnet
模式只读研究
工具Read、Glob、Grep、Bash
调用方式在计划模式下自动触发
Claude的使用场景:在计划模式下研究代码库以制定计划时使用。防止无限嵌套(子代理无法生成子代理)。

General-Purpose Agent

通用型代理

Capable agent for complex, multi-step tasks requiring both exploration AND action.
PropertyValue
ModelSonnet
ModeRead AND write
ToolsAll tools
PurposeComplex research, multi-step operations, code modifications
When Claude uses it:
  • Task requires both exploration and modification
  • Complex reasoning needed to interpret search results
  • Multiple strategies may be needed
  • Task has multiple dependent steps

适用于需要同时进行探索和操作的复杂多步骤任务的全能代理。
属性
模型Sonnet
模式可读可写
工具所有工具
用途复杂研究、多步骤操作、代码修改
Claude的使用场景
  • 任务需要同时进行探索和修改
  • 需要复杂推理来解读搜索结果
  • 可能需要多种策略
  • 任务包含多个依赖步骤

Creating Custom Sub-Agents

创建自定义子代理

File Locations

文件位置

TypeLocationScopePriority
Project
.claude/agents/
Current project onlyHighest
User
~/.claude/agents/
All projectsLower
CLI
--agents '{...}'
Current sessionMiddle
When names conflict, project-level takes precedence.
⚠️ CRITICAL: Session Restart Required
Agents are loaded at session startup only. If you create new agent files during a session:
  1. They won't appear in
    /agents
  2. Claude won't be able to invoke them
  3. Solution: Restart Claude Code session to discover new agents
This is the most common reason custom agents "don't work" - they were created after the session started.
类型位置作用范围优先级
项目级
.claude/agents/
仅当前项目最高
用户级
~/.claude/agents/
所有项目较低
CLI级
--agents '{...}'
当前会话中等
当名称冲突时,项目级代理优先。
⚠️ 重要提示:需重启会话
代理仅在会话启动时加载。如果在会话期间创建新的代理文件:
  1. 它们不会出现在
    /agents
    列表中
  2. Claude无法调用它们
  3. 解决方案:重启Claude Code会话以识别新代理
这是自定义代理“无法工作”的最常见原因——它们是在会话启动后创建的。

File Format

文件格式

Markdown files with YAML frontmatter:
yaml
---
name: code-reviewer
description: Expert code reviewer. Use proactively after code changes.
tools: Read, Grep, Glob, Bash
model: inherit
permissionMode: default
skills: project-workflow
hooks:
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "./scripts/run-linter.sh"
---

Your sub-agent's system prompt goes here.

Include specific instructions, best practices, and constraints.
带有YAML前置元数据的Markdown文件:
yaml
---
name: code-reviewer
description: 专业代码评审员。在代码变更后主动使用。
tools: Read, Grep, Glob, Bash
model: inherit
permissionMode: default
skills: project-workflow
hooks:
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "./scripts/run-linter.sh"
---

你的子代理系统提示内容写在这里。

包含具体说明、最佳实践和约束条件。

Configuration Fields

配置字段

FieldRequiredDescription
name
YesUnique identifier (lowercase, hyphens)
description
YesWhen Claude should use this agent
tools
NoComma-separated list. Omit entirely = inherit ALL tools (including MCP)
model
No
sonnet
,
opus
,
haiku
, or
inherit
. Default: sonnet
permissionMode
No
default
,
acceptEdits
,
dontAsk
,
bypassPermissions
,
plan
,
ignore
skills
NoComma-separated skills to auto-load (sub-agents don't inherit parent skills)
hooks
No
PreToolUse
,
PostToolUse
,
Stop
event handlers
字段是否必填描述
name
唯一标识符(小写、连字符分隔)
description
Claude应使用此代理的场景
tools
逗号分隔的工具列表。完全省略 = 继承所有工具(包括MCP)
model
sonnet
opus
haiku
inherit
。默认值:sonnet
permissionMode
default
acceptEdits
dontAsk
bypassPermissions
plan
ignore
skills
自动加载的技能列表(逗号分隔,子代理不继承父代理技能)
hooks
PreToolUse
PostToolUse
Stop
事件处理器

MCP Tool Inheritance (CRITICAL)

MCP工具继承(关键)

To access MCP tools from a sub-agent, you MUST omit the
tools
field entirely.
When you specify ANY tools in the
tools
field, it becomes an allowlist. There is no wildcard syntax.
yaml
undefined
要让子代理访问MCP工具,必须完全省略
tools
字段。
当你在
tools
字段中指定任何工具时,它将成为一个允许列表。不支持通配符语法。
yaml
undefined

❌ WRONG - "" is interpreted literally as a tool named "", not a wildcard

❌ 错误 - ""会被字面解析为名为""的工具,而非通配符

tools: Read, Grep, Glob, "*"
tools: Read, Grep, Glob, "*"

❌ WRONG - this is an allowlist, agent cannot access MCP tools

❌ 错误 - 这是允许列表,代理无法访问MCP工具

tools: Read, Grep, Glob
tools: Read, Grep, Glob

✅ CORRECT - omit tools field entirely to inherit ALL tools including MCP

✅ 正确 - 完全省略tools字段以继承所有工具(包括MCP)

tools field omitted

tools字段已省略

model: sonnet

**Key insight**: The `"*"` is NOT valid wildcard syntax. When parsed, it's treated as a literal tool name that doesn't exist.

**Agent restart required**: Changes to agent config files only take effect after restarting Claude Code session.
model: sonnet

**核心见解**:`"*"`不是有效的通配符语法。解析时会被视为一个不存在的字面工具名称。

**需重启代理**:代理配置文件的修改仅在重启Claude Code会话后生效。

Available Tools Reference

可用工具参考

Complete list of tools that can be assigned to sub-agents:
ToolPurposeType
ReadRead files (text, images, PDFs, notebooks)Read-only
WriteCreate or overwrite filesWrite
EditExact string replacements in filesWrite
MultiEditBatch edits to single fileWrite
GlobFile pattern matching (
**/*.ts
)
Read-only
GrepContent search with regex (ripgrep)Read-only
LSList directory contentsRead-only
BashExecute shell commandsExecute
BashOutputGet output from background shellsExecute
KillShellTerminate background shellExecute
TaskSpawn sub-agentsOrchestration
WebFetchFetch and analyze web contentWeb
WebSearchSearch the webWeb
TodoWriteCreate/manage task listsOrganization
TodoReadRead current task listOrganization
NotebookReadRead Jupyter notebooksNotebook
NotebookEditEdit Jupyter notebook cellsNotebook
AskUserQuestionInteractive user questionsUI
EnterPlanModeEnter planning modePlanning
ExitPlanModeExit planning mode with planPlanning
SkillExecute skills in conversationSkills
LSPLanguage Server Protocol integrationAdvanced
MCPSearchMCP tool discoveryAdvanced
Tool Access Patterns by Agent Type:
Agent TypeRecommended ToolsNotes
Read-only reviewers
Read, Grep, Glob, LS
No write capability
File creators
Read, Write, Edit, Glob, Grep
⚠️ No Bash - avoids approval spam
Script runners
Read, Write, Edit, Glob, Grep, Bash
Use when CLI execution needed
Research agents
Read, Grep, Glob, WebFetch, WebSearch
Read-only external access
Documentation
Read, Write, Edit, Glob, Grep, WebFetch
No Bash for cleaner workflow
Orchestrators
Read, Grep, Glob, Task
Minimal tools, delegates to specialists
Full accessOmit
tools
field (inherits all)
Use sparingly
⚠️ Tool Access Principle: If an agent doesn't need Bash, don't give it Bash. Each bash command requires approval, causing workflow interruptions. See "Avoiding Bash Approval Spam" below.
可分配给子代理的完整工具列表:
工具用途类型
Read读取文件(文本、图片、PDF、笔记本)只读
Write创建或覆盖文件写入
Edit文件中的精确字符串替换写入
MultiEdit单个文件的批量编辑写入
Glob文件模式匹配(
**/*.ts
只读
Grep正则表达式内容搜索(ripgrep)只读
LS列出目录内容只读
Bash执行shell命令执行
BashOutput获取后台shell的输出执行
KillShell终止后台shell执行
Task生成子代理编排
WebFetch获取并分析网页内容网络
WebSearch网页搜索网络
TodoWrite创建/管理任务列表组织
TodoRead读取当前任务列表组织
NotebookRead读取Jupyter笔记本笔记本
NotebookEdit编辑Jupyter笔记本单元格笔记本
AskUserQuestion交互式用户提问UI
EnterPlanMode进入计划模式规划
ExitPlanMode退出计划模式并返回计划规划
Skill在对话中执行技能技能
LSP语言服务器协议集成高级
MCPSearchMCP工具发现高级
按代理类型划分的工具访问模式:
代理类型推荐工具说明
只读评审员
Read, Grep, Glob, LS
无写入权限
文件创建者
Read, Write, Edit, Glob, Grep
⚠️ 不要提供Bash - 避免频繁的审批请求
脚本运行器
Read, Write, Edit, Glob, Grep, Bash
需要执行CLI命令时使用
研究代理
Read, Grep, Glob, WebFetch, WebSearch
只读外部访问
文档处理
Read, Write, Edit, Glob, Grep, WebFetch
不使用Bash以简化工作流
编排器
Read, Grep, Glob, Task
最小化工具集,将任务委托给专业代理
全权限省略
tools
字段(继承所有工具)
谨慎使用
⚠️ 工具访问原则:如果代理不需要Bash,就不要提供Bash。每个bash命令都需要用户审批,会导致工作流中断。请参阅下文“避免Bash审批请求泛滥”。

Avoiding Bash Approval Spam (CRITICAL)

避免Bash审批请求泛滥(关键)

When sub-agents have Bash in their tools list, they often default to using
cat > file << 'EOF'
heredocs for file creation instead of the Write tool. Each unique bash command requires user approval, causing:
  • Dozens of approval prompts per agent run
  • Slow, frustrating workflow
  • Hard to review (heredocs are walls of minified content)
Root Causes:
  1. Models default to bash for file ops - Training data bias toward shell commands
  2. Bash in tools list = Bash gets used - Even if Write tool is available
  3. Instructions get buried - A "don't use bash" rule at line 300 of a 450-line prompt gets ignored
Solutions (in order of preference):
  1. Remove Bash from tools list (if not needed):
    yaml
    # Before - causes approval spam
    tools: Read, Write, Edit, Glob, Grep, Bash
    
    # After - clean file operations
    tools: Read, Write, Edit, Glob, Grep
    If the agent only creates files, it doesn't need Bash. The orchestrator can run necessary scripts after.
  2. Put critical instructions FIRST (immediately after frontmatter):
    markdown
    ---
    name: site-builder
    tools: Read, Write, Edit, Glob, Grep
    model: sonnet
    ---
    
    ## ⛔ CRITICAL: USE WRITE TOOL FOR ALL FILES
    
    **You do NOT have Bash access.** Create ALL files using the **Write tool**.
    
    ---
    
    [rest of prompt...]
    Instructions at the top get followed. Instructions buried 300 lines deep get ignored.
  3. Remove contradictory instructions:
    markdown
    # BAD - contradictory
    Line 75: "Copy images with `cp -r intake/images/* build/images/`"
    Line 300: "NEVER use cp, mkdir, cat, or echo"
    
    # GOOD - consistent
    Only mention the pattern you want used. Remove all bash examples if you want Write tool.
When to keep Bash:
  • Agent needs to run external CLIs (wrangler, npm, git)
  • Agent needs to execute scripts
  • Agent needs to check command outputs
Testing: Before vs after removing Bash:
  • Before (with Bash): 11+ heredoc approval prompts, wrong patterns applied
  • After (no Bash): Mostly Write tool usage, correct patterns, minimal prompts
当子代理的工具列表包含Bash时,它们通常会默认使用
cat > file << 'EOF'
heredoc语法创建文件,而非使用Write工具。每个唯一的bash命令都需要用户审批,导致:
  • 每次代理运行都会出现数十个审批提示
  • 工作流缓慢、令人沮丧
  • 难以评审(heredoc是大量压缩内容)
根本原因
  1. 模型默认使用bash进行文件操作 - 训练数据偏向shell命令
  2. 工具列表包含Bash = 会被使用 - 即使Write工具可用
  3. 说明被忽略 - 450行提示中第300行的“不要使用bash”规则会被忽略
解决方案(按优先级排序):
  1. 从工具列表中移除Bash(如果不需要):
    yaml
    # 修改前 - 导致审批请求泛滥
    tools: Read, Write, Edit, Glob, Grep, Bash
    
    # 修改后 - 简洁的文件操作
    tools: Read, Write, Edit, Glob, Grep
    如果代理仅需创建文件,则不需要Bash。编排器可在之后运行必要的脚本。
  2. 将关键说明放在最前面(紧跟前置元数据):
    markdown
    ---
    name: site-builder
    tools: Read, Write, Edit, Glob, Grep
    model: sonnet
    ---
    
    ## ⛔ 重要提示:所有文件操作使用Write工具
    
    **你没有Bash访问权限**。所有文件创建必须使用**Write工具**
    ---
    
    [其余提示内容...]
    顶部的说明会被遵循,而埋在300行后的说明会被忽略。
  3. 移除矛盾的说明
    markdown
    # 错误示例 - 矛盾
    第75行:"使用`cp -r intake/images/* build/images/`复制图片"
    第300行:"永远不要使用cp、mkdir、cat或echo"
    
    # 正确示例 - 一致
    仅提及你希望使用的模式。如果希望使用Write工具,移除所有bash示例。
何时保留Bash:
  • 代理需要运行外部CLI(wrangler、npm、git)
  • 代理需要执行脚本
  • 代理需要检查命令输出
测试对比:移除Bash前后的差异:
  • 移除前(含Bash):11+次heredoc审批提示,应用了错误模式
  • 移除后(无Bash):主要使用Write工具,模式正确,提示极少

Using /agents Command (Recommended)

使用/agents命令(推荐)

/agents
Interactive menu to:
  • View all sub-agents (built-in, user, project)
  • Create new sub-agents with guided setup
  • Edit existing sub-agents and tool access
  • Delete custom sub-agents
  • See which sub-agents are active
/agents
交互式菜单,可用于:
  • 查看所有子代理(内置、用户级、项目级)
  • 通过引导式设置创建新代理
  • 编辑现有代理和工具访问权限
  • 删除自定义代理
  • 查看哪些代理处于活动状态

CLI Configuration

CLI配置

bash
claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

bash
claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

Using Sub-Agents

使用子代理

Automatic Delegation

自动委托

Claude proactively delegates based on:
  • Task description in your request
  • description
    field in sub-agent config
  • Current context and available tools
Tip: Include "use PROACTIVELY" or "MUST BE USED" in description for more automatic invocation.
Claude会根据以下因素主动委托任务:
  • 你的请求中的任务描述
  • 子代理配置中的
    description
    字段
  • 当前上下文和可用工具
提示:在描述中包含“主动使用”或“必须使用”可提高自动调用的概率。

Explicit Invocation

显式调用

> Use the test-runner subagent to fix failing tests
> Have the code-reviewer subagent look at my recent changes
> Ask the debugger subagent to investigate this error
> 使用test-runner子代理修复失败的测试
> 让code-reviewer子代理检查我最近的变更
> 请debugger子代理调查此错误

Resumable Sub-Agents

可恢复子代理

Sub-agents can be resumed to continue previous conversations:
undefined
子代理可恢复以继续之前的对话:
undefined

Initial invocation

初始调用

Use the code-analyzer agent to review the auth module [Agent completes, returns agentId: "abc123"]
使用code-analyzer代理评审auth模块 [代理完成,返回agentId: "abc123"]

Resume with full context

恢复完整上下文

Resume agent abc123 and now analyze the authorization logic

**Use cases**:
- Long-running research across multiple sessions
- Iterative refinement without losing context
- Multi-step workflows with maintained context
恢复代理abc123并分析授权逻辑

**适用场景**:
- 跨多个会话的长期研究
- 不丢失上下文的迭代优化
- 保持上下文的多步骤工作流

Disabling Sub-Agents

禁用子代理

Add to settings.json permissions:
json
{
  "permissions": {
    "deny": ["Task(Explore)", "Task(Plan)"]
  }
}
Or via CLI:
bash
claude --disallowedTools "Task(Explore)"

在settings.json权限中添加:
json
{
  "permissions": {
    "deny": ["Task(Explore)", "Task(Plan)"]
  }
}
或通过CLI:
bash
claude --disallowedTools "Task(Explore)"

Agent Orchestration

代理编排

Sub-agents can invoke other sub-agents, enabling sophisticated orchestration patterns. This is accomplished by including the
Task
tool in an agent's tool list.
子代理可以调用其他子代理,实现复杂的编排模式。这通过在代理的工具列表中包含
Task
工具来实现。

How It Works

工作原理

When a sub-agent has access to the
Task
tool, it can:
  • Spawn other sub-agents (built-in or custom)
  • Coordinate parallel work across specialists
  • Chain agents for multi-phase workflows
yaml
---
name: orchestrator
description: Orchestrator agent that coordinates other specialized agents. Use for complex multi-phase tasks.
tools: Read, Grep, Glob, Task  # ← Task tool enables agent spawning
model: sonnet
---
当子代理有权访问
Task
工具时,它可以:
  • 生成其他子代理(内置或自定义)
  • 协调跨专业代理的并行工作
  • 为多阶段工作流链式调用代理
yaml
---
name: orchestrator
description: 协调其他专业代理的编排器代理。用于复杂的多阶段任务。
tools: Read, Grep, Glob, Task  # ← Task工具启用代理生成功能
model: sonnet
---

Orchestrator Pattern

编排器模式

yaml
---
name: release-orchestrator
description: Coordinates release preparation by delegating to specialized agents. Use before releases.
tools: Read, Grep, Glob, Bash, Task
---

You are a release orchestrator. When invoked:

1. Use Task tool to spawn code-reviewer agent
   → Review all uncommitted changes

2. Use Task tool to spawn test-runner agent
   → Run full test suite

3. Use Task tool to spawn doc-validator agent
   → Check documentation is current

4. Collect all reports and synthesize:
   - Blockers (must fix before release)
   - Warnings (should address)
   - Ready to release: YES/NO

Spawn agents in parallel when tasks are independent.
Wait for all agents before synthesizing final report.
yaml
---
name: release-orchestrator
description: 通过委托给专业代理来协调发布准备工作。发布前使用。
tools: Read, Grep, Glob, Bash, Task
---

你是发布编排器。调用时:

1. 使用Task工具生成code-reviewer代理
   → 评审所有未提交的变更

2. 使用Task工具生成test-runner代理
   → 运行完整测试套件

3. 使用Task工具生成doc-validator代理
   → 检查文档是否为最新版本

4. 收集所有报告并综合:
   - 阻塞问题(发布前必须修复)
   - 警告(应解决)
   - 是否可发布:是/否

任务独立时并行生成代理。
综合最终报告前等待所有代理完成。

Practical Examples

实际示例

Multi-Specialist Workflow:
User: "Prepare this codebase for production"

orchestrator agent:
  ├─ Task(code-reviewer) → Reviews code quality
  ├─ Task(security-auditor) → Checks for vulnerabilities
  ├─ Task(performance-analyzer) → Identifies bottlenecks
  └─ Synthesizes findings into actionable report
Parallel Research:
User: "Compare these 5 frameworks for our use case"

research-orchestrator:
  ├─ Task(general-purpose) → Research framework A
  ├─ Task(general-purpose) → Research framework B
  ├─ Task(general-purpose) → Research framework C
  ├─ Task(general-purpose) → Research framework D
  ├─ Task(general-purpose) → Research framework E
  └─ Synthesizes comparison matrix with recommendation
多专业工作流:
用户:"准备此代码库以投入生产"

编排器代理:
  ├─ Task(code-reviewer) → 评审代码质量
  ├─ Task(security-auditor) → 检查漏洞
  ├─ Task(performance-analyzer) → 识别瓶颈
  └─ 将发现结果综合为可执行报告
并行研究:
用户:"比较这5个框架是否适合我们的使用场景"

研究编排器:
  ├─ Task(general-purpose) → 研究框架A
  ├─ Task(general-purpose) → 研究框架B
  ├─ Task(general-purpose) → 研究框架C
  ├─ Task(general-purpose) → 研究框架D
  ├─ Task(general-purpose) → 研究框架E
  └─ 综合对比矩阵并给出推荐

Nesting Depth

嵌套深度

LevelExampleStatus
1Claude → orchestrator✅ Works
2orchestrator → code-reviewer✅ Works
3code-reviewer → sub-task⚠️ Works but context gets thin
4+Deeper nesting❌ Not recommended
Best practice: Keep orchestration to 2 levels deep. Beyond that, context windows shrink and coordination becomes fragile.
层级示例状态
1Claude → 编排器✅ 正常工作
2编排器 → code-reviewer✅ 正常工作
3code-reviewer → 子任务⚠️ 可工作但上下文受限
4+更深嵌套❌ 不推荐
最佳实践:将编排限制在2层深度。超过此深度后,上下文窗口会缩小,协调会变得不稳定。

When to Use Orchestration

何时使用编排

Use OrchestrationUse Direct Delegation
Complex multi-phase workflowsSingle specialist task
Need to synthesize from multiple sourcesSimple audit or review
Parallel execution importantSequential is fine
Different specialists requiredSame agent type
使用编排使用直接委托
复杂的多阶段工作流单一专业任务
需要从多个来源综合结果简单审计或评审
并行执行很重要顺序执行即可
需要不同专业的代理同一类型代理即可

Orchestrator vs Direct Delegation

编排器 vs 直接委托

Direct (simpler, often sufficient):
User: "Review my code changes"
Claude: [Invokes code-reviewer agent directly]
Orchestrated (when coordination needed):
User: "Prepare release"
Claude: [Invokes release-orchestrator]
        orchestrator: [Spawns code-reviewer, test-runner, doc-validator]
        orchestrator: [Synthesizes all reports]
        [Returns comprehensive release readiness report]
直接委托(更简单,通常足够):
用户:"评审我的代码变更"
Claude:[直接调用code-reviewer代理]
编排(需要协调时):
用户:"准备发布"
Claude:[调用release-orchestrator]
        编排器:[生成code-reviewer、test-runner、doc-validator]
        编排器:[综合所有报告]
        [返回全面的发布就绪报告]

Configuration Notes

配置注意事项

  1. Tool access propagates: An orchestrator with
    Task
    can spawn any agent the session has access to
  2. Model inheritance: Spawned agents use their configured model (or inherit if set to
    inherit
    )
  3. Context isolation: Each spawned agent has its own context window
  4. Results bubble up: Orchestrator receives agent results and can synthesize them

  1. 工具访问会传递:拥有
    Task
    工具的编排器可以生成会话有权访问的任何代理
  2. 模型继承:生成的代理使用其配置的模型(如果设置为
    inherit
    则继承)
  3. 上下文隔离:每个生成的代理都有自己的上下文窗口
  4. 结果向上传递:编排器接收代理结果并可进行综合

Advanced Patterns

高级模式

Background Agents (Async Delegation)

后台代理(异步委托)

Send agents to the background while continuing work in your main session:
Ctrl+B during agent execution moves it to background.
> Use the research-agent to analyze these 10 frameworks
[Agent starts working...]
[Press Ctrl+B]
→ Agent continues in background
→ Main session free for other work
→ Check results later with: "What did the research agent find?"
Use cases:
  • Long-running research tasks
  • Parallel documentation fetching
  • Non-blocking code reviews
将代理移至后台,同时在主会话中继续工作:
代理执行期间按Ctrl+B将其移至后台。
> 使用research-agent分析这10个框架
[代理开始工作...]
[按Ctrl+B]
→ 代理在后台继续工作
→ 主会话可自由处理其他工作
→ 稍后使用以下命令查看结果:"research-agent发现了什么?"
适用场景
  • 长期研究任务
  • 并行文档获取
  • 非阻塞代码评审

Model Selection Strategy

模型选择策略

Quality-First Approach: Default to Sonnet for most agents. The cost savings from Haiku rarely outweigh the quality loss.
ModelBest ForSpeedCostQuality
sonnet
Default for most agents - content generation, reasoning, file creationBalancedStandard✅ High
opus
Creative work, complex reasoning, quality-critical outputsSlowerPremium✅ Highest
haiku
Only for simple script execution where quality doesn't matter2x faster3x cheaper⚠️ Variable
inherit
Match main conversationVariesVariesMatches parent
Why Sonnet Default?
Testing showed significant quality differences:
  • Haiku: Wrong stylesheet links, missing CSS, wrong values, incorrect patterns
  • Sonnet: Correct patterns, proper validation, fewer errors
Task TypeRecommended ModelWhy
Content generationSonnetQuality matters
File creationSonnetPatterns must be correct
Code writingSonnetBugs are expensive
Audits/reviewsSonnetJudgment required
Creative workOpusMaximum quality
Deploy scriptsHaiku (OK)Just running commands
Simple format checksHaiku (OK)Pass/fail only
Pattern: Default Sonnet, use Opus for creative, Haiku only when quality truly doesn't matter:
yaml
---
name: site-builder
model: sonnet  # Content quality matters - NOT haiku
tools: Read, Write, Edit, Glob, Grep
---

---
name: creative-director
model: opus  # Creative work needs maximum quality
tools: Read, Write, Edit, Glob, Grep
---

---
name: deploy-runner
model: haiku  # Just running wrangler commands - quality irrelevant
tools: Read, Bash
---
质量优先方法:大多数代理默认使用Sonnet模型。Haiku的成本节约通常无法弥补质量损失。
模型最佳用途速度成本质量
sonnet
大多数代理的默认选择 - 内容生成、推理、文件创建平衡标准✅ 高
opus
创意工作、复杂推理、质量关键型输出较慢溢价✅ 最高
haiku
仅适用于简单脚本执行,质量无关紧要的场景快2倍便宜3倍⚠️ 不稳定
inherit
与主对话匹配可变可变与父代理匹配
为何默认选择Sonnet?
测试显示显著的质量差异:
  • Haiku:错误的样式表链接、缺失CSS、错误值、不正确的模式
  • Sonnet:正确的模式、适当的验证、更少错误
任务类型推荐模型原因
内容生成Sonnet质量重要
文件创建Sonnet模式必须正确
代码编写Sonnet错误代价高昂
审计/评审Sonnet需要判断能力
创意工作Opus最高质量
部署脚本Haiku(可行)仅需运行命令
简单格式检查Haiku(可行)仅需通过/失败结果
模式:默认使用Sonnet,创意工作使用Opus,仅当质量确实无关紧要时才使用Haiku:
yaml
---
name: site-builder
model: sonnet  # 内容质量重要 - 不使用haiku
tools: Read, Write, Edit, Glob, Grep
---

---
name: creative-director
model: opus  # 创意工作需要最高质量
tools: Read, Write, Edit, Glob, Grep
---

---
name: deploy-runner
model: haiku  # 仅运行wrangler命令 - 质量无关紧要
tools: Read, Bash
---

Agent Context Considerations

代理上下文注意事项

Agent context usage depends heavily on the task:
ScenarioContextTool CallsWorks?
Deep research agent130k90+✅ Yes
Multi-file audit80k+50+✅ Yes
Simple format check3k5-10✅ Yes
Chained orchestrationVariesVaries✅ Depends on task
Reality: Agents with 90+ tool calls and 130k context work fine when doing meaningful work. The limiting factor is task complexity, not arbitrary token limits.
What actually matters:
  • Is the agent making progress on each tool call?
  • Is context being used for real work vs redundant instructions?
  • Are results coherent at the end?
When context becomes a problem:
  • Agent starts repeating itself or losing track
  • Results become incoherent or contradictory
  • Agent "forgets" earlier findings in long sessions
代理上下文使用情况在很大程度上取决于任务:
场景上下文工具调用次数是否可行
深度研究代理130k90+✅ 是
多文件审计80k+50+✅ 是
简单格式检查3k5-10✅ 是
链式编排可变可变✅ 取决于任务
实际情况:拥有90+次工具调用和130k上下文的代理在执行有意义的工作时运行良好。限制因素是任务复杂性,而非任意的令牌限制。
真正重要的是
  • 代理每次工具调用是否都在取得进展?
  • 上下文是否用于实际工作而非冗余说明?
  • 最终结果是否连贯?
上下文出现问题的迹象
  • 代理开始重复自身或失去跟踪
  • 结果变得不连贯或矛盾
  • 代理在长会话中“忘记”早期发现

Persona-Based Routing

基于角色的路由

Prevent agents from drifting into adjacent domains with explicit constraints:
yaml
---
name: frontend-specialist
description: Frontend code expert. NEVER writes backend logic.
tools: Read, Write, Edit, Glob, Grep
---

You are a frontend specialist.

BOUNDARIES:
- NEVER write backend logic, API routes, or database queries
- ALWAYS use React patterns consistent with the codebase
- If task requires backend work, STOP and report "Requires backend specialist"

FOCUS:
- React components, hooks, state management
- CSS/Tailwind styling
- Client-side routing
- Browser APIs
This prevents hallucination when agents encounter unfamiliar domains.
通过明确的约束防止代理偏离到相邻领域:
yaml
---
name: frontend-specialist
description: 前端代码专家。永远不要编写后端逻辑。
tools: Read, Write, Edit, Glob, Grep
---

你是前端专家。

边界:
- 永远不要编写后端逻辑、API路由或数据库查询
- 始终使用与代码库一致的React模式
- 如果任务需要后端工作,停止并报告“需要后端专家”

关注点:
- React组件、hooks、状态管理
- CSS/Tailwind样式
- 客户端路由
- 浏览器API
这可防止代理在遇到不熟悉领域时产生幻觉。

Hooks Patterns

Hooks模式

Hooks enable automated validation and feedback:
Block-at-commit (enforce quality gates):
yaml
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: |
            if [[ "$BASH_COMMAND" == *"git commit"* ]]; then
              npm test || exit 1
            fi
Hint hooks (non-blocking feedback):
yaml
hooks:
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "./scripts/lint-check.sh"
          # Exits 0 to continue, non-zero to warn
Best practice: Validate at commit stage, not mid-plan. Let agents work freely, catch issues before permanent changes.
Hooks启用自动验证和反馈:
提交时阻塞(实施质量门):
yaml
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: |
            if [[ "$BASH_COMMAND" == *"git commit"* ]]; then
              npm test || exit 1
            fi
提示hooks(非阻塞反馈):
yaml
hooks:
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "./scripts/lint-check.sh"
          # 返回0继续,非零值发出警告
最佳实践:在提交阶段验证,而非计划中途。让代理自由工作,在永久变更前发现问题。

Nested CLAUDE.md Context

嵌套CLAUDE.md上下文

Claude automatically loads
CLAUDE.md
files from subdirectories when accessing those paths:
project/
├── CLAUDE.md              # Root context (always loaded)
├── src/
│   └── CLAUDE.md          # Loaded when editing src/**
├── tests/
│   └── CLAUDE.md          # Loaded when editing tests/**
└── docs/
    └── CLAUDE.md          # Loaded when editing docs/**
Use for: Directory-specific coding standards, local patterns, module documentation.
This is lazy-loaded context - sub-agents get relevant context without bloating main prompt.
当访问特定路径时,Claude会自动加载子目录中的
CLAUDE.md
文件:
project/
├── CLAUDE.md              # 根上下文(始终加载)
├── src/
│   └── CLAUDE.md          # 编辑src/**时加载
├── tests/
│   └── CLAUDE.md          # 编辑tests/**时加载
└── docs/
    └── CLAUDE.md          # 编辑docs/**时加载
用途:特定目录的编码标准、本地模式、模块文档。
这是懒加载上下文——子代理获取相关上下文而不会使主提示膨胀。

Master-Clone vs Custom Subagent

主克隆 vs 自定义子代理

Two philosophies for delegation:
Custom Subagents (explicit specialists):
Main Claude → task-runner agent → result
  • Pros: Isolated context, specialized prompts, reusable
  • Cons: Gatekeeper effect (main agent loses visibility)
Master-Clone (dynamic delegation):
Main Claude → Task(general-purpose) → result
  • Pros: Main agent stays informed, flexible routing
  • Cons: Less specialized, may need more guidance
Recommendation: Use custom agents for well-defined, repeated tasks. Use Task(general-purpose) for ad-hoc delegation where main context matters.

两种委托理念:
自定义子代理(显式专业代理):
主Claude → 任务运行代理 → 结果
  • 优点:上下文隔离、专业提示、可重用
  • 缺点:守门人效应(主代理失去可见性)
主克隆(动态委托):
主Claude → Task(general-purpose) → 结果
  • 优点:主代理保持知情、灵活路由
  • 缺点:专业化程度较低,可能需要更多指导
推荐:将自定义代理用于定义明确的重复任务。当主上下文重要时,使用Task(general-purpose)进行临时委托。

Delegation Patterns

委托模式

The Sweet Spot

最佳适用场景

Best use case: Tasks that are repetitive but require judgment.
✅ Good fit:
   - Audit 70 skills (repetitive) checking versions against docs (judgment)
   - Update 50 files (repetitive) deciding what needs changing (judgment)
   - Research 10 frameworks (repetitive) evaluating trade-offs (judgment)

❌ Poor fit:
   - Simple find-replace (no judgment needed, use sed/grep)
   - Single complex task (not repetitive, do it yourself)
   - Tasks with cross-item dependencies (agents work independently)
最佳用例重复但需要判断的任务。
✅ 合适场景:
   - 审计70个技能(重复)并对照文档检查版本(需要判断)
   - 更新50个文件(重复)并决定需要修改的内容(需要判断)
   - 研究10个框架(重复)并评估权衡(需要判断)

❌ 不合适场景:
   - 简单的查找替换(无需判断,使用sed/grep)
   - 单个复杂任务(非重复,自行处理)
   - 存在跨项目依赖的任务(代理独立工作)

Core Prompt Template

核心提示模板

This 5-step structure works consistently:
markdown
For each [item]:
1. Read [source file/data]
2. Verify with [external check - npm view, API, docs]
3. Check [authoritative source]
4. Evaluate/score
5. FIX issues found ← Critical: gives agent authority to act
Key elements:
  • "FIX issues found" - Without this, agents only report. With it, they take action.
  • Exact file paths - Prevents ambiguity and wrong-file edits
  • Output format template - Ensures consistent, parseable reports
  • Item list - Explicit list of what to process
以下5步结构始终有效:
markdown
对于每个[项目]:
1. 读取[源文件/数据]
2. 使用[外部检查 - npm view、API、文档]验证
3. 检查[权威来源]
4. 评估/评分
5. 修复发现的问题 ← 关键:赋予代理行动权限
关键要素:
  • “修复发现的问题” - 没有此内容,代理仅报告问题。有此内容,代理将采取行动。
  • 精确文件路径 - 防止歧义并避免编辑错误文件
  • 输出格式模板 - 确保一致、可解析的报告
  • 项目列表 - 明确指定要处理的内容

Batch Sizing

批量大小

Batch SizeUse When
3-5 itemsComplex tasks (deep research, multi-step fixes)
5-8 itemsStandard tasks (audits, updates, validations)
8-12 itemsSimple tasks (version checks, format fixes)
Why not more?
  • Agent context fills up
  • One failure doesn't ruin entire batch
  • Easier to review smaller changesets
Parallel agents: Launch 2-4 agents simultaneously, each with their own batch.
批量大小适用场景
3-5个项目复杂任务(深度研究、多步骤修复)
5-8个项目标准任务(审计、更新、验证)
8-12个项目简单任务(版本检查、格式修复)
为何不更大?
  • 代理上下文会被填满
  • 单个失败不会破坏整个批次
  • 更易于评审较小的变更集
并行代理:同时启动2-4个代理,每个代理处理自己的批次。

Workflow Pattern

工作流模式

┌─────────────────────────────────────────────────────────────┐
│  1. PLAN: Identify items, divide into batches               │
│     └─ "58 skills ÷ 10 per batch = 6 agents"                │
├─────────────────────────────────────────────────────────────┤
│  2. LAUNCH: Parallel Task tool calls with identical prompts │
│     └─ Same template, different item lists                  │
├─────────────────────────────────────────────────────────────┤
│  3. WAIT: Agents work in parallel                           │
│     └─ Read → Verify → Check → Edit → Report                │
├─────────────────────────────────────────────────────────────┤
│  4. REVIEW: Check agent reports and file changes            │
│     └─ git status, spot-check diffs                         │
├─────────────────────────────────────────────────────────────┤
│  5. COMMIT: Batch changes with meaningful changelog         │
│     └─ One commit per tier/category, not per agent          │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  1. 计划:识别项目,划分为批次               │
│     └─ "58个技能 ÷ 每批次10个 = 6个代理"                │
├─────────────────────────────────────────────────────────────┤
│  2. 启动:使用相同提示并行调用Task工具 │
│     └─ 相同模板,不同项目列表                  │
├─────────────────────────────────────────────────────────────┤
│  3. 等待:代理并行工作                           │
│     └─ 读取 → 验证 → 检查 → 编辑 → 报告                │
├─────────────────────────────────────────────────────────────┤
│  4. 评审:检查代理报告和文件变更            │
│     └─ git status、抽查差异                         │
├─────────────────────────────────────────────────────────────┤
│  5. 提交:将变更批量提交并附上有意义的变更日志         │
│     └─ 按层级/类别提交,而非按代理提交          │
└─────────────────────────────────────────────────────────────┘

Prompt Templates

提示模板

Audit/Validation Pattern

审计/验证模式

markdown
Deep audit these [N] [items]. For each:

1. Read the [source file] from [path]
2. Verify [versions/data] with [command or API]
3. Check official [docs/source] for accuracy
4. Score 1-10 and note any issues
5. FIX issues found directly in the file

Items to audit:
- [item-1]
- [item-2]
- [item-3]

For each item, create a summary with:
- Score and status (PASS/NEEDS_UPDATE)
- Issues found
- Fixes applied
- Files modified

Working directory: [absolute path]
markdown
深度审计这些[N]个[项目]。对于每个项目:

1. 读取[路径]中的[源文件]
2. 使用[命令或API]验证[版本/数据]
3. 检查官方[文档/来源]的准确性
4. 评分1-10并记录任何问题
5. 直接在文件中修复发现的问题

要审计的项目:
- [项目1]
- [项目2]
- [项目3]

对于每个项目,创建包含以下内容的摘要:
- 评分和状态(通过/需要更新)
- 发现的问题
- 应用的修复
- 修改的文件

工作目录:[绝对路径]

Bulk Update Pattern

批量更新模式

markdown
Update these [N] [items] to [new standard/format]. For each:

1. Read the current file at [path pattern]
2. Identify what needs changing
3. Apply the update following this pattern:
   [show example of correct format]
4. Verify the change is valid
5. Report what was changed

Items to update:
- [item-1]
- [item-2]
- [item-3]

Output format:
| Item | Status | Changes Made |
|------|--------|--------------|

Working directory: [absolute path]
markdown
将这些[N]个[项目]更新为[新标准/格式]。对于每个项目:

1. 读取[路径模式]下的当前文件
2. 识别需要修改的内容
3. 按照以下模式应用更新:
   [展示正确格式的示例]
4. 验证变更有效
5. 报告修改内容

要更新的项目:
- [项目1]
- [项目2]
- [项目3]

输出格式:
| 项目 | 状态 | 修改内容 |
|------|--------|--------------|

工作目录:[绝对路径]

Research/Comparison Pattern

研究/对比模式

markdown
Research these [N] [options/frameworks/tools]. For each:

1. Check official documentation at [URL pattern or search]
2. Find current version and recent changes
3. Identify key features relevant to [use case]
4. Note any gotchas, limitations, or known issues
5. Rate suitability for [specific need] (1-10)

Options to research:
- [option-1]
- [option-2]
- [option-3]

Output format:
markdown
研究这些[N]个[选项/框架/工具]。对于每个选项:

1. 检查官方文档[URL模式或搜索]
2. 查找当前版本和最近变更
3. 识别与[使用场景]相关的关键功能
4. 记录任何陷阱、限制或已知问题
5. 对[特定需求]的适用性评分(1-10)

要研究的选项:
- [选项1]
- [选项2]
- [选项3]

输出格式:

[Option Name]

[选项名称]

  • Version: X.Y.Z
  • Key Features: ...
  • Limitations: ...
  • Suitability Score: X/10
  • Recommendation: ...

---
  • 版本:X.Y.Z
  • 关键功能:...
  • 限制:...
  • 适用性评分:X/10
  • 推荐:...

---

Example Custom Sub-Agents

自定义子代理示例

Code Reviewer

代码评审员

yaml
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---

You are a senior code reviewer ensuring high standards of code quality and security.

When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately

Review checklist:
- Code is clear and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed

Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)

Include specific examples of how to fix issues.
yaml
---
name: code-reviewer
description: 专业代码评审专家。主动评审代码的质量、安全性和可维护性。编写或修改代码后立即使用。
tools: Read, Grep, Glob, Bash
model: inherit
---

你是确保代码质量和安全高标准的资深代码评审员。

调用时:
1. 运行git diff查看最近变更
2. 关注修改的文件
3. 立即开始评审

评审清单:
- 代码清晰可读
- 函数和变量命名恰当
- 无重复代码
- 适当的错误处理
- 无暴露的密钥或API密钥
- 实现了输入验证
- 良好的测试覆盖率
- 考虑了性能因素

按优先级组织反馈:
- 关键问题(必须修复)
- 警告(应修复)
- 建议(考虑改进)

包含修复问题的具体示例。

Debugger

调试器

yaml
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---

You are an expert debugger specializing in root cause analysis.

When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works

Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states

For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations

Focus on fixing the underlying issue, not the symptoms.
yaml
---
name: debugger
description: 针对错误、测试失败和意外行为的调试专家。遇到任何问题时主动使用。
tools: Read, Edit, Bash, Grep, Glob
---

你是专注于根本原因分析的专家调试器。

调用时:
1. 捕获错误消息和堆栈跟踪
2. 确定重现步骤
3. 隔离故障位置
4. 实施最小化修复
5. 验证解决方案有效

调试流程:
- 分析错误消息和日志
- 检查最近的代码变更
- 形成并测试假设
- 添加策略性调试日志
- 检查变量状态

对于每个问题,提供:
- 根本原因解释
- 支持诊断的证据
- 具体代码修复
- 测试方法
- 预防建议

专注于修复根本问题,而非症状。

Data Scientist

数据科学家

yaml
---
name: data-scientist
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
tools: Bash, Read, Write
model: sonnet
---

You are a data scientist specializing in SQL and BigQuery analysis.

When invoked:
1. Understand the data analysis requirement
2. Write efficient SQL queries
3. Use BigQuery command line tools (bq) when appropriate
4. Analyze and summarize results
5. Present findings clearly

Key practices:
- Write optimized SQL queries with proper filters
- Use appropriate aggregations and joins
- Include comments explaining complex logic
- Format results for readability
- Provide data-driven recommendations

Always ensure queries are efficient and cost-effective.

yaml
---
name: data-scientist
description: 专注于SQL查询、BigQuery操作和数据洞察的数据分析专家。数据分析任务和查询时主动使用。
tools: Bash, Read, Write
model: sonnet
---

你是专注于SQL和BigQuery分析的数据科学家。

调用时:
1. 理解数据分析需求
2. 编写高效的SQL查询
3. 适当使用BigQuery命令行工具(bq)
4. 分析并总结结果
5. 清晰呈现发现

关键实践:
- 编写带适当过滤条件的优化SQL查询
- 使用适当的聚合和连接
- 包含解释复杂逻辑的注释
- 格式化结果以提高可读性
- 提供基于数据的推荐

始终确保查询高效且具成本效益。

Commit Strategy

提交策略

Agents don't commit - they only edit files. This is by design:
Agent DoesHuman Does
Research & verifyReview changes
Edit filesSpot-check diffs
Score & reportgit add/commit
Create summariesWrite changelog
Why?
  • Review before commit catches agent errors
  • Batch multiple agents into meaningful commits
  • Clean commit history (not 50 tiny commits)
  • Human decides commit message/grouping
Commit pattern:
bash
git add [files] && git commit -m "$(cat <<'EOF'
[type]([scope]): [summary]

[Batch 1 changes]
[Batch 2 changes]
[Batch 3 changes]

🤖 Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"

代理不提交 - 它们仅编辑文件。这是有意设计的:
代理负责人类负责
研究与验证评审变更
编辑文件抽查差异
评分与报告git add/commit
创建摘要编写变更日志
原因
  • 提交前评审可发现代理错误
  • 将多个代理的变更批量提交为有意义的提交
  • 整洁的提交历史(而非50个微小提交)
  • 人类决定提交消息/分组
提交模式:
bash
git add [files] && git commit -m "$(cat <<'EOF'
[type]([scope]): [summary]

[批次1变更]
[批次2变更]
[批次3变更]

🤖 由[Claude Code](https://claude.com/claude-code)生成
EOF
)"

Error Handling

错误处理

When One Agent Fails

当一个代理失败时

  1. Check the error message
  2. Decide: retry that batch OR skip and continue
  3. Don't let one failure block the whole operation
  1. 检查错误消息
  2. 决定:重试该批次 OR 跳过并继续
  3. 不要让单个失败阻塞整个操作

When Agent Makes Wrong Change

当代理做出错误变更时

  1. git diff [file]
    to see what changed
  2. git checkout -- [file]
    to revert
  3. Re-run with more specific instructions
  1. git diff [file]
    查看变更内容
  2. git checkout -- [file]
    撤销变更
  3. 使用更具体的说明重新运行

When Agents Conflict

当代理发生冲突时

Rare (agents work on different items), but if it happens:
  1. Check which agent's change is correct
  2. Manually resolve or re-run one agent

很少见(代理处理不同项目),但如果发生:
  1. 检查哪个代理的变更正确
  2. 手动解决或重新运行其中一个代理

Best Practices

最佳实践

  1. Start with Claude-generated agents: Use
    /agents
    to generate initial config, then customize
  2. Design focused sub-agents: Single, clear responsibility per agent
  3. Write detailed prompts: Specific instructions, examples, constraints
  4. Don't give Bash unless needed: Prevents approval spam (see "Avoiding Bash Approval Spam")
  5. Put critical instructions FIRST: Instructions at top of prompt get followed, buried ones get ignored
  6. Remove contradictory instructions: If you want Write tool, remove all bash examples
  7. Default to Sonnet model: Quality matters more than cost savings (see Model Selection)
  8. Version control: Check
    .claude/agents/
    into git for team sharing
  9. Use inherit for model sparingly: Better to explicitly set model for predictable behavior

  1. 从Claude生成的代理开始:使用
    /agents
    生成初始配置,然后自定义
  2. 设计专注的子代理:每个代理承担单一、明确的职责
  3. 编写详细提示:具体说明、示例、约束条件
  4. 除非需要否则不提供Bash:避免审批请求泛滥(见“避免Bash审批请求泛滥”)
  5. 将关键说明放在最前面:提示顶部的说明会被遵循,埋在后面的会被忽略
  6. 移除矛盾的说明:如果希望使用Write工具,移除所有bash示例
  7. 默认使用Sonnet模型:质量比成本节约更重要(见模型选择)
  8. 版本控制:将
    .claude/agents/
    提交到git以实现团队共享
  9. 谨慎使用inherit模型:显式设置模型以获得可预测的行为

Performance Considerations

性能考虑

ConsiderationImpact
Context efficiencyAgents preserve main context, enabling longer sessions
LatencySub-agents start fresh, may add latency gathering context
ThoroughnessExplore agent's thoroughness levels trade speed for completeness

考虑因素影响
上下文效率代理保留主上下文,支持更长会话
延迟子代理从零开始,收集上下文可能增加延迟
细致度Explore代理的细致度级别在速度和完整性之间权衡

Quick Reference

快速参考

Built-in agents:
  Explore  → Haiku, read-only, quick/medium/thorough
  Plan     → Sonnet, plan mode research
  General  → Sonnet, all tools, read/write

Custom agents:
  Project  → .claude/agents/*.md (highest priority)
  User     → ~/.claude/agents/*.md
  CLI      → --agents '{...}'

Config fields:
  name, description (required)
  tools, model, permissionMode, skills, hooks (optional)

Tool access principle:
  ⚠️ Don't give Bash unless agent needs CLI execution
  File creators: Read, Write, Edit, Glob, Grep (no Bash!)
  Script runners: Read, Write, Edit, Glob, Grep, Bash (only if needed)
  Research: Read, Grep, Glob, WebFetch, WebSearch

Model selection (quality-first):
  Default: sonnet (most agents - quality matters)
  Creative: opus (maximum quality)
  Scripts only: haiku (just running commands)
  ⚠️ Avoid Haiku for content generation - quality drops significantly

Instruction placement:
  ⛔ Critical instructions go FIRST (right after frontmatter)
  ⚠️ Instructions buried 300+ lines deep get ignored
  ✅ Remove contradictory instructions (pick one pattern)

Delegation:
  Batch size: 5-8 items per agent
  Parallel: 2-4 agents simultaneously
  Prompt: 5-step (read → verify → check → evaluate → FIX)

Orchestration:
  Enable: Add "Task" to agent's tools list
  Depth: Keep to 2 levels max
  Use: Multi-phase workflows, parallel specialists

Advanced:
  Background: Ctrl+B during agent execution
  Context: 130k+ and 90+ tool calls work fine for real work
  Hooks: PreToolUse, PostToolUse, Stop events

Resume agents:
  > Resume agent [agentId] and continue...

内置代理:
  Explore  → Haiku、只读、quick/medium/thorough
  Plan     → Sonnet、计划模式研究
  General  → Sonnet、所有工具、可读可写

自定义代理:
  Project  → .claude/agents/*.md(最高优先级)
  User     → ~/.claude/agents/*.md
  CLI      → --agents '{...}'

配置字段:
  name、description(必填)
  tools、model、permissionMode、skills、hooks(可选)

工具访问原则:
  ⚠️ 除非代理需要执行CLI,否则不要提供Bash
  文件创建者:Read、Write、Edit、Glob、Grep(不要Bash!)
  脚本运行器:Read、Write、Edit、Glob、Grep、Bash(仅在需要时)
  研究:Read、Grep、Glob、WebFetch、WebSearch

模型选择(质量优先):
  默认:sonnet(大多数代理 - 质量重要)
  创意:opus(最高质量)
  仅脚本:haiku(仅运行命令)
  ⚠️ 内容生成避免使用Haiku - 质量显著下降

说明放置:
  ⛔ 关键说明放在最前面(紧跟前置元数据)
  ⚠️ 埋在300+行后的说明会被忽略
  ✅ 移除矛盾的说明(选择一种模式)

委托:
  批量大小:每个代理5-8个项目
  并行:同时2-4个代理
  提示:5步结构(读取 → 验证 → 检查 → 评估 → 修复)

编排:
  启用:在代理工具列表中添加"Task"
  深度:最多保持2层
  使用:多阶段工作流、并行专业代理

高级功能:
  后台:代理执行期间按Ctrl+B
  上下文:130k+和90+工具调用在实际工作中运行良好
  Hooks:PreToolUse、PostToolUse、Stop事件

恢复代理:
  > 恢复代理[agentId]并继续...

References

参考资料

Official Documentation

官方文档

Community Resources

社区资源


Last Updated: 2026-02-02

最后更新:2026-02-02