cheat sheet

Claude Code Subagents

Spawn isolated subagents with the Task tool — Plan, Explore, general-purpose, project-defined agents, isolation modes including worktrees, background runs, and orchestration patterns.

Claude Code Subagents

What it is

Subagents are isolated Claude instances spawned from a parent session via the Task tool. Each subagent has its own context window, tool permissions, and (optionally) its own working directory or git worktree, and returns a final summary back to the parent — the parent never sees the subagent's intermediate steps. Use them for parallel research, isolation-sensitive edits (so a risky operation cannot disturb the main session), background work that takes minutes to hours, and to escape from a polluted context without losing forward progress. They are Claude Code's answer to "I want to fan out and merge" — comparable in spirit to map/reduce, but with each map being a full agentic Claude.

When to use a subagent

Reach for a subagent when at least one of these applies:

ReasonWhy subagent over inline
Parallel researchTwo questions can be investigated simultaneously
Long contextThe task needs to read many files but only the summary matters
Risk isolationThe work should not touch the main checkout
Different toolingSubagent uses Plan-mode (read-only) while parent edits
Background workThe task takes minutes; parent should keep going

Skip subagents when the work is short, sequential, and shares context tightly with the rest of the conversation — the spawn overhead outweighs the benefit.

Available subagent types

Claude Code ships with three built-in agent types. Projects and users can register additional ones via .claude/agents/<name>.md.

AgentReadEditRun shellNetworkTypical use
general-purposeyesyesyesyesDefault — broad agentic work
planyesnono (read-only bash)yesInvestigation, design, audits
exploreyesnoyes (read-only)yesDeep codebase walks
text
> /agents

Output:

text
Configured agents:
  general-purpose   — broad agentic work (full toolset)
  plan              — read-only investigation
  explore           — codebase walks
  reviewer          — security-focused PR review (project)

The Task tool

The underlying primitive is the Task tool, exposed to Claude as a regular function. When Claude calls Task, the harness spins up a fresh agent with the requested type and prompt, runs it to completion, and returns its final message as the tool result.

text
Task(
  subagent_type: "general-purpose" | "plan" | "explore" | "<custom-name>",
  description: "<short label shown in UI>",
  prompt: "<full task prompt the subagent receives>"
)

