1. Why Context Isolation Beats One Giant Chat Thread
A subagent is a focused specialist spawned by your main coding agent to execute one bounded job inside its own private context window, governed by its own system prompt, model, and tool permissions, returning only a distilled final report.
Quick Navigation
The Context Economy: Expensive Exploration Dies Locally, Cheap Truth Flows Up
2. Four Multi-Agent Topologies & When to Delegate
"Multi-agent coding" actually describes four distinct operating patterns. Picking the right pattern before you write a prompt saves both wall-clock time and 3x–5x in wasted token spend.
One context window, one tool loop. Best for 30-second targeted edits, interactive steering, and sequential steps that all rely on the exact same files already in memory.
Coordinator spawns clean-slate specialists (researcher, test-writer, reviewer) via sequential pipelines, parallel fan-out, or intent routing, then merges their summaries.
/subtask • fork)Clones your entire active conversation into a background branch sharing your prompt cache. Ideal when a side task needs everything discussed so far without polluting your main thread.
Multiple long-lived peer sessions collaborating across a shared message board or task roster (Antigravity /teamwork Swarms, Claude Agent Teams) on multi-hour parallel builds.
The Money-Saving Decision Matrix: Inline vs. Subagent vs. Fork vs. Swarm
| Task Signal | Do Inline (Main) | Focused Subagent | Context Fork | Peer Swarm / Team |
|---|---|---|---|---|
| Output Volume | Small code diff you will keep editing | Floods of grep hits, stack traces, or test logs | Side artifact (PR notes, unit test draft) | Multiple full subsystems + integration checks |
| Context Needed | Already loaded in current chat | Fits cleanly in a 4-sentence briefing | Needs 100% of current chat decisions | Shared design spec + live peer board updates |
| Back-and-Forth | High interactive human steering | Self-contained input → report contract | Fire-and-forget from current state | Agents negotiate API contracts laterally |
| Safety Posture | Uses your session's full toolset | Strict least-privilege (e.g., read-only) | Inherits parent tools & prompt cache | Per-worker git worktrees + dedicated verifier |
| Token Cost | 1x (lowest baseline) | 1.2x–3x (cheap model offset) | Low first turn (shared cache hit!) | 4x–8x (highest; reserve for big scope) |
isolation: worktree. • 2. Not a free cache: Every fresh spawn re-reads files unless you resume its Agent ID. • 3. Not zero-cost: Five parallel agents spend ~5x the tokens. • 4. Not a replacement for Skills: If a reusable workflow needs main-chat context (like formatting a commit), make it a SKILL.md, not a subagent.
3. Annotated Tour: Subagent Spec & Live Dispatch Monitor
Every modern subagent system pairs a declarative definition file (left) with a live task & transcript monitor (right) so you can inspect active models, tool boundaries, and isolated worktrees at a glance.
1. Run
git diff and read every modified file in full.2. Execute the test suite and verify exit codes.
[file:line] evidence.
4
src/routes/orders.ts in isolated git branchSendMessage(ag_03m8) for Round 2!/subtask drafting release notes (shared prompt cache)
Numbered Architecture & Control Reference
.claude/agents/ (also auto-detected by Cursor and VS Code!) so your entire engineering team shares identical specialists.description: The orchestrator reads this string to decide when to auto-delegate. Include trigger phrases like "Use proactively after...".Edit and Write guarantees the reviewer cannot "helpfully" rewrite broken code while auditing it.VERDICT: SHIP | FIX structure lets the coordinator branch cleanly without guessing./tasks Panel: Displays every running and recent subagent with its active model, effort level, turn count, and color badge; press Enter to inspect its raw log.ag_03m8). Messaging that ID resumes its full memory for Round 2 instead of paying to re-read the repository from scratch.
4. The 4 Topologies & Subagent Frontmatter Reference
A subagent file is plain Markdown: YAML frontmatter between --- fences on top, and the specialist's system prompt below. Only name and description are mandatory—every other key sharpens cost, isolation, or safety.
Complete Subagent YAML Frontmatter Reference
| Field | Req? | Behavior, Precedence & Practical Guidance |
|---|---|---|
name |
Yes | Unique lowercase-hyphen ID (e.g., codebase-researcher). Avoid colons (reserved for plugin namespaces). |
description |
Yes | Natural-language classifier trigger telling the coordinator when to delegate (all agents share a 15K-token startup budget). |
tools |
No | Explicit allowlist (Read, Grep, Glob, Bash). Warning: omitting tools inherits every session & MCP tool! |
disallowedTools |
No | Denylist subtracted before tools resolves (e.g., Write, Edit, Agent, mcp__github). |
model |
No | haiku, sonnet, opus, full ID, or inherit. Precedence: per-call → frontmatter → CLAUDE_CODE_SUBAGENT_MODEL → parent. |
permissionMode |
No | default, acceptEdits, auto, dontAsk (pre-allowed only), plan (read-only), or bypassPermissions (CI containers only). |
hooks |
No | Agent-scoped lifecycle scripts (PreToolUse, PostToolUse, Stop) to validate CLI arguments or auto-format edits. |
isolation • maxTurns • memory |
No | isolation: worktree prevents parallel edit collisions; maxTurns caps runaway spend; memory: project persists notes. |
name / description keys cause silent skips at startup. Run claude plugin validate .claude/agents (and /doctor to spot duplicate names) right after editing!
5. Prompt Anatomy & 3 Production-Grade Subagents
You do not need twenty exotic agents. Ninety percent of real-world engineering teams get maximum leverage from just three tightly scoped specialists: a Scout, a Test-Runner, and a Skeptical Critic.
The 5-Part Subagent Specification Formula (Color-Coded)
Three Battle-Tested Agents Ready for .claude/agents/ (or Any Repo)
codebase-researcherPosture: Read-only scout on a fast, low-cost model.
---
name: codebase-researcher
description: Read-only repo
investigator. Use before
planning or implementation.
tools: Read, Grep, Glob
model: haiku
color: cyan
---
Never edit files. Map exact
entry points & conventions.
Return ONLY:
## Findings (file:line)
## Key Files
## Conventions Observed
## Open Questionstest-writerPosture: Edit-capable, scoped strictly to test suites.
---
name: test-writer
description: Writes & runs unit
and route tests after code
changes. Use proactively.
tools: Read, Write, Edit,
Grep, Glob, Bash
model: sonnet
---
1. Match existing fixtures &
naming in tests/.
2. Write failing cases first,
then run suite until green.
3. Never alter prod src/ code;
report prod bugs upstream!skeptical-reviewerPosture: Blind adversarial verifier; returns verdict only.
---
name: skeptical-reviewer
description: Adversarial diff
reviewer. Use before telling
the user work is complete.
tools: Read, Grep, Glob, Bash
model: sonnet
maxTurns: 25
---
Assume changes are broken until
proven. Read full changed files
& run tests yourself. Return:
## VERDICT: SHIP | FIX
## Blocking [file:line]
## Verification Evidenceskeptical-reviewer in a clean context forces cold, independent verification of the actual git diff and exit codes!
6. Invocation Mechanics, Context Forks & Concurrency
Understanding what crosses the context boundary at launch—and when to reach for a fork or resume instead of a fresh spawn—eliminates the "amnesia tax" between pipeline stages.
Four Ways to Trigger a Subagent (From Soft Routing to Guaranteed Pinning)
| Trigger Mechanism | Syntax Example | Guarantee & Under-the-Hood Behavior |
|---|---|---|
| 1. Automatic Delegation | "Audit the auth module and summarize risks." | Coordinator matches task intent against loaded description strings and calls the Agent tool automatically. |
| 2. Natural-Language Name | "Use the skeptical-reviewer agent on my diff." | Very high likelihood; coordinator still composes the task briefing passed across the boundary. |
3. Explicit @ Mention |
@agent-skeptical-reviewer check HEAD~1 |
Guaranteed execution of that exact subagent. Note: your coordinator still writes the subagent's briefing prompt! |
| 4. Whole-Session Mode | claude --agent skeptical-reviewer |
Runs your main thread itself under that agent's system prompt, tool allowlist, and model from turn one. |
Clean-Slate Subagent vs. Context Fork (/subtask • fork)
- Sees at startup: Its own Markdown prompt, the coordinator's briefing, repo
CLAUDE.md/AGENTS.md, git status snapshot, and preloadedskills. - Watch out: Built-in lightweight scouts (like
Explore) skipCLAUDE.mdto save tokens—restate critical folder exclusions directly in your prompt!
/subtask or fork)- Sees at startup: Your complete parent conversation history, tools, and system prompt—while keeping all new tool calls isolated in the background!
- Cache superpower: Shares the parent's prompt cache, making its first turn dramatically cheaper than re-briefing 40K tokens of context from scratch.
Three Runtime Rules Every Orchestrator Should Know
Completed agents retain an Agent ID. Asking the coordinator to "resume that same reviewer" sends a follow-up via SendMessage with full history intact—zero re-reading!
Subagents can spawn child helpers up to 3 layers deep by default (tuned via ..._MAX_SUBAGENT_SPAWN_DEPTH; set 1 for flat hub-and-spoke). Forks never re-fork.
Up to 20 background subagents run simultaneously before queueing (tuned via ..._MAX_CONCURRENT_SUBAGENTS). Press Ctrl+B anytime to background a live run.
7. Least-Privilege Scoping & Command-Inspecting Hooks
Once subagents run unattended in the background—often reading untrusted web pages, GitHub issues, or third-party READMEs—prompt politeness is not a security boundary. Enforce blast-radius limits in configuration.
Write, Edit & Agentplan or dontAskLayer 1 & 2: Tool Filtering Dials & Per-Agent Permission Modes
- Narrow job? Use
tools:tools: Read, Grep, Globguarantees zero file writes and zero shell access. - Broad job? Use
disallowedTools: Subtract dangerous capabilities likeWrite, Edit, mcp__github. - Restrict who spawns whom: A main coordinator with
tools: Agent(researcher, test-writer), Readis structurally blocked from spawning any unlisted editor!
permissionMode Safelyplan: Enforces structural read-only mode inside scouts.acceptEdits: Smooth local coding inside isolated worktrees.dontAsk: Auto-denies anything outside pre-approved rules—ideal for unattended background runs.- Note: If your parent session runs
bypassPermissions, children inherit it—reserve bypass strictly for disposable containers!
Layer 3: Argument-Level Guardrails with a PreToolUse Bash Hook
Giving an analyst tools: Bash lets it run psql—but also rm -rf! Pair frontmatter hooks with a 10-line validator script where exit 2 blocks bad commands and feeds stderr straight back to the subagent:
# .claude/agents/db-analyst.md
---
name: db-analyst
description: Read-only SQL reporting analyst.
tools: Bash, Read
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/readonly-sql.sh"
---#!/usr/bin/env bash
# ./scripts/readonly-sql.sh (remember: chmod +x!)
CMD=$(jq -r '.tool_input.command // empty')
if echo "$CMD" | grep -qiE \
'\b(INSERT|UPDATE|DELETE|DROP|ALTER|TRUNCATE|rm)\b'; then
echo "Blocked: SELECT queries only." >&2
exit 2 # Hard-blocks call & informs agent!
fi
exit 08. 5 Copy-Paste Orchestration Recipes That Pay Off Daily
Drop these five battle-tested prompts straight into your coordinator session. Each combines explicit boundaries, isolation, and convergence rules so agents finish cleanly without babysitting.
| Recipe & Pattern | Agents & Isolation Setup | Copy-Paste Kickoff Prompt |
|---|---|---|
| 1. Sharded Repo Security & Architecture Audit Parallel Fan-Out → Merge |
3x codebase-researcherModel: haiku / flashWorkspace: shared read-only |
"Spawn 3 parallel codebase-researcher subagents covering src/auth/, src/billing/, and src/webhooks/. Each must return a 250-word report of entry points, external calls, and authz gaps. Merge all three into one prioritized risk table." |
| 2. Writer + Blind Adversarial Critic Gate Sequential + Bounded Loop |
Main builder + skeptical-reviewerCap: 3 rounds max Uses stateful Resume |
"Implement cursor pagination on GET /orders. Then run skeptical-reviewer on the diff. If it returns FIX, patch blocking items and resume the exact same reviewer to re-verify. Stop at SHIP or escalate after 3 rounds." |
| 3. Competing Hypothesis Bug Hunt Parallel Evidence Race |
2x read-only debug scouts Model: sonnet / promaxTurns: 20 each |
"Users see intermittent 502s on checkout. Spawn 2 parallel scouts: Scout A investigates connection-pool exhaustion in src/db/; Scout B investigates Stripe webhook retries in src/payments/. Require file:line proof to crown a winner." |
| 4. Spec-to-Slice Parallel Feature Build Worktree Builder Fan-Out |
2x builders w/ isolation: worktree (or workspace: "share") + 1x verifier |
"From our approved API contract, spawn Builder A in a worktree owning src/api/export/ and Builder B in a worktree owning src/ui/export/. Neither may touch outside files. Merge both branches and run test-writer end-to-end." |
| 5. Zero-Regression Migration Pipeline 4-Hop Handoff Chain |
researcher → Migrator → test-writer → skeptical-reviewer |
"Run a 4-stage pipeline to upgrade our auth middleware: (1) codebase-researcher lists every callsite; (2) migrate callsites in main thread; (3) test-writer adds regression coverage; (4) skeptical-reviewer verifies backward compatibility." |
/compact—buying back sharp model attention immediately!
9. One Mental Model Across Every Major Coding Agent
In 2026, subagent concepts converged across the entire industry—and several editors even auto-load .claude/agents/ directly! Use this Rosetta Stone to translate any orchestration workflow in seconds.
| Capability | Claude Code | Google Antigravity | Cursor (3.x) | Copilot & OpenAI Codex |
|---|---|---|---|---|
| Definition Location | .claude/agents/*.md~/.claude/agents/ |
Built-in + Plugin agents + dynamic define_subagent |
.cursor/agents/*.md(also reads .claude/!) |
Copilot: .github/agents/Codex: .codex/agents/*.toml |
| Explicit Dispatch | @agent-name, prose, or claude --agent |
invoke_subagent tool, /browser, /teamwork |
/name slash command in chat or prose |
Copilot: agents: allowlistCodex: spawn_agent prompt |
| Tool & Sandbox Lock | tools / disallowedTools + PreToolUse hooks |
EnableWriteTools, EnableMCPTools, sandbox |
readonly: true flag in YAML frontmatter |
Copilot: ['read','search']Codex: sandbox_mode |
| Parallel Git Isolation | isolation: worktree in frontmatter |
Workspace: "share" or "branch" clone |
Worktree env on request or /in-cloud VM |
Copilot: cloud PR branch Codex: session worktrees |
| Context Fork & Resume | /subtask fork + SendMessage to ID |
fork:"coordinator" + send_message(id) |
Resume agent <id>; /goal long runs |
Copilot: UI handoffsCodex: resume_agent |
| Peer Team Mode | Agent Teams & cross-session messaging | Native swarm board (/teamwork) |
Agents Window multi-VM & /autopilot |
VS Code Agent Host (5-deep) & Agent Merge |
The Polyglot Repository Layout: Commit Once, Run in Every Client
my-repository/
├─ AGENTS.md # Universal repo rules & cmds
├─ .claude/agents/ # Canonical Markdown agents
│ ├─ researcher.md # Read by Claude/Cursor/VSCode
│ └─ reviewer.md # Adversarial diff gate
├─ .agents/skills/ # On-demand SKILL.md playbooks
├─ .cursor/agents/ # Optional Cursor overrides
├─ .github/agents/ # Optional Copilot handoffs
└─ .codex/agents/*.toml # Optional Codex TOML roles- Start with
AGENTS.md+.claude/agents/: Both Cursor and VS Code detect.claude/agents/*.mdnatively, while Antigravity, Codex, and Cursor all obey rootAGENTS.mdinstructions. - Know what silently drops: Advanced Claude fields (
hooks,permissionMode,memory,isolation) are ignored by other clients—keep core role rules in the Markdown body too!
10. End-to-End Orchestration Pipeline & Cost Engineering
Smart orchestration pairs a frontier reasoning coordinator with fast, inexpensive specialist workers—delivering cleaner architecture and independent verification at a fraction of an all-frontier swarm bill.
6 Token & Cost Guardrails That Prevent Multi-Agent Bill Shock
Keep opus / gemini-pro on your coordinator, pin haiku / flash on file scouts, and use sonnet on builders. Set CLAUDE_CODE_SUBAGENT_MODEL as a safe floor.
Five parallel subagents spend ~5x tokens, and ten verbose return summaries will overflow your coordinator's context window! Never fan out what one Grep can answer.
Every installed agent's description loads into session preamble on turn 1. Keep descriptions to 1–2 crisp sentences; put detailed instructions in the Markdown body.
maxTurns & Round CapsPut maxTurns: 20–30 on exploratory or review agents, and cap critic loops at 3 rounds where only blocking defects trigger another iteration.
cacheTtl: 1hUse /subtask forks when side tasks need heavy shared history (free prompt-cache hit!), and set experimental: { cacheTtl: 1h } on long-running specialists.
Every token a subagent returns gets billed again on every subsequent turn of your main session. Demand 250-word bulleted memos citing file:line.
11. Troubleshooting Clinic & Pre-Flight Cheat Sheet
Keep this back-page clinic within reach whenever a custom subagent fails to trigger, loses context across stages, or stalls silently in the background.
Top 7 Subagent & Orchestration Pitfalls (& Their 10-Second Fixes)
| Symptom / Failure Mode | Root Cause & 10-Second Fix |
|---|---|
| Coordinator never auto-delegates to my custom agent | Vague description (e.g., "Helps with tests"). Rewrite as a sharp trigger: "Use proactively right after code edits to write and run unit tests"—or pin via @agent-name. |
| Newly created agent file is completely invisible | .claude/agents/ folder did not exist at session start, or YAML frontmatter has syntax errors / colons in name. Restart session and run claude plugin validate .claude/agents. |
| Stage 2 worker repeats Stage 1's mistakes or searches | Amnesia across clean-slate hops. Require Stage 1's output contract to list disproved dead ends, pass its report into Stage 2's prompt, or use /subtask (fork) / SendMessage resume. |
| Two parallel builders overwrote each other's edits | Shared git checkout with overlapping files. Add isolation: worktree (or Antigravity Workspace: "share") per builder, or partition strict non-overlapping directory ownership. |
| Critic review loop burns tokens forever on tiny nits | Fresh reviewer respawned each round without convergence rules. Always resume the same reviewer ID, split Blocking vs. Non-Blocking, and cap at 3 rounds max. |
| Background subagent hangs mid-run without finishing | Waiting on an interactive tool approval prompt surfaced in your main window—or folder trust wasn't accepted for project hooks. Answer the prompt or use acceptEdits / dontAsk. |
Built-in Explore scout ignored my CLAUDE.md rules |
By design, lightweight built-in Explore/Plan scouts skip CLAUDE.md to save startup tokens. Put critical constraints (like "ignore vendor/") directly in the delegation prompt—or use your own custom scout! |
researcher, test-writer, and skeptical-reviewer.isolation: worktree or disjoint folder boundaries.Write / Edit from scouts & critics; gate Bash with hooks.SendMessage instead of respawning.file:line citations so reports carry cleanly.maxTurns + a 3-round escalation rule before walking away!codebase-researcher.md and skeptical-reviewer.md (from Page 6) into your repo's .claude/agents/ folder, commit them to Git, and run your very next feature as Scout → Build → Blind Critic. You will feel the jump in context clarity on turn one!