Skip to main content

Anatomy of Subagents

Specialized subagents, patterns, orchestration, and best practices.

Subagents

Specialized AI teammates that handle focused work in parallel โ€” so your main agent stays sharp and your team ships faster.


TL;DRโ€‹

  • A subagent (a.k.a. agent) is a lightweight, purpose-built Claude persona with its own prompt, tools, permissions, and triggers.
  • They run under the main orchestrator (Claude Code) to complete parts of a larger goal โ€” sequentially or in parallel.
  • Defined as one YAML file per agent under agents/.
  • Best when each subagent does one job, really well.
  • Right governance turns them from "neat demo" into auditable, reusable teammates.

Why this mattersโ€‹

Think of a film set. Instead of one person doing direction, lighting, sound, and editing, you hire specialists. Subagents are your AI film crew โ€” each focused, predictable, and replaceable.

Bottom line: Specialization beats genius generalists. Decompose the problem, delegate to specialists, combine the best.


The Big Pictureโ€‹

Bottom line: One orchestrator plans and delegates; many specialists deliver in parallel; results merge back.


When to Use Subagentsโ€‹

  • Tasks can run independently or in parallel.
  • Each task needs different expertise or tools.
  • You want predictable, repeatable outputs.
  • Complex workflows need focus and safety boundaries.
  • Consistent quality and auditability matter.

๐Ÿ’ก Tip: If a single prompt keeps drifting, that's the signal to split the work into subagents.


Directory Structureโ€‹

agents/
โ”œโ”€โ”€ code-reviewer.yml
โ”œโ”€โ”€ test-writer.yml
โ”œโ”€โ”€ security-auditor.yml
โ”œโ”€โ”€ docs-writer.yml
โ””โ”€โ”€ devops-sre.yml
  • One file (YAML) per subagent.
  • Shared folder, checked into the repo.
  • Versioned and peer-reviewed like code.
  • Document purpose, triggers, and examples in each file.
  • Keep examples up to date.

๐Ÿ’ก Tip: Store agents in the repo so the whole team benefits.


Subagent Anatomy (zoom in)โ€‹

# agents/code-reviewer.yml
name: code-reviewer # unique id (use kebab-case)
description: Reviews PRs for quality, security, & tests. # used for routing & discovery

model: claude-opus-4 # which model to use

system_prompt: |
You are a senior engineer and strict code reviewer.
Follow project conventions in CLAUDE.md.
Output must include: summary, risks, missing tests,
and concrete fixes with file:line references.

tools: # allowed tools
- Read
- Bash
- Grep
- WebSearch

permissions: # sandbox boundary
allow: ["Read", "Bash(npm test)", "WebSearch"]
deny: ["WriteOutsideWorkspace", "Bash(rm -rf *)"]

triggers: ["review", "audit", "pr", "quality", "code-reviewer"]

timeout_ms: 120000 # safety cap
max_tokens: 8000 # output budget
tags: ["quality", "review"] # categorization
version: 1.0.0 # version for tracking
notes: |
Optional additional instructions, examples, or rules below.

Common Fields Referenceโ€‹

FieldTypeRequiredPurpose
namestringโœ… YesUnique id for the agent
descriptionstringโœ… YesOne-line summary (used for auto-routing)
modelstringNoWhich model to use
system_promptstringโœ… YesThe persona, rules, and examples
toolsarrayNoAllowed tools
permissionsobjectNoAllow / deny lists
triggersarrayNoKeywords for auto-activation
timeout_msnumberNoMax runtime in milliseconds
max_tokensnumberNoOutput token budget
tagsarrayNoCategorization metadata
versionstringNoSemVer for change tracking

Step-by-Step Setupโ€‹

1. Create the agents directoryโ€‹

mkdir -p agents

2. Create your first agentโ€‹

cat > agents/code-reviewer.yml <<'EOF'
name: code-reviewer
description: Reviews PRs for quality, security, and tests.
model: claude-opus-4
system_prompt: |
You are a strict senior reviewer. Follow CLAUDE.md.
Output: 1) Risks 2) Missing tests 3) Concrete fixes.
tools: [Read, Bash, Grep]
permissions:
allow: ["Read", "Bash(npm test)"]
deny: ["WriteOutsideWorkspace"]
triggers: ["review", "audit", "pr"]
timeout_ms: 120000
max_tokens: 8000
EOF

3. Register agents in CLAUDE.mdโ€‹

## Available subagents
- `@code-reviewer` โ€” PR & code reviews
- `@test-writer` โ€” unit + integration tests
- `@security-auditor` โ€” vulnerability scans
- `@docs-writer` โ€” API docs & READMEs
- `@devops-sre` โ€” CI/CD, infra, deploys

4. Invoke itโ€‹

"Use @code-reviewer on this PR."

Or let auto-activation pick it up via triggers ("review this PR").

5. Iterateโ€‹

Refine system_prompt after each real run; commit the change with a SemVer bump.


Design Patternsโ€‹

1. Sequential Pipelineโ€‹

A โ†’ B โ†’ C โ†’ D

One after another. Use when steps depend on each other.

2. Parallel Fan-outโ€‹

โ”Œโ”€ B
A โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€ C
โ””โ”€ D

Multiple specialists run independently, results merge.

3. Router / Selectorโ€‹

A โ”€โ”€โ–บ [router] โ”€โ”€โ–บ B | C | D

Orchestrator picks the best specialist by intent.

4. Reflect & Retryโ€‹

A โ”€โ”€โ–บ critic โ”€โ”€โ–บ (fail) โ”€โ”€โ–บ improve โ”€โ”€โ–บ A

Specialist + critic loop until quality threshold met.

5. Plan & Act (ReAct)โ€‹

Think โ†’ Act โ†’ Observe โ†’ Repeat

Iterate small actions guided by reasoning.

๐Ÿ’ก Tip: Start simple. Add parallelism only when it demonstrably helps.


Invocation & Triggersโ€‹

Explicit invokeโ€‹

@code-reviewer โ€” review this PR.
Use @test-writer to add unit tests.
Ask @security-auditor for a risk check.

Auto-activationโ€‹

When the user says:

  • "review" / "audit" / "pr" โ†’ routes to @code-reviewer
  • "test" / "unit" / "coverage" โ†’ routes to @test-writer
  • "security" / "vulnerability" / "secret" โ†’ routes to @security-auditor

๐Ÿ’ก Tip: Keep trigger words realistic and unambiguous โ€” synonyms the team actually uses.


How Subagents Work Togetherโ€‹

  1. Break the goal into steps (orchestrator plans).
  2. Delegate to the right specialists.
  3. Run in parallel or sequence based on dependencies.
  4. Merge, critique, and return the result.
  5. Iterate if quality thresholds aren't met.

SubagentBest forKey toolsTypical output
code-reviewerPR reviews, quality gatesRead, Bash, GrepReview report
test-writerUnit & integration testsRead, Edit, BashTests + coverage
security-auditorVulnerabilities, secretsRead, WebSearch, BashRisk report
docs-writerDocs, READMEs, API refsRead, EditMarkdown docs
refactorCode cleanup & designRead, Edit, BashRefactored code
bug-triageIssue classificationRead, WebSearchTriage summary
devops-sreCI/CD, infra, deploysBash, Read, WebSearchRunbook / plan
release-managerChangelogs, version bumpsRead, Edit, BashRelease notes

Permissions & Safetyโ€‹

โœ… DOโ€‹

  • Grant least-privilege access.
  • Limit write operations.
  • Deny destructive commands (rm -rf, sudo).
  • Use specific tool names, not wildcards.
  • Review subagent changes like production code.
  • Log sensitive actions to an audit trail.

โŒ DON'Tโ€‹

  • Allow WriteOutsideWorkspace.
  • Allow Bash(rm -rf *).
  • Use allow: ["*"].
  • Hard-code secrets in the YAML.
  • Skip reviews & audits.
  • Ignore timeout_ms.

๐Ÿ’ก Tip: Safe by default. Escalate only when needed, with a paper trail.


Common Patterns & Recipesโ€‹

Pattern 1 โ€” Self-check loopโ€‹

# orchestrator pseudocode
- @claude-code: write code
- @code-reviewer: review
- if review.fails && attempts < 3: goto write code

Pattern 2 โ€” Fan-out reviewโ€‹

on PR open:
parallel:
- @code-reviewer
- @security-auditor
- @test-writer
merge: combined report

Pattern 3 โ€” Strict reviewer personaโ€‹

system_prompt: |
Be ruthless. Reject any change without tests.
Never approve secrets in code.
Output format: Risks | Missing Tests | Fixes (file:line).

Pattern 4 โ€” Cost-aware fallbackโ€‹

model: claude-haiku-4 # cheap default
escalate_to: claude-opus-4
escalate_when: "risk == high || diff_lines > 500"

Pattern 5 โ€” Auditable subagentโ€‹

hooks:
on_invoke: ["./scripts/audit-agent.sh start"]
on_complete: ["./scripts/audit-agent.sh end"]

Pattern 6 โ€” Domain-specific personaโ€‹

name: hipaa-reviewer
system_prompt: |
You are a HIPAA compliance reviewer.
Flag any PHI handling without proper encryption or access controls.
Cite specific HIPAA rules in your findings.
tags: ["compliance", "healthcare"]

Variants for Different Team Settingsโ€‹

๐Ÿ‘ค Solo developerโ€‹

One agent: @code-reviewer. Run it before every commit.

name: code-reviewer
description: Quick PR check before commit.
model: claude-haiku-4
system_prompt: |
Quick review. Focus on bugs and missing tests.
tools: [Read, Bash]
permissions: { allow: ["Read", "Bash(npm test)"] }
triggers: ["review", "check"]

๐Ÿ‘ฅ Small team (2โ€“10)โ€‹

Add @test-writer and @docs-writer. Wire into PR templates.

PR Checklist:
- [ ] Ran @code-reviewer
- [ ] Updated tests (@test-writer if missing)
- [ ] Updated docs (@docs-writer if API changed)

๐Ÿข Enterprise / regulatedโ€‹

  • Pin model versions for reproducibility.
  • Add @security-auditor with deny-by-default.
  • Log every invocation to SIEM.
  • PR review required on every agent change.
  • Run agents in isolated containers when handling sensitive data.
permissions:
allow: ["Read"]
deny: ["Bash", "Write", "WebFetch"]
hooks:
on_invoke: ["./scripts/audit-siem.sh"]
timeout_ms: 60000

๐ŸŒ Open-sourceโ€‹

  • Share agents/ in the repo so forks inherit them.
  • Document each agent's purpose, triggers, and tools.
  • Keep prompts generic (no internal jargon).

Bottom line: Same YAML, escalating governance.


Anatomy of a Single Run โ€” Zoomed Inโ€‹

1. User: "Audit our auth flow."
2. Orchestrator routes to @security-auditor (trigger: "audit").
3. Agent loads CLAUDE.md + reads src/auth/**.
4. Runs scripts/secret-scan.sh.
5. Generates risk report:
- ๐Ÿ”ด Critical: missing rate limit on /login
- ๐ŸŸก Concern: JWT secret rotation overdue
- ๐ŸŸข Info: CSRF protection in place
6. Returns structured output to orchestrator.
7. Orchestrator hands off fixes to @refactor.

Best Practices โœ…โ€‹

  • One job per subagent.
  • Write clear, concrete prompts โ€” include examples.
  • Provide examples & output format.
  • Limit tools to only what's needed.
  • Define triggers with synonyms the team actually uses.
  • Set timeout_ms & max_tokens โ€” runaway costs hurt.
  • Version like code (SemVer).
  • Measure & improve continuously based on feedback.

Anti-Patterns โŒโ€‹

  • Mega-agent that does everything.
  • Vague prompts ("be helpful").
  • Too many tools or permissions.
  • No triggers or poor triggers.
  • No timeouts or budgets.
  • Hard-coded secrets or paths.
  • No review or change control.
  • Forgetting to update examples when behavior drifts.

Troubleshootingโ€‹

SymptomLikely causeFix
Agent not usedTriggers don't matchAdd synonyms to triggers:
Poor / generic outputPrompt too vagueAdd examples & strict format rules
Tool errorMissing permissionGrant the specific tool
Runs too longNo timeoutSet timeout_ms
Too much textNo max_tokens budgetSet max_tokens
Repeats itselfNo critic stepAdd a self-check or reviewer agent
Wrong agent pickedRouter logic weakTighten descriptions & triggers
Costs spikeHigh-end model on cheap tasksAdd cost-aware fallback

Getting Started (6 steps)โ€‹

  1. Identify recurring, focused tasks in your team's day.
  2. Sketch the subagent prompt in plain English.
  3. Define triggers & permissions (deny by default).
  4. Set timeouts & token budgets.
  5. Test & refine iteratively on real tasks.
  6. Share with your team via the repo + CLAUDE.md.

Starter Template (copy & adapt)โ€‹

name: my-agent
description: Do one thing really well.
model: claude-sonnet-4
system_prompt: |
You are a helpful expert.
Be concise and specific.
tools: [Read]
permissions:
allow: ["Read"]
deny: ["WriteOutsideWorkspace"]
triggers: ["mytask"]
timeout_ms: 60000
max_tokens: 4000
version: 1.0.0
tags: ["generic"]
notes: |
Add notes or references here.

๐Ÿ’ก Tip: Start with one agent. Clone & specialize as patterns emerge.


Glossaryโ€‹

  • Subagent / Agent โ€” A scoped Claude persona invoked by the main session.
  • Orchestrator โ€” The top-level Claude that plans and delegates.
  • Trigger โ€” A keyword or phrase that auto-activates an agent.
  • Tool โ€” A capability the agent may call (Read, Bash, etc.).
  • System prompt โ€” The fixed persona/rules text.
  • Router โ€” Logic (or a model) that picks which agent runs.
  • Critic โ€” A subagent or rule that validates another's output.
  • Fan-out โ€” Parallel execution of multiple subagents on the same input.
  • Reflect & retry โ€” Iteratively improve via self-critique.

Further Readingโ€‹

  • Search: "Claude Code subagents documentation"
  • Search: "agentic workflows orchestrator pattern"
  • Search: "awesome-claude-agents GitHub"
  • Search: "multi-agent LLM coordination patterns"

๐Ÿช™ Golden Rulesโ€‹

  • ๐Ÿง  Specialize ruthlessly โ€” one job per agent.
  • ๐ŸŽฏ Delegate deliberately โ€” right agent, right task.
  • ๐Ÿ›ก๏ธ Be safe by default โ€” least privilege always.
  • ๐Ÿ” Iterate & improve โ€” feedback makes better agents.
  • ๐Ÿ“ Document everything โ€” future-you will thank you.

Remember: Great subagents are like great teammates โ€” focused, trustworthy, and easy to work with.