Output: (none — schema-only; the harness invokes Task on Claude's behalf)

You usually do not call Task directly — you ask Claude to "spawn a subagent" or "fan out" and the model picks the right type and prompt. But it can be invoked explicitly via custom slash commands with the subagent: frontmatter key.

Spawning a subagent from the REPL

Just ask. Claude knows about Task and uses it when the situation warrants.

text
> Spawn a Plan agent to investigate how authentication works in this codebase 
  and produce a written report. Don't make any edits.

Output:

text
[Task: plan]   Investigating auth module
  → reads src/auth/, follows imports, summarises in 220 lines
[Task done]
Report:
  1. Auth is handled in src/auth/jwt.py via PyJWT
  2. Tokens are stored in HttpOnly cookies
  ...

Parallel subagents

A parent can spawn multiple subagents at once and merge their results. This is the canonical pattern for fan-out research.

text
> Spawn three Plan agents in parallel:
  1. Find every async function that doesn't await its result
  2. List all SQL queries that aren't parameterized
  3. Find every TODO/FIXME older than 90 days
  Merge findings into one report grouped by severity.

Output:

text
[Task: plan #1]  awaiting-issues          → 4 findings
[Task: plan #2]  sql-injection-audit      → 1 finding
[Task: plan #3]  stale-todos              → 12 findings
[Merge complete]

Subagents share the same prompt cache as the parent, so spinning up three is roughly 1.3× the cost of one — not 3× — provided they read overlapping context.

Project-defined agents

Define a custom subagent by dropping a Markdown file under .claude/agents/<name>.md. The frontmatter declares the agent's name, allowed tools, and (optionally) its system prompt; the body is the default prompt Claude uses when invoking the agent.

markdown
---
name: reviewer
description: "Security-focused PR reviewer"
allowedTools: [Read, Glob, Grep, Bash(git diff:git log:git show)]
model: claude-opus-4-7
---

You are a senior security engineer reviewing a pull request. Focus on:
1. Injection vulnerabilities (SQL, command, XSS)
2. Auth bypass and authorization mistakes
3. Secrets in code or test fixtures
4. Insecure defaults (e.g. http instead of https)

Report findings as a Markdown table: Severity | File:Line | Issue | Fix.
Be terse. Never apply edits.

Save as .claude/agents/reviewer.md. Confirm:

text
> /agents

Output:

text
Configured agents:
  general-purpose
  plan
  explore
  reviewer          ← (project)

Then spawn it like any built-in:

text
> Use the reviewer agent on the staged diff.

Output:

text
[Task: reviewer]   Reviewing 142 lines of diff
[Task done]
| Severity | File:Line | Issue | Fix |
|----------|-----------|-------|-----|
| High     | src/db.py:88 | SQL string-concat | Use parameterised query |

User-defined agents

User-global agents live under ~/.claude/agents/<name>.md with the same schema. They show up everywhere, but a project-scoped definition with the same name overrides them.

bash
mkdir -p ~/.claude/agents

Output: (none — exits 0 on success)

Isolation modes

Subagents inherit the parent's working directory by default. For sensitive or risky work, escalate isolation with the isolation frontmatter key or runtime flag.

IsolationBehaviorWhen to use
inheritSame cwd as parent (default)Most cases
tempdirSubagent gets a clean temp directorySpike or scratch work
worktreeSpawn a git worktree add and run inside itRisky refactor; don't touch main checkout
markdown
---
name: spike-typescript
description: "Throwaway spike: convert a file to TypeScript"
isolation: worktree
allowedTools: [Read, Edit, Write, Bash(npx tsc *:npx tsc --noEmit)]
---

Convert the requested file to TypeScript and verify it typechecks.
Return the resulting code. Do not commit.

Output: (none — file applies when spike-typescript is invoked)

Worktree isolation

Worktree isolation is the strongest practical isolation Claude Code offers — the subagent gets its own git worktree on a fresh branch, so anything it writes lives outside your main checkout until you choose to merge or discard it.

text
> Use the spike-typescript agent on src/utils.js.

Output:

text
[Task: spike-typescript]   isolation=worktree
  git worktree add /tmp/claude-spike-abc /home/alice/Code/myproject
  cd /tmp/claude-spike-abc
  edits src/utils.ts
  npx tsc --noEmit src/utils.ts → ok
[Task done]
Branch claude-spike-abc created with 1 file changed.

When the subagent finishes, the parent receives the diff and you can choose to merge, cherry-pick, or git worktree remove --force to discard.

Background subagents

A subagent with background: true runs without blocking the parent. The parent gets back a handle (an opaque task ID) and can poll for completion or fire-and-forget.

markdown
---
name: nightly-audit
description: "Long-running architecture audit"
background: true
allowedTools: [Read, Glob, Grep]
---

Walk the entire repo and produce a JSON report:
- files larger than 500 lines
- circular imports
- exports with zero in-repo usages
Write the report to /tmp/audit.json. Return the path when done.

Output: (none — file applies when nightly-audit is invoked)

text
> Spawn the nightly-audit agent in the background.

Output:

text
[Task: nightly-audit, background]  task_id=task_01abc
Use the Monitor tool or `/agents status task_01abc` to follow progress.
text
> /agents status task_01abc

Output:

text
task_01abc  nightly-audit  running  3m12s elapsed   reading src/api/
text
> /agents wait task_01abc

Output:

text
task_01abc  nightly-audit  done    7m48s total
Report at /tmp/audit.json

Background subagents keep the parent session alive. If you /exit, pending background tasks are cancelled. Use a Stop hook to log unfinished tasks if you need recovery.

Plan mode in depth

plan is the most-used subagent type. It runs Claude with read-only tools and a system prompt that biases hard toward analysis. The agent produces a numbered plan; the parent decides whether to apply it.

text
> Use a plan agent to design a Redis-caching layer for the user service.

Output:

text
[Task: plan]   Designing Redis cache for user service
[Task done]

Plan:
1. Add `redis` dependency and config (REDIS_URL env var).
2. Introduce src/cache/redis.py with get/set/delete helpers.
3. Wrap UserService.get_by_id() with cache-aside pattern.
4. Add unit tests using fakeredis.
5. Migration plan: deploy in shadow mode for 24h before switching reads.

Apply this plan? [y/N]

/plan <prompt> is a built-in slash command that wraps a single user prompt in a Plan agent without you having to ask for it.

Explore mode in depth

explore is similar to plan but designed for "what's in this codebase?" walks. It can run read-only shell commands (ls, grep, git log, cat) but cannot edit.

text
> Use an explore agent to map the data model and how requests flow through 
  the FastAPI app.

Output:

text
[Task: explore]   Mapping data model + request flow
[Task done]

## Data model
  - src/models/user.py — User (uuid, email, created_at)
  - src/models/session.py — Session (id, user_id, expires_at)
  - src/models/post.py — Post (id, user_id, body, ...)

## Request flow
  POST /login → src/api/auth.py:login() → src/services/auth.py:authenticate()
              → src/models/user.py + src/models/session.py
  ...

Orchestration patterns

Research-then-implement

text
> Step 1: spawn a Plan agent to investigate how feature X works.
  Step 2: based on its report, implement the requested change inline.

Output:

text
[Task: plan]   Investigation done.
[Inline]       Applying changes...

Parallel triage

When triaging a long list of bugs, fan out one subagent per item.

text
> For each of these 5 issues (#101, #102, #103, #104, #105), spawn an explore 
  agent to identify the file most likely responsible. Return a single table.

Output:

text
[Task: explore #101]  → src/api/users.py
[Task: explore #102]  → src/utils/format.py
[Task: explore #103]  → src/auth/jwt.py
[Task: explore #104]  → src/api/posts.py
[Task: explore #105]  → src/db/migrations/2026_05_01_add_index.py

Worktree refactor with verification

text
> Use spike-typescript on src/utils.js, run tests in the worktree, and if 
  green, open a draft PR with the changes.

Output:

text
[Task: spike-typescript]  isolation=worktree
  edits src/utils.ts
  npx tsc --noEmit → ok
  npm test → 142 passed
  gh pr create --draft --title "Spike: utils.js → TypeScript"
[Task done]
PR #423 opened.

Long context offload

When the parent context is filling up, push a chunk of investigative work to a subagent whose final summary is far smaller than the files it read.

text
> Spawn an explore agent to summarise the 2,000 lines in legacy/ into a 
  30-line cheat sheet. Then forget legacy/ and continue with the refactor.

Output:

text
[Task: explore]   Read 38 files in legacy/ (2,142 lines)
[Task done]
30-line summary returned.

Parent context savings: ~46,000 tokens.

Spawning a subagent from a slash command

A custom slash command can route to a specific subagent by setting subagent: in frontmatter.

markdown
---
description: "Read-only audit via the explore agent"
subagent: explore
allowedTools: [Read, Glob, Grep]
---

Audit the project for architectural drift:
1. Layering violations
2. Files larger than 500 lines
3. Dead exports
Return a single Markdown report.

Invoke with /audit. The harness routes the prompt to an explore agent automatically.

Inspecting active subagents

text
> /agents list

Output:

text
ACTIVE
  task_01abc  reviewer        running   2m18s elapsed
  task_01def  nightly-audit   running   8m44s elapsed
DONE (this session)
  task_01ghi  plan            done      0m22s
text
> /agents cancel task_01def

Output:

text
task_01def  cancelled.

Common pitfalls

  1. Spawning when inline would do — for trivial work the spawn overhead and round-trip make subagents slower; reserve them for fan-out or isolation.
  2. Subagent loses cwdtempdir and worktree isolation modes start in a new directory; commands relying on ./relative paths fail. Use absolute paths in the prompt.
  3. Background subagents and /clear/clear does not cancel background tasks; they continue running but their results land in a cleared session and may be lost.
  4. Worktree leftoversgit worktree does not auto-clean; periodically git worktree prune and git worktree list to garbage-collect.
  5. Tool permissions inherited — if the parent has Bash(rm *) denied, the subagent does too; explicit allowedTools in the agent file overrides this.
  6. Plan agent making edits — a plan agent has no edit tools at all; if you ask it to write a file it will refuse. Use general-purpose after the plan is approved.
  7. Background tasks orphaning hooks — a SubagentStop hook fires when a background task ends; ensure it does not block on user interaction.

Real-world recipes

Spike a risky refactor in a worktree

text
> Use a worktree-isolated general-purpose agent to convert src/auth/ from 
  callbacks to async/await. Run the full test suite in the worktree before 
  returning. Do not commit.

Output:

text
[Task: general-purpose, isolation=worktree]
  refactored 4 files
  npm test → 142 passed
[Task done]
Diff returned. Worktree at /tmp/claude-spike-abc kept for review.

Audit-then-fix with two agents

text
> Step 1: spawn a plan agent to audit src/ for missing error handling.
  Step 2: feed its report to a general-purpose agent and apply the fixes.

Output:

text
[Task: plan]            5 issues found
[Task: general-purpose] 5 fixes applied

Parallel "search the docs" fan-out

When you need to find something across multiple unrelated docs sets.

text
> Spawn three explore agents, each with --add-dir to a different docs root:
  1. /home/alice/docs/internal
  2. /home/alice/docs/vendor-a
  3. /home/alice/docs/vendor-b
  Each: find the canonical guidance on retry policies. Return one merged table.

Output:

text
[Task: explore #1] → internal: max 3 retries, exponential backoff
[Task: explore #2] → vendor-a: max 5 retries, fixed backoff
[Task: explore #3] → vendor-b: not specified
[Merged]

Background nightly audit

Wire a project-defined nightly-audit agent to a cron-triggered headless run.

bash
0 3 * * * cd ~/Code/myproject && claude --dangerously-skip-permissions \
  -p "Spawn the nightly-audit agent and write its output to /tmp/audit-$(date +%F).json"

Output: (none — exits 0 on success)