Chapter 4 · Subagents 01 / 19
Mastering Claude Code · A 10-Part Series

Subagents in Claude Code

How to delegate work to specialized assistants with their own context windows — agent files, worktree isolation, persistent memory, and experimental agent teams.

Sid Dani · June 2026
01 · The Problem

Your context window is finite — subagents spend someone else's

Long sessions die of context pollution: every file read, every test log, every dead end lands in the one window you have. A subagent is a specialized assistant Claude Code delegates a task to — it gets its own context window, its own system prompt, and its own tool permissions, does the work with a clean slate, and hands back only the result.

That one move buys five things at once: context preservation, specialized expertise with higher success rates, reusability across projects and teams, flexible permissions per agent type, and parallel scale — multiple agents on different aspects simultaneously.

Chapter 3's context: fork was the preview. This chapter is the machinery underneath — and /agents is the quick-start command for all of it.
02 · The Architecture

Delegation runs 60k tokens of work — your window pays for the summary

Main agent · the resource to protect
Your conversation — coordinator, synthesizes everything
50,000 tokens
delegates — each subagent starts with a clean slate + task brief only
Subagent 1 · fresh window
Code reviewer
20,000 tokens
Subagent 2 · fresh window
Test engineer
20,000 tokens
Subagent 3 · fresh window
Documentation
20,000 tokens
returns — results only, distilled back to the main agent
Latency is the tax: a clean slate must re-gather its bearings before it produces. Spend a subagent on heavy work; keep quick tasks in the main window.
03 · Anatomy

An agent is a Markdown file — /agents writes it for you

---
name: test-runner
description: Use proactively to run
  tests and fix failures
tools: Read, Edit, Bash   # optional
model: sonnet            # optional
---

You are a test automation expert.
When you see code changes, run the
tests. If they fail, fix them while
preserving the original test intent.
  • Only name (lowercase + hyphens) and description are required — everything below the frontmatter is the system prompt
  • /agents is the interactive menu: view all agents, guided create, edit tools, delete, see which wins a duplicate
  • Or skip the menu: mkdir -p .claude/agents and drop .md files in — that's the whole install
Same pattern as skills: frontmatter decides behavior, Markdown body is the expertise. Start with a Claude-generated agent, then iterate.
04 · Locations

Four places define agents — closest to the session wins

1 · --agents '{…}'CLI flag, JSON — session only, overrides every other source
2 · .claude/agents/Project — commit to git, the whole team gets them
3 · ~/.claude/agents/User — follows you across all projects
4 · <plugin>/agents/Plugin — shipped via installed plugins, lowest priority
  • Duplicate names → the higher-priority source shadows the lower one
  • claude agents lists everything grouped by source — and flags the overrides
  • --agents JSON needs description + prompt; tools and model optional — perfect for scripted, one-session agents
05 · Power Fields

A dozen optional fields tune tools, models, and behavior

1Tool scoping

tools: lists exact tools (omit = inherit all), patterns like Bash(npm:*) work, and Agent(worker, researcher) allowlists which subagents it may spawn (Task renamed to Agent in v2.1.63 — old refs still alias). disallowedTools: bans tools outright.

2Model & effort

model: sonnet · opus · haiku · a full model ID · inherit. effort: low → max scales reasoning depth per agent.

3Preloaded context

skills: injects full skill content at startup — and since v2.1.133 subagents also discover the whole skill catalog via the Skill tool. mcpServers: attaches MCP servers.

4Behavior controls

permissionMode (default · acceptEdits · dontAsk · bypassPermissions · plan), maxTurns caps the loop, hooks: run scoped to this agent only, initialPrompt auto-submits a first turn when it runs as the main agent.

Four more fields — memory, background, isolation, context: fork — are big enough to earn their own slides ahead.
06 · Built-ins

Six built-ins are already running — you've used subagents all along

general-purposeInherits your model, all tools — complex multi-step research and modification
PlanRead, Glob, Grep, Bash — the researcher behind plan mode
ExploreHaiku, strictly read-only — fast codebase search at "quick", "medium", or "very thorough" depth
BashTerminal commands in a separate context window
statusline-setupSonnet — configures the status line display
Claude Code GuideHaiku, read-only — answers questions about Claude Code itself
Every time plan mode researched your codebase, a subagent did it — custom agents just let you author the specialist yourself.
07 · Invocation

Describe the task and Claude delegates — or name the agent and guarantee it

1Automatic

Claude matches your request against each agent's description. Add "use PROACTIVELY" or "MUST BE USED" to the description to bid for automatic delegation.

2Explicit

"Use the test-runner subagent to fix failing tests" — name it in plain English and Claude routes the task there.

3Guaranteed

@"code-reviewer (agent)" — the @-mention bypasses delegation heuristics entirely. The named agent runs, full stop.

4Session-wide

claude --agent code-reviewer (or "agent" in settings.json) runs the whole session as that agent. Main-thread honoring is scoped: mcpServers loads via --agent (v2.1.117+); permissionMode applies to built-in agents (v2.1.119+); tools only in --print mode (v2.1.119+).

Since v2.1.140 agent matching is case- and separator-insensitivecode-reviewer, Code Reviewer, code_reviewer all resolve to the same agent instead of silently falling back to the default.
08 · Lifecycle

Agents resume with full context and chain into pipelines

Resume — pick up where it left off

> Use the code-analyzer agent to start
  reviewing the authentication module
# returns agentId: "abc123"

> Resume agent abc123 and now analyze
  the authorization logic as well

The conversation continues with full context preserved — long research across sessions, iterative refinement without starting over.

Chain — output feeds the next agent

> First use the code-analyzer subagent
  to find performance issues,
  then use the optimizer subagent
  to fix them

Sequenced delegation in one request — each subagent's findings become the input for the next, with the main agent coordinating.

09 · Persistent Memory

memory: gives an agent knowledge that compounds across sessions

memory: user~/.claude/agent-memory/<name>/ — personal notes across all projects
memory: project.claude/agent-memory/<name>/ — project knowledge, shared with the team
memory: local.claude/agent-memory-local/<name>/ — project knowledge, never committed
  • The first 200 lines of MEMORY.md auto-load into the agent's system prompt each run
  • Read, Write, Edit are auto-enabled so the agent manages its own memory files
  • The agent can grow extra files in its directory as its knowledge accumulates
This is Chapter 2's lesson applied to specialists: a researcher that remembers last week's findings beats one that re-derives them every session.
10 · Background

background: true keeps slow work off your main thread

A background subagent runs while you keep working — set background: true in frontmatter to make an agent always run that way, or press Ctrl+B to background a task that's already running.

Ctrl+BBackground the currently running subagent task
Ctrl+F (twice)Kill all background agents — second press confirms
auto-denyBackground agents deny any permission that isn't pre-approved — they can't stop to ask you
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1Environment variable disables background task support entirely
The auto-deny rule is the design constraint: pre-approve the permissions a background agent needs, or watch it fail silently mid-run.
11 · Worktree Isolation

isolation: worktree lets an agent edit without touching your tree

1
Spawn
isolation: worktree
frontmatter flag
2
Branch
Own worktree + branch
created automatically
3
Work
Edits land in isolation
main tree untouched
If no changes
Worktree auto-cleaned
nothing to review, nothing left behind
If changes exist
Returns worktree path + branch
you review or merge on your terms
Two agents implementing two features can't trample each other's diffs — each works on its own branch, and nothing reaches your working tree without review.
12 · Forked Context

context: fork starts the agent knowing everything you know

The clean slate is the default — and usually the point. context: fork inverts it: the subagent inherits the parent's full conversation at the moment of forking, explores an alternative path, and reports back without disturbing the original. GA in v2.1.117; on external builds set CLAUDE_CODE_FORK_SUBAGENT=1.

Explore an alternative implementationfork — a clean slate would lose the work so far
Long research mid-conversationfork — the existing context is the input
Independent specialized taskclean — history would only distract
Avoiding context pollutionclean — isolation is the whole goal
Ask one question: is the conversation so far an asset or a liability for this task? Asset → fork. Liability → clean slate.
13 · Agent Teams

Teams are peers with a mailbox — subagents are specialists with a report

Agent Teams (experimental, off by default, v2.1.32+) coordinate multiple full Claude Code instances: a team lead assigns work through a shared task list with automatic dependency tracking, and teammates message each other directly through a mailbox.

DelegationSubagent: parent waits for a result · Team: teammates execute independently
ContextSubagent: fresh per subtask, distilled back · Team: each keeps a persistent window
CommunicationSubagent: results to parent only · Team: direct inter-agent messages via mailbox
CoordinationSubagent: parent-managed · Team: shared task list resolves dependencies itself
ResumptionSubagent: supported · Team: not supported with in-process teammates
Best forSubagent: focused, well-defined subtasks · Team: parallel work that needs cross-talk
14 · Teams in Practice

Teams need one env var — and a task list that runs itself

Running a team

  • Enable: CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 (env or settings.json)
  • Then just ask: "Build the auth module. Use a team — one teammate for API, one for schema, one for tests"
  • The lead plans first — you approve the plan before any code changes
  • Display: --teammate-mode auto · in-process (default) · tmux split-panes; Shift+Down hops between panes
  • Two team hook events: TeammateIdle and TaskCompleted

Limits to design around

  • Keep teams at 3–5 teammates, tasks at 5–15 minutes, different files per teammate
  • One team per session · no nested teams · lead role can't transfer
  • In-process teammates can't resume after the session ends
  • Split-panes need tmux/iTerm2 — not VS Code terminal, Windows Terminal, or Ghostty
  • Experimental: test on non-critical work first
Config lives at ~/.claude/teams/{team-name}/config.json — but the real control surface is task sizing and file separation.
15 · Guardrails & Runtime

The runtime has rules: no nesting, scoped plugins, traceable spend

1Plugin agents are sandboxed

Plugin-provided subagents may not declare hooks, mcpServers, or permissionMode — a plugin can't escalate privileges or smuggle in arbitrary commands through an agent file.

2No nested spawning

Subagents cannot spawn other subagents. To control delegation from the top, allowlist with Agent(worker, researcher) in the tools field — the allowlist governs what the spawning session may delegate to; only the named agents may be spawned.

3Transcripts & compaction

Every run is logged at ~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonl; context auto-compacts at ~95% capacity (override: CLAUDE_AUTOCOMPACT_PCT_OVERRIDE).

4Observability (v2.1.139)

Subagent API calls carry x-claude-code-agent-id + x-claude-code-parent-agent-id headers, mirrored as OpenTelemetry span attributes — attribute spend per agent type, rebuild invocation trees, alert on runaways.

16 · The Gallery

Nine ready-made agents ship with this chapter — tool grants match the job

code-reviewerRead, Grep, Glob, Bash — quality + security review, severity-ranked findings
clean-code-reviewerSame tools — Clean Code / SOLID enforcement with file:line fixes
secure-reviewerRead, Grep only — security audit that physically cannot execute or modify
test-engineerRead, Write, Bash, Grep — test suites targeting >80% coverage
debuggerRead, Edit, Bash, Grep, Glob — root-cause analysis, minimal fix, verify
performance-optimizerRead, Edit, Bash, Grep, Glob — profile, fix the biggest bottleneck, re-measure
implementation-agentFull toolset incl. Write — end-to-end feature implementation
documentation-writerRead, Write, Grep — API docs, guides, architecture docs
data-scientistBash, Read, Write · model: sonnet — SQL + BigQuery analysis
Read the grants as policy: reviewers read, builders write, the security agent can't run anything. Install: cp 04-subagents/*.md .claude/agents/ then verify with /agents.
17 · Best Practices

Delegate the heavy, skip the quick — and give every agent one job

Do

  • Delegate multi-step features, parallel work, long-running analysis
  • Design focused agents — single, clear responsibility
  • Write detailed prompts: role, priorities in order, output format, action steps
  • Start restrictive on tools — read-only for analysts, expand only when needed
  • Version-control project agents so the team shares them

Don't

  • Spawn an agent for quick single tasks — the clean slate adds pure latency
  • Create overlapping agents with the same role
  • Grant tools the job doesn't need
  • Mix concerns in one agent's prompt
  • Forget to pass the context the agent needs — it can't see your conversation
The system-prompt recipe from the examples: specific role → ordered priorities → output format → "when invoked, do X first." Every gallery agent follows it.
18 · Recap

Isolation is the whole game — everything else is configuration

A subagent is a Markdown file: frontmatter sets the tools, model, and permissions; the body is the system prompt. The description decides when Claude delegates automatically. Of every feature so far, subagents are the only one with an isolated context window — and four fields extend it: memory persists knowledge, background unblocks your thread, isolation: worktree protects your tree, context: fork shares your history. When specialists need to talk to each other, that's agent teams.

Copy code-reviewer.md into .claude/agents/ today — its description says "use PROACTIVELY", so it'll fire on its own after your next code change. Chapter 5: MCP, where agents reach outside the machine.
Sid Dani