Claude Code Agents
Create and maintain Claude Code agents/subagents with predictable behavior, least-privilege tools, and explicit delegation contracts.
Quick Start
- Create an agent file at
.claude/agents/<agent-name>.md (kebab-case filename).
- Add YAML frontmatter (required:
name, description; optional: tools, model, permissionMode, skills, hooks).
- Write the agent prompt: responsibilities, workflow, and an output contract.
- Minimize tools: start read-only, then add only what the agent truly needs.
- Test on a real task and iterate.
Minimal template:
---
name: sql-optimizer
description: Optimize SQL queries, explain tradeoffs, and propose safe indexes
tools: Read, Grep, Glob
model: sonnet
---
# SQL Optimizer
## Responsibilities
- Diagnose bottlenecks using query shape and plans when available
- Propose optimizations with risks and expected impact
## Workflow
1. Identify the slow path and data volume assumptions
2. Propose changes (query rewrite, indexes, stats) with rationale
3. Provide a verification plan
## Output Contract
- Summary (1–3 bullets)
- Recommendations (ordered)
- Verification (commands/tests to run)
Workflow (2026)
- Define the agent’s scope and success criteria.
- Choose a model based on risk, latency, and cost (default to
sonnet for most work).
- Choose tools via least privilege; avoid granting
Edit/Write unless required.
- If delegating with
Task, define a handoff contract (inputs, constraints, output format).
- Add safety rails for destructive actions and secrets.
- Add a verification step (checklist, tests, or a dedicated verifier agent).
Frontmatter Fields (Summary)
name (REQUIRED): kebab-case; match filename (without .md).
description (REQUIRED): state when to invoke + what it does; include keywords users will say.
tools (OPTIONAL): explicit allow-list; prefer small, purpose-built sets.
model (OPTIONAL): haiku for fast checks, sonnet for most tasks, opus for high-stakes reasoning, inherit to match parent.
permissionMode (OPTIONAL): prefer defaults; change only with a clear reason and understand the tradeoffs.
skills (OPTIONAL): preload skill packs for domain expertise; keep the list minimal.
hooks (OPTIONAL): automate guardrails; prefer using the hooks skill for patterns and safety.
For full tool semantics and permission patterns, use references/agent-tools.md. For orchestration and anti-patterns, use references/agent-patterns.md.
2026 Best Practices (Domain Expertise)
- Use small, specialized agents; avoid “god agents”.
- Keep agent prompts short; put repo conventions in
CLAUDE.md/project memory and domain knowledge in skills.
- Budget context: pass file paths, minimal snippets, and constraints; avoid dumping long logs/code.
- Use explicit handoffs for subagents: “Goal / Constraints / Inputs / Output Contract”.
- Add a verifier step for risky changes (security, migrations, infra, auth).
- Treat CLI fields/features as moving; verify against official docs in
data/sources.json.
Validation Checklist
- Frontmatter:
name matches filename; description is single-line and trigger-oriented; tools are minimal; model fits risk.
- Prompt: responsibilities are concrete; workflow is actionable; output contract is explicit.
- Delegation: subagent briefs are specific and bounded; orchestrator verifies integration.
- Safety: confirm destructive ops; avoid secrets/PII; follow repository policies.
Navigation
frameworks/shared-skills/skills/agents-subagents/references/agent-patterns.md
frameworks/shared-skills/skills/agents-subagents/references/agent-tools.md
frameworks/shared-skills/skills/agents-subagents/references/subagent-interruption-recovery.md
frameworks/shared-skills/skills/agents-subagents/data/sources.json
frameworks/shared-skills/skills/agents-skills/SKILL.md
frameworks/shared-skills/skills/agents-hooks/SKILL.md
Subagent Interruption Recovery Protocol
Interruptions are normal in multi-agent runs. Treat them as recoverable state transitions, not total failures.
Recovery Loop
- Capture partial output from interrupted agent.
- Classify interruption cause (
manual redirect, timeout, context overflow, tool error).
- Decide resume strategy:
- resume same agent with narrowed scope, or
- spawn replacement agent with explicit handoff from checkpoint.
- Prevent duplicate work by marking completed subtasks before rerun.
- Re-verify integration assumptions after recovery.
Required Checkpoint Fields
- completed work
- pending work
- owned files
- unresolved blocker
- next exact command/task
Anti-Pattern
Do not restart full fan-out blindly after one interruption. Resume the smallest affected unit first.
Operational Guardrails: Subagent Orchestration
Use these defaults unless the user explicitly asks for wider fan-out.
Worktree Isolation
For parallel subagent execution, use one Git worktree per agent to prevent file conflicts and index lock contention. See AI Agent Worktrees for setup, directory conventions, safety patterns, and cleanup.
Hard Limits
- Keep active subagents <= 3.
- Keep each subagent scope to one responsibility and a bounded file set.
- Do not let multiple subagents edit the same file in parallel.
- Use one worktree per subagent when running parallel agents locally.
Handoff Template (Standard)
Goal:
Constraints:
Owned files:
Do-not-touch files:
Output format:
Definition of done:
Context-Rich Handoff Template (For Parallel/Swarm Execution)
When dispatching multiple subagents from a plan, front-load each agent with structured context. This reduces token usage, tool calls, and drift.
## Context
- Plan: [plan filename or path]
- Goals: [relevant overview from plan — what this task achieves]
- Dependencies: [prerequisite tasks + their outputs/files]
- Related tasks: [sibling tasks and their function]
## Scope
- Files to create/modify: [full paths]
- Files to read (not modify): [paths for reference only]
- Do-not-touch: [files owned by other agents]
## Acceptance Criteria
- [Criterion 1]
- [Criterion 2]
- [Test/verification command]
## Implementation Steps
1. Read the plan at [path] for full context
2. [Concrete step]
3. [Concrete step]
4. Verify: [specific check]
Why this works: Subagents have no prior context. Without front-loaded detail, they spend tokens rediscovering the codebase. With it, they execute focused work immediately.
Wave Dispatch Protocol
When executing plans with dependency graphs, use waves:
- Read the dependency graph from the plan.
- Identify all tasks with no unmet dependencies (Wave 1).
- Launch one subagent per unblocked task (using context-rich handoff template).
- Wait for all agents in the wave to complete.
- Validate each agent's output before proceeding.
- Identify newly unblocked tasks → launch next wave.
- Repeat until all tasks complete.
Single-wave shortcut: If only one task is unblocked, launch one agent. Don't force parallelism.
Merge Discipline
- Wait for subagent outputs.
- Review for overlap/conflicts.
- Integrate one subagent result at a time.
- Run verification gates before final synthesis.
Conflict Resolution (Parallel Outputs)
When parallel agents produce conflicting changes:
- Detect: Check for overlapping file edits, incompatible interface changes, or divergent assumptions.
- Prioritize: The agent working on the dependency (upstream task) takes priority for shared interfaces.
- Resolve: The orchestrator (not subagents) reconciles conflicts — it has the full plan context.
- Re-run if needed: If conflict resolution invalidates a task's output, re-dispatch that single task with updated context.
- Document: Record the conflict and resolution in the plan for traceability.
Stop Conditions
Stop and re-plan when:
- two subagents propose conflicting edits to same module,
- repeated retries happen without new evidence,
- context window starts dropping prior decisions,
- conflict resolution would require re-running more than half the completed tasks.
Fact-Checking
- Use web search/web fetch to verify current external facts, versions, pricing, deadlines, regulations, or platform behavior before final answers.
- Prefer primary sources; report source links and dates for volatile information.
- If web access is unavailable, state the limitation and mark guidance as unverified.
1---2name: agents-subagents3description: Create AI coding agent subagents with YAML frontmatter and least-privilege tools. Use when designing delegation, tool selection, or safety rules.4---5
6# Claude Code Agents
7
8Create and maintain Claude Code agents/subagents with predictable behavior, least-privilege tools, and explicit delegation contracts.
9
10## Quick Start
11
121. Create an agent file at `.claude/agents/<agent-name>.md` (kebab-case filename).
132. Add YAML frontmatter (required: `name`, `description`; optional: `tools`, `model`, `permissionMode`, `skills`, `hooks`).
143. Write the agent prompt: responsibilities, workflow, and an output contract.
154. Minimize tools: start read-only, then add only what the agent truly needs.
165. Test on a real task and iterate.
17
18Minimal template:
19
20```markdown
21---
22name: sql-optimizer
23description: Optimize SQL queries, explain tradeoffs, and propose safe indexes
24tools: Read, Grep, Glob
25model: sonnet
26---
27
28# SQL Optimizer
29
30## Responsibilities
31- Diagnose bottlenecks using query shape and plans when available
32- Propose optimizations with risks and expected impact
33
34## Workflow
351. Identify the slow path and data volume assumptions
362. Propose changes (query rewrite, indexes, stats) with rationale
373. Provide a verification plan
38
39## Output Contract
40- Summary (1–3 bullets)
41- Recommendations (ordered)
42- Verification (commands/tests to run)
43```
44
45## Workflow (2026)
46
471. Define the agent’s scope and success criteria.
482. Choose a model based on risk, latency, and cost (default to `sonnet` for most work).
493. Choose tools via least privilege; avoid granting `Edit`/`Write` unless required.
504. If delegating with `Task`, define a handoff contract (inputs, constraints, output format).
515. Add safety rails for destructive actions and secrets.
526. Add a verification step (checklist, tests, or a dedicated verifier agent).
53
54## Frontmatter Fields (Summary)
55
56- `name` (REQUIRED): kebab-case; match filename (without `.md`).
57- `description` (REQUIRED): state when to invoke + what it does; include keywords users will say.
58- `tools` (OPTIONAL): explicit allow-list; prefer small, purpose-built sets.
59- `model` (OPTIONAL): `haiku` for fast checks, `sonnet` for most tasks, `opus` for high-stakes reasoning, `inherit` to match parent.
60- `permissionMode` (OPTIONAL): prefer defaults; change only with a clear reason and understand the tradeoffs.
61- `skills` (OPTIONAL): preload skill packs for domain expertise; keep the list minimal.
62- `hooks` (OPTIONAL): automate guardrails; prefer using the hooks skill for patterns and safety.
63
64For full tool semantics and permission patterns, use `references/agent-tools.md`. For orchestration and anti-patterns, use `references/agent-patterns.md`.
65
66## 2026 Best Practices (Domain Expertise)
67
68- Use small, specialized agents; avoid “god agents”.
69- Keep agent prompts short; put repo conventions in `CLAUDE.md`/project memory and domain knowledge in skills.
70- Budget context: pass file paths, minimal snippets, and constraints; avoid dumping long logs/code.
71- Use explicit handoffs for subagents: “Goal / Constraints / Inputs / Output Contract”.
72- Add a verifier step for risky changes (security, migrations, infra, auth).
73- Treat CLI fields/features as moving; verify against official docs in `data/sources.json`.
74
75## Validation Checklist
76
77- Frontmatter: `name` matches filename; `description` is single-line and trigger-oriented; tools are minimal; model fits risk.
78- Prompt: responsibilities are concrete; workflow is actionable; output contract is explicit.
79- Delegation: subagent briefs are specific and bounded; orchestrator verifies integration.
80- Safety: confirm destructive ops; avoid secrets/PII; follow repository policies.
81
82## Navigation
83
84- `frameworks/shared-skills/skills/agents-subagents/references/agent-patterns.md`
85- `frameworks/shared-skills/skills/agents-subagents/references/agent-tools.md`
86- `frameworks/shared-skills/skills/agents-subagents/references/subagent-interruption-recovery.md`
87- `frameworks/shared-skills/skills/agents-subagents/data/sources.json`
88- `frameworks/shared-skills/skills/agents-skills/SKILL.md`
89- `frameworks/shared-skills/skills/agents-hooks/SKILL.md`
90
91## Subagent Interruption Recovery Protocol
92
93Interruptions are normal in multi-agent runs. Treat them as recoverable state transitions, not total failures.
94
95### Recovery Loop
96
971. Capture partial output from interrupted agent.
982. Classify interruption cause (`manual redirect`, `timeout`, `context overflow`, `tool error`).
993. Decide resume strategy:
100 - resume same agent with narrowed scope, or
101 - spawn replacement agent with explicit handoff from checkpoint.
1024. Prevent duplicate work by marking completed subtasks before rerun.
1035. Re-verify integration assumptions after recovery.
104
105### Required Checkpoint Fields
106
107- completed work
108- pending work
109- owned files
110- unresolved blocker
111- next exact command/task
112
113### Anti-Pattern
114
115Do not restart full fan-out blindly after one interruption. Resume the smallest affected unit first.
116
117## Operational Guardrails: Subagent Orchestration
118
119Use these defaults unless the user explicitly asks for wider fan-out.
120
121### Worktree Isolation
122
123For parallel subagent execution, use one Git worktree per agent to prevent file conflicts and index lock contention. See **[AI Agent Worktrees](../dev-git-workflow/references/ai-agent-worktrees.md)** for setup, directory conventions, safety patterns, and cleanup.
124
125### Hard Limits
126
127- Keep active subagents <= 3.
128- Keep each subagent scope to one responsibility and a bounded file set.
129- Do not let multiple subagents edit the same file in parallel.
130- Use one worktree per subagent when running parallel agents locally.
131
132### Handoff Template (Standard)
133
134```text
135Goal:
136Constraints:
137Owned files:
138Do-not-touch files:
139Output format:
140Definition of done:
141```
142
143### Context-Rich Handoff Template (For Parallel/Swarm Execution)
144
145When dispatching multiple subagents from a plan, front-load each agent with structured context. This reduces token usage, tool calls, and drift.
146
147```text
148## Context
149- Plan: [plan filename or path]
150- Goals: [relevant overview from plan — what this task achieves]
151- Dependencies: [prerequisite tasks + their outputs/files]
152- Related tasks: [sibling tasks and their function]
153
154## Scope
155- Files to create/modify: [full paths]
156- Files to read (not modify): [paths for reference only]
157- Do-not-touch: [files owned by other agents]
158
159## Acceptance Criteria
160- [Criterion 1]
161- [Criterion 2]
162- [Test/verification command]
163
164## Implementation Steps
1651. Read the plan at [path] for full context
1662. [Concrete step]
1673. [Concrete step]
1684. Verify: [specific check]
169```
170
171**Why this works:** Subagents have no prior context. Without front-loaded detail, they spend tokens rediscovering the codebase. With it, they execute focused work immediately.
172
173### Wave Dispatch Protocol
174
175When executing plans with dependency graphs, use waves:
176
1771. Read the dependency graph from the plan.
1782. Identify all tasks with no unmet dependencies (Wave 1).
1793. Launch one subagent per unblocked task (using context-rich handoff template).
1804. Wait for all agents in the wave to complete.
1815. Validate each agent's output before proceeding.
1826. Identify newly unblocked tasks → launch next wave.
1837. Repeat until all tasks complete.
184
185**Single-wave shortcut:** If only one task is unblocked, launch one agent. Don't force parallelism.
186
187### Merge Discipline
188
1891. Wait for subagent outputs.
1902. Review for overlap/conflicts.
1913. Integrate one subagent result at a time.
1924. Run verification gates before final synthesis.
193
194### Conflict Resolution (Parallel Outputs)
195
196When parallel agents produce conflicting changes:
197
1981. **Detect**: Check for overlapping file edits, incompatible interface changes, or divergent assumptions.
1992. **Prioritize**: The agent working on the dependency (upstream task) takes priority for shared interfaces.
2003. **Resolve**: The orchestrator (not subagents) reconciles conflicts — it has the full plan context.
2014. **Re-run if needed**: If conflict resolution invalidates a task's output, re-dispatch that single task with updated context.
2025. **Document**: Record the conflict and resolution in the plan for traceability.
203
204### Stop Conditions
205
206Stop and re-plan when:
207- two subagents propose conflicting edits to same module,
208- repeated retries happen without new evidence,
209- context window starts dropping prior decisions,
210- conflict resolution would require re-running more than half the completed tasks.
211
212## Fact-Checking
213
214- Use web search/web fetch to verify current external facts, versions, pricing, deadlines, regulations, or platform behavior before final answers.
215- Prefer primary sources; report source links and dates for volatile information.
216- If web access is unavailable, state the limitation and mark guidance as unverified.