Claude Code no longer runs one conversation at a time. A session can delegate to subagents, copy itself into a background session, hand you a dashboard of parallel work in agent view, and, if you turn on the experimental feature, coordinate a whole agent team with a shared task list and a mailbox. Each of these runs on the same engine but makes different promises about context, permissions, isolation, cost and where results land. Most multi-agent failures come from mixing those promises up: a reviewer that could write files, a "read-only" helper that inherited bypassPermissions, two teammates overwriting one file, or a background session deleted along with its uncommitted worktree.
This session is the implementation and design layer. Core 2 introduced subagents from the user side, and Core 4 showed day-to-day parallel sessions. Here you write agent files field by field, predict exactly which tools, model and permission mode a worker resolves to, run and govern teams and background sessions, write delegation briefs and result contracts that hooks can enforce, and orchestrate parallel work through worktrees to a clean merge. Autonomy 3 builds on this to run teams at scale with autonomy.
By the end you will be able to:
Write and debug .claude/agents/*.md files, including memory, hooks, MCP scoping and worktree isolation, and know which fields a plugin silently drops.
Choose between a subagent, a fork, /branch, a background session, an agent team, /batch and a cloud session for a given fan-out, and explain the cost of each.
Run background work from the shell and from agent view, script its state with claude agents --json, and wire notifications through the Notification hook.
Write briefs and handoff contracts with a result format and failure report that a SubagentStop or TaskCompleted hook can check.
Plan worktree lanes, merge order and conflict resolution, and pick the right cross-agent channel, from SendMessage to A2A.
Facts on this page are as of 2026-10-24 · v2.1.310. Agent view is a research preview and agent teams are experimental, so keys, states and flags in those sections can change; version-gated features are marked "requires v2.1.x+".
From left to right you give up more direct control and gain more parallel capacity. Subagents and forks report into your conversation. Background sessions report to you through agent view. Teammates report to the lead, and to each other. Cloud sessions keep running with your laptop closed. Every option multiplies token use. Hover or tab to a marker to see who coordinates it and where its results land; the widening token band shows a direction, not a measurement.
Custom Subagents
A custom subagent is a Markdown file that turns a side task you keep delegating into a named worker. The worker gets its own context window, system prompt, tool set, model and permission mode, and only its final message returns. This topic covers the file format field by field, how Claude Code resolves tools, model and mode when the worker launches, and how a worker keeps memory across sessions.
Agent Files
What it is. When Claude delegates, it calls the Agent tool. The tool starts a worker in a separate context window, the worker runs its own agentic loop, and the parent sees only the worker's final result, not its intermediate tool calls. The docs put the purpose plainly: use one "when a side task would flood your main conversation with search results, logs, or file contents you won't reference again". The worker "sends its own requests, which count toward the same usage limits as your main conversation". An agent file makes that worker reusable: a YAML frontmatter block configures it, and the Markdown body becomes its system prompt.
.claude/agents/code-reviewer.md
---
name: code-reviewer
description: Reviews diffs for correctness and security. Use proactively after code changes.
tools: Read, Bash
model: sonnet
---
You are a senior reviewer. Read the diff with `git diff main...HEAD`, then the
changed files. Report only correctness and security problems, each with
file:line, the failing scenario, and a suggested fix. Don't edit files.
The list is Read, Bash rather than Read, Grep, Glob, Bash because on macOS, Linux and WSL Claude Code provides Grep and Glob to a subagent only when its tools list names them and leaves Bash out; with Bash in the list they don't resolve, and the reviewer searches with grep and find through Bash. "Don't edit files" is advisory here: Bash can write, so see Persistent Memory and Handoff Contracts for making read-only stick.
The body is the whole prompt the worker gets: "Subagents receive only this system prompt plus basic environment details like the working directory, not the Claude Code system prompt." Claude Code still adds CLAUDE.md, a git status snapshot and any preloaded skills to its context (see Briefs for the full list).
Where definitions come from
When two definitions share a name, the higher-priority location wins:
Priority
Location
Scope
Notes
1
managed settings .claude/agents/
organization
Deployed by admins; beats project and user agents with the same name
2
--agents '{…}' JSON
this session
Not saved to disk; a JSON file path works only with -p (v2.1.281+)
3
.claude/agents/
project
Walked up from the working directory; closest definition wins. Commit it.
4
~/.claude/agents/
you, every project
Doesn't travel to teammates or cloud sessions
5
plugin agents/
where the plugin is enabled
Subfolders namespace the name: my-plugin:review:security
All five sources feed one registry keyed by the name field. Project and user folders are scanned recursively, but the subfolder doesn't change identity there. In plugins it does. If two files in one directory declare the same name, Claude Code loads one of them "chosen by filesystem read order rather than a documented precedence"; /doctor reports the duplicate. Hover or tab to a source or a registry row: shadowed definitions sit ghosted behind the winner. The agent names are illustrative.
Claude Code watches ~/.claude/agents/ and .claude/agents/, so an edited file applies to the next delegation within seconds. Three cases still need a restart: the first file in an agents directory that didn't exist when the session started, agents under an --add-dir directory, and sessions started with --disable-slash-commands.
Built-in subagents
Agent
Model
What it's for
Explore
main conversation's model (with Fable as main, on a subscription, Console or ANTHROPIC_BASE_URL gateway it runs the opus alias model)
Read-only search; Claude picks quick, medium or very thorough. Skips CLAUDE.md and git status.
Plan
inherits main
Read-only research during plan mode. Skips CLAUDE.md and git status.
general-purpose
CLAUDE_CODE_SUBAGENT_MODEL if set, else main
Exploration plus action, every subagent tool
claude
none of its own
Catch-all; the default agent for a dispatched background session
statusline-setup / claude-code-guide
Sonnet / Haiku
/statusline; Claude Code feature questions
A project or user agent named Explore overrides the built-in and keeps its own model, so model: haiku in such a file moves exploration to a cheaper model. CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1 (v2.1.198+) removes just those two.
Invoking a subagent
Natural language. "Use the code-reviewer subagent on my last commit." Claude decides whether to delegate, based on the request and each agent's description. "Use proactively" in a description encourages delegation.
@-mention.@"code-reviewer (agent)" look at the auth changes, or type @agent-code-reviewer. This guarantees which agent runs, but Claude still writes its task prompt from your message.
Whole session.claude --agent code-reviewer, or "agent": "code-reviewer" in .claude/settings.json. The agent's prompt replaces the Claude Code system prompt; CLAUDE.md still loads. The startup header shows @code-reviewer.
Session-only definitions.claude --agents '{"reviewer": {"description": "…", "prompt": "…", "tools": ["Read","Grep"]}}'. The JSON uses prompt for the body and ignores color and experimental.
Pitfall: /agents is not claude agentsOn v2.1.198 and later, /agents only "prints a reminder to ask Claude or edit .claude/agents/ and ~/.claude/agents/ directly". The Running/Library wizard many tutorials show existed on v2.1.197 and earlier. claude agents, typed in your shell, opens agent view, which is a different feature (see Background Sessions). Also, the tool is Agent since v2.1.63; Task(...) in old permission rules still works as an alias.
When a file "doesn't exist"Claude Code silently skips an agent file with no name, an opening --- that isn't on line 1, a name that starts with -, contains : or runs past 256 characters, a name with no description, or YAML that doesn't parse. Run claude --debug and read ~/.claude/debug/<session-id>.txt, or check a directory before a session with claude plugin validate .claude/agents (v2.1.233+; it doesn't flag a missing name).
Forks: a subagent without a file
A fork "inherits everything the main session has at the moment it spawns": system prompt, tools, model and history. It drops input isolation but keeps output isolation, since only its result comes back. Because its prompt and tool definitions match the parent's, its first request reuses the parent's prompt cache, so "a fork costs less than a fresh subagent for tasks that need the same context". Fork mode lets Claude start forks itself and is on by default in interactive sessions (v2.1.232+). Four commands copy or move the conversation, and they're easy to confuse:
Pick a command to see where the copy runs, where you end up, and where its result goes. Toggle agent view off to see how /fork changes meaning and /subtask disappears. Behavior as documented on the Commands and Subagents pages for v2.1.212+.
What an Agent tool call carries, and where the transcript goes
The Agent tool call is the delegation on the wire. The documented inputs are the subagent_type (a call without one fails with subagent_type is required if the session has no general-purpose agent to fall back on), the task prompt Claude writes, and optional name, model, effort (v2.1.292+) and isolation: "worktree". A name makes the worker addressable later with SendMessage, and with agent teams enabled it turns the call into a teammate launch (see Agent Teams). The SDK docs state the consequence for briefs bluntly: "The only content you pass from parent to subagent is the Agent tool's prompt string."
Each run writes its own transcript to ~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonl. Main-conversation compaction doesn't touch it, it survives restarts of the same session, and Claude Code deletes it after cleanupPeriodDays (30 by default). A subagent compacts its own window independently; its transcript records {"type": "system", "subtype": "compact_boundary", "compactMetadata": {"trigger": "auto", "preTokens": 167189}}. Two limits govern fan-out: nesting goes "up to three layers below the main conversation" (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH; 1 turns nesting off) and 20 subagents may run at once (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS, v2.1.217+), after which spawning fails with Concurrent subagent limit reached. There's no cap on the total over a session. Source: sub-agents.
Frontmatter Fields
What it is. Nineteen fields control a subagent. Only name and description are required. "Multi-word field names use camelCase … and must match the table exactly: Claude Code ignores a field it doesn't recognize without reporting an error." That silence is the main failure mode, so treat the table below as a spelling reference.
Field
Values and behavior
name
Required. At most 256 characters, no :, can't start with -. Hooks receive it as agent_type. The filename doesn't have to match.
description
Required. When Claude should delegate. Combined descriptions over 15,000 tokens trigger a startup warning.
tools
Allowlist as Read, Grep, Bash or a YAML list; supports mcp__github__*. Omitted = inherit every tool available to subagents.
disallowedTools
Denylist, applied beforetools. Bash(git push *) removes all of Bash.
model
sonnet, opus, haiku, fable, a full ID such as claude-opus-5-5, or inherit.
permissionMode
default, acceptEdits, auto, dontAsk, bypassPermissions, plan (manual aliases default). Ignored for plugin subagents.
maxTurns
Turn cap. At the limit, output returns marked partial (v2.1.246+) and the agent can be resumed.
autoCompactWindow
100000–1000000 tokens (v2.1.296+). Write 200000; frontmatter reads 200k as 200, which is out of range and ignored.
skills
Skills whose full content is injected at startup (first 32 names). Can't preload disable-model-invocation: true skills.
mcpServers
Names of configured servers or inline definitions (stdio, http, sse, ws). Ignored for plugin subagents.
hooks
Lifecycle hooks scoped to this agent; Stop becomes SubagentStop. Ignored for plugin subagents; project files need workspace trust.
memory
user, project or local persistent memory.
background
true keeps it in the background even when Claude asks to wait.
omitClaudeMd
true skips user, project and local CLAUDE.md (managed policy still loads). v2.1.271+. Ignored when run with --agent.
effort
low, medium, high, xhigh, max (model-dependent). Beaten by CLAUDE_CODE_EFFORT_LEVEL.
isolation
worktree: a temporary git worktree branched from the default branch, removed if unchanged.
Auto-submitted first turn when the agent runs as the main session agent. Ignored for plugin subagents.
experimental
A map. cacheTtl: 5m or 1h (v2.1.248+). Must be nested, not top-level.
Why it matters. Most fields fail open. A typo such as disallowed_tools or permissionmode leaves the agent running with every inherited tool and the inherited mode, and nothing tells you. On v2.1.296+ claude --debug writes up to five unrecognized top-level fields, with the likely intended name, under does not recognize or apply in the debug log.
Fill in the fields and read the generated .claude/agents/<name>.md. The linter applies the documented rules: name constraints, the 200k trap, plugin-ignored fields, specifiers in disallowedTools, nested cacheTtl, and fields that only apply in one run mode. The card shows the agent as Claude Code will read it, with each lint mark pinned to the field it's about. It can't check whether your prompt is any good.
A fuller example, using fields that interact:
.claude/agents/migration-runner.md
---
name: migration-runner
description: Applies one database migration in isolation and reports test results. Use when asked to write or apply a migration.
tools: Read, Edit, Write, Bash
disallowedTools: WebFetch, WebSearch
model: sonnet
effort: high
maxTurns: 40
isolation: worktree
skills:
- db-conventions
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./.claude/hooks/block-prod-db.sh"
onFailure: block
experimental:
cacheTtl: 1h
color: orange
---
Write the migration under migrations/, apply it to the local test database
with `make db-test`, and run `make test`. Finish with the JSON report described
in the db-conventions skill. Never connect to any host other than localhost.
Descriptions are a routing budget
Every non-built-in agent's description sits in the main context so Claude can route to it. Past 15,000 tokens of combined descriptions, Claude Code warns at startup with the total and still loads every agent. Two practical consequences: keep descriptions to a sentence about when to delegate and move the how into the body, which loads only when the agent runs; and measure routing instead of guessing. For agents shipped in a plugin, claude plugin eval runs realistic prompts with and without the plugin and scores whether delegation happened (see Agents 3). Inline mcpServers are the same trade in the other direction: a server defined only in an agent's frontmatter adds its tool descriptions to that agent's context, not the parent's.
Tools and Models
How tools resolve. A subagent starts from the main conversation's built-in and MCP tools and is narrowed by two filters. The first removes a fixed list from every subagent, "even when listed in the tools field": Agent (only at the depth limit), AskUserQuestion, EndConversation, EnterPlanMode, ExitPlanMode (unless permissionMode: plan), ScheduleWakeup, WaitForMcpServers and Workflow. The second applies to background subagents, which are the default: they keep every MCP tool but only Read, Grep, Glob, LSP, Bash, PowerShell, Edit, Write, NotebookEdit, WebFetch, WebSearch, TodoWrite, Skill, ToolSearch, EnterWorktree, ExitWorktree, Monitor, TaskStop, SendMessage and Artifact. "So the same definition can resolve to different tools in the foreground and the background." Forks skip both filters. In auto mode, Claude Code also gives local non-fork subagents SubagentHandback (v2.1.271+) for delivering their report, even when tools omits it (see Result Formats).
Your fields then apply: disallowedTools first, then tools against what's left. A tool in both is removed. Server-wide entries work in both fields: mcp__github__* in tools grants one server; mcp__github in disallowedTools withholds it; mcp__* withholds every MCP tool. If nothing in tools resolves (typos, or tools subagents can't have), the launch usually fails with an error naming the entries rather than starting a toolless worker.
Blocking commands, not tools. To keep Bash but forbid git push, add Bash(git push *) to permissions.deny in settings. That rule applies to the main conversation and every subagent. It matches the command text Claude usually writes and "isn't a security boundary around the program": /usr/bin/git push or bash -c 'git push' don't match it. For a hard limit, use the sandbox or remove Bash.
Restricting which agents an agent may spawn.tools: Agent(worker, researcher), SendMessage, Read, Bash is an allowlist only for an agent running as the main thread with claude --agent. Include SendMessage if it should resume its workers: resuming goes through that tool, and an explicit tools list doesn't add it for you. In an ordinary subagent the parenthesized list is ignored and Agent just enables nesting.
Scoping MCP to one agent. Inline mcpServers connect when the agent starts and disconnect when it ends, so the parent never pays for their tool descriptions. Project agent files need the folder trusted before inline servers load (v2.1.238+).
How the model resolves. Claude Code uses the first that applies (order since v2.1.251; earlier, the env var came first):
the per-invocation model parameter Claude passes on the Agent call;
the frontmatter model, where inherit means the main conversation's model;
CLAUDE_CODE_SUBAGENT_MODEL, if set to an alias or ID (inherit = unset);
the main conversation's model.
One subtlety: a family alias from step 1 or 2 resolves to the main conversation's exact model when the main model is in that family, including a [1m] suffix. An alias in the env var always resolves to the version the alias points to. To pin every subagent, teammate and workflow agent to one model, set CLAUDE_CODE_SUBAGENT_MODEL_FORCE=1 as well (v2.1.257+); forks still run on the main model. Run /tasks while an agent runs to see its model and effort on the row (v2.1.242+). Effort resolves similarly: per-invocation effort (v2.1.292+), then the effort field, then the session, with CLAUDE_CODE_EFFORT_LEVEL beating all of them. Since v2.1.198 subagents inherit the main conversation's extended-thinking setting, and a subagent's context window is sized by its own model.
Set the definition and the launch conditions. The tool pool falls through the filters in order: each bar catches its tools on the ledge beside it with the reason, and the tray at the bottom is what the worker ends up with. The model panel walks the model order. The tool pool is a representative subset of a real session; pick the platform to see Grep and Glob drop out on macOS, Linux and WSL whenever Bash is listed or the list is inherited. Alias targets assume the Anthropic API (opus → Opus 5.5, sonnet → Sonnet 5.5, haiku → Haiku 5.5, fable → Fable 5.1).
Model routing that pays offAnthropic's guidance on Opus 5.5 costs is to "move down to Sonnet or Haiku for lookups, not for writing code" (claude.dev). In agent files that means model: haiku on search and log-reading agents and inherit or opus on agents that write code. Evaluate on your own codebase before standardizing; the Agents 2 session covers measuring it.
Does a cheaper worker save money?
Not by default. Anthropic's cost guide measured a frontier orchestrator handing bulk work to lower-cost workers. "Delegation saved money in only two situations" (measured with workers on Claude Sonnet 5, an earlier model): "Routine work with a long cost tail (an easy slice of BrowseComp)" and "Work larger than one context window". Otherwise, "When the work is one dependent chain, or fits in a single context without a long cost tail, the orchestrator's model alone at lower effort came out ahead in every case measured". Even for the routine case the advice is to "measure this case first, for accuracy as well as cost". The same page says the model selection matrix "lists Claude Haiku 5.5 for sub-agent tasks; before you use it as a worker, measure it on your own workload" (optimizing for cost and intelligence). For Claude Code, the rule is to delegate to keep the main context clean (see Briefs) and to split work that won't fit in one window. Before you push every worker down to model: haiku to save money, whether through a CLAUDE.md line, the model field or CLAUDE_CODE_SUBAGENT_MODEL, compare that setup against the main model alone at a lower effort.
Pitfall: assuming the split is the cheap optionA frontier lead with cheaper workers looks as if it should keep most of the accuracy for a fraction of the cost. Outside the two cases above, the cost guide measured the opposite, so price the lead model alone at lower effort before you standardize on a split.
Subagents and the prompt cache
A non-fork subagent has its own system prompt and tools, so it builds its own cache from scratch, and its requests fall outside the main conversation's cache lifetime: per the prompt-caching docs, subagents, compaction and titles default to a 5-minute TTL even when the main conversation gets an hour on a subscription. experimental.cacheTtl: 1h in one agent file (v2.1.248+) or subagentPromptCacheTtl in settings raises it, at the higher 1-hour write rate; the agent-file value is ignored while your subscription is using usage credits. A fork matches the parent's prefix and reads the parent's cache. A subagent resumed with SendMessage "can keep reading the prompt cache the original run warmed", which makes resuming cheaper than re-spawning for follow-ups. Changing a subagent's model mid-project throws its cache away, since caches are per model. See prompt-caching and Agents 1 for the cache mechanics.
Permission Mode
What it is.permissionMode picks the mode the worker runs in, using config values (Manual mode is default). Leave it unset and the worker inherits the main conversation's mode. The catch is that the main conversation's mode decides whether your value is used at all:
Main in bypassPermissions, acceptEdits or auto: the subagent runs in that same mode, "and Claude Code ignores the permissionMode you set". Under auto mode the classifier evaluates the subagent's calls with the main conversation's rules and reviews its work and final report before delivery.
Main in plan: the subagent stays in plan mode whichever permissionMode you set, unless it runs as an agent-team teammate, which follows the teams' plan rules. With dontAsk set it also doesn't prompt: an action plan mode would ask you to approve is denied instead.
Main in default or dontAsk: the subagent runs in the mode you set, except that a bypassPermissions value keeps the main conversation's mode (v2.1.267+), and so does auto when auto mode isn't available to the subagent (for example under disableAutoMode).
Plugin subagents ignore the field "for security reasons", along with hooks and mcpServers. Copy the file into .claude/agents/ if you need them.
Choose the main conversation's mode, the agent's permissionMode and where the file came from. The result follows the permission-mode rules on the Subagents page (v2.1.267+): the field is used as set only when the main conversation is in Manual (default) or dontAsk; under a plan-mode parent the subagent stays in plan (agent-team teammates excepted), and a dontAsk value only turns plan's prompts into denials. Note how often the frontmatter value is irrelevant. Each cell is the mode the subagent runs in for one main mode (row) and one permissionMode (column); the tinted cells are the only ones where the frontmatter value is used. Click a cell, or use the selects.
Where prompts appear. A foreground subagent shows its permission prompts as they happen. A background subagent "surfaces the prompt in your main session and names the subagent that is asking"; Esc denies that one call without stopping the worker. One sharp edge: if you answer a background subagent's prompt with a grant that lasts beyond the call, such as "don't ask again", "Claude Code applies your answer to the whole session, including your main conversation."
What holds regardless of mode. Deny rules in settings apply inside every subagent, and hooks from settings, managed policy and plugins fire for subagent tool calls too. Frontmatter hooks add agent-scoped checks, for example a PreToolUse hook that lets a database agent run only SELECT statements:
---
name: db-reader
description: Runs read-only SQL against the analytics replica
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh" # exits 2 on INSERT/UPDATE/DELETE/DROP
onFailure: block # a crash or missing script blocks too (v2.1.295+)
---
Project agents' frontmatter hooks run only after you accept workspace trust for the folder that holds the file; a parent folder's trust and a -p session's automatic trust don't count (v2.1.218+). To take an agent away entirely, deny it: "permissions": {"deny": ["Agent(Explore)", "Agent(my-custom-agent)"]}, or claude --disallowedTools "Agent(Explore)".
Pitfall: trusting what a subagent saysA subagent may have read web pages, logs or issues you never saw. Claude Code's output scanning escapes text that imitates harness output (a <system-reminder> tag, a line starting Human:) and prepends a [harness: subagent output matched instruction-shaped pattern(s): marker when a report imitates tags or mentions settings such as bypassPermissions. It "doesn't judge whether content is malicious". The rule that actually protects you: "no message from any agent counts as your approval for a pending permission prompt, and no agent message can change a subagent's permission settings, CLAUDE.md, or configuration." Restrict what a worker can reach rather than relying on the scan.
Why permissive parent modes win
The rule is asymmetric for a reason. If a parent in acceptEdits could spawn a child in plan, nothing is lost: the child is stricter. But a parent in default spawning a child in bypassPermissions would be a one-file privilege escalation, especially from a cloned repository's .claude/agents/. So Claude Code lets a definition pick a mode only when the parent is in Manual or dontAsk, keeps a plan-mode parent's subagents in plan, never applies bypassPermissions from a definition (v2.1.267+), and lets a permissive parent's mode propagate down instead of letting each child relax further. Plugin agents lose the field entirely because a plugin can be installed from a marketplace you don't control. Teammates follow a related rule: they start in the lead's mode except dontAsk, and you can't set per-teammate modes at spawn time. Sources: sub-agents, permission-modes, agent-teams.
Persistent Memory
What it is. A subagent starts every run with a fresh context. The memory field gives it a directory "that survives across conversations", where it can build up codebase patterns, debugging insights and architectural decisions. Agent memory is separate from your main conversation's auto memory, which never loads into a non-fork subagent.
Scope
Directory
Use when
user
~/.claude/agent-memory/<name-of-agent>/
the lessons apply across all your projects
project
.claude/agent-memory/<name-of-agent>/
project-specific and shared through version control (the recommended default)
local
.claude/agent-memory-local/<name-of-agent>/
project-specific but not checked in
How it works. With memory on, three things change at launch: the system prompt gains instructions for reading and writing the directory; it also includes "the first 200 lines or 25KB of MEMORY.md in the memory directory, whichever comes first, with instructions to curate MEMORY.md if it exceeds that limit"; and Read, Write and Edit are enabled automatically so the agent can maintain its files. Subagent memory is part of auto memory, so autoMemoryEnabled: false or CLAUDE_CODE_DISABLE_AUTO_MEMORY makes the field do nothing.
Only the head of MEMORY.md is injected; other files in the directory are read on demand with the Read tool. The agent curates its own index, so treat MEMORY.md like a table of contents, not a log. Switch between launch, when only the head above the fold joins the subagent's system prompt, and the run, when it reads a topic file with Read and writes back with Write or Edit; hover a part for what it holds. The file length and topic names are illustrative.
How to use it. Put the habit in the body so the agent maintains memory without being asked:
.claude/agents/code-reviewer.md
---
name: code-reviewer
description: Reviews diffs for correctness and security. Use proactively after code changes.
tools: Read, Grep, Glob
memory: project
---
Before reviewing, read MEMORY.md in your memory directory and any notes it
points to. After the review, record new recurring issues, fragile modules, and
project conventions you had to infer. One line per fact in MEMORY.md, details in
topic files. Remove notes that turned out to be wrong.
You can also steer it per task: "Review this PR, and check your memory for patterns you've seen before", then "save what you learned to your memory."
Pitfall: memory quietly adds write toolsBecause Read, Write and Edit are enabled for memory, a reviewer you limited to tools: Read, Grep, Glob can now write files. If "read-only" matters, add an agent-scoped PreToolUse hook on Edit|Write that resolves tool_input.file_path and exits 2 unless it is inside that agent's own memory directory (the exercise below has one). Treat the hook as defense in depth: it sees only Edit and Write calls, so an agent that also has Bash can still write files through the shell (Edit deny rules would catch sed, tee and redirects there, but not a script that opens files itself, and they apply to the whole session). Leave Bash out of a reviewer that should stay read-only, or turn on the sandbox's write rules for it. Combining isolation: worktree with memory: project isn't a substitute: where project memory lands for a worktree-isolated subagent isn't documented.
Memory is persistent inputAnything the agent writes to memory is re-read in every later run, before your task. A note written while the agent was reading an untrusted issue or web page becomes a standing instruction. Keep project memory under code review like any other file the model reads, and prune it when the code changes.
Exercise: a reviewer that learns your repo
In a real repository: (1) create .claude/agents/code-reviewer.md with memory: project, read-only tools (no Bash), and the memory habit above; (2) add a PreToolUse frontmatter hook that only lets Edit and Write touch the agent's own directory under .claude/agent-memory/; (3) ask Claude to review two different recent commits with the agent; (4) inspect what it wrote, then run /tasks during the second run to confirm its model.
Show a solution
.claude/agents/code-reviewer.md
---
name: code-reviewer
description: Reviews diffs for correctness and security. Use proactively after code changes.
tools: Read, Grep, Glob
model: sonnet
memory: project
hooks:
PreToolUse:
- matcher: "Edit|Write"
hooks:
- type: command
command: "./.claude/hooks/memory-only-writes.sh"
onFailure: block
---
Review the files named in your task for correctness and security problems,
with file:line evidence. Before reviewing, read MEMORY.md in your memory
directory and any notes it points to. After the review, record new recurring
issues, fragile modules, and conventions you had to infer: one line per fact
in MEMORY.md, details in topic files. Remove notes that turned out to be wrong.
.claude/hooks/memory-only-writes.sh
#!/usr/bin/env bash
# Edit/Write only inside this agent's memory directory.
# Defense in depth: it sees Edit and Write calls only. File-tool paths arrive absolute.
# Any internal error blocks the call (exit 2); onFailure: block covers a hook that can't start.
set -o pipefail
trap 'echo "memory-only-writes: error on line $LINENO; blocking" >&2; exit 2' ERR
for cmd in jq python3; do
command -v "$cmd" >/dev/null || { echo "memory-only-writes: $cmd missing; blocking" >&2; exit 2; }
done
[ -n "${CLAUDE_PROJECT_DIR:-}" ] || { echo "memory-only-writes: CLAUDE_PROJECT_DIR unset; blocking" >&2; exit 2; }
input=$(cat)
path=$(jq -r '.tool_input.file_path // empty' <<<"$input")
canon() { python3 -c 'import os,sys; print(os.path.realpath(sys.argv[1]))' "$1"; }
root=$(canon "$CLAUDE_PROJECT_DIR/.claude/agent-memory/code-reviewer")
real=$(canon "${path:-/nonexistent}")
case "$real/" in
"$root"/*) exit 0 ;;
esac
echo "code-reviewer may only write under .claude/agent-memory/code-reviewer/ (got: $path)" >&2
exit 2
Resolving the path with realpath before comparing defeats …/.claude/agent-memory/../../src/app.py and symlinks, and comparing against this agent's own directory rejects any other folder that happens to be named agent-memory. Without Bash, the reviewer reads files Claude names in the brief rather than running git diff; pass the changed paths (or the diff) in the delegation. Expect .claude/agent-memory/code-reviewer/MEMORY.md plus a topic file or two after the first review, and the second review to cite a pattern from the first. If nothing was written, check that auto memory isn't disabled and that the trust dialog was accepted for the folder (frontmatter hooks are skipped until it is, and the debug log says so).
What you build: a kit of four project subagents for the sample app (code-explorer on Haiku with maxTurns: 12; test-runner with disallowedTools and a frontmatter PreToolUse hook that allows only test commands; reviewer on Sonnet at effort: high; implementer with isolation: worktree, permissionMode: acceptEdits and experimental.cacheTtl), plus validate_agents.py, which checks any agents directory against the documented frontmatter, runs the kit's hook against documented payloads, and proves it catches every mistake in bad/.
cd labs && python3 agents-4/subagents_kit/validate_agents.py
cp -r agents-4/subagents_kit/kit/.claude <repo>/ # install the kit into a repo
claude --agents "$(python3 agents-4/subagents_kit/validate_agents.py --emit-agents-json)" # or try it for one session
What to observe: the bad/ samples that hit a documented silent-skip reason (bad YAML, frontmatter not on line 1, a : in the name, no description) are reported as SKIPPED, and others are flagged for max_turns, 200k, duplicate names, out-of-range values, Grep or Glob listed alongside Bash, a lead agent without SendMessage, and memory that quietly enables writes. The README compares this with claude plugin validate, which catches only parse errors and a missing description. Offline by default.
An agent file is configuration plus a system prompt; identity is the name field, and the highest-priority location wins.
Unknown or misspelled fields are ignored silently; validate files and read the debug log.
Tools pass through two built-in filters plus your fields; background subagents get a narrower built-in set than foreground ones.
The model order is per-invocation, frontmatter, env var, main model; …_FORCE=1 pins everything.
A permissive main mode overrides permissionMode; plugin agents can't set modes, hooks or MCP servers.
Memory persists across sessions, injects the head of MEMORY.md, and enables write tools, so review and constrain it.
Agent Teams
An agent team is several full Claude Code sessions working one problem: a lead that plans, assigns and synthesizes, and teammates that claim tasks from a shared list and message each other directly. It is the built-in option designed for workers that message each other and self-coordinate, rather than only reporting to their caller. It is also experimental, disabled by default, and the most expensive way to parallelize, so this topic covers the mechanics precisely enough to decide when it's worth it.
Team Lead and Teammates
Experimental and disabled by default"Agent teams are experimental and disabled by default." Without CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1, "no team is set up at session start, no team directories are written, and Claude does not spawn or propose teammates." Some 2026 changelog entries call teams a research preview; the docs' label is the current one. Expect the known limitations listed below.
The team name is session- plus the first eight characters of the session ID. There's one team per session and no project-level team file: .claude/teams/teams.json in a repo is just a file. Reusable roles live in agent files instead (below).
Teammates talk to each other through mailboxes and coordinate through the task list. Permission prompts from every teammate surface in the lead, where only you can answer them. You can also message any teammate directly. Hover or tab to a seat, the task list or a message line. The three lenses are the docs' PR-review example.
How a team starts. Ask for one in plain language. The docs' example starts "Spawn three teammates to review PR #142:" and gives each one a lens: security implications, performance impact, test coverage. Mechanically, "Claude launches a teammate when it calls the Agent tool with a name while agent teams are enabled, unless the call is a fork or passes isolation on the call itself. Claude Code doesn't ask you to confirm the launch." Because Claude also names ordinary subagents on its own, enabling teams changes everyday delegation: teams "can form even when you didn't ask for one". Set the variable to 0 in settings to get plain subagents back without restarting. Teams never form in -p or the Agent SDK; a named subagent there stays a subagent.
What a teammate knows. Each teammate "loads the same project context as a regular session: CLAUDE.md, MCP servers, and skills" and receives the lead's spawn prompt. "The lead's conversation history does not carry over." Its model comes from the spawn prompt, then the subagent definition's model, then CLAUDE_CODE_SUBAGENT_MODEL, then the lead's model. (teammateDefaultModel was removed in v2.1.234.) Effort follows the lead.
Permissions. "Teammates start with the lead's permission mode, except dontAsk mode, which they don't inherit. If the lead runs with --dangerously-skip-permissions, all teammates do too." Their prompts surface in the lead session for you to approve. There's one designed exception: a teammate spawned while the lead is in plan mode works read-only until its plan is ready, then sends a plan approval request. "If you haven't changed that teammate's permission mode since it was spawned, Claude Code approves the plan as soon as the request arrives, without the lead reviewing it." Its edits and commands still go through prompts. If you instead put a running in-process teammate into plan mode with Shift+Tab while viewing its session, the lead reviews that run's plan, and you still aren't asked to approve it (agent-teams).
Reusing agent files as teammate roles
"Spawn a teammate using the security-reviewer agent type to audit the auth module" applies parts of .claude/agents/security-reviewer.md, and which parts depends on the display mode:
Definition part
In-process teammate
Split-pane teammate
tools
applied, plus SendMessage, and the Task tools in a session that has them
applied
model
applied
applied
disallowedTools, effort
applied
documented only for in-process
autoCompactWindow
applied (v2.1.296+)
ignored
body
appended to the default system prompt
replaces the default system prompt
mcpServers
ignored (loads project and user servers)
applied
skills
not applied
not applied
Cost and team size
The agent-teams page says teams "use significantly more tokens than a single session" and "token usage scales with the number of active teammates". The costs page gives one number with a condition attached: "Agent teams use approximately 7x more tokens than standard sessions when teammates run in plan mode." Don't quote "7x" as a general multiplier. The documented levers: use Sonnet for teammates, keep teams small, keep spawn prompts focused, and shut teammates down when they're done, since "each active teammate continues consuming tokens until it exits". In-process teammates' cache lasts five minutes by default; subagentPromptCacheTtl: "1h" extends it at the higher write rate.
Toy model, illustrative numbers. Wall-clock time follows an Amdahl-style curve with a per-teammate coordination cost; tokens grow linearly with teammates, as the docs state. Neither curve is a measurement of Claude Code. The point is the shape: speedup flattens or reverses while cost keeps climbing, which is why the docs recommend starting with 3–5 teammates and note that "three focused teammates often outperform five scattered ones".
Limitation (docs heading)
What it means in practice
No session resumption with in-process teammates
/resume and /rewind don't restore them; the lead may message teammates that no longer exist. Tell it to spawn new ones.
One team per session; no nested teams
Teammates can't spawn teammates. Only the lead manages the team.
No background subagents from in-process teammates
A teammate's own subagents run in the foreground; background: true errors.
Lead is fixed; permissions set at spawn
You can't promote a teammate or set per-teammate modes when spawning.
Task status can lag; shutdown can be slow
Check stuck dependencies by hand; teammates finish their current call before exiting.
Teams versus subagents versus the "C compiler" harness
The docs' comparison: subagents return a result to the caller and "main agent manages all work"; teammates are "fully independent", message each other, and self-coordinate through a shared list. Use teams for research and review, new modules with clear ownership, debugging with competing hypotheses, and cross-layer changes; avoid them for "sequential tasks, same-file edits, or work with many dependencies". Anthropic's February 2026 post on building a C compiler with 16 parallel Claudes is often cited as "agent teams", but it describes a custom harness (a Docker container per agent, git-based locks, a loop around claude -p run with --dangerously-skip-permissions inside containers), not this feature. Its lessons still transfer: a near-perfect verifier, terse test output, and the observation that one giant task blocks all parallelism. Sources: agent-teams, Anthropic engineering.
Messaging
What it is. Teammates communicate with the SendMessage tool, which writes to the recipient's mailbox file. Claude Code validates every entry when it reads a mailbox; malformed entries are reported and removed, valid ones still delivered. A message counts as sent "only when the write to the recipient's mailbox file succeeds"; if the disk is full or the directory isn't writable, the sender gets an error and nothing is sent.
How delivery works.
Automatic delivery. Messages reach recipients without polling.
Idle notifications. "When a teammate finishes and stops, it automatically notifies the lead and includes its final answer in the notification." A turn that ends on an API error notifies the lead with the error text.
One recipient per message. "To reach everyone, send one message per recipient." There's no broadcast.
Names. The lead names every teammate at spawn; any teammate can message any other by name. Tell the lead what to call them so your later prompts can refer to "the researcher".
Protocol messages. Beyond plain text, the team uses structured messages such as shutdown_request and plan_approval_response. "Ask the researcher teammate to shut down" makes the lead send a shutdown request, which the teammate can approve or reject with an explanation.
you → leadUsers report the app exits after one message. Spawn 3 teammates named net, state and config to test competing hypotheses and try to disprove each other.
tool_use · Agent (name: "net"){"subagent_type": "general-purpose", "name": "net", "prompt": "Hypothesis: the websocket closes after the first frame. Reproduce with…"}
tool_use · SendMessage (state → net){"to": "net", "summary": "server keeps socket open", "message": "Server logs show the socket open for 30 s after the first reply; your close-frame theory doesn't match. Check the client's reconnect flag."}
idle notification · net → leadConfirmed: client sets reconnect=false when the session token refreshes. Repro: scripts/repro_exit.sh (fails 10/10). Evidence: src/client/session.ts:88.
leadConsensus from net and state: the token-refresh path disables reconnect. config ruled out env differences. Writing findings to docs/incidents/exit-after-one.md.
Illustrative transcript with abbreviated tool inputs. The docs name SendMessage's to (agent name or ID) and optional summary inputs; the rest of the shape is for illustration.
Why it matters: messages carry no authority. "When one agent sends another a message over SendMessage, Claude Code tells the receiving agent the message came from another Claude session, not from you. A teammate can't approve a permission prompt or supply consent on your behalf, and a teammate that was denied an action can't relay it to another teammate to bypass the check." In auto mode the classifier treats relayed approval claims as untrusted and "reviews each message before Claude Code delivers it"; a blocked message never arrives.
Talking to teammates yourself. In in-process mode, select a teammate with ↑/↓ and press Enter to view its transcript and type to it; Esc interrupts its turn while you're viewing it. Plain text and skills go to that teammate, but built-in commands go to the lead: /compact, /clear and /rewind ask for confirmation, and /model and /fast refuse, because "a teammate's model and fast mode are fixed when it spawns".
Follow one run from enabling the feature to cleanup: the lead's terminal on the left, the team's directories on the right, with what each step adds or changes lit. Each step names the file or hook involved. Task files under tasks/ aren't named in the docs, so they show as entries. Order of events is illustrative; the mechanics come from the agent-teams and hooks pages.
Pitfall: the lead does the work itself"Sometimes the lead starts implementing tasks itself instead of waiting for teammates." Say "Wait for your teammates to complete their tasks before proceeding." The opposite also happens: the lead decides the team is finished before all tasks are done. Tell it to keep going, and back that up with a TaskCompleted gate (next concept).
Shared Task List
What it is. The shared task list holds work items with three states, pending, in progress and completed, and optional dependencies. A task that depends on others waits until they're done: "when a teammate completes a task that other tasks depend on, it unblocks the dependent tasks without any action from you." The lead can assign tasks explicitly, or teammates self-claim "the next unassigned, unblocked task" when they finish one. "Task claiming uses file locking to prevent race conditions." Press Ctrl+T in the lead to toggle the list.
Check that the Task tools exist on your modelThe list is driven by the Task tools (TaskCreate, TaskGet, TaskList, TaskUpdate). On Claude Code v2.1.268+ they are "available by default only on Opus 4.7, Sonnet 4.6, Haiku 4.5, and earlier models". On Opus 5.5, Sonnet 5.5 and other newer models, interactive sessions leave them out unless you opt in with CLAUDE_CODE_ENABLE_TODO_TOOLS=1 or name one in --allowedTools or --tools. Background and cloud sessions always have them. Without them, "an agent coordinates with its team through messages instead of the shared task list", and the TaskCreated hook never fires. In-process teammates have them when your session does. A split-pane teammate is a separate process: with no --tools list or deny rule, "the teammate has the task-tracking tools its own model has by default" (tools reference).
# an agent team with a real task list on a 5.x model
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 CLAUDE_CODE_ENABLE_TODO_TOOLS=1 claude
Sizing tasks. Too small and "coordination overhead exceeds the benefit"; too large and "teammates work too long without check-ins". Aim for self-contained units with a clear deliverable such as a function, a test file or a review. "Having 5-6 tasks per teammate keeps everyone productive and lets the lead reassign work if someone gets stuck." If the lead creates too few, ask it to split the work.
Quality gates with hooks
Three hook events turn the task list into an enforcement point. None take matchers; all fire on every occurrence, all carry agent_id for the subagent or in-process teammate involved (v2.1.290+), and exit code 2 pushes back with stderr as feedback:
Event
Fires when
Exit 2 does
Extra input fields
TaskCreated
TaskCreate creates a task
prevents creation (so does JSON {"decision": "block", "reason": …})
#!/usr/bin/env bash
# TaskCompleted gate: a task closes only when tests pass in the task's working directory.
# onFailure has no effect on TaskCompleted, so the script fails closed itself (exit 2),
# with a limit so a broken gate can't send a teammate back forever.
set -o pipefail
gate=require-green-tests
state="${TMPDIR:-/tmp}/claude-gates"; mkdir -p "$state" || exit 2
fail() { # internal error: exit 2 up to 3 times in a row, then let it through and log why
local n; n=$(( $(cat "$state/$gate.errors" 2>/dev/null || echo 0) + 1 )); echo "$n" > "$state/$gate.errors"
if [ "$n" -gt 3 ]; then echo "$(date) $gate broken: $1" >> "$state/gate-errors.log"; exit 0; fi
echo "$gate: $1" >&2; exit 2
}
trap 'fail "error on line $LINENO"' ERR
command -v jq >/dev/null || fail "jq missing"
input=$(cat)
subject=$(jq -r '.task_subject' <<<"$input")
cwd=$(jq -r '.cwd // empty' <<<"$input")
{ [ -n "$cwd" ] && cd "$cwd"; } || fail "can't enter the task's directory '$cwd'"
command -v make >/dev/null || fail "make missing"
rm -f "$state/$gate.errors" # the gate itself works; reset its error count
if ! out=$(make test 2>&1); then
echo "Task '$subject' can't close: tests fail. Last lines:" >&2
tail -n 15 <<<"$out" >&2
exit 2 # completion prevented; stderr goes back to the model
fi
exit 0
Two details from the hooks reference: when TaskUpdate triggered the event, {"continue": false} is ignored and only exit 2 blocks; and onFailure: "block" has no effect on TaskCompleted, TeammateIdle, Stop or SubagentStop. That has two consequences. A gate that can't start at all (wrong path, not executable, missing interpreter) lets the action through on these events whatever the script would have said, so run each gate once by hand and watch for the hook-error notice. And a script that fails closed by exiting 2 on its own internal errors sends the worker back against a problem it can't fix, so it needs an attempt limit too. The gates on this page check for jq, trap errors to exit 2, and give up after three consecutive internal errors, logging the reason to $TMPDIR/claude-gates/gate-errors.log. The opposite risk is a gate that can never pass: it keeps the teammate working, and spending tokens, indefinitely, so pair it with a counter like the one in the exercise below.
Six tasks with dependencies, three teammates that self-claim. Step time forward and watch file-locked claims, blocked dependents and the TaskCompleted gate. Turn on "status lag" to reproduce the documented limitation where a teammate forgets to mark a task completed and its dependents stall. Toy model: durations and failure rates are illustrative.
Display Modes
What it is. Teammates run in one of two display modes:
In-process (default)
All teammates run inside your terminal. The agent panel below the prompt lists them: ↑/↓ select, Enter opens a transcript to read or message, Esc clears or interrupts, x stops a teammate, Ctrl+T toggles the task list. Works in any terminal with no setup. Idle rows hide 30 seconds after the whole panel goes idle, and when more than three teammates are idle, the rows beyond the first three collapse into one N idle agents row.
Split panes
Each teammate is its own Claude Code process in a tmux or iTerm2 pane: you see everyone at once and click into a pane to interact. Requires tmux, or iTerm2 with the it2 CLI and the Python API enabled (iTerm2 → Settings → General → Magic → Enable Python API). Not supported in VS Code's integrated terminal, Windows Terminal or Ghostty.
How to choose it. Set teammateMode in ~/.claude/settings.json, or pass claude --teammate-mode auto for one session (the flag "is experimental and doesn't appear in claude --help"):
~/.claude/settings.json
{ "teammateMode": "auto" }
"in-process": the default.
"auto": split panes when you're already inside a tmux session, or in iTerm2 with it2 installed; in-process otherwise.
"tmux": split-pane mode, auto-detecting tmux or iTerm2 from your terminal.
"iterm2": native iTerm2 panes; errors with an install command if it2 is missing.
Pick a teammateMode and a terminal to see a wireframe of the screen you'd get. The result follows the documented rules; behavior in unsupported terminals beyond "not supported" isn't documented, so the widget says so.
Why the choice matters beyond looks. A split-pane teammate is a separate process, so several things differ: the agent definition's body replaces its system prompt instead of being appended, its mcpServers apply, autoCompactWindow is ignored, the docs describe disallowedTools and effort only for in-process teammates, and whether it has the Task tools depends on its own model rather than the lead's session. Lead effort reaches split-pane teammates only from v2.1.186, and they respect --setting-sources from v2.1.281.
Cleaning up split panesIf a tmux session outlives the team, list and kill it: tmux ls, then tmux kill-session -t <session-name>. In iTerm2, tmux -CC is "the suggested entrypoint into tmux".
Exercise: a read-only review team
The docs advise starting with tasks that "don't require writing code". In a repo with an open PR: enable teams (and CLAUDE_CODE_ENABLE_TODO_TOOLS=1 if you're on a 5.x model), start in plan mode, and ask for three named reviewers (security, performance, tests) that each report findings with file:line evidence and challenge one other reviewer's top finding. Add a TeammateIdle hook that exits 2 unless the teammate's findings file exists under .review/. Afterwards, inspect ~/.claude/tasks/ and compare /usage against a single-session review of the same PR.
Show a solution
/plan
Spawn three teammates named sec, perf and tests to review PR #142. Each writes
findings to .review/<name>.md as a list of {file:line, problem, scenario, severity}.
After writing, each must message one other teammate challenging their top finding.
Use Sonnet for each teammate. Wait for all three before you summarize.
.claude/hooks/require-findings.sh
#!/usr/bin/env bash
# TeammateIdle gate: keep a teammate working until its findings file exists.
# TeammateIdle has no stop_hook_active and onFailure doesn't apply, so the script
# counts its own pushes back and fails closed on internal errors, with a limit on both.
set -o pipefail
gate=require-findings
state="${TMPDIR:-/tmp}/claude-gates"; mkdir -p "$state" || exit 2
fail() { # internal error: exit 2 up to 3 times in a row, then let it through and log why
local n; n=$(( $(cat "$state/$gate.errors" 2>/dev/null || echo 0) + 1 )); echo "$n" > "$state/$gate.errors"
if [ "$n" -gt 3 ]; then echo "$(date) $gate broken: $1" >> "$state/gate-errors.log"; exit 0; fi
echo "$gate: $1" >&2; exit 2
}
trap 'fail "error on line $LINENO"' ERR
command -v jq >/dev/null || fail "jq missing"
input=$(cat)
name=$(jq -r '.teammate_name // empty' <<<"$input")
cwd=$(jq -r '.cwd // empty' <<<"$input")
key="$state/idle-$(jq -r '.session_id' <<<"$input")-${name:-unknown}"
rm -f "$state/$gate.errors"
if [ -n "$name" ] && [ -s "${cwd:-.}/.review/${name}.md" ]; then rm -f "$key"; exit 0; fi
n=$(( $(cat "$key" 2>/dev/null || echo 0) + 1 )); echo "$n" > "$key"
if [ "$n" -gt 3 ]; then # after three reminders, stop the teammate instead of looping
jq -n --arg r "${name:-teammate} never wrote .review/${name:-name}.md after 3 reminders" '{continue: false, stopReason: $r}'
exit 0
fi
echo "Write your findings to .review/${name:-your-name}.md before going idle." >&2
exit 2
TeammateIdle has no stop_hook_active field, so a gate that just exits 2 until a file appears can keep a stuck teammate going forever; the counter turns the fourth attempt into {"continue": false, "stopReason": …}, which stops the teammate and shows you the reason. Expect the three findings files, a task directory that survives the session, and a /usage several times a single review's. Because the lead was in plan mode, the teammates started read-only and their plans were auto-approved; their file writes still prompted in the lead.
Key takeaways
Teams are experimental and off by default; enabling them turns any subagent Claude names into a teammate, without asking.
Teammates get CLAUDE.md, MCP and skills plus the spawn prompt, never the lead's history; put task context in the spawn prompt.
Messages between agents carry no approval; permission prompts surface in the lead, except plan approvals, which are automatic for a teammate spawned in plan mode.
On 5.x models the shared task list needs CLAUDE_CODE_ENABLE_TODO_TOOLS=1 in interactive sessions.
TaskCompleted and TeammateIdle hooks with exit 2 are the enforcement points; write them to fail closed.
Cost scales with teammates; "about 7x" applies to teammates in plan mode. Start with 3–5 teammates and 5–6 tasks each.
Background Sessions
A background session is a whole Claude Code conversation that keeps running with no terminal attached, hosted by a supervisor process on your machine. You dispatch several, get on with your own work, and step in only when one needs you. Agent view is the dashboard for them; a handful of shell commands script them; notifications tell you when to look. This topic covers all four, including the one behavior that destroys work if you don't know it: what deleting a session removes.
Agent View
What it is.claude agents opens agent view, "one screen for all your background sessions: what's running, what needs your input, and what's done". It takes over the terminal, lists every background session across all your projects (narrow with claude agents --cwd ~/projects/my-app), and has a dispatch input at the bottom. It's a research preview, added in v2.1.139: "The interface and keyboard shortcuts may change as the feature evolves."
Groups run top to bottom: Pinned, Ready for review (an open PR needing review or failing checks), Needs input, Working, Completed. ✻ or an animated ✽ means the process is running or needs you, ∙ means it exited (reply or attach restarts it from the saved conversation), and ✢ marks a /loop session sleeping between iterations. #2048 links the session's pull request. Hover or tab to a callout to light the rows it names. Rows are the docs' example.
How to read it. Each row's icon color shows one of six states:
State
Icon
Meaning
Working
animated
"Claude is actively running tools or generating a response"
Needs input
yellow
waiting on an answer, a permission decision, a sandbox network prompt or an MCP input request; also commands that need an attached terminal, such as /install-github-app
Idle
dimmed
nothing to do, ready for your next prompt
Completed
green
the task finished successfully
Failed
red
the task ended with an error
Stopped
grey
stopped with Ctrl+X or claude stop, killed from outside, or ended while the background service was off
A Haiku-class model writes each row's one-line summary at the end of every turn (and every few minutes during long turns); between those, the row text updates "at most once every 15 seconds from the session's own recent output without sending a model request". Press Space to open the peek panel: it shows the exact question a waiting session asks, a finished session's result, or a working session's status sentence, and you can reply there without attaching. Replies to a permission prompt or dialog don't answer it; attach with → for those. A reply that is exactly /stop stops the session.
Key
Action
Key
Action
↑/↓
move between rows
Space
peek / close peek
Enter or →
attach (Enter submits when typing)
Ctrl+Enter
dispatch and attach at once
Ctrl+T
pin (keeps the process alive while idle)
Ctrl+X
stop; again within two seconds deletes
Ctrl+S
group by state or directory
Ctrl+R
rename
Ctrl+F
find by name (v2.1.288+)
?
all shortcuts
The dispatch input doubles as a filter: s:working, s:blocked, a:<agent>, n:<text> (v2.1.287+), o:<text> for result text, or a PR number or URL. To make plain claude open agent view, run /config defaultToAgentsView=true; to switch the feature off entirely, set disableAgentView: true or CLAUDE_CODE_DISABLE_AGENT_VIEW (admins can enforce it through managed settings).
A toy agent view with four sessions, drawn as lifelines over time: a thick bar while working, a dashed bar while it needs you, ∙ where the process stops. Select a lane, then use the key buttons; the strip under the lanes is that session's agent-view row. "Advance 30 min" moves time forward: working sessions finish or ask for input, and finished sessions left unattached and unpinned for about an hour have their process stopped (∙), as the supervisor does. Timings are illustrative.
A triage pass
Agent view pays off as a short loop you run a few times a day:
Name sessions when you dispatch them (claude --bg --name, or Ctrl+R on a row), so the list reads like a task board rather than a column of truncated prompts.
Start at the top. Agent view lists every session "grouped by state, with pinned sessions and the ones that need you at the top": Ready for review and Needs input sit above Working and Completed. Take Needs input first, since those sessions are blocked until you answer.
Peek and answer in place. Press Space on a waiting row, then "Type a reply and press Enter to send it without leaving agent view." For a question with numbered choices, press the number, then Enter. ↑ and ↓ move the open peek panel to the next row.
Attach only when you must. Enter or → on a row attaches. You need it for permission prompts and dialogs, which a peek reply doesn't answer, and whenever you want the whole transcript.
Sweep Ready for review, then Completed. Open each PR from the row's label, read finished results in the peek panel, and clean up finished sessions with the rules under Attach, Logs and Stop.
Ready for review
∙ docs-sweep 18 broken links fixed · #2051 1h
Needs input
✻ checkout-retry-bug idempotency key or row lock? 12m
✻ deps-audit Allow Bash(npm outdated --json)? 4m
Working
✽ search-latency profiling the /search handler 31m
peek · checkout-retry-bug
Double charge reproduced. Fix with (1) an idempotency key
or (2) a row lock?
waiting 3m
> 1, plus a regression test that fails without it
Illustrative mock: session names, summaries and times are made up. The layout loosely follows the docs' description of rows and the peek panel. deps-audit is waiting on a permission prompt, so it needs an attach, not a reply.
On Amazon Bedrock or Google Cloud's Agent Platform. Agent view works on cloud providers too. A background session keeps "that shell's cloud provider selection too, such as CLAUDE_CODE_USE_BEDROCK or CLAUDE_CODE_USE_VERTEX, along with its ANTHROPIC_DEFAULT_*_MODEL aliases", so dispatch from a shell where the provider already works. Row summaries go "through your normal provider". If no Haiku-class model is configured there, they use the session's main model, and setting ANTHROPIC_DEFAULT_HAIKU_MODEL lets you choose one. Agent view is still a research preview, so re-check these keys after you upgrade.
What doesn't show up"Interactive sessions you have open in other terminals don't appear until you background them", and subagents and teammates that a session spawns "aren't listed as separate rows". Agent view is for sessions, not for workers inside them; use /tasks inside a session for those.
Starting Background Work
Five entry points.
From agent view. Type a task and press Enter; "every prompt you enter here starts its own new session". Prefixes route it: <agent-name> <prompt> or @<agent-name> picks a subagent as the main agent, @<repo> a directory, ! <command> a shell job, #<number> a PR. Type /model opus to change the dispatch model for the rest of that agent-view run.
From your shell with --bg (or --background). The prompt is positional; "Claude Code rejects --bg combined with -p or --print before any session is created."
From inside a session with /bg [prompt] (alias of /background) or ← on an empty prompt, which backgrounds the session and opens agent view with its row selected.
As a copy with /fork [prompt]: the original keeps running here, the copy becomes a new row.
On exit: quitting a session with running background work offers "Move to background and exit".
# dispatch, name, and pick an agent
claude --bg --name "flaky-test-fix" "investigate the flaky SettingsChangeDetector test"
claude --agent code-reviewer --bg "address review comments on PR 1234"
# continue an existing conversation in the background (in place on v2.1.257+)
claude --resume 1f0e2c9a-6d0b-4c11-9f39-2a77c1d4e8b5 --bg "finish the migration"
# a shell job instead of a Claude session: no model, output kept in memory
claude --bg --exec 'pytest -x'
After --bg, Claude Code prints the short ID and the management commands:
backgrounded · 7c5dcf5d · flaky-test-fix
claude agents list sessions
claude attach 7c5dcf5d open in this terminal
claude logs 7c5dcf5d show recent output
claude stop 7c5dcf5d stop this session
Which permission mode it gets. A session you background with /bg or ← keeps its mode. One dispatched from claude agents in a shell, or with claude --bg, "starts the way a new claude session in that directory would". One dispatched from an agent view you opened with ← takes the target directory's permissions.defaultMode first, then the mode of the session you came from, and Claude Code refuses a project-level defaultMode more permissive than that session. For a new session that order is the --permission-mode flag, then permissions.defaultMode, then the built-in default (auto mode for interactive sessions on v2.1.283+, and on every plan and provider from v2.1.284). Put an auto or bypassPermissionsdefaultMode in ~/.claude/settings.json: from .claude/settings.json or .claude/settings.local.json, auto falls back to the built-in default and bypassPermissions starts the session in Manual, and neither falls through to your user settings. For a dispatch from an agent view you opened with ←, the two "take effect only from managed settings, a --settings file, or ~/.claude/settings.json". Decide the mode on purpose for unattended work: one that prompts on every edit sits in Needs input all afternoon, and one in a permissive mode acts without you watching. To set defaults for everything you dispatch from one agent view, open it with flags: claude agents --permission-mode plan --model opus --effort high.
How edits are isolated. "Before editing files, Claude moves the session into an isolated git worktree under .claude/worktrees/, so parallel sessions can read the same checkout but each writes to its own." Claude skips the move for a session you backgrounded from the foreground (it keeps editing where it was), for sessions already inside a linked worktree, outside git without a WorktreeCreate hook, and for writes outside the working directory. "worktree": {"bgIsolation": "none"} in .claude/settings.json turns isolation off for a repo (v2.1.143+). In a worktree it created, Claude preserves the work before finishing: it commits without asking and pushes when there's a remote, opens a draft PR when the task calls for one, and never pushes to main or master, force-pushes or merges. "Your git instructions take precedence" if CLAUDE.md says you handle git. Every job ends "with a report saying what it did and where the work is: a path, a branch, a pull request, or the answer itself."
Pitfall: ten sessions, ten times the quota"Background sessions consume your subscription usage the same as interactive sessions, so running ten agents in parallel uses quota roughly ten times as fast as running one." Each session is a full conversation with its own context and cache. Dispatch the tasks that are actually independent, and give each a clear stopping condition.
What carries over when you background a session
The background session continues the saved conversation. Running background shell commands, backgrounded subagents, /loop tasks and artifact-comment replies "keep running in the background session"; "a subagent moves together with everything it started, so it carries over only when all of that work can move too". A dynamic workflow "continues only when Claude relaunches it in the background session", and any of its subagents still running "start over and spend their tokens again". Running monitors can't move, so the Background this session? dialog asks before stopping them. A foreground shell command still running when the switch happens is stopped, and the new process has no record it started, so Claude may run it again; press Ctrl+B first to turn it into a background command. Launch flags carry through (--mcp-config, --settings, --setting-sources, --add-dir, --plugin-dir, --fallback-model, --allow-dangerously-skip-permissions), and each session gets CLAUDE_JOB_DIR pointing at ~/.claude/jobs/<id>, whose tmp/ directory Write and Edit can use without prompting. Source: agent-view.
Attach, Logs and Stop
What it is. Every background session has a short ID (its directory name under ~/.claude/jobs/), and the shell commands below manage it without opening agent view. attach and logs also accept part of a session's name (v2.1.290+).
Command
Purpose
claude attach <id|name>
Open the session in this terminal; Claude posts a recap of what happened while you were away
claude logs <id|name>
Print recent output
claude stop <id> (also claude kill)
Stop a session; transcript and worktree are kept
claude respawn <id> / --all
Restart one or all sessions, e.g. onto an updated binary; a saved conversation resumes
claude rm <id>
Remove a session, and its Claude-created worktree when that's safe
claude agents --json [--all] [--cwd <path>]
Print sessions as JSON and exit: "the supported way to read session state from outside Claude Code"
claude daemon status | logs | stop --any
Inspect, follow (~/.claude/daemon.log) or stop the supervisor; stop --any also stops every session it hosts unless you add --keep-workers
Attaching and detaching. An attached session behaves like any session, always in fullscreen rendering. Detach with ← on an empty prompt or /exit (back to agent view), or Ctrl+Z (back to where you started). Ctrl+C still interrupts; twice on an empty prompt detaches. "Detaching never stops a background session"; to end one from inside, run /stop. /status shows Session kind as background job · attached or background job · unattended.
Scripting state. Poll claude agents --json --all and read state (working, blocked, done, failed, stopped), status (busy, waiting, idle while the process lives) and waitingFor (permission prompt, input needed, sandbox request, worker request, dialog open). "A session that finished its turn and is waiting for your next instruction reads done, not blocked." Don't parse ~/.claude/jobs/<id>/state.json: "The files under ~/.claude/jobs/<id>/ are not a stable interface."
# list background sessions that need you, with what they're waiting for
claude agents --json --all \
| jq -r '.[] | select(.kind == "background" and .state == "blocked")
| "\(.id)\t\(.name // "-")\t\(.waitingFor // "first prompt or error")"'
How the supervisor treats sessions. Working sessions, sessions paused on a prompt, and attached sessions keep their process. A finished or waiting session left unattached "for about an hour" has its process stopped to free resources (the conversation stays on disk and resumes when you reply), unless you pin it with Ctrl+T. A crashed session is restarted. Sessions survive sleep and auto-updates; a shutdown stops them, and they show failed if you come back within 48 hours or stopped ("ended while the background service was off") after that. Attaching or replying restarts them from the saved conversation.
What deleting a session removes
This is the part to memorize. Deleting (Ctrl+X twice in agent view, or claude rm) keeps the transcript, reachable through claude --resume, but treats the Claude-created worktree differently depending on the path and its state:
Choose how you delete and what's in the session's worktree; the shelf shows what the delete sweeps away and what stays. Outcomes follow the "What deleting a session removes" rules on the agent-view page (flags need v2.1.260 and v2.1.268).
Commit before you delete in agent view"Agent view removes it, including uncommitted changes, so commit what you want to keep first." claude rm is the gentler path: it keeps a worktree with uncommitted changes, along with the session row. Unpushed commits block both paths once; deleting again discards them.
Notifications
What it is. Background work is only useful if you hear when it needs you. Claude Code has three signals, each with different conditions:
The footer hint. In a regular session the prompt footer shows ← 2 agents when two background sessions are waiting on you, and briefly ← 2 done when sessions finish while none need input. It refreshes about every ten seconds while the terminal is focused.
Terminal notifications. "While agent view is open, Claude Code also sends a notification through your configured terminal notification channel when a local background session starts needing your input, finishes, or fails." /loop sessions notify only when they need input.
The Notification hook. The same events fire the Notification hook with notification_typeagent_needs_input or agent_completed, which you can route anywhere: a desktop alert, a chat webhook, a phone push.
The channel comes from preferredNotifChannel (shown in /config as Local notifications): "auto" sends a desktop notification in iTerm2, Ghostty and Kitty and rings the bell in Terminal.app only when its audible bell is off; the others are "terminal_bell", "iterm2", "iterm2_with_bell", "kitty", "ghostty" and "notifications_disabled". Crucially, "you receive these hook events even with desktop notifications turned off: the preferredNotifChannel setting, including notifications_disabled, changes only how you're alerted, not whether your hook runs."
A matcher made only of letters, digits, _, -, spaces, commas and | is a list of exact names, so agent_needs_input|agent_completed selects exactly those two types; a matcher with any other character is treated as a regular expression. Other types worth knowing: permission_prompt (after a prompt has waited about six seconds without typing), idle_prompt (about 60 seconds after a response, only if no background agent is still running), the elicitation_* types for MCP input, and the quota_auto_resume_* types (v2.1.234+).
Pick an event, whether agent view is open, your channel and your terminal. The widget reports whether a terminal notification appears and whether your Notification hook runs, with the documented reason. Timing thresholds are the documented approximate ones.
Waiting on one particular sessionFor a single long task in another session on the same machine, ask Claude: "Tell me when the migration session finishes what it's working on." Claude subscribes with SendMessage's notify_when_idle input (v2.1.236+ in both sessions), which costs the watched session no tokens; the notice arrives as a line in your conversation, and the subscription lapses after 12 hours.
Exercise: a background triage desk
(1) Install the Notification hook above and set preferredNotifChannel to notifications_disabled so only your hook alerts you. (2) From your shell, dispatch three named sessions: a flaky-test investigation, a dependency-update check in --permission-mode plan, and a --bg --exec test run. (3) Open claude agents, peek at each, answer one question from the peek panel, and pin one. (4) Write a one-line watcher with claude agents --json --all that prints sessions in blocked. (5) Delete the shell job and one finished session with claude rm, and check what happened to its worktree.
Show a solution
claude --bg --name flaky "find why tests/test_settings.py::test_reload flakes; report root cause with a repro command"
claude --bg --name deps --permission-mode plan "list outdated dependencies and the risk of upgrading each"
claude --bg --exec 'pytest -x -q'
claude agents # Space to peek, type a reply, Ctrl+T to pin
watch -n 15 "claude agents --json --all | jq -r '.[] | select(.state==\"blocked\") | .name // .id'"
claude rm <id> # keeps a worktree that has uncommitted changes
The notification should fire only while agent view is open, since agent_needs_input and agent_completed are tied to it. The shell job's row and in-memory output disappear about five minutes after pytest exits, so read its output with claude logs before then. The flaky-test session, if it edited files, worked in .claude/worktrees/ and committed there.
Key takeaways
claude agents is agent view (research preview since v2.1.139); /agents is an unrelated reminder.
Dispatch with the agent-view input, claude --bg (never with -p), /bg, ← or /fork; pass the permission mode explicitly for unattended work.
Dispatched sessions move into .claude/worktrees/ before editing and commit their work; backgrounded foreground sessions edit in place.
Script with claude agents --json --all; blocked means it needs you, done means it finished its turn.
Deleting in agent view removes the worktree with uncommitted changes; claude rm keeps it. Commit first.
Background notifications and agent_* hook types fire only while agent view is open; hooks run even with notifications disabled.
Delegation
Every worker in this session starts from a few hundred words of text and returns a few hundred more. The quality of a multi-agent run is mostly the quality of those two messages. This topic is about writing them for Claude Code specifically: what actually reaches a worker, how to turn a brief into a contract that hooks and tool limits enforce, what shape results should take, and how Claude Code reports failure so you can design for it.
Briefs
Why delegate: context, not only parallelism
Parallelism is the obvious reason to delegate. Context is the other, though the reason has shifted: the best-practices page now says "Running out of context is rarely the problem anymore." The cost is that long output stays put. One session that does everything pulls every file dump, test log, dead-end refactor and page of grep output into its own window, where it would "ride along for the rest of the session" and be re-sent on every turn. A subagent avoids that. It starts with a clean window, explores as much as the task needs and returns a short summary; its reading stays in its own window and never reaches yours. The sub-agents page gives the rule: use one "when a side task would flood your main conversation with search results, logs, or file contents you won't reference again". The price is tokens: "every subagent sends its own requests and they count against the same usage as your main conversation." The brief going in and the summary coming out are all that cross between the windows, which is why the rest of this topic is about them.
Several clerks work at once, each at its own desk, where its reads, logs and dead ends pile up and stay. Press fan out to send three briefs together. In the foreground, subagents "block the main conversation until complete": you wait at the window. In the background, they "run concurrently while you continue working", and each letter arrives "as a completion notification in a later turn" (with nothing configured, a subagent Claude spawns from your main conversation starts in the background). Clerks Claude named can pass each other notes by name with SendMessage (sub-agents). Every letter that comes back is pinned to your one context window, so returns add up: "Running many subagents that each return detailed results can consume significant context." In the foreground you get a partial letter noting it didn't finish; in the background the clerk is marked failed and its last output comes back with the API error. Why only the brief crosses in and only the report comes out is drawn once, in Core 2's subagent boundary. Pile sizes, timings and the fill per letter are illustrative.
The toy model below puts rough numbers on those piles: the same three hours of work, first in one window, then spread over three subagents.
Toy model with illustrative numbers, not measurements. In "One session", every read, test run and dead end stays in the main window, which is 92% full by hour three in this toy model. In "Delegated", three subagents absorb that work in their own windows, where it stays, and only their summaries reach the main window.
When not to delegate
Tightly coupled edits to the same files. When two workers would have to change one module in step, coordinating them costs more than the context you save. Keep the change in one session or a short pipeline (see "When parallelism doesn't help" under Parallel Patterns).
When you need the detail, not a digest. A worker hands back a summary, and a summary of a subtle bug is a worse bug report. Chase a race or a flaky interaction in the main session, or have the worker write the raw evidence (exact commands, output, file:line) to a file you read yourself.
Tiny tasks. A non-fork worker builds its own prompt cache from scratch (see the cache deep dive under Tools and Models), so for a one-line fix or a single lookup the spawn overhead outweighs the win.
Fold or keep a subagent (agents you build)
The same trade-off applies when you design an agent of your own. The Claude Platform article When to fold subagents into your main agent loop (Diane Sarkis, October 22, 2026) reports that across several enterprise deployments, a single agent with skills "frequently outperformed both the one-prompt-for-everything design and the subagent design on quality, and often at a lower cost and latency per task". The mechanism is progressive disclosure: "the agent sees short descriptions of the skills and tools, which are fully loaded only when needed". Claude Code works the same way with skills and tool search. The article keeps a subagent for three conditions and names the patterns that should make you fold one in:
Keep it as a subagent when (the article)
Fold it in when you see (the article)
"A single agent loop hits measurable performance degradation from context bloat"
the architecture "becoming a copy of their org chart (Conway’s law at work)"
"Multiple tasks need to be tackled in parallel with fresh context windows that can be discarded once the task is done"
the Frankenprompt: "Every team adds a sentence to the system prompt, resulting in conflicting rules and no consistent voice"
"A single agent struggles to select appropriate tools or there are conflicting instructions in the system prompt"
"overly localized evals": "Everyone adds their own evals that are overly optimized for their subtask"
Latency is part of the case, as one customer's result rather than a rule: comparing its multi-agent harness with a single agent loop, it "saw a roughly 2x faster runtime with the latter". When you do split, the article's rule is "dividing by context: give each subagent a piece of work that needs little from the rest of the system and have it hand back a compact result". Split by problem type instead and the agents play a "telephone game", "passing information back and forth with each handoff degrading fidelity". On tools, it advises grouping them by user intent, because "once you exceed 30-50 tool definitions in the system prompt, tool choice tends to degrade".
Migrate as an eval loop. The article folds subagents in "one at a time", says to "Compare eval performance with and without the subagent", and to look past the total: "don’t just examine the final score, take a look at which tasks flipped". In its sample support agent, one fold lowered latency but broke a process that had been passing, and the break "only showed up in one run out of two", so run each task more than once. Its closing advice: "Build a small end-to-end eval, fold in one subagent, and keep it as a subagent only if the folded version scores worse". The same trade-off applies to your own Claude Code subagents and skills; the eval habits for measuring it are in Agents 5 Evals.
The brief itself
What it is. A brief is the task text a worker starts from. For a non-fork subagent, Claude writes it: "Claude composes a delegation message that summarizes the task, and the subagent works from there." The Agent SDK docs state the constraint that follows: "The only content you pass from parent to subagent is the Agent tool's prompt string." You influence that string three ways: through your request (what you ask Claude to delegate and how), through the agent's body (a standing brief that applies to every task), and through CLAUDE.md, which most subagents load.
What reaches a non-fork subagent at startup, per the docs:
Arrives
its own system prompt (the agent body) plus environment details
the task message Claude writes
CLAUDE.md files, rules and AGENTS.md (not for Explore, Plan or omitClaudeMd)
a git status snapshot (not for Explore or Plan)
preloaded skills
a sibling roster of named agents, when it has SendMessage
Never arrives
your conversation history
files Claude already read, skills already invoked
your output style
your auto memory
your context window size (it uses its own model's)
anything you said "earlier" but Claude didn't put in the brief
What a good brief contains. Anthropic's multi-agent research post found that delegation needs "an objective, an output format, guidance on the tools and sources to use, and clear task boundaries"; without them, early versions duplicated work and "spawned 50 subagents for simple queries" (Anthropic engineering). The cloud-sessions field guide puts the same idea as a ticket: "Write each task as a self-contained ticket that states what's wrong, what done looks like, and how to prove it" (claude.dev). For Claude Code, add the things the worker can't see: decisions already made, things already tried, and when to stop and ask. And watch for context leaks: "as discussed", "the file above" and "the error we saw" point at history the worker never receives.
✗ What Claude writes when you say "use a subagent to look into the flaky test"
"Investigate why the checkout test is flaky and fix it." No path, no definition of done, no limit on edits, no output shape. The worker may rewrite the test, raise a timeout, and report "fixed".
✓ What you get when your request carries the brief
"Use a subagent, read-only. Objective: find why tests/checkout/test_retry.py::test_idempotent_capture fails about 1 in 20 CI runs, so we can decide today whether to quarantine it. Scope: tests/checkout/ and services/payments/; don't edit files or touch CI config. Known: raising the timeout to 30 s didn't help; capture idempotency uses Postgres advisory locks (ADR-031). Done when the root cause is one of test-order, timing, product bug or infra, with a repro command and its failure rate over 50 runs. Return the JSON report from docs/agent-report.md. Stop after about 40 tool calls and return what you have, marked partial."
Paste or edit a brief and read it back as the printed delegation form the worker gets: each of the 11 blank lines is written in with the words the check found, an empty one stays as underscores with the form's hint, and leaked references to your history are struck through. This is a heuristic keyword check, like the lab's linter: it can tell you a definition of done is missing, not whether yours is right. Load the weak and strong examples to compare.
Standing brief vs task briefPut what's true for every task in the agent body: the role, the boundaries, the report format, the stop rules. Put what's specific in the request. A good test: if you'd have to repeat it every time you delegate, it belongs in the body. If a CLAUDE.md rule must reach a worker that skips CLAUDE.md (Explore, Plan, omitClaudeMd), "restate it in the prompt you give Claude when delegating."
Briefs for the other worker types. A teammate gets the lead's spawn prompt and no history, so the docs' advice is to "include task-specific details in the spawn prompt", for example the module path, what to focus on, the auth scheme, and "Report any issues with severity ratings". A background session gets exactly your dispatch prompt and nothing else from your terminal. A fork is the exception: it inherits everything, so its brief can be one line (/subtask draft unit tests for the parser changes so far).
What you build: a brief template with Goal, Context, Constraints, Out of scope, Deliverable, Done when, Budget and Escalate when sections, and a linter that flags context leaks ("as discussed", "the file above"), vague goals, done-when items nobody can check, paths that don't exist in the repo, and a missing write scope.
cd labs && python3 agents-4/delegation_brief.py
python3 agents-4/delegation_brief.py --template # a blank brief
# real run (costs money)
claude -p --agent implementer --permission-mode acceptEdits --worktree brief-run \
--max-turns 25 --max-budget-usd 0.50 \
"$(python3 agents-4/delegation_brief.py --render brief.md)"
# -p never removes its worktree; after you've reviewed or copied the changes:
git worktree unlock .claude/worktrees/brief-run 2>/dev/null # -p leaves it locked
git worktree remove --force .claude/worktrees/brief-run && git branch -D worktree-brief-run
The last command is a real run and costs money, so it carries a turn cap and a budget cap. -p never removes the worktree it creates. Once you've reviewed or copied the changes, remove it with --force (the implementer doesn't commit, so the worktree is dirty) and delete its worktree-brief-run branch. A -p run also leaves the lock it took on the worktree "in place until a later session's stale-lock sweep releases it", and git won't remove a locked worktree with a single --force, so the block unlocks it first. The run passes the mode and worktree explicitly: -p starts in Manual on v2.1.302+, so edits would be denied, and the docs promise that --agent applies the agent's "tool restrictions and model", not its permissionMode or isolation. What to observe: the leaky sample scores 0 because the subagent would get only the prompt string, the vague one scores 3, and the good one 100. The rules are regexes over the text, so treat each finding as a question to answer, not a verdict. Offline; no API key needed.
What it is. A handoff contract is a brief whose terms are checkable and, where possible, enforced. Prose in a prompt is advisory; the docs' best-practices page makes the distinction for every instruction, and it applies equally here. A prompt, CLAUDE.md or a skill is read by the model, and "there's no guarantee that it'll follow your instructions". A hook, a deny rule or a managed setting is different: "Claude Code applies this every time, no matter what the model decided to do." Claude Code gives you a mechanism for most clauses of a contract:
Contract clause
Advisory form
Guarded by the harness
Verified afterwards
Scope: what it may touch
"don't edit outside src/payments/"
tool removal (tools / disallowedTools); an Edit deny rule, which also covers the Bash file commands Claude Code recognizes and redirect targets, but not scripts that open files themselves; sandbox write rules, the only OS-level layer; a PreToolUse guard matched on Edit, defense in depth that sees no Bash writes at all; isolation: worktree to limit the blast radius
git diff --name-only on the worker's branch before merging
maxTurns (partial output on hit); --max-turns and --max-budget-usd for headless runs
num_turns, total_cost_usd in the result
Definition of done
"done when tests pass"
a report gate that runs the check; TaskCompleted exit 2 for teams
re-run the tests yourself or in CI
Output shape
"return JSON with status and evidence"
a report gate: PreToolUse on SubagentHandback in auto mode, SubagentStop otherwise; --json-schema for headless
the caller parses it and treats a malformed report as a failure
Escalation
"ask before touching migrations"
permission prompts (background subagents surface them in your session); ask rules
n/a
Authority
"only the user can approve"
built in: no agent message counts as approval or can change config
n/a
The agent file carries the standing contract and the brief the task-specific one. Settings, the sandbox and hooks are the parts the worker can't talk its way around, though a hook only sees the calls its matcher selects. The report gate sits wherever the report arrives: SubagentHandback in auto mode, SubagentStop otherwise. Hover or tab to a part; switch auto mode to move the report gate.
How to apply it. A contract-shaped agent file, with the enforced parts in frontmatter and the advisory parts in the body:
.claude/agents/test-fixer.md
---
name: test-fixer
description: Fixes one failing test without changing product behavior. Use when a single test fails.
tools: Read, Edit, Bash
maxTurns: 30
isolation: worktree
hooks:
PreToolUse:
- matcher: "Edit"
hooks:
- type: command
command: "./.claude/hooks/tests-only-edits.sh" # guard: exit 2 unless the path is under tests/
onFailure: block
- matcher: "Bash"
hooks:
- type: command
command: "./.claude/hooks/test-commands-only.sh" # guard: allow pytest invocations only
onFailure: block
- matcher: "SubagentHandback"
hooks:
- type: command
command: "./.claude/hooks/require-report.sh" # report gate in auto mode (Result Formats)
onFailure: block
Stop:
- hooks:
- type: command
command: "./.claude/hooks/require-report.sh" # becomes SubagentStop: report gate in other modes
---
You fix exactly one failing test, named in your task.
Scope: edit files under tests/ only. If the fix needs a product change, stop
and report status "blocked" with the product change you'd propose.
Done: the named test passes 20 runs in a row (`pytest -q <test> --count 20`)
and the rest of its module still passes.
Report: the JSON block defined in docs/agent-report.md, as the last thing you write.
The two PreToolUse guards are defense in depth, not the boundary. Each sees only the calls its matcher selects: the Edit guard never sees sed -i, python -c or cat > run through Bash, and a Bash guard that matches command strings can't see what a test file does when it runs. Permission rules reach further. Per the permissions page, Edit and Read deny rules also apply "to file commands Claude Code recognizes in Bash, such as cat, head, tail, sed, and tee" (tee from v2.1.269) and to redirect targets such as > file, so a permissions.deny entry Edit(/src/**) would stop sed -i src/app.py and cat > src/app.py. They don't cover "a Python or Node script that opens files itself". Deny rules are also session-wide, so they suit a session dedicated to this work rather than one where you edit src/ yourself. Only the sandbox's sandbox.filesystem write rules are enforced at the OS level, for Bash and every child process. Then verify the scope clause after the fact, before you merge the worker's branch:
# anything this prints is a file the test-fixer changed outside tests/
git diff --name-only main...<test-fixer-branch> | grep -v '^tests/'
Pitfall: the contract that only the reviewer readsA beautifully worded scope clause does nothing if the agent inherits Edit everywhere and the main session is in acceptEdits (which overrides permissionMode). Decide which clauses you'd be upset to see violated, guard those, and verify them. Two operational traps: frontmatter hooks in a project agent run only after you accept workspace trust for the folder that holds the file, and a -p session's automatic trust doesn't count, so in CI they're skipped unless that folder's trust is already on record. For headless runs, register the same scripts as settings hooks instead (not as well), filtered on the agent_type field of the hook input. And keep the scripts small and fail closed: a PreToolUse guard that crashes falls through unless you set onFailure: "block" (v2.1.295+), as every PreToolUse entry on this page does. Stop-type events ignore that field; see the shared task list section for what that means for gates there.
Advisory, guarded and verified: three layers
Think of each clause at three strengths. Advisory: the worker is told (brief, body, CLAUDE.md). Cheap, flexible, and reliable most of the time on current models, but a worker under pressure from a failing test or an injected instruction can drift. Guarded: the harness refuses the call. Tool removal, deny rules, sandbox rules and maxTurns are hard limits for the calls they cover (deny rules are mod-proof only with managed settings or a Team or Enterprise /login as the session's credential; otherwise an installed mod can approve a call a deny rule refuses, and an API key or CLAUDE_CODE_OAUTH_TOKEN doesn't count as that login); a PreToolUse exit 2 is defense in depth, because a hook sees only the calls its matcher selects and can be routed around through another tool. Verified: something independent checks the outcome after the fact (a report gate or TaskCompleted gate that runs tests, a diff check on the branch, a fresh-context reviewer subagent, CI). Anthropic's harness-design work found that "tuning a standalone evaluator to be skeptical turns out to be far more tractable than making a generator critical of its own work" (Anthropic engineering). A good contract uses all three: advise everything, guard the irreversible with hard limits where they exist, verify the deliverable. The guardrail mechanics are in Agents 5.
Result Formats
What returns. Each worker type hands back something different, and only that:
Worker
What the caller receives
Foreground subagent
Its final message, as the Agent tool result. "The parent doesn't see the subagent's intermediate tool calls or outputs, only that final result."
Background subagent
The same report "as a completion notification in a later turn", marked as an automated event, not a message from you
Teammate
Messages, plus an idle notification to the lead that "includes its final answer"
Background session
Nothing to any agent; it reports to you: the row summary, the peek panel, and a closing report naming "a path, a branch, a pull request, or the answer itself"
Headless claude -p
--output-format json gives result, stop_reason, terminal_reason, subtype, session_id, total_cost_usd; with --json-schema, a validated structured_output. Check stop_reason first ("refusal" means the model declined), then terminal_reason: anything but "completed" is a failure
Why format matters. The caller is a model with a context window. "Running many subagents that each return detailed results can consume significant context." A consistent result format keeps returns short, makes synthesis mechanical, and lets a hook check the result. Three practical rules: ask for a fixed structure (status, summary, evidence, changed files, open questions); require evidence the caller can check (file:line, the exact command and its output); and write bulky artifacts to files, returning their paths. Anthropic's research system had subagents write to the filesystem "to minimize the 'game of telephone'". In background sessions, $CLAUDE_JOB_DIR/tmp is a collision-free place for that.
docs/agent-report.md (referenced by agent bodies)
End every task with one fenced JSON block, and nothing after it:
{"status": "done | partial | blocked | failed",
"summary": "one or two sentences",
"evidence": ["path:line or command → observed output"],
"files_changed": ["path"],
"open_questions": ["…"],
"safe_to_retry": true}
Enforcing it: first check where the report arrives. It depends on the permission mode the worker runs in:
Auto mode, the built-in start mode for interactive terminal and VS Code sessions since v2.1.283. Claude Code gives every local non-fork subagent the SubagentHandback tool (v2.1.271+), "even if you leave it out of tools or list it in disallowedTools", and the subagent delivers its report through it; the classifier reviews the report before delivery. In SubagentStop, last_assistant_message then "holds the subagent's closing text, if any, which is not the delivered report". Check the report in a PreToolUse hook matched on SubagentHandback, where it arrives as tool_input.message, and deny an invalid one with permissionDecision: "deny" and a reason.
Manual, acceptEdits, plan and dontAsk, including claude -p, which starts in Manual on v2.1.302+. The report is the final message, and a SubagentStop hook receives it as last_assistant_message. Returning decision: "block" with a reason "keeps the subagent running and delivers reason to the subagent as its next instruction". Check stop_hook_active so a worker that can't comply doesn't loop: it makes the block a one-time nudge. Don't rely on Claude Code's cap of eight consecutive continuations (CLAUDE_CODE_STOP_HOOK_BLOCK_CAP) instead, because it resets every time the subagent calls a tool, so a worker that re-runs the tests between blocks never reaches it.
One script can serve both paths, keyed on hook_event_name. Register it in one place: in the agent's frontmatter (interactive sessions, trusted folder), as in the test-fixer above, or in settings filtered on agent_type (headless), as in the tab below, not both. Claude Code de-duplicates an identical handler only across settings files, so a frontmatter copy plus a settings copy runs the script twice per event, and the denial counter then lets a bad report through after one denial instead of two. The handback path has no stop_hook_active, so a worker that can't produce a valid report could retry the handback indefinitely; the script counts denials per session and agent in a state file and lets the report through after two. Any hard gate needs its own counter like this. The docs only say to read the report with a PreToolUse or PostToolUse hook; they don't describe how a subagent reacts to a denied handback, so on your version confirm that it retries with a corrected report rather than ending. Either way, if a subagent in auto mode ends without a successful handback, nothing reached the gate: treat a missing report as a failure in the caller. The PreToolUse entry sets onFailure: "block" so a crashing gate denies rather than allows; the SubagentStop entry can't, so the script limits its own retries.
.claude/hooks/require-report.sh
#!/usr/bin/env bash
# Report gate for test-fixer and code-reviewer. Two paths:
# PreToolUse on SubagentHandback (auto mode): the report is tool_input.message
# SubagentStop (other modes, claude -p): the report is last_assistant_message
# Internal errors (no jq, bad input) fail closed, with a limit so the gate can't loop.
set -o pipefail
gate=require-report
state="${TMPDIR:-/tmp}/claude-gates"; mkdir -p "$state" || exit 2
fail() { # internal error: exit 2 up to 3 times in a row, then let it through and log why
local n; n=$(( $(cat "$state/$gate.errors" 2>/dev/null || echo 0) + 1 )); echo "$n" > "$state/$gate.errors"
if [ "$n" -gt 3 ]; then echo "$(date) $gate broken: $1" >> "$state/gate-errors.log"; exit 0; fi
echo "$gate: $1" >&2; exit 2
}
trap 'fail "error on line $LINENO"' ERR
command -v jq >/dev/null || fail "jq missing"
input=$(cat)
event=$(jq -r '.hook_event_name' <<<"$input")
agent=$(jq -r '.agent_type // ""' <<<"$input")
rm -f "$state/$gate.errors"
case "$agent" in test-fixer|code-reviewer) ;; *) exit 0 ;; esac
reason="End with the JSON report from docs/agent-report.md: status must be done, partial, blocked or failed, with evidence."
valid() { # true when the text's last fenced json block has a known status
local report
report=$(printf '%s' "$1" | awk '/^```json/{f=1;buf="";next} /^```/{if(f){last=buf};f=0;next} f{buf=buf $0 "\n"} END{printf "%s", last}')
case "$(jq -r '.status // empty' <<<"$report" 2>/dev/null)" in done|partial|blocked|failed) return 0 ;; esac
return 1
}
if [ "$event" = "PreToolUse" ]; then
# No stop_hook_active here, so count denials per session and agent.
key="$state/handback-$(jq -r '"\(.session_id)-\(.agent_id)"' <<<"$input")"
if valid "$(jq -r '.tool_input.message // ""' <<<"$input")"; then rm -f "$key"; exit 0; fi
n=$(( $(cat "$key" 2>/dev/null || echo 0) + 1 )); echo "$n" > "$key"
if [ "$n" -gt 2 ]; then rm -f "$key"; exit 0; fi # after two denials, let it through and reset; the caller treats a bad report as a failure
jq -n --arg r "$reason" '{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: $r}}'
exit 0
fi
# SubagentStop
[ "$(jq -r '.stop_hook_active' <<<"$input")" = "true" ] && exit 0 # nudge once, then let it stop
[ "$(jq -r '.permission_mode // ""' <<<"$input")" = "auto" ] && exit 0 # auto: checked at SubagentHandback
valid "$(jq -r '.last_assistant_message // ""' <<<"$input")" && exit 0
jq -n --arg r "$reason" '{decision: "block", reason: $r}'
exit 0
.claude/settings.json: use this or the frontmatter hooks, not both
{
"session_id": "abc123",
"hook_event_name": "SubagentStop",
"permission_mode": "default",
"stop_hook_active": false,
"agent_id": "def456",
"agent_type": "test-fixer",
"agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",
"last_assistant_message": "Fixed the race in the fixture. All tests pass."
}
example input (excerpt)
{
"session_id": "abc123",
"hook_event_name": "PreToolUse",
"permission_mode": "auto",
"agent_id": "def456",
"agent_type": "test-fixer",
"tool_name": "SubagentHandback",
"tool_input": { "message": "Fixed the race in the fixture. All tests pass." }
}
The matcher test-fixer|code-reviewer contains only letters, hyphens and |, so Claude Code reads it as a list of exact agent names, not a regex. The SubagentHandback input is abbreviated to the fields the script reads; the full set follows the common PreToolUse input.
Edit the subagent's report and run the gate, with auto mode on (the report goes through SubagentHandback) or off (it's the final message seen by SubagentStop). The simulator applies the same logic as require-report.sh and shows the hook's input, its output, and what Claude Code does with it, including the stop_hook_active second pass and the handback path's own denial counter (run an invalid report three times). It models the documented decision flow; how a subagent reacts to a denied handback isn't documented.
Two more detailsSubagentStop also fires for Claude Code's internal agents (prompt suggestions, /btw) with an empty or session-level agent_type, which is another reason to set a matcher; a matcher that names agent types doesn't match an empty one. And to add context to the parent after a subagent returns, use PostToolUse on the Agent tool.
Failure Reporting
What it is. Workers fail in two ways: the harness fails them (API errors, turn limits, being stopped), or they fail at the task and say something misleading about it. Claude Code reports the first kind in specific, documented ways, and you design the result format to catch the second.
Situation
What Claude Code reports
Foreground subagent cut off by a rate limit, overload or server error after producing text
The partial output "with a note that the subagent was cut off and didn't finish its task"
Foreground subagent with no text output (or only tool calls)
Agent terminated early due to an API error, plus the error detail
Background subagent ends on an API error
Marked failed; the completion message names the error "and includes the subagent's last output, so partial work isn't lost"
Subagent hits maxTurns
Output marked partial (v2.1.246+); Claude can resume it to continue
A fallback model chain covers the failure
Nothing fails: the subagent switches to the first model in the chain that accepts the request
Teammate turn ends on an API error
The lead is notified that it failed, with the error text
Background session errors
Row turns Failed; state: "failed" in claude agents --json
How to recover. Resuming is usually better than re-spawning: a resumed subagent keeps "their full conversation history, including all previous tool calls, results, and reasoning" and its warmed cache. Claude resumes with SendMessage to the agent ID or name ("Continue that code review and now analyze the authorization logic"). Three limits: Explore and Plan are one-shot and can't be resumed; a subagent you stopped yourself (with x in /tasks) won't auto-resume, and "the message is refused and Claude is told the agent was cancelled"; and SendMessage refuses a name that now points at a newer agent, to avoid delivering to the wrong one. For teams, when a teammate stops early, read its transcript, then "give them additional instructions directly" or "spawn a replacement teammate". For background sessions, peek, attach, or claude respawn <id>.
Pick what went wrong. The widget shows what reaches the caller, the recovery move, and what to change so it doesn't recur. Rows marked "harness" are documented Claude Code behavior; rows marked "task" are failures of the work itself, which only your result format and verification can catch.
The failure you must design for. The harness can't tell you when a worker confidently reports success it didn't achieve. The harness-design post is blunt: agents asked to evaluate their own work "tend to respond by confidently praising the work". So a failure report is a required part of the contract, not an afterthought: a status that can be partial, blocked or failed; what was attempted; what side effects happened (files written, branches pushed, external calls); and whether it's safe_to_retry. Then verify the claimed evidence independently, with a gate hook, a fresh-context reviewer subagent, or CI, before you act on "done".
Exercise: break your own contract
Using the test-fixer agent and require-report.sh above (or your own versions): (1) give it a test that can't be fixed from tests/ alone and check that it reports blocked with a proposed product change instead of editing product code; (2) set maxTurns: 3 and confirm the result comes back marked partial, then ask Claude to resume it; (3) temporarily make the report gate demand a field the agent's body doesn't mention. In a Manual-mode session, watch one block, one retry and the stop_hook_active pass-through; in auto mode, watch the SubagentHandback call get denied and note how the subagent responds on your version.
Show a solution
(1) The PreToolUse guard rejects edits outside tests/ with exit 2, and the body's stop rule tells it to report blocked; if it instead loops on rejected edits, tighten the body ("after one rejected edit outside tests/, stop"). (2) With maxTurns: 3, the Agent result is marked partial; "Continue the test-fixer's work" makes Claude call SendMessage to its ID, and /tasks shows it running again under the same ID. (3) In Manual mode the first stop is blocked with your reason delivered as its next instruction; on the second stop stop_hook_active is true and the script exits 0, so the run ends even if the report is still wrong. That's the design: the hook nudges once, and the parent sees an invalid report it must treat as a failure. In auto mode the SubagentStop path exits 0 (the report never reaches it), and the PreToolUse path denies the handback with your reason; expect the subagent to see that as a tool error and try again, but check, since the docs don't specify it. If the scope guard in (1) seemed to hold, also run the git diff --name-only check: a Bash command can change a product file without touching the Edit guard.
Key takeaways
A non-fork subagent knows only its body, the brief Claude writes, CLAUDE.md, git status and preloaded skills; your history never reaches it.
Briefs need an objective, an output format, tool and source guidance, and boundaries, plus decisions made, things tried and when to stop.
Guard the clauses you can't afford to see violated with hard limits (tools, deny rules, sandbox, maxTurns), treat PreToolUse guards as defense in depth, and verify the outcome. Advise the rest.
Ask for a fixed, short, evidence-bearing result; write bulky artifacts to files; check the shape where the report arrives: SubagentHandback in auto mode, SubagentStop otherwise.
Claude Code reports API errors, turn limits and stops in documented ways; resume with SendMessage rather than re-spawning.
Design the report for false success: status values beyond "done", side effects, retry safety, and independent verification.
Orchestration
Orchestration is the part around the workers: giving each one a place to write, choosing the parallel shape that fits the work, deciding where and in what order results rejoin, resolving the conflicts that appear there, and choosing how agents talk across the boundary of a session or an organization. Claude Code has built-in pieces for each, and the orchestrator is usually you or the main conversation using them deliberately.
Worktrees
What it is. A worktree is "a separate working directory with its own files and branch, sharing the same repository history and remote as your main checkout". It's the isolation primitive under almost every parallel pattern in Claude Code.
claude --worktree feature-auth # or -w: .claude/worktrees/feature-auth/ on branch worktree-feature-auth
claude -w # unnamed: Claude picks a name such as bright-running-fox
claude --worktree "#1234" # check out PR/MR head into .claude/worktrees/pr-1234 (quote the #)
claude -p --worktree lint-fix "…" # headless runs skip the trust check, and never clean up
echo ".claude/worktrees/" >> .gitignore
Four ways to get one: --worktree at launch; asking Claude to "work in a worktree" (it calls EnterWorktree); isolation: worktree on a subagent; and automatically, for background sessions that are about to edit. Claude Code's defaults: worktrees live under .claude/worktrees/, branch from the repository's default branch, and contain only tracked files.
Base branch."worktree": {"baseRef": "fresh"} (default) branches from the remote default branch, fetching origin/HEAD if it's over 24 hours stale; "head" branches from your local HEAD, carrying unpushed commits. It can't name a branch. This matters for subagents: with the default, an isolation: worktree subagent doesn't see your feature branch's commits at all.
Gitignored files. "A worktree is a fresh checkout, so untracked files like .env or .env.local from your main repository are not present." List them in .worktreeinclude (gitignore syntax; only files that are also gitignored are copied).
Setup. Dependencies aren't installed in a fresh worktree; tell Claude to install them or use a SessionStart hook.
Hooks.${CLAUDE_PROJECT_DIR} keeps pointing at the main checkout; the hook input's cwd follows Claude into the worktree. Read cwd when a hook needs the worktree path.
Files and branches are per worktree; the .git object store, project plugins, "don't ask again" Bash approvals (saved to the main checkout's .claude/settings.local.json) and, when the worktree has none of its own, untracked .claude/skills, agents and commands are shared. Hover or tab to a tower or a conduit to light it. The worktree names are the examples from the commands above.
How isolation is enforced. While a session or subagent is isolated, Claude Code blocks four things: edits that target the main checkout; Bash, PowerShell or Monitor commands whose working directory resolves there; git redirected into it (git -C, --git-dir, GIT_DIR, GIT_WORK_TREE, or a cd before git); and commands whose text it can't verify keeps git inside the worktree. What it doesn't track: "a command that writes into the main checkout without running git there, such as cp or a shell redirect, isn't refused by them." That's what permission rules and the sandbox are for.
Cleanup. Exiting an interactive worktree session removes a clean unnamed worktree and its branch, prompts for named or dirty ones, and prints a claude --worktree <name> --resume command if you keep it. -p runs never clean up. Subagent and background-session worktrees are removed by a periodic sweep after cleanupPeriodDays, unless they still hold changes or unpushed commits; Claude Code holds a git worktree lock on each while its agent runs.
Outdated advice: hand-rolled worktree scriptsMany 2025 posts show git worktree add ../app-feature -b feature plus a script to copy .env and launch Claude there. That still works (Claude Code treats a worktree you created yourself as already isolated and leaves it in place on cleanup), but the built-in path gives you .worktreeinclude, PR checkout, enforced isolation, resume and sweeping. Use git directly only for a specific existing branch or a location outside the repo.
Parallel Patterns
The menu. The docs list "five ways to work on several tasks at once": subagents, agent view, agent teams, dynamic workflows and projects. Three tools support them: worktrees, cross-session messaging and /batch. Three more features look parallel but aren't ways of splitting work: a background Bash command (one shell command that doesn't block the conversation), forked subagents ("a way to spawn a subagent, not a separate surface") and cloud scheduled tasks. The docs' decision questions are the useful part:
Who coordinates? Claude inside one conversation (subagents); you (agent view); Claude supervising a group (teams); a script (dynamic workflows).
Do workers need to talk? Subagents report only to their caller; agent-view sessions only to you; teammates message each other. Cross-session messaging links sessions you run yourself.
Do tasks touch the same files? Use worktrees. "Agent teams don't isolate teammates in worktrees", so partition files.
Pattern
Claude Code realization
Merge point
Fan-out research
"Research the authentication, database, and API modules in parallel using separate subagents"
Main conversation synthesizes
Writer / fresh-context reviewer
Implement in the main session, review with a read-only reviewer subagent that sees only the diff
You decide on findings
Competing hypotheses
Agent team told to "try to disprove each other's theories"
Lead writes the consensus
Pipeline
"Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them"
Each stage feeds the next
Mass mechanical change
/batchmigrate src/ from JavaScript to TypeScript: researches, presents a plan for your approval, then runs 5 to 30 worktree-isolated subagents that each run tests and publish their change. Needs git or a WorktreeCreate hook
Each unit publishes its own change
Independent tickets
Several claude --bg sessions, or the agent-view input
Branches and draft PRs you review
Laptop-off work
claude --cloud "…": it "clones your current directory's GitHub remote at your current branch, not your local checkout, so push first if you have local commits". With no git remote, or a github.com repo without the Claude GitHub App, it bundles and uploads your local repository instead (history plus uncommitted changes to tracked files)
Cloud branch and PR
Scripted fan-out
A shell or SDK loop over claude -p --worktree <name> with JSON output
Your script's report
Describe the work and the planner ranks the options by the docs' decision questions, with the command to start and the caveats that apply. It's a scoring heuristic, not a rule engine: treat close scores as a judgment call.
A minimal scripted fan-out. The fanout_orchestrator.py lab builds the same shape with a JSON schema, a total budget cap and a merge report. This version is read-only; widen the tools deliberately:
fanout.sh (run from the repository root)
#!/usr/bin/env bash
# One headless run per package, each in its own worktree, results collected as JSON.
set -euo pipefail
mkdir -p .fanout
for pkg in auth billing search; do
claude -p --worktree "audit-$pkg" \
--tools "Read,Grep,Glob" --allowedTools "Read" "Grep" "Glob" --permission-mode dontAsk \
--strict-mcp-config --disallowedTools "mcp__*" --no-session-persistence \
--max-turns 25 --max-budget-usd 2 --output-format json \
"Audit packages/$pkg for unsafe deserialization. Return JSON: {status, findings:[{file, line, issue}], confidence}." \
> ".fanout/$pkg.json" &
done
wait
jq -s 'map({ok: (.stop_reason != "refusal" and .terminal_reason == "completed"), stop_reason, terminal_reason, subtype, cost: .total_cost_usd, session: .session_id, result})' .fanout/*.json
Check stop_reason first, then terminal_reason, then subtype, the order the Agent SDK reference gives. A declined response has stop_reason: "refusal", usually with subtype: "success", and its terminal_reason can still read "completed". Treat any other run whose terminal_reason isn't "completed" as a failure too, even when subtype says "success": real runs have returned subtype: "success" with terminal_reason: "api_error".
Every option multiplies tokens"Running several sessions or subagents at once multiplies token usage." Inside one session, parallel subagents also return into one context window. Two hard limits apply there: 20 concurrent subagents and three levels of nesting by default. Headless worktrees aren't cleaned up, so remove them with git worktree remove when the script finishes.
What you build: an orchestrator that plans N tasks as branches, worktrees and capped claude -p --output-format json --json-schema runs (read-only by default: --tools Read,Grep,Glob --permission-mode dontAsk, per-task --max-turns and --max-budget-usd, a total cap), then builds a merge report: per-task outcome, a file-overlap matrix, a suggested merge order and a trial merge.
cd labs && python3 agents-4/fanout_orchestrator.py # plan + exact commands, report from recorded results
cd labs && python3 agents-4/fanout_orchestrator.py --simulate # real temp worktrees and a trial merge, no model
cd labs && python3 agents-4/fanout_orchestrator.py --real # costs money; prints the total cap first
What to observe: a task that ends with error_max_turns is marked not mergeable; two tasks that share a file are flagged in the overlap matrix, and in --simulate that prediction becomes a real conflict in the trial merge into fanout/integration. --allow-writes lets workers edit; --repo PATH fans out from your own repo and prints cleanup commands instead of deleting your branches.
Two observations from Anthropic's own multi-agent work hold up. The 2025 research-system post found that "most coding tasks involve fewer truly parallelizable tasks than research", and that multi-agent systems used about 15 times the tokens of chat. The 2026 C-compiler post hit the coupled-task wall directly: when every agent needed the same bug fixed, all 16 agents converged on it, and progress only resumed once a reference compiler was used as an oracle to split the work. In Claude Code terms: parallelize along file and module boundaries with an independent check per unit (/batch's design), keep coupled work in one session or a short pipeline, and use teams for exploration and review rather than for co-editing.
Merge Points
What it is. A merge point is where parallel work rejoins and someone has to decide what's true. Claude Code has three kinds: synthesis in a context window (the main conversation reading subagent reports, or a lead reading teammates' final answers); merges in git (branches from worktree sessions, background sessions and /batch units); and handoffs between sessions (a session telling another what landed). Each needs a check, because parallel work that was right in isolation can be wrong together.
Three worktree lanes branch from the default branch. They merge one at a time in dependency order, and the integration suite runs after every merge, not just at the end, so a failure points at one lane. Later lanes rebase onto the updated default branch before they merge. Press replay to couple the cars one at a time, or hover a car; the three lanes are the toy example from the simulator below.
How to run them in Claude Code.
Merge in a sensible order. The cloud field guide's advice: "Split parallel tasks along file boundaries, merge the branches in a sensible order." Shared foundations (schema, config, interfaces) go first; leaf features after.
Check after each merge. Run the integration suite, or have a fresh-context reviewer subagent read the combined diff. A merge that's textually clean can still break behavior.
Let review be the bottleneck on purpose. Agent view's Ready for review group and the row PR labels (yellow while checks are pending or failing, green when they pass, purple when merged) are a review queue. Don't dispatch more lanes than you can review.
Base dependent work correctly. When a later lane builds on an earlier one, use worktree.baseRef: "head" or start it from the earlier branch, rather than the default "fresh" base. When a session that moved into a worktree on a branch runs /fork, the copy is told to base its new branch on yours if its task builds on your work.
Announce what landed. With cross-session messaging, tell the other sessions what landed. The docs' example message has the summary "Schema migration finished" and the text "The new column is tenant_id, and rebasing on main is safe now."
Synthesis is a merge point tooWhen five subagents return findings, the main conversation's summary is a merge. Ask for it explicitly ("deduplicate, rank by severity, and list contradictions between reports"), and give subagents a shared result format so contradictions are visible. For teams, the docs' debate pattern ends with "Update the findings doc with whatever consensus emerges".
Exercise: one lead, a worker per feature
Start in a session that already has a custom verify skill, recorded as in Delivery 4. Worker worktrees branch from the remote default branch by default, so commit that skill and get it onto the remote default branch first, or commit it and set "worktree": {"baseRef": "head"} in your settings so worker worktrees branch from your local HEAD. (1) Shrink the earlier conversation and say what comes next: /compact we are going to build new features and test them with /verify. (2) Pick two or three small, independent features and tell the session it's the lead: it starts one worker per feature, each in its own worktree, and doesn't write feature code itself. (3) Each worker implements its feature, runs the verify skill, and opens a draft PR (or your code-review system's equivalent) with evidence: screenshots, or a recording of the verify run. (4) Watch each worker's evidence before you read its diff, then merge one lane at a time as described above.
Done when two or more PRs are up, one per feature, each with evidence that shows the feature working. Common failure: the lead starts editing files itself, the same trap described under Messaging. Tell it to hand the feature to a worker. A worker that opens a PR without evidence goes back to the verify skill.
Show a reference solution
You are the lead for this round. Don't edit feature code yourself.
Features: (a) "/" focuses the search box, (b) a dark-mode toggle in settings,
(c) CSV export on the orders page.
For each feature, start one subagent in its own worktree (isolation: worktree).
Give each a brief with the feature, the files it may touch, and what done means.
Each worker must: implement only its feature, run our project verify skill,
save screenshots under evidence/<feature>/ on its branch, and open a draft PR
with gh pr create --draft that links the evidence and says what the verify run
covered and what it didn't.
Wait for every worker, then give me one table: feature, PR, verify result, risks.
Expect one worktree and branch per worker under .claude/worktrees/, and a lead context that holds only the briefs and the short reports. Use the skill you recorded, not the bundled /verify: the bundled one "runs only when you invoke it", so a worker can't call it. If you'd rather watch the workers in agent view, dispatch them yourself with one claude --bg --name <feature> "…" per feature; each session moves into its own worktree before editing and opens a draft PR when the task calls for one.
Conflict Resolution
Prevent first. Most conflicts are planning errors. Partition by file ownership: "Two teammates editing the same file leads to overwrites. Break the work so each teammate owns a different set of files." Teams share one checkout, so for them partitioning is the only protection. For worktree lanes, overlapping files don't corrupt anything while they work, but they turn into git conflicts at merge time. Write each lane's expected file footprint into its brief, and serialize lanes that share hot files (lockfiles, route tables, central config, a CHANGELOG.md).
Kinds of conflict.
Textual: two branches change the same lines. Git stops the merge.
Auto-merged: same file, different hunks. Git merges it; usually fine, worth a glance.
Semantic: no textual overlap, but the combination is wrong, for example one lane renames a function another lane's new code calls. Only tests or review catch it.
Overwrite: two agents in one checkout edit one file; the later write wins silently. This is the agent-team failure mode.
Three background sessions finished in their own worktrees. Pick a merge order and whether lanes rebase before merging and whether integration tests run after each merge. The simulator classifies each merge as clean, auto-merged, conflict or semantic break, based on each lane's file and hunk footprint, drawn as bars on each file's line ruler: overlaps that conflict are lit with the merge step where they surface. Toy model: the footprints are made up, the git behavior is simplified.
Resolve deliberately. When a textual conflict appears, resolve it where the context is: in the worktree of the lane being merged, with that lane's session (attach to it, or claude --worktree <name> --resume), because it knows why it made its change. Rebase it onto the updated default branch, resolve, run the tests, and only then merge. For a conflict between two lanes' intents rather than lines, a short dedicated session that reads both diffs and both reports, and proposes one resolution for you to approve, beats letting either lane "win". Afterwards, update the briefs: a conflict you had to resolve by hand is a partitioning lesson.
Exercise: three lanes, one merge
In a sample repo, dispatch three background sessions with claude --bg --name: one adds a config option, one uses that option in a new endpoint, one updates the docs and CHANGELOG.md. Before dispatching, write each lane's expected file footprint in its prompt. When all three finish, merge them yourself in the order you'd choose, running the test suite after each merge, and note every conflict and how you resolved it.
Show a solution
Merge the config lane first (foundation), then the endpoint lane after rebasing it onto the updated default branch (it depends on the option), then docs. The endpoint lane was probably written against a guessed option name; if the config lane chose a different name, the merge is textually clean but tests fail: a semantic conflict. CHANGELOG.md conflicts between the docs lane and any lane that also touched it, which is why hot files should be owned by one lane. Lesson for next time: base the endpoint lane on the config lane's branch (worktree.baseRef: "head" from that branch, or dispatch it after the first merge), and give the changelog to a single owner.
Cross-Agent Protocols
What it is. Agents in Claude Code talk over a handful of channels, each with its own reach and trust rules. Picking the right one is mostly about the boundary you're crossing: inside a session, between your sessions, into another tool, or into another organization.
Channel
Reach
Notes
SendMessage to a subagent
Workers in this session, by agent ID or name
Resumes a finished subagent with its history and cache; doesn't require teams
Team mailbox
Lead and teammates
Plain text plus structured protocol messages (shutdown_request, plan approvals) that stay within the team
Cross-session messaging
Your other sessions on this machine; other machines and cloud sessions via Remote Control
v2.1.224+ (v2.1.234+ on native Windows); ListAgents / /list-agents; plain text only
MCP (claude mcp serve)
Any MCP client that wants Claude Code as a tool
stdio server; "your own client is responsible for implementing user confirmation"
Headless JSON
Scripts, CI, other programs
claude -p --output-format json, --json-schema, or the Agent SDK
A2A
Agents owned by other teams or organizations
Not built into Claude Code; wrap it yourself
Cross-session messaging, precisely. Claude discovers targets with ListAgents and sends with SendMessage; you can name a target with an @-mention (Let @api-worker know the schema migration finished, v2.1.232+). Delivery happens between tool calls in an active turn, or starts a new turn in an idle session. Incoming messages are marked as coming from another session and are constrained: "It can't approve anything", "It can't change configuration", "Commands don't run" (a /compact in a message is plain text), and "Permission prompts still fire". crossSessionInbound sets accept, hold or refuse; with nothing set, Claude Code holds messages for your approval when exactly one side bypasses permission prompts, and drops held messages after dialogExpiry (five minutes by default). Loops are throttled: identical repeats are dropped and at most 50 accepted messages queue. claude --bare sessions don't bind an inbox at all.
Walkthrough: one rename, two sessions
Two sessions build features of one app in separate worktrees. customer-profile works on the profile page and shipping-emails on the order-shipped email, and both read the users table. When the profile session renames a column, you don't switch terminals. You tell it who needs to know, and Claude writes the message.
you · in customer-profiletell shipping-emails we renamed users.name to display_name
tool_use · ListAgents(finds shipping-emails, a live session on this machine)
tool_use · SendMessage (customer-profile → shipping-emails){"to": "shipping-emails", "message": "users.name is now users.display_name (migration 0042, merged to main). Anything that still reads users.name will fail; switch it to users.display_name."}
shipping-emails · incoming› Message from @customer-profile: users.name is now users.display_name (migration… (ctrl+o to expand)
claude · shipping-emailsGood timing: templates/order_shipped.html still reads users.name. Switching it and the mailer query to users.display_name, then rerunning the email snapshot tests.
Illustrative: session names, the migration and the file paths are made up, and tool inputs are abbreviated. The preview line follows the format in the docs.
Three things to notice. The message arrives inline in the other transcript under the sender's name, as a one-line preview you expand with Ctrl+O, and the receiving Claude reads the full text either way. It carries only text: "A message is a piece of text one Claude writes to another, never the sender's conversation history or files." So it must state the facts itself (old name, new name, where the change landed). And the receiver fixes its template under its own permissions, because the message approves nothing. Details: cross-session messaging.
MCP versus A2A. MCP standardizes agent-to-tool calls, where the caller stays in control of each step; A2A standardizes agent-to-agent delegation across ownership boundaries, with discovery through Agent Cards, task lifecycles, streaming and artifacts. Claude Code speaks MCP in both directions. The Claude Code docs index has no A2A page, so to put a Claude Code agent behind an A2A endpoint you'd build a small server around the Agent SDK and map A2A tasks to sessions and results yourself. Reach for that only when the agents have different owners, deployments or trust domains; inside one repository, a subagent or a session message is simpler. MCP servers are in Agents 3.
For each scenario, pick the channel you'd use, then check. The explanations cite the reach and trust rule that decides it.
The same rule on every channelWhether a message comes from a subagent report, a teammate, another session or an MCP client, it is input, not authority. Claude Code enforces this for its own channels; for claude mcp serve and anything you build around the SDK, you must enforce it yourself.
How the inbound default decides per message
When no crossSessionInbound value applies, Claude Code groups sessions into two classes: those that bypass permission prompts and everyone else (in interactive terminal sessions with bypass available, plan mode counts as bypassing; auto, acceptEdits and dontAsk count as prompting). A prompting receiver delivers each message unless the sender identifies itself as bypassing, in which case it holds it for your approval. A bypassing receiver holds every message unless the sender also bypasses. The asymmetry stops an unattended bypass session from becoming a relay that turns another session's words into unprompted actions. In -p sessions there's no dialog, so held messages wait until dialogExpiry (set it to "never" to keep them until the session ends). Requiring approval for cross-machine messages and turning messaging off are separate settings. Source: cross-session-messaging.
Key takeaways
claude --worktree, isolation: worktree and background dispatch give each writer its own checkout; .worktreeinclude brings gitignored files along.
Worktrees branch from the default branch unless worktree.baseRef is "head"; isolation blocks edits and git in the main checkout, not cp.
Choose the parallel shape by who coordinates, whether workers talk, and whether they share files; all of them multiply tokens.
Merge one lane at a time in dependency order with an integration check after each merge; synthesis of reports is a merge point too.
Prevent conflicts by file ownership; resolve them in the lane's own worktree with its own session.
Pick the channel by boundary: SendMessage, team mailbox, cross-session messaging, MCP, headless JSON, A2A. None of them carries approval.
Session wrap-up
The model to keep. Every multi-agent feature in Claude Code is the same engine with a different contract. A subagent is a fresh context with your chosen tools, model and mode that returns one message. A fork is a subagent that inherits everything and shares your cache. A background session is a whole conversation hosted by the supervisor, isolated in a worktree before it edits, reporting to you through agent view. An agent team is several sessions with a mailbox and a task list, coordinated by a lead, experimental and expensive. Worktrees isolate writers, merge points rejoin them, and briefs and result formats are the only thing that crosses between them, so they deserve the same care as code, plus hooks where a clause must hold.
If you need…
Use
Watch out for
a side task out of your context
subagent (agent file or built-in)
misspelled fields, inherited permissive modes
a side task that needs everything you know
/subtask
no input isolation; can't fork again
to try another direction yourself
/branch
the original is only reachable via /resume
independent tasks you check later
claude --bg, agent view
quota ×N; deleting removes worktrees
workers that debate or coordinate
agent team
experimental; overwrites without partitioning; Task tools on 5.x
one big mechanical change
/batch or a dynamic workflow
units must be independent and testable
Connections. The user-side view of subagents and parallel sessions is in Core 2 and Core 4. The SDK's agents option and subagent models are in Agents 2; plugins that ship agents are in Agents 3. Guardrails, evals and observability for multi-agent runs are in Agents 5, and running teams with autonomy at scale is Autonomy 3.
Labs for this session
Lab
Run
What you get
subagents_kit/
python3 agents-4/subagents_kit/validate_agents.py
Four project subagents with a scoped PreToolUse hook, and a validator for the documented frontmatter rules and silent skips
fanout_orchestrator.py
python3 agents-4/fanout_orchestrator.py (--simulate for real worktrees without a model, --real to spend money)
Capped headless runs in worktrees, an overlap matrix, a merge order and a trial merge
delegation_brief.py
python3 agents-4/delegation_brief.py
A brief template, a linter for context leaks and uncheckable done criteria, and a renderer to a prompt string
Run from labs/. All three are offline by default and never use --dangerously-skip-permissions.
What to do next. Convert one delegation you repeat weekly into an agent file with a result format and a SubagentStop gate. Run one week of independent tasks through claude --bg and agent view with the Notification hook installed, and keep a note of every merge conflict you resolve; those notes are your partitioning rules. Then try a read-only agent team on a real PR review and compare its findings and /usage with a single reviewer subagent before deciding where teams belong in your workflow.