In Agents 4 you learned the mechanics: agent files, agent teams, background sessions, delegation briefs and worktrees. This session runs those mechanics as an engineering team. Several Claude Code agents plan, build, review and validate in parallel for hours at a time, inside boundaries the harness enforces, while a human keeps the final say over what ships.
Agent teams fail the way human teams do. Roles blur, two workers edit the same file, a review queue grows without bound, a question never reaches the person who can answer it, and nobody notices the worker that has been stuck for forty minutes. Agents add failure modes of their own: they don't get tired, they rarely say they're unsure, and they'll spend tokens confidently in the wrong direction. Adding agents is easy. Raising throughput without losing control is the engineering problem.
The one-line model for this sessionTeam throughput ≈ min(agent capacity, review capacity, merge capacity) − coordination tax − rework from collisions. Organization and Coordination cut the coordination tax. Parallelism raises agent capacity without creating collisions. Routing spends tokens where they pay off. Supervision bounds rework and risk and keeps a human in charge.
After this session you will be able to:
Define planner, builder, reviewer and validator roles as .claude/agents/*.md files whose access is enforced by tool lists, deny rules, hooks and worktrees, not by persona prompts.
Pick the right coordination mechanism (subagents, agent teams, background sessions, dynamic workflows, /batch) and wire shared goals, task dependencies and two-way handoffs through files and hooks.
Run parallel work in worktrees, cloud sessions and agent view, and plan the merge points that actually cap throughput.
Route each role to a model and effort level (including opusplan and the advisor tool) by capability, cost, speed and risk.
Supervise a running team: read state from claude agents --json, detect collisions early, intervene with the lightest effective action, and keep merges and irreversible actions in human hands.
Version stampEverything here is as of 2026-10-24 (Claude Code v2.1.310). Agent teams are experimental and disabled by default, agent view is a research preview, and the advisor tool is experimental. Commands and defaults in these areas change often, so features that need a minimum version are marked "requires v2.1.xxx+". The running example, a four-agent feature pipeline, is introduced in Organization and reused in every later topic.
In Claude Code a role is a file. .claude/agents/reviewer.md holds a role's job description (the Markdown body becomes its system prompt) and its terms of employment (frontmatter: tools, disallowedTools, model, effort, isolation, memory, hooks). The persona text says what a role should do. The frontmatter, your settings and your hooks decide what it can do. A role the harness doesn't enforce is only a costume.
Hover or tab to a role for its tools, model and artifact; the human merge edge is lit to start. Every arrow carries an artifact: a plan file, a branch, a verdict, an evidence block. The lead routes work and never writes product code. The reviewer and validator can't edit. Only the human merges into main. You'll build this exact pipeline in the worked example below.
Planner, Builder, Reviewer and Validator Roles
What it is. Four roles, each defined by the artifact it produces and the authority it holds. The planner turns a request into a written plan: steps, file ownership, acceptance checks. The builder changes code on its own branch. The reviewer reads the diff against the plan with fresh eyes and returns a verdict. The validator runs the checks and returns evidence. You can add a researcher, but the built-in Explore agent already covers read-only codebase search, so most teams don't need a fifth role.
How it works in Claude Code. Each role is a subagent file in .claude/agents/ (project, committed) or ~/.claude/agents/ (personal). Only name and description are required. Claude delegates when a task matches the description, or you invoke a role explicitly with @agent-reviewer or @"reviewer (agent)". Every non-fork subagent starts from a fresh context: its own system prompt (the body), the delegation message the caller writes, the CLAUDE.md hierarchy, a git status snapshot and any skills listed in skills. It doesn't see your conversation, the files you've already read or your auto memory. It returns a summary, not its transcript. /agents no longer opens a wizard (it prints a reminder), so create the files yourself or ask Claude to.
Read, Grep, Glob, Write (writes limited to docs/plans/ by a hook)
opus · high
Plan quality decides the outcome; no Bash means Glob and Grep come back and nothing executes
Builder
Commits on its own branch
Read, Edit, Write, Bash; isolation: worktree
opus · medium here; sonnet for routine code
This feature touches login security, so Opus; the worktree keeps its edits out of your checkout
Reviewer
VERDICT: PASS|FAIL plus findings tied to lines
Read, Bash (Bash for git diff and search); disallowedTools: Edit, Write, NotebookEdit
opus · high; no memory (it would re-enable Write and Edit)
Never saw the build conversation, so it can't share the builder's rationalizations
Validator
EVIDENCE: the commands it ran and their results
Read, Bash; no edit tools
sonnet · medium
Running tests and reading output is routine; evidence beats assertion
Why it matters. Splitting roles gives you separation of duties. The agent that wrote a change is the worst judge of it, because its context is full of the reasons it made each choice. A fresh reviewer has only the diff and the plan. The split also controls cost and context: verbose test output stays in the validator's window, and only a short evidence block returns to the lead. Anthropic's own guidance is to keep the writer and the judge separate, "ask Claude for evidence", and remember that "A reviewer that's asked to find problems will always find something" (best practices). So give the reviewer pass/fail criteria, and cap the build/review loop.
The Claude Code team's own code-review practice, from its blog post How the Claude Code team does code review: "After three rounds, the reviewer asks the author to step back".
How to apply it.
Name each role's output artifact and where it lands before you write any persona text. An artifact is reviewable; a vibe isn't.
Write routing descriptions, not biographies: "Use after the builder reports a commit. Reviews the diff against the plan; never edits." Claude matches on description.
Give review roles an explicit contract: what counts as a blocking finding, the verdict line format, and "report gaps that affect correctness and skip style".
Keep the role count small. Four roles plus a lead is already five context windows per feature.
Pitfalls
The reviewer that fixes things. If the reviewer can edit, it "fixes" what it found, and nobody reviews the fix. Remove the edit tools, and don't give it memory: persistent memory automatically enables Read, Write and Edit so the agent can manage its memory files (sub-agents).
The validator that makes tests pass. A validator with Edit will eventually edit the test. Validators report and never repair.
The cheap builder. The official cost guidance is to "move down to Sonnet or Haiku for lookups, not for writing code" (What a task costs on Opus 5.5). Sonnet is a fine builder for most code; Haiku isn't. Save money on the validator and on searches, not on the role that writes the diff.
Assuming plan approval is a checkpoint. In an agent team, a teammate's plan approval request is granted automatically by the lead session "without the lead reviewing it". Review the plan yourself before you spawn builders.
Assign each task to a role, then press Check. Each answer comes with the reason the boundary sits where it does.
The rule behind every answer: a role that produces an artifact must not be the role that approves it, and any work that needs a judgment call about risk goes up to the lead or the human.
Bounded Access
What it is.Bounded access means each role can reach only the tools, paths and commands its job needs, and the harness, not the prompt, enforces the limit. Claude Code gives you five layers, and you'll usually combine at least three:
Tool availability: the subagent's tools allowlist and disallowedTools denylist. Claude Code applies disallowedTools first, then resolves tools against what remains. A tool that isn't in the set can't be called at all. tools: mcp__github__* grants one MCP server, and disallowedTools: mcp__* withholds every MCP tool.
Permission rules in settings (permissions.deny, ask, allow). They apply to the main conversation and to every subagent. Rules are evaluated deny → ask → allow, and "if a tool is denied at any level, no other level can allow it" (permissions).
Permission mode, which subagents usually inherit (details in the deep dive below).
Hooks. Settings-level PreToolUse hooks fire for subagent tool calls too, and their input carries agent_type (the subagent's name), so one script can enforce per-role rules. Frontmatter hooks run only while that agent is active, and for a project agent they need workspace trust on the folder that holds the file.
Isolation: isolation: worktree for file edits, and the sandbox for shell commands. The sandbox is off by default.
Why it matters. A parallel team multiplies both the useful actions and the mistakes. A role with Bash and no other limits can do anything your user account can do, in every session at once. Bounding access turns "the builder pushed to main" from a likely incident into one that can't happen.
How to apply it. Start from the artifact. The reviewer produces text, so it gets read tools plus Bash for git diff, and no edit tools. The planner produces one file, so it gets Write plus a hook that limits writes to docs/plans/. Put irreversible commands in settings deny rules so they bind every role. For a lead that runs as the main thread with claude --agent feature-lead, tools: Agent(planner, builder, reviewer, validator), SendMessage, Read, Bash limits which subagents it can spawn. That parenthesized allowlist applies only to an agent running as the main thread; inside an ordinary subagent definition the type list is ignored. List SendMessage explicitly: an explicit tools list on the main thread gives it exactly those tools, and without SendMessage the lead can delegate but can't resume a subagent it already ran.
.claude/settings.json (excerpt). It binds every role, the main session included.
Read and Edit deny rules also cover the Bash file commands Claude Code recognizes (cat, head, tail, sed, and tee from v2.1.269) and redirect targets, so the two Read rules above also stop cat .env. They don't cover scripts that open files themselves (a Python or Node one-liner) or commands that never name the file (grep -r). For OS-level enforcement, use the sandbox (permissions).
Pitfalls that look like protection
disallowedTools: Bash(git push *) removes all of Bash, not just pushes. To keep Bash and block one command, use a permissions.deny rule.
A Bash deny rule matches command text, not the program.Bash(git push *) doesn't match git -C . push, and the narrower Bash(git push * main) used on this page also misses git push -f origin main, git push origin HEAD:main and +main refspecs. Back it with server-side branch protection and, for shell writes, the sandbox.
Bash in a "read-only" role is a write tool.sed -i and > redirects edit files without calling the Edit tool, so a hook matched on Edit|Write never sees them. A settings Edit(...) deny rule does catch sed -i, tee and redirect targets, but not scripts (Python, Node) or commands that don't name the file, and it binds every role. Use deny rules for paths no agent should write, such as Edit(./.env) or Edit(./.claude/**). Per-role limits on shell writes need a Bash-aware hook or the sandbox.
Unknown frontmatter fields are ignored silently. A typo such as disallowed-tools in a subagent file means no restriction at all. That's the skills spelling; subagent files use camelCase disallowedTools. Run with --debug; v2.1.296+ logs fields it "does not recognize or apply".
Plugin subagents ignore hooks, mcpServers and permissionMode "for security reasons". Copy the file into .claude/agents/ if you need them.
Pick a role and the main session's permission mode, toggle the settings layers, and see how Claude Code would decide each probe action. The logic follows the documented order: tool availability first, then hooks, then deny → ask → allow rules, then the mode. It's a simplified model, not the full rule engine.
Each probe is a track crossing the layers in the documented order; a block mark shows the layer that decided it, a ? a prompt, and an arrow a call that runs. Watch two things. First, frontmatter permissionMode: plan stops mattering as soon as the main session is in auto mode. Second, pick the reviewer under acceptEdits or auto: its sed -i write gets through every layer shown here unless you add a Bash-aware hook. A settings Edit(./README.md) deny rule would also catch it, but for every role at once. The sandbox wouldn't stop it, because sandboxed writes to the working directory are allowed by default.
How Claude Code computes a subagent's effective tool set
Start pool. Omit tools and the subagent inherits every tool available to subagents. Several tools are always removed: AskUserQuestion, EndConversation, EnterPlanMode, ExitPlanMode (unless permissionMode: plan), ScheduleWakeup, WaitForMcpServers, Workflow, and Agent once the nesting depth limit is reached (three layers below the main conversation by default, CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH).
Background filter. Subagents run in the background by default (v2.1.198+). A background subagent keeps 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 among the built-ins. So the same definition can resolve differently in the foreground and the background.
disallowedTools, then tools. A tool listed in both is removed. If nothing in tools resolves, for example because every entry is misspelled, Claude Code refuses to launch with "Agent would be spawned with zero tools".
Glob and Grep. On macOS, Linux and WSL these two are absent by default, and search runs through Bash (find and grep backed by embedded bfs and ugrep). Listing Glob or Grep in toolswithoutBash brings them back for that subagent. That's why the planner above has no Bash: its searches stay inside tools you can reason about.
Injected tools. In auto mode (v2.1.271+), a local non-fork subagent also gets SubagentHandback to deliver its report, "even if you leave it out of tools or list it in disallowedTools". In-process teammates get SendMessage, plus the Task tools where the session has them.
Forks skip both filters: they have the parent's exact system prompt and tools, which is also why they share its prompt cache.
Why permissionMode in frontmatter rarely does what you expect
The main conversation's mode decides whether a subagent's permissionMode is used at all (sub-agents · Permission modes):
Main in auto, acceptEdits or bypassPermissions: the subagent runs in the main mode, and its permissionMode is ignored. In auto, the classifier evaluates the subagent's calls with the main conversation's rules, and it reviews the subagent's work and final report before that report is delivered.
Main in default (Manual), dontAsk or plan: the subagent's own value applies, except that a subagent never escalates to bypassPermissions (v2.1.267+), and auto falls back when auto mode isn't available to it.
Since v2.1.283, auto is the built-in starting mode for interactive terminal and VS Code sessions, so in practice a planner's permissionMode: plan is usually ignored. Don't rely on it for read-only behavior. Rely on the tool list. Teammates in an agent team take the lead's mode at spawn (except dontAsk, which they don't inherit), and you can't set per-teammate modes at spawn time.
Worked Example: A Four-Agent Feature Pipeline
Here is the whole team as files you can commit. A lead runs as the main thread (claude --agent feature-lead) and drives four role subagents through plan → build → review → validate, with at most two build/review rounds, and then hands you a branch plus evidence. Two hooks make the roles real. guard-ownership.sh enforces an ownership map on every edit. require-verdict.sh sends a reviewer or validator report without a verdict line back (once at the end of a run; at each handback in auto mode, where maxTurns bounds it), and the lead treats a report that still lacks one as FAIL. A settings deny list keeps main out of reach.
---
name: planner
description: Turns a feature request into a written plan with file ownership and acceptance checks. Use first for any multi-file feature. Never edits source code.
tools: Read, Grep, Glob, Write
model: opus
effort: high
color: purple
---
You are the planner. Read the request and the code it touches, then write
ONE file: docs/plans/<slug>.md with these sections:
## Goal one paragraph, user-visible outcome
## Steps numbered, each small enough for one commit
## Ownership path prefixes the builder may edit; everything else is read-only
## Acceptance checks a validator can run (commands + expected result)
## Risks what could break, and what to do if it does
## Open questions anything you could not decide from the code
## Decisions empty at first; the lead has you append each answer to an Open question
Don't guess at product decisions: list them under Open questions.
Report back with the plan path and the open questions, nothing else.
---
name: builder
description: Implements one approved plan from docs/plans/ on its own branch, commits, and reports the commit. Use after the plan is approved, or to fix findings a reviewer returned.
tools: Read, Edit, Write, Bash
model: opus
effort: medium
isolation: worktree
maxTurns: 80
color: blue
---
You implement exactly the plan you are given. Edit only paths listed under
"Ownership". If the plan is wrong or a needed change is outside your paths,
STOP and report it as BLOCKED with the reason; don't work around it.
Before reporting: run the plan's Acceptance commands yourself, commit with
a message that names the plan, and return:
STATUS: DONE | BLOCKED
BRANCH: <branch> COMMIT: <sha> WORKTREE: <path>
NOTES: decisions you made that the reviewer should check
---
name: reviewer
description: Reviews a builder's commit against its plan with fresh context. Use after every builder report. Read-only; never edits.
tools: Read, Bash
disallowedTools: Edit, Write, NotebookEdit # redundant with tools; keeps a later edit to tools honest
model: opus
effort: high
maxTurns: 40
color: orange
---
Review `git diff <base>...<branch>` against the plan file you are given.
Blocking findings are ONLY: behavior that contradicts the plan's Goal or
Acceptance, a correctness or security bug, or an edit outside Ownership.
Style preferences are never blocking.
Put this on a line of its own, choosing one value:
VERDICT: PASS | FAIL | BLOCKED
Then list findings as `path:line: problem -> suggested fix`.
---
name: validator
description: Runs a plan's acceptance checks on a branch and reports evidence. Use after the reviewer passes. Never edits files or tests.
tools: Read, Bash
model: sonnet
effort: medium
maxTurns: 30
color: green
---
Check out nothing and change nothing. Run each command under "Acceptance"
in the plan, in the worktree path you are given. Never edit a test or update
snapshots to make a check pass.
Put this on a line of its own, choosing one value:
VERDICT: PASS | FAIL | BLOCKED
Then an EVIDENCE block: each command, its exit code, and the 3-5 output
lines that prove the result.
---
name: feature-lead
description: Runs the plan, build, review, validate pipeline for one feature. Start it with claude --agent feature-lead.
tools: Agent(planner, builder, reviewer, validator), SendMessage, Read, Bash
model: sonnet
effort: medium
---
You coordinate; you never write product code.
1. Delegate to planner. Show me the plan path and its Open questions,
and wait for my go-ahead. Then commit the plan file, so the builder's
worktree (branched from HEAD) contains it.
2. Delegate to builder with the plan path. If BLOCKED, bring the reason to me.
When I decide, have the planner append my answer under Decisions, commit
the plan, and resume the same builder with SendMessage.
3. Delegate to reviewer with the plan path, base branch and builder branch.
On FAIL, send the findings to builder and review again. Maximum 2 rounds,
then stop and summarize the disagreement for me.
4. On PASS, delegate to validator with the plan and the worktree path.
Treat any reviewer or validator report without a VERDICT line as FAIL.
5. Finish with: branch, commit, verdicts, evidence, open risks.
You never merge, never push to main, and never resolve an Open question yourself.
#!/usr/bin/env bash
# PreToolUse on Edit|Write|NotebookEdit. Defense in depth: deny rules, worktrees
# and the sandbox are the boundary; this catches role drift at the first edit.
set -euo pipefail
input=$(cat)
agent=$(jq -r '.agent_type // empty' <<<"$input")
file=$(jq -r '.tool_input.file_path // .tool_input.notebook_path // empty' <<<"$input")
cwd=$(jq -r '.cwd' <<<"$input") # follows Claude, including any cd
map="${CLAUDE_PROJECT_DIR}/.claude/ownership.json"
[[ -z "$agent" || -z "$file" ]] && exit 0 # not a governed role
jq -e --arg a "$agent" 'has($a)' "$map" >/dev/null || exit 0
root=$(git -C "$cwd" rev-parse --show-toplevel 2>/dev/null || echo "$cwd") # worktree or repo root
rel="${file#"$root"/}"
if jq -e --arg a "$agent" --arg p "$rel" \
'.[$a] | any(. as $pre | $p | startswith($pre))' "$map" >/dev/null; then
exit 0
fi
jq -n --arg r "$agent may not edit $rel (see .claude/ownership.json). Report the change you need to the lead instead." \
'{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: $r}}'
#!/usr/bin/env bash
# Enforces the upward half of the handoff contract for reviewer and validator.
# Auto mode (v2.1.271+): the report arrives as SubagentHandback tool_input.message (PreToolUse).
# SubagentStop still fires afterwards, but its last_assistant_message is only closing text: skip it.
# Other modes: the report is the subagent's final text (SubagentStop last_assistant_message).
input=$(cat)
case "$(jq -r '.agent_type // empty' <<<"$input")" in reviewer|validator) ;; *) exit 0 ;; esac
if [[ "$(jq -r '.hook_event_name' <<<"$input")" == "PreToolUse" ]]; then
report=$(jq -r '.tool_input.message // ""' <<<"$input")
else
[[ "$(jq -r '.stop_hook_active' <<<"$input")" == "true" ]] && exit 0 # never loop
[[ "$(jq -r '.permission_mode // ""' <<<"$input")" == "auto" ]] && exit 0 # checked at handback
report=$(jq -r '.last_assistant_message // ""' <<<"$input")
fi
grep -Eq '^VERDICT: (PASS|FAIL|BLOCKED)$' <<<"$report" && exit 0
echo "Report contract: include a line 'VERDICT: PASS|FAIL|BLOCKED' and list the evidence you used." >&2
exit 2
Run it. Make the scripts executable (chmod +x .claude/hooks/*.sh), add .claude/worktrees/ to .gitignore, and accept the workspace trust dialog once by running claude in the repository. Then start the lead:
# interactive: you answer the plan checkpoint yourself
claude --agent feature-lead "Add per-IP rate limiting to POST /api/login as described in docs/specs/rate-limit.md"
# headless variant for CI or a scripted run: -p starts in Manual mode (v2.1.302+), so grant exactly what the roles need
claude -p --agent feature-lead --permission-mode acceptEdits \
--allowedTools "Bash(git commit *)" "Bash(npm test *)" \
--max-turns 60 --max-budget-usd 8 --output-format json \
"Plan only, then stop: rate limiting for POST /api/login per docs/specs/rate-limit.md"
Two details in these files are easy to miss. First, "worktree": {"baseRef": "head"}: by default a subagent's worktree branches from the remote default branch, so it wouldn't contain the plan file the planner just wrote. With "head" it branches from your local HEAD, which is why the lead commits the plan before delegating. Uncommitted files never reach a worktree. Second, the builder reports its WORKTREE path because its worktree outlives it (a worktree with unpushed commits stays on disk), and that's where the validator runs the checks.
In the headless variant, nobody answers the plan checkpoint, so the prompt asks for the plan only. Also note that -p runs never clean up the worktrees they create. Remove them with git worktree remove.
The lead holds the loop, the subagents hold the work, and the human holds two gates: the plan and the merge. Step through: each station prints its artifact, and the failed first review drops the feature onto the return belt back to the builder. The commits, verdicts and log lines are illustrative.
The same team as an agent team
The definitions double as teammate roles. With agent teams enabled, ask the lead in an interactive session: "Create an agent team. Spawn teammates using the planner, builder, reviewer and validator agent types. Name them planner, builder, reviewer, validator. Make tasks with dependencies: plan → build → review → validate." Four things change, and each one matters:
No worktree. A teammate applies the definition's tools, model and body (plus disallowedTools and effort in-process), but not isolation. All teammates edit the lead's working directory, so the ownership hook goes from nice-to-have to essential.
No preloaded skills. A teammate loads skills from your project and user settings; the definition's skills field isn't applied.
The task list needs the Task tools. On Opus 5.5, Sonnet 5.5 and other current models, TaskCreate and friends are off in an interactive session unless you opt in: set CLAUDE_CODE_ENABLE_TODO_TOOLS=1, or name a Task tool in --allowedTools or --tools. In-process teammates follow the lead's session. A split-pane teammate is its own process: it inherits your --tools list and deny rules (v2.1.309+), not --allowedTools or a CLAUDE_CODE_ENABLE_TODO_TOOLS you exported in your shell, so pass the variable with claude --settings '{"env":{"CLAUDE_CODE_ENABLE_TODO_TOOLS":"1"}}' or name the tools in --tools; otherwise its own model's default decides. Without them, teammates coordinate by messages only and the TaskCompleted gate never fires.
Permissions come from the lead. Teammates start in the lead's mode, and their prompts surface in the lead's terminal for you to answer.
Different gates.require-verdict.sh hooks SubagentStop and the SubagentHandback tool, which belong to subagents. For teammates, gate reports with a TeammateIdle or TaskCompleted hook instead.
Be honest about what the team buys here: plan → build → review → validate is a strict sequence, and sequential work is where the docs say a single session or subagents do better. The team version pays off once the graph has real width, for example two builders on separate layers, or a reviewer and a validator working in parallel on the previous round while the builder starts the next task.
Choose the roles, then each role's model, effort and isolation, and whether the team runs as subagents or as an agent team. The composer writes the frontmatter and flags combinations the docs warn against. The token estimate is a toy model with illustrative numbers.
Try switching to "agent team" with two builders: the worktree warning appears because teammates don't get isolation. Then put the builder on Haiku and read the routing warning.
Exercise: install the pipeline in a scratch repository
Copy the five agent files, settings.json, ownership.json and both hook scripts into a throwaway repository that has a test suite. Run the interactive command against a small feature. Then (1) ask the builder, through the lead, to also edit README.md, and (2) tell the reviewer, in its delegation prompt, to "skip the verdict line this time". Record what each hook did.
Show what to expect
(1) The README edit is denied by guard-ownership.sh with the reason "builder may not edit README.md …". The builder should report BLOCKED, per its prompt, rather than work around the denial. If it tries echo … >> README.md through Bash instead, the guard can't see it, because it only watches Edit|Write|NotebookEdit. That's the gap a Bash-aware hook, the sandbox, or an Edit(./README.md) deny rule for that path closes.
(2) The reviewer's handback (auto mode) or final text (other modes) fails the regex, and the hook exits 2. The reviewer gets the contract message and usually re-sends its report with a verdict line. In Manual, acceptEdits and plan modes this is a one-time nudge: on the second stop, stop_hook_active is true and the script lets the report through whatever it says, which is why the lead's prompt treats a missing VERDICT as FAIL. A hard gate needs its own counter or state file. In auto mode it's the PreToolUse hook on SubagentHandback that refuses the report; the SubagentStop branch exits 0 in auto mode, because SubagentStop still fires after a handback with only the subagent's closing text in last_assistant_message. Check the debug log (claude --debug) to see which one fired. If neither fired, check that the scripts are executable: a hook that can't start is a non-blocking error.
Key takeaways
A role is a .claude/agents/<role>.md file. Define it by the artifact it produces and the authority it holds, not by a persona.
Separate writing from judging: the reviewer and validator get no edit tools, run in fresh contexts, and must return a verdict line plus evidence.
Enforce access in layers: tool lists, settings deny rules, PreToolUse hooks keyed on agent_type, worktrees and the sandbox. permissionMode frontmatter is ignored when the main session runs in auto, acceptEdits or bypassPermissions.
Bash is the hole in most role designs, and a Bash deny rule matches text, not programs. Back irreversible limits with branch protection.
The same definitions work as agent-team teammates, minus isolation and skills. On current models the shared task list needs the Task tools turned on (CLAUDE_CODE_ENABLE_TODO_TOOLS=1), and a strictly sequential pipeline gains little from a team.
Coordination
Coordination is about who holds the plan and where shared state lives. With subagents, the caller holds the plan and the state lives in its context window. In an agent team, the lead holds it and the state lives in a shared task list and mailboxes on disk. In a dynamic workflow, a script holds it. Whatever the mechanism, anything that every agent must know (the goal, the definition of done, the dependencies, the open questions) has to live in a file or a message, because no agent inherits another agent's memory.
Press send work to play the message traffic; the peer messages that only a team has carry the highlight. Left: subagents report only to their caller, and the caller is the only integration point. Right: teammates claim work from a shared task list and message each other directly, while the lead creates tasks and synthesizes. The right shape buys peer communication and pays for it with a full context window per teammate.
Agent Teams
What it is. An agent team is a set of coordinated Claude Code sessions. One session is the team lead. It spawns teammates, which are separate, full Claude Code instances, assigns work through a shared task list, and synthesizes results. Teammates message each other, and you, directly. The feature is "experimental and disabled by default" (agent teams).
Formation. You describe the task and the teammates in plain language. Claude launches a teammate whenever it calls the Agent tool with a name while teams are enabled (unless the call is a fork or passes isolation on the call itself), and it doesn't ask you to confirm. Claude also names ordinary subagents on its own so it can message them later. So with teams enabled, teams can form when you didn't ask for one, and a definition's isolation: worktree doesn't prevent it. If you want subagents back, set the variable to "0"; Claude Code rereads it on the next spawn.
Interactive only. Spawning teammates needs an interactive session. Under -p and in the Agent SDK, a named subagent runs as an ordinary subagent even with teams enabled.
Mechanics recap. Where the team config, mailboxes and task list live on disk, the in-process panel keys, and the split-pane display modes are covered in Agents 4 · Agent Teams. Two facts matter at scale: the task list under ~/.claude/tasks/{team-name}/ survives the session (the config doesn't), and split panes need tmux or iTerm2, not VS Code's terminal, Windows Terminal or Ghostty.
Models and effort. A teammate's model comes from the first of: the model your spawn prompt names, the definition's model (inherit = the lead's), CLAUDE_CODE_SUBAGENT_MODEL (if not inherit), the lead's current model. Effort follows the lead's unless an in-process teammate's definition sets effort. A teammate's model and fast mode are fixed at spawn. teammateDefaultModel was removed in v2.1.234.
Permissions. Teammates start in the lead's permission mode (except dontAsk). An in-process teammate runs under the lead's live allow and deny rules; a split-pane teammate starts with the lead's command-line deny rules and --tools list (v2.1.309+) but not --allowedTools, so put pre-approvals in --settings under permissions.allow. Their prompts appear in the lead session for you to answer. A message from another agent is labeled as coming from another Claude session: "A teammate can't approve a permission prompt or supply consent on your behalf." In auto mode, the classifier reviews every inter-agent message before delivery.
Why it matters. Teams are the only built-in mechanism in which workers talk to each other without routing everything through one context. That pays off for research and review, for competing debugging hypotheses, and for cross-layer features in which each teammate owns a layer. It doesn't pay off for sequential work, same-file edits or work with many dependencies, where "a single session or subagents are more effective".
How to apply it. Start with research or review tasks before parallel implementation. Use 3–5 teammates with 5–6 tasks each, and remember that "three focused teammates often outperform five scattered ones". Name the teammates in your spawn instruction so you can refer to them later. Pre-approve common safe commands before spawning, because every teammate's permission prompts land in your terminal. Shut teammates down when their work is done ("Ask the researcher teammate to shut down"), because each one keeps consuming tokens until it exits.
Limitations to design around
No resume./resume and /rewind don't bring back in-process teammates. After a resume, the lead may message teammates that no longer exist; tell it to spawn new ones.
One team per session, no nested teams, fixed lead. Teammates can't spawn teammates, and you can't promote a teammate to lead.
Task status can lag. A teammate may fail to mark its task completed, which blocks every dependent task. Check whether the work is done, then update the status or nudge the teammate.
The lead does the work itself. Sometimes the lead starts implementing instead of waiting. The documented fix is to tell it: "Wait for your teammates to complete their tasks before proceeding".
No shared task list on current models without opt-in. In interactive sessions the Task tools are on by default only on Opus 4.7, Sonnet 4.6, Haiku 4.5 and earlier (the default set as of v2.1.268). On Opus 5.5 and Sonnet 5.5, set CLAUDE_CODE_ENABLE_TODO_TOOLS=1 (v2.1.233+) or name a Task tool in --allowedTools or --tools, or teammates coordinate by messages alone. Background and cloud sessions get the tools on every model (task tool availability).
Mechanism
Who holds the plan
Where results live
Scale
Status (Oct 2026)
Subagents
Claude, turn by turn
Caller's context window
A few per turn; 20 concurrent max (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS)
GA
Agent team
The lead, turn by turn
Shared task list + mailboxes
A handful of long-running peers
Experimental
Background sessions (agent view)
You
Each session's branch / PR
As many as your rate limits allow
Research preview
Dynamic workflow
A script
Script variables
Dozens to hundreds; 16 concurrent, 1,000 per run
v2.1.154+
/batch
Claude's approved plan
One worktree and change per unit
5–30 independent units
Bundled skill
Answer the questions about the job. The recommender scores each mechanism against documented capabilities and limits (for example, "teams never run under -p") and explains the score.
The plane is conceptual, not measured: across, how independent the units are; up, how much the workers must talk. The hard constraints come first (headless, survives a closed laptop, mid-run input) and grey whole territories out with the reason. Scoring only ranks what's left, and the pin lands in the best open territory. Notice how often "single session" wins when units overlap.
Inside a team: claims, mailboxes and why "sent" means written
The task list is a directory, not a server. Claiming a task takes a file lock, which is how two teammates racing for the same pending task don't both win. A pending task with unresolved dependencies can't be claimed. When a teammate completes a task that others depend on, Claude Code unblocks the dependents automatically.
Mailboxes are JSON files, one per agent. Claude Code validates every entry when it reads a mailbox: malformed entries are reported as errors and removed, and valid ones are still delivered. A message, whether plain text or a structured protocol message such as a plan approval or shutdown request, counts as sent only when the write to the recipient's file succeeds. A full disk or an unwritable directory surfaces as an error to the sender instead of a silently lost message.
Idle notifications are push, not poll: when a teammate stops, it notifies the lead and includes its final answer. A teammate whose turn ended on an API error notifies the lead with the error text. A message also wakes a teammate that's waiting to retry a failed API request, so it retries immediately.
The lifecycle split matters for audits. config.json disappears at session end, but the task list survives. To reconstruct what a team did after the fact, read ~/.claude/tasks/{team-name}/ and the transcripts, not the team config.
Shared Goals
What it is. A shared goal is the outcome and definition of done that every agent works toward, written where every agent can read it. Agents don't share a mind. Each one knows only what was loaded into its own context, so "shared" has to mean "delivered to each of them".
How it works in Claude Code. Each kind of agent starts with a different slice of context, and that decides where the goal must live:
A subagent gets its own system prompt, the delegation message, the CLAUDE.md hierarchy, git status and its preloaded skills. It doesn't get your conversation or your auto memory. "The only content you pass from parent to subagent is the Agent tool's prompt string" (SDK subagents).
A teammate loads CLAUDE.md, MCP servers and skills like any session, plus the spawn prompt. "The lead's conversation history does not carry over."
A background session is a full session in its directory, so it reads that checkout's CLAUDE.md and your user settings.
A cloud session that clones from GitHub reads only what's committed and pushed (CLAUDE.md, rules, skills, agents, the project .claude/settings.json) plus server-managed settings. Your ~/.claude stays on your laptop.
So the durable goal goes in committed files: a spec or plan with a Goal and an Acceptance section, and a task file. Each delegation or spawn prompt then carries a pointer to those files plus the task-specific slice. For the lead, /goal <condition> (v2.1.139+) keeps it working across turns until a completion condition holds, which stops a lead that declares victory early.
Why it matters. Goals that live only in a conversation are lost twice: they never reach the other agents, and they can be summarized away when the lead's context compacts. Anthropic's Opus 5.5 guidance is to "keep a checklist in TASKS.md", because a list in a file survives compaction (Getting the most out of Opus 5.5).
How to apply it.
Spawn a builder teammate using the builder agent type, named api-builder, with this prompt:
"Goal: per-IP rate limiting on POST /api/login (docs/plans/rate-limit.md, section Goal).
You own: src/api/login/, src/middleware/ratelimit/, tests/api/login/.
Done when: every command under Acceptance in the plan passes, and you've committed.
Read-only for you: everything else. If a change is needed there, message the lead.
Stop and ask before anything destructive or any change to the public API."
One definition of done for the whole team, in the plan file, so the builder's "tests pass" and the product's "users can't brute-force logins" can't drift apart.
Keep spawn prompts focused. Everything in a spawn prompt "adds to their context from the start" (costs), so point to files rather than pasting them.
Put team-wide conventions (branch naming, commit format, the stop-and-ask rule) in the project CLAUDE.md, which every agent loads.
Pitfalls
"As we discussed" in a spawn prompt. The teammate wasn't there.
A plan in your working tree but not committed or pushed. Cloud sessions clone the remote, and fresh worktrees branch from the remote default branch.
Local optimization: a validator told only "make the suite green" will find the cheapest way to make it green. Give every role the product goal, not just its own step.
Every agent kind is a column and every context source a row; hover a dot for its note, and pick a kind to highlight its column. Each dot follows the sub-agents, agent-teams, agent-view and cloud docs. "Not stated" means the docs don't say, so don't depend on it either way.
The only items that reach every kind of agent are the prompt you write and what's committed to the repository. That's where shared goals belong.
Task Dependencies
What it is. A task graph: work items with "blocked by" edges. The longest chain through it, the critical path, sets the minimum wall-clock time no matter how many agents you add. Good decomposition shortens the critical path. Adding agents only fills the slack beside it.
How it works in Claude Code. In an agent team the shared task list is the graph. Tasks are pending, in progress or completed. A pending task with unresolved dependencies can't be claimed. When its dependencies complete, Claude Code unblocks it without any action from you. The lead can assign tasks, or a teammate that finishes picks up "the next unassigned, unblocked task on its own". Two hooks let you gate the graph deterministically (hooks):
TaskCreated: exit 2 deletes the task and returns your stderr to Claude as the tool error. Use it to enforce naming or require an owner and a done-when line.
TaskCompleted: exit 2 keeps the task open and feeds stderr back. It fires both when an agent marks a task completed and when a teammate ends its turn with tasks in progress. Neither hook supports matchers, and neither fires in a session without the Task tools.
#!/usr/bin/env bash
# .claude/hooks/task-done-gate.sh, registered under "TaskCompleted" (no matcher).
# A task may close only if the tests for the area it names pass.
input=$(cat)
subject=$(jq -r '.task_subject' <<<"$input")
area=$(grep -Eo '^\[(api|web|db)\]' <<<"$subject" | tr -d '[]')
[[ -z "$area" ]] && { echo "Task subjects must start with [api], [web] or [db]." >&2; exit 2; }
if ! npm test --silent -- "tests/$area" >/tmp/task-gate.log 2>&1; then
echo "Tests in tests/$area fail; fix them before completing '$subject'. Tail:" >&2
tail -n 15 /tmp/task-gate.log >&2
exit 2
fi
exit 0
Outside a team, dependencies live wherever the plan lives. A lead running subagents encodes the order in its prompt (as feature-lead.md does). /batch requires its 5–30 units to be independent. A dynamic workflow encodes the graph in its script. In every case, the cheapest dependency to remove is the one between producer and consumer of an interface: do a contract-first task that fixes the API shape or schema, and the two sides can then run in parallel against it.
Why it matters. Most "the team is slow" problems are dependency problems: one giant task everyone waits on, a stale in progress status blocking three teammates, or two "independent" tasks that turn out to share a file. Anthropic's C-compiler experiment with 16 parallel agents hit exactly this: when every agent needed the same bug fixed, parallelism collapsed until an oracle split the work again (Building a C compiler with a team of parallel Claudes).
How to apply it. Size tasks as "self-contained units that produce a clear deliverable, such as a function, a test file, or a review", 5–6 per teammate. Ask the lead to split work if it creates too few tasks. Name the critical path in the plan so the strongest model and the earliest review go there.
Seven tasks for a login-rate-limit feature (durations are illustrative). Change the number of teammates, decouple the frontend from the backend with a contract-first task, or simulate a teammate that forgets to mark its task completed. The schedule is critical-path list scheduling: whenever a teammate is free, it claims the unblocked task with the longest remaining path to the finish, which is what a lead assigning work well does.
Past two or three teammates, the makespan stops shrinking because the critical path dominates. Contract-first shortens the path itself (13 → 9 with three teammates). With three or more teammates, a stale status costs more than losing a teammate.
The math: why more teammates stop helping
Let T₁ be the total work (sum of task durations) and T∞ the critical-path length. For any schedule on N workers, the makespan satisfies T_N ≥ max(T₁/N, T∞). Any greedy schedule, one that never leaves a worker idle while a task is claimable, achieves T_N ≤ T₁/N + T∞ (the greedy-scheduling bound of Graham 1966 and Brent 1974). So once N ≳ T₁/T∞, the parallelism of the graph, extra teammates buy almost nothing. For the default graph in the widget, T₁ = 20 and T∞ = 13, so the parallelism is about 1.5: a second teammate helps, and a third is mostly idle. With the contract-first task, T₁ = 21 but T∞ = 9, so the parallelism rises to about 2.3 and the third teammate starts to earn its tokens.
Which greedy schedule matters. The widget prioritizes by remaining path length. A naive "claim the longest task" rule, roughly what unguided self-claiming does, makes contract-first worse with two teammates (14 instead of 12), because it starts the long docs task before the short contract that unblocks the UI. That's the argument for having the lead assign critical-path tasks explicitly rather than leaving every claim to the teammates.
Two levers change the bound itself. Decoupling (contract-first) lowers T∞. Splitting a long task into independent pieces lowers T∞ and raises the useful N. A stale status, a task that's done but still in progress, adds its delay to every path through it, which is why the agent-teams docs list "task status can lag" as a limitation to watch.
Coordination overhead isn't in this bound. Each extra teammate has its own context, its own spawn prompt and its own messages, and costs grow roughly linearly with team size, so the economic optimum sits below the throughput optimum.
Bidirectional Handoffs
What it is. A handoff contract has two halves. The downward brief says: goal, scope, owned files, done-when, required evidence, and when to stop and ask. The upward report says: status, artifacts (paths, branches, commits), evidence, decisions made, and open questions or blockers. "Bidirectional" means questions and blockers travel up as reliably as results do, instead of dying inside a worker's context.
How it works in Claude Code.
Subagents can't ask you.AskUserQuestion is always removed from subagents. A subagent that needs a decision must end its run and return the question, which is why the builder's contract has STATUS: BLOCKED. Claude can then resume the same subagent with SendMessage (by agent ID or name). It keeps its full history and tool set, so the answer doesn't cost a fresh start. Its prompt cache survives only if the answer comes back within the cache TTL, 5 minutes for subagents by default, and a human decision usually takes longer. Explore and Plan are one-shot and can't be resumed.
Turn limits return partial work. A subagent that hits its maxTurns returns its output marked partial (v2.1.246+), and it can be resumed.
Teammates talk directly. Any teammate can message any other by name. A teammate that stops sends the lead an idle notification with its final answer, and you can message any teammate yourself.
Separate sessions use cross-session messaging. Claude finds targets with ListAgents and sends with SendMessage. /list-agents (alias /peers, v2.1.224+) shows who's reachable. You can name a target with @api-worker (v2.1.232+), and a session can ask another session on the same machine for one notice when it next goes idle (v2.1.236+). The receiving session decides with crossSessionInbound: accept, hold or refuse.
builder → lead (report)STATUS: BLOCKED. The plan limits by IP, but requests reach us through the CDN, and every client appears as one of 4 CDN addresses. Options: (a) trust X-Forwarded-For from the CDN range, (b) limit per username. This is a product and security decision; not choosing it myself.
lead → youThe builder is blocked on a product decision: rate-limit key behind the CDN. (a) X-Forwarded-For from trusted CDN ranges, or (b) per username. The reviewer flagged (b) as enabling account lockout attacks. Which do you want?
you(a), and only trust the header from the ranges in config/cdn.json.
tool_use · SendMessage → builder{"to": "builder", "message": "Decision: use X-Forwarded-For only when the peer address is in config/cdn.json ranges; otherwise the socket address. Add a test for a spoofed header from a non-CDN peer."}
tool_resultbuilder resumed with its history intact (its cache had expired: the decision took longer than the 5-minute subagent TTL)
Authority is not transferable. A message between agents or sessions arrives marked as coming from another session, not from you. It can't approve a pending permission prompt, Claude is told never to change permissions or CLAUDE.md because another session asked, and slash commands in a message arrive as plain text and never run (cross-session messaging). A teammate that was denied an action can't relay it to another teammate to get around the check.
Why it matters. In practice the downward brief is usually decent and the upward path is broken. Workers guess instead of asking, because asking is expensive or impossible. Make BLOCKED a cheap, expected outcome, and make the report format machine-checkable, so a hook can push back on a report that hides its status and the lead can treat a still-missing status as a failure.
How to apply it.
## Team conventions (project CLAUDE.md)
- Stop and ask only when you can't continue without a decision, or before anything destructive.
- Every subagent and teammate report starts with STATUS: DONE | BLOCKED | PARTIAL.
- BLOCKED reports name the decision needed and at most three options, each with its tradeoff.
- Never resolve an Open question from a plan yourself; send it up.
Enforce the format with require-verdict.sh from the worked example, or with a TeammateIdle hook that exits 2 until the teammate has written its report file.
Count the hops: builder → lead → you → lead → builder. Each hop is a place a question can die. The question goes up as lit beacons and the decision comes down as a flag; each tower's plate names what lights it. Tick "builder without the BLOCKED contract" to see a tower whose plate reads "if the agent chooses": the design goal is that none of them depends on an agent choosing to escalate on its own. The plates are this course's protocol; the mechanisms are from the docs.
How Claude Code defends the handoff channel
A subagent may have read files, web pages or command output nobody reviewed, so its report is a prompt-injection vector into the main conversation. Claude Code scans each subagent's final report before Claude reads it (subagent output scanning). It inserts a backslash into text that imitates its own output (a <system-reminder> tag, a line starting Human:), and it prepends a [harness: subagent output matched instruction-shaped pattern(s): marker when the report imitates such tags or mentions permission settings like bypassPermissions. The report also arrives under a header saying its instructions "carry no authority from you". The scan doesn't judge intent, and any tool call the report provokes still goes through permissions and the sandbox.
In auto mode the classifier adds two checks for inter-agent messages: an approval claim relayed from another agent is untrusted input, and every message, including structured ones such as shutdown requests and plan-approval responses, is reviewed before delivery. A blocked message never reaches the recipient.
For cross-session messages, the default (no crossSessionInbound set) depends on permission-mode classes. A session that prompts for permissions (auto, acceptEdits and dontAsk all count as prompting) accepts messages, and holds one only when the sender says it bypasses prompts. A session that bypasses prompts holds every message for your approval unless the sender also bypasses. Held messages expire with dialogExpiry (five minutes by default), and at most 100 are held.
Exercise: run a research team, then measure what it cost
Enable agent teams (and CLAUDE_CODE_ENABLE_TODO_TOOLS=1 if your lead runs a current model). Ask for three teammates to investigate one real bug in your codebase from competing hypotheses, named h1, h2, h3, each told to message the others when it rules a hypothesis out. Watch the task list with Ctrl+T. When they finish, run /usage and compare the token totals with a single-session investigation of a similar bug.
Show what to look for
You should see the lead create tasks, each teammate claim one, and at least one cross-teammate message ("h2: ruled out the cache, the stale value predates it"). If the teammates never message each other, your spawn prompt didn't ask them to, or the work wasn't really parallel. The /usage attribution breakdown should show the extra spend. The docs put agent teams at "approximately 7x more tokens than standard sessions when teammates run in plan mode", and more teammates or longer runs push that up. If the team found the cause faster, decide whether that wall-clock gain was worth the multiple; for routine bugs it usually isn't.
Key takeaways
Agent teams (experimental, interactive only) give you a lead, full-session teammates, a shared task list and mailboxes. They pay off for research, review and cross-layer work, not for sequential or same-file work.
With teams enabled, any subagent Claude names becomes a teammate, without confirmation. Turn the variable off to get plain subagents back.
No agent inherits another's conversation. Shared goals live in committed files plus focused spawn prompts, and /goal keeps the lead honest.
The task list enforces dependencies with file-locked claims. TaskCreated/TaskCompleted hooks gate it, but only when the Task tools are present.
Make the upward path cheap: STATUS/VERDICT lines, BLOCKED as a normal outcome, resume with SendMessage, and hooks that refuse reports without a status. Messages between agents never carry your authority.
Parallelism
Parallel agents need two things: a separate place to write, and a single place to converge. Claude Code gives you three places to run them (worktrees on your machine, background sessions under agent view, and cloud VMs) and leaves the convergence, the merge point, to you. Isolation is mostly configuration. The merge point is where throughput is won or lost.
Click the lanes in the order you'd merge them, and hover the parts for what each check covers. Every worktree shares the repository's .git (history, branches, remotes) but has its own files and branch. Claude Code blocks edits and git commands that reach back into the main checkout. All the parallel work funnels into pull requests that one reviewer (you) merges, in an order you choose.
Worktrees
What it is. A git worktree is a second working directory on its own branch that shares the repository's history and remotes. Running each parallel session or subagent in its own worktree gives it its own copy of the files, so one agent's half-finished edit can't break another agent's build.
How it works in Claude Code.
claude -w feature-auth --tmux # .claude/worktrees/feature-auth/, branch worktree-feature-auth, own tmux session
echo ".claude/worktrees/" >> .gitignore
The rest of the CLI (PR checkouts with -w "#1234", --resume into a kept worktree, exit cleanup) is in Core 4 · Parallel Work. This section is about running many of them.
Base. New worktrees branch from the remote default branch (worktree.baseRef: "fresh", the default); Claude Code fetches it first if the repository hasn't been fetched in the last 24 hours. "head" branches from your local HEAD, including unpushed commits. You can't set it to a branch name.
A fresh checkout is missing your untracked files. List gitignored files such as .env in .worktreeinclude. Symlink heavy directories with worktree.symlinkDirectories, and use worktree.sparsePaths in big monorepos.
Subagents.isolation: worktree in a definition, or "use worktrees for your agents" in a prompt, gives each subagent a temporary worktree. Claude Code removes it if the subagent made no changes, and holds a git worktree lock on it while the agent runs. A worktree with changes stays until a periodic sweep (governed by cleanupPeriodDays) can remove it without losing work.
Enforcement. While a session is isolated, Claude Code applies four checks to it and its subagents: it blocks Edit/Write targeting the main checkout, commands whose working directory resolves there, git redirected there (git -C, --git-dir, GIT_DIR, a cd before git), and commands whose git usage it can't verify from the text. "None of them tracks which files a shell command writes", so cp or a > redirect into the main checkout is governed only by your permissions and sandbox.
Shared with the main checkout:.git; project-scope plugins (v2.1.200+); Bash "don't ask again" approvals, saved to the main checkout's .claude/settings.local.json (v2.1.211+); and, when the worktree has none of its own, untracked .claude/skills, agents and commands.
# .worktreeinclude (gitignore syntax; only files that match AND are gitignored are copied)
.env
.env.local
config/dev-secrets.json
Why it matters. Without isolation, parallel agents share one working tree, and every "edit, run tests" cycle races against every other agent's edits. Worktrees turn that race into an explicit merge you control.
How to apply it. Give every writing agent a worktree: claude -w for sessions you drive yourself, isolation: worktree for builder subagents, and agent view's automatic isolation for background sessions. Split tasks along file boundaries. Decide baseRef deliberately: "fresh" for independent tasks off main, "head" when subagents must build on uncommitted plans or on a feature branch.
Pitfalls
Agent teams don't isolate teammates. And with teams enabled, a named subagent launches as a teammate in the main working directory, even if its frontmatter says isolation: worktree.
Shared runtime resources. Worktrees separate files, not ports, databases or caches. Two dev servers on port 3000 collide. Give each worktree its own port and database name, for example through a SessionStart hook that derives them from the worktree path in its cwd input.
Disk bounds the worktree count. Each worktree is a full copy of the working files. Bun's migration (case study under Merge Points) put 64 agents in 4 worktrees, 16 each, because one worktree per agent didn't fit on disk. Agents that share a worktree need rules that keep them apart.
Hook paths don't follow the worktree.${CLAUDE_PROJECT_DIR} still points at the main checkout. Read the hook input's cwd when the script needs the worktree.
-p never cleans up. Non-interactive runs leave their worktrees (and locks) in place. Clean them with git worktree remove, running git worktree unlock first if needed.
Instruction drift. A subagent in its own worktree takes its instruction files from the main conversation, not from the worktree's branch, so a CLAUDE.md change on that branch doesn't reach it.
Cloud Sessions
What it is. A cloud session runs Claude Code on an Anthropic-managed VM (or a self-hosted environment) instead of your machine. It keeps working with your laptop closed, starts each task from a clean clone, and doesn't compete for your CPU, ports or disk. Anthropic's blog field guide (Addy Osmani, October 2026) describes the VM as "about 4 vCPUs, 16 GB of RAM, and 30 GB of disk" (Claude Code in the cloud). The docs don't publish VM specs, so treat those numbers as a snapshot.
How it works.
# plan locally, commit and push the plan, then fan out: one VM per command
claude --permission-mode plan # agree on docs/plans/logger.md, commit, push
claude --cloud "Execute the plan in docs/plans/logger.md"
claude --cloud "Fix the flaky test in auth.spec.ts"
claude --cloud "Update the API documentation for /v2/orders"
claude -p "Also add a changelog entry" --cloud <session-id> # queue one follow-up, then exit
claude --teleport <session-id> # pull a finished session into your terminal
/autofix-pr # from a PR branch: a cloud session watches CI and review comments
What it clones.--cloud "clones your current directory's GitHub remote at your current branch, not your local checkout, so push first". The bundle-upload fallback and the other single-session details are in Autonomy 1 · Runtime. When it clones from GitHub, push the plan before you dispatch. With no git remote, or without the Claude GitHub App on the repository, it uploads a bundle of your history plus uncommitted changes to tracked files instead (credential-like files are left out on macOS, Linux and WSL); CCR_FORCE_BUNDLE=1 forces a bundle.
What config it sees. Only the committed project .claude/settings.json and server-managed settings, never user or local settings or local plugins. CLAUDE.md, rules, skills, agents and commands travel with the repository. Your team's agent files must be committed to work in the cloud.
Handoff is one-way.--teleport (needs clean git state, the branch pushed and the same claude.ai account) pulls a cloud session down. Nothing pushes a terminal session up.
Auto-fix./autofix-pr subscribes a cloud session to the PR's CI failures and review comments. It pushes clear fixes, asks you about ambiguous ones, and replies to review threads under your GitHub account, labeled as Claude Code. GitHub sends no webhook when the base branch moves, so it can't react to merge conflicts: ask the session to rebase.
Why it matters. Cloud sessions are the cheapest way to raise agent capacity without raising local contention, and they're the only option here that survives a closed laptop: local background sessions survive sleep but stop at shutdown. The constraint is that everything must be expressible as "a self-contained ticket that states what's wrong, what done looks like, and how to prove it", because the VM knows only the repository.
How to apply it. Plan locally in plan mode, commit and push the plan, then dispatch one --cloud command per independent task. Review results as PRs, or teleport a session when you need to take over.
Pitfalls
Unpushed work is invisible to a VM that clones from GitHub, and your ~/.claude is invisible to every cloud session.
Rate limits are shared. "Running multiple tasks in parallel consumes more rate limits proportionately."
Comment-triggered automation. Auto-fix replies can trigger workflows that run on issue_comment (Atlantis, Terraform Cloud, custom Actions). Disable auto-fix where a PR comment can deploy infrastructure.
Network isolation has a hole by design. "When running with network access disabled, Claude Code can still communicate with the Anthropic API, which may allow data to exit the VM."
Availability. Pro, Max and Team plans, and Enterprise users with premium or Chat + Claude Code seats, with the org policy enabled. ZDR, HIPAA and CMEK organizations can't use cloud sessions.
Agent View
What it is.Agent view, opened with claude agents, is one terminal screen for all your background sessions: "what's running, what needs your input, and what's done" (agent view). Each background session is a full Claude Code conversation hosted by a supervisor process, so it keeps running after you close the terminal. It has been a research preview since v2.1.139, and "the interface and keyboard shortcuts may change".
How it works.
claude --bg "Fix the N+1 query in OrdersController#index" # dispatch and return immediately
claude --bg --name "flaky-auth" --model sonnet "Find why auth.spec flakes"
claude --agent reviewer --bg "Review PR #1234 against docs/plans/rate-limit.md"
claude --bg --exec 'pytest -x' # a shell job, not a Claude session
claude agents # open agent view
claude attach flaky-auth # by name needs v2.1.290+; an ID always works
claude logs flaky-auth
claude stop <id> # transcript and worktree are kept
claude respawn <id> # restart, e.g. after an update
claude rm <id> # remove from the list
Rows and states. Working (animated), Needs input (yellow), Idle (dimmed), Completed (green), Failed (red), Stopped (grey). A Haiku-class model writes each row's one-line summary at turn end. A #1234 label links the session's PR: grey for a draft or closed PR, yellow while waiting on checks or review (or when checks failed), green when checks pass with no blocking review, purple when merged.
Supervising from the list. The keys and filters are covered in Agents 4 · Background Sessions. The ones a supervisor uses all day are Space (peek and reply), Ctrl+T (pin so an idle process stays alive) and the s:blocked filter.
Isolation and git. "Before editing files, Claude moves the session into an isolated git worktree under .claude/worktrees/." When it has isolated itself, it commits without asking, pushes the branch if there's a remote, and opens a draft PR when the task calls for one. It never pushes to main or master, force-pushes or merges, and your own git instructions in the task, CLAUDE.md or memory take precedence. A session you sent to the background with ← or /background keeps editing where it was. Turn isolation off per repository with worktree.bgIsolation: "none".
Lifecycle. Sessions survive sleep and supervisor restarts, and stop at shutdown. Idle unattached sessions have their process stopped after about an hour unless pinned. Dispatch defaults (model, permission mode, effort, agent) come from your user settings or from flags passed to claude agents.
Why it matters. Agent view is the lightest way to run a parallel team you supervise yourself. There's no lead and no shared task list: each session reports to you, each gets its own worktree and branch, and the PR label tells you when a result is ready to review.
How to apply it. Dispatch independent, well-specified tasks, one per row. Pin the long ones. Use s:blocked as your inbox. Read results through the PR label, and review and merge when it turns green.
Pitfalls
Deleting a session deletes its worktree, uncommitted changes included. claude rm keeps a worktree with uncommitted changes, and both refuse while a worktree has unpushed commits (--discard-unpushed to override).
Quota. "Background sessions consume your subscription usage the same as interactive sessions." Ten parallel agents burn quota roughly ten times as fast.
Don't parse ~/.claude/jobs/. Those files "are not a stable interface". Use claude agents --json.
Subagents and teammates never get their own rows, and sessions running in other terminals don't appear until you background them.
Step through one session's life as tracking scans, newest on top, the current one in the accent: dispatched, working, into its worktree, needs input, working again, a draft PR (grey), PR checks once you mark it ready (yellow), PR ready (green), merged (purple). Notice when the session moves into its worktree and what it does with git on its own. Times, paths and the PR number are illustrative.
Merge Points
What it is. A merge point is where parallel work converges: a PR you review, an integration branch, the lead's synthesis step, or a workflow's final stage. Every parallel plan has at least one, and it's usually serial, usually human, and usually the bottleneck. Anthropic's cloud field guide (Claude Code in the cloud) says to "split parallel tasks along file boundaries, merge the branches in a sensible order", and Simon Willison (community post, 2025) names the constraint: the bottleneck "is how fast I can review the results" (Embracing the parallel coding agent lifestyle).
How it works. Claude Code gives each parallel unit a branch (worktrees, background sessions, cloud sessions, /batch units). The convergence uses ordinary git and your review process, plus a few Claude Code helpers:
# before merging: would branch B still merge cleanly onto main after A lands? (git 2.38+)
git merge-tree --write-tree origin/main worktree-feature-a >/dev/null && echo "A merges cleanly"
git merge-tree --write-tree worktree-feature-a worktree-feature-b >/dev/null || echo "A and B conflict"
# which files do two branches both touch? (the cheapest collision signal)
comm -12 <(git diff --name-only main...worktree-feature-a | sort) \
<(git diff --name-only main...worktree-feature-b | sort)
Order. Merge producers before consumers (contracts, schemas, shared libraries), then leaves. After each merge, have the remaining sessions rebase. Claude can tell them what landed with cross-session messaging ("Let @web-builder know the 429 response shape merged").
Semantic conflicts. Git catches textual overlap only. Two branches that merge cleanly can still break each other: one renames a function, the other adds a call to the old name. Run the validator on the merged result, not just on each branch.
Review load. With one reviewer, each PR waits behind every PR ahead of it. If PRs arrive faster than you review them, the queue grows without bound, and more agents only make it longer. Cut review time per PR: smaller PRs, a reviewer subagent or /code-review pre-pass, and validator evidence attached to the PR.
Why it matters. Parallelism moves cost from writing to integrating. A team that writes code twice as fast but merges at the same speed delivers at the same speed, with more stale branches. Planning the merge point first (what merges in what order, and who reviews) is what turns agent capacity into shipped work.
How to apply it. Write the merge order into the plan. Cap work in progress at roughly what you can review in a sitting. Make every PR carry its own evidence. Rebase in-flight work after each merge.
Twelve tasks, each built by an agent in about 40 minutes, then reviewed and merged by one human. Each merge can force an open PR to rebase and be re-reviewed, with a probability set by the file-overlap slider. It's a seeded toy model averaged over 30 runs; the numbers are illustrative, not measurements.
The scene replays one seeded run: agents drop PRs into the queue in front of your desk, merges bounce overlapping PRs back as rebases, and the floor strip is twelve reviews back to back. Scrub or play it, then push the agent count up with review at 20 minutes: the makespan floors at about 12 × 20 minutes plus the first build, no matter how many agents you add. Then raise file overlap: the whole curve lifts, because each merge forces rebases and longer re-checks on the PRs waiting in your queue. Watch the rebase count climb with the agent count while the makespan doesn't improve: past two agents, more agents buy more rebases, not more throughput.
Why the review queue explodes: a queueing view
Treat yourself as a single server. PRs arrive at rate λ (PRs per hour, roughly the number of agents divided by the build time) and you review at rate μ = 60 / R for R minutes per review. Utilization is ρ = λ/μ. For an M/M/1 queue the mean wait before review starts is W_q = ρ / (μ − λ), which grows without bound as ρ → 1. Kingman's approximation for general arrivals and service, W_q ≈ (ρ/(1−ρ)) · ((c_a² + c_s²)/2) · R, adds that variability (bursty arrivals, uneven PR sizes) multiplies the wait.
Three agents that each finish a PR every 40 minutes give λ = 4.5 per hour. At R = 12 minutes, μ = 5, ρ = 0.9, and the expected wait is 0.9 / 0.5 hours ≈ 1.8 hours per PR, even though you're "only" 90% busy. Halving R through a reviewer pre-pass gives μ = 10, ρ = 0.45 and a wait of about 5 minutes. That's why review-time reduction beats agent addition once you pass ρ ≈ 0.7.
Rebases add work at the merge point: each merge can invalidate the other PRs that are open at that moment, and the number open grows with the agent count. That's the effect the simulator's overlap slider shows.
Case study: Bun's Zig→Rust migration
A public example of a merge point designed before the fan-out is Bun's rewrite from Zig to Rust (Jarred Sumner, Rewriting Bun in Rust, Bun blog, 2026-07-08). The post discloses that Bun was acquired by Anthropic in December 2025 and that the author used a pre-release Claude Fable 5. The rewrite ran as "about 50 dynamic workflows in Claude Code run continuously over the course of 11 days".
The compiler-error phase (phase D in the post) shows the design best. cargo check wrote about 16,000 errors to a file, grouped by crate, and the workflow divided them among 64 Claudes, "16 loops across 4 worktrees, each one Claude fixing, two reviewing, one applying" (16 Claudes per worktree). Each crate went through 1 fixer, then 2 adversarial reviewers who saw only the diff, then 1 applier. Two rules removed the usual collisions instead of detecting them: cargo check ran only at the start, and there was "no git until the end". The rewrite merged after 11 days with 0 tests skipped or deleted, for about $165,000 at API pricing.
The lesson the post draws is about where the human works: "fixing the process that generates the code instead of hand-fixing the code". The author monitored the workflows, read their output and had Claude edit the loop. One such edit gave the reviewers a rule to enforce: "If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code."
Step through the grid: 4 worktrees of 16 Claudes, each loop a fixer, two reviewers and an applier. Every number here comes from the Bun post. Notice what the loop leaves out: the compiler runs once before the fan-out, there's no git until the end, and no agent reviews its own change. The human's arrow points at the workflow, not at the code.
Bun's phase D, mapped to this session's concepts
What Bun did
The concept here
Where
A checker's output (≈16,000 errors by crate) became the work queue
Error-driven fan-out, sized to the independent pieces a deterministic check defines
From the post: May 3 → merged May 14, 6,778 commits, and 5.9 billion uncached input, 690 million output and 72 billion cached input tokens before the merge, around $165,000 at API pricing.
Don't copy the size: 64 Claudes at once, run by one engineer watching it closely, at a company Anthropic owns, on a pre-release model. Copy the shape (check → queue → fix → independent reviews → apply) and the habit of fixing the loop, starting on one unit with a small workflow size.
Exercise: two worktrees, one merge order
Pick two small changes in one repository that touch different directories, plus one change that touches a file both of them use. Run each in its own worktree (claude -w a, claude -w b, claude -w c), or dispatch them with claude --bg. Before merging anything, use the git diff --name-only overlap check and git merge-tree --write-tree to predict which pairs conflict. Choose a merge order, merge, and rebase the rest after each step.
Show a reference approach
The overlap check should flag the third change against whichever of the first two shares its file. Merge the change that defines or modifies the shared file first, if it's the producer (a schema, a helper), so the consumers rebase onto the new shape once. If merge-tree reports a conflict, resolve it in the consumer's worktree (git rebase origin/main there, or ask that session to rebase) rather than on main. Finally, run the test suite on main after the last merge. A clean textual merge doesn't prove semantic compatibility. Remember to remove the worktrees you kept, and that deleting a background session in agent view deletes its worktree.
Exercise: design a Bun-style error-driven workflow for your own refactor
Pick a large change that a deterministic check can enumerate: a stricter compiler mode, a new lint rule, a removed deprecated API. Write the workflow brief before running anything. Which check generates the queue, and when does it run? What's the unit, and why are units independent? What does each role see? How many worktrees does your disk allow, and how many agents share each? Which rules keep those agents apart? Which invariants do reviewers enforce? Run it on one unit, read every diff, and for anything you'd reject, change the brief, not the code.
Show a reference brief
For a TypeScript monorepo after turning on "strict": true. Paste it into a session started in a worktree (claude -w strict-a); a second worktree can take the other half of the packages.
use a workflow to fix the type errors that strict mode causes, package by package, for the packages listed under "Units"
Queue: at the very start, run `npx tsc --noEmit -p packages/<name>` once for each unit and save the output to errors/<name>.txt. Don't run tsc or the tests again until every unit is done.
For each unit:
1. One fixer fixes the errors in errors/<name>.txt and edits only files under packages/<name>/.
2. Two reviewers review the fixer's diff independently. Give each one only the diff and the error file, not the fixer's reasoning. Tell them to assume the change is wrong and to look for behavior changes, `any` or `@ts-ignore` added to silence an error, stubbed functions, and skipped or weakened tests. If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code.
3. One applier applies the reviewers' findings, then commits only that unit's files.
Rules: no git command other than the applier's commit. Never skip, delete or weaken a test.
At the end, run `npx tsc --noEmit` and the test suite once, and report which units still fail and why.
Units: packages/utils
The first run has one unit on purpose: a workflow can't pause for your sign-off mid-run, so the trial and the full run are separate workflows. After the trial, fix the brief (a reviewer that missed an any, a fixer that strayed outside its package), not the diff, then add the remaining packages. Each unit takes four agents, so a longer Units list asks for more than the small guideline, and the prompt wins over the guideline. On a shared account, run the remaining packages one unit per workflow instead.
Key takeaways
claude -w, isolation: worktree and agent view's automatic isolation give each writer its own checkout. Configure .worktreeinclude, baseRef and symlinkDirectories so fresh checkouts work.
Worktree isolation blocks edits, working directories and git redirects into the main checkout. It doesn't track shell writes, ports or databases.
Cloud sessions add capacity that survives a closed laptop, but when they clone from GitHub they see only what's pushed. Teleport is one-way.
Agent view is a supervisor's inbox: states, PR labels, peek and attach. Background sessions commit and push their own branch but never touch main.
The merge point sets throughput. Merge producers first, check overlap before merging, validate the merged result, and cut review time before adding agents.
Routing
Routing decides which model, at which effort, through which mechanism, handles each piece of work. In a team it's mostly static: you set it once per role in frontmatter. The rule of thumb from Anthropic's own guidance is to spend capability where judgment and code are produced (planning, building, reviewing) and save it where work is lookup or routine (search, running checks, summarizing). Risk then overrides cost: the riskier the action, the stronger the model, the higher the effort, and the more human gates around it.
Hover a stage for what it filters. Hard constraints come first: what your provider offers, what availableModels allows, and what the risk tier requires. Then capability, effort and cost choose among what's left. The result lands in a concrete place: a frontmatter model and effort, a spawn prompt, /model, or /advisor.
Model Choice
What it is. Choosing a model per role, per task or per phase. In Claude Code you express it through model aliases (opus, sonnet, haiku, fable, opusplan), full model IDs, or inherit. "Aliases point to the recommended version for your provider and update over time" (model configuration).
Alias
Anthropic API
Bedrock / Agent Platform
Foundry
opus
Opus 5.5
Opus 5.5
Opus 4.6
sonnet
Sonnet 5.5
Sonnet 4.5
Sonnet 4.5
haiku
Haiku 5.5
Haiku 4.5
Haiku 4.5
On third-party providers, unpinned aliases resolve to Claude Code's built-in default, which can lag. Pin them with ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL and ANTHROPIC_DEFAULT_HAIKU_MODEL. A Bedrock teammate on plain sonnet (Sonnet 4.5) can't use auto mode.
How it reaches each agent.
Subagents: per-invocation model on the Agent call → frontmatter model → CLAUDE_CODE_SUBAGENT_MODEL → the main conversation's model (this order since v2.1.251). CLAUDE_CODE_SUBAGENT_MODEL_FORCE=1 (v2.1.257+) puts every subagent on one model. Workflow agents follow the same order, with a model the script names counting as per-invocation.
Teammates: the model the spawn prompt names → the definition's model → CLAUDE_CODE_SUBAGENT_MODEL → the lead's model. Fixed at spawn. /model typed while viewing a teammate doesn't run, because it would set the lead's model.
Main session:/model → --model → ANTHROPIC_MODEL → the model setting. Built-in Explore uses the main model (on Fable it uses the opus alias model with a subscription, Console or gateway), so an Opus lead makes every search Opus-priced unless you route searches to your own Haiku agent.
opusplan uses opus in plan mode and sonnet for execution. Set it with /model opusplan (or --model opusplan) on the session that plans. It's a session-level alias: the documented values for a subagent's model field are sonnet, opus, haiku, fable, a full model ID or inherit.
The advisor tool (experimental) lets the working model consult a stronger one "at key moments": before committing to an approach, when an error keeps recurring, before declaring done. Enable with /advisor opus, claude --advisor opus or "advisorModel": "opus". The advisor must rank at or above the main model (for example, Sonnet 5.5 accepts Fable, Opus 5 or later, or Sonnet 5.5 as advisor). Subagents inherit the advisor and apply the same pairing check. It's server-side and runs on the Anthropic API only, not on Bedrock, Claude Platform on AWS, Agent Platform or Foundry. Through an LLM gateway (ANTHROPIC_BASE_URL), it works only if the gateway forwards the request intact to the Anthropic API. Claude decides when to call it, and no setting caps or forces calls (advisor).
Approach
When the stronger model runs
Who triggers it
Cache effect
Advisor tool
At decision points mid-task
Claude calls it
Toggling doesn't invalidate the main cache; each call re-reads the full transcript uncached
opusplan
During plan mode
You enter plan mode
Entering or leaving plan mode switches models, so it rebuilds the cache
Subagent model
For the whole delegated subtask
Claude delegates, or you invoke it
Separate cache per subagent
Why it matters. In a team the model choice multiplies: five agents on the wrong default means five times the waste, or five times the risk. Official guidance gives four anchors. From the costs page: "Sonnet handles most coding tasks well and costs less than Opus. Reserve Opus for complex architectural decisions or multi-step reasoning"; "Use Sonnet for teammates. It balances capability and cost for coordination tasks"; and "For simple subagent tasks, specify model: haiku". From What a task costs on Opus 5.5: "move down to Sonnet or Haiku for lookups, not for writing code". The worked example's builder runs on Opus only because the feature is security-sensitive. That's the risk floor from the Risk article, not the default.
How to apply it. Set model in every role file; never leave a role on inherit by accident, because then it follows whatever you last picked with /model. Pair a Sonnet lead with an Opus advisor for long coordination runs where most turns are routine. Use opusplan on a session you drive yourself, and per-role model fields for a pipeline.
Here the lead runs Sonnet and consults Opus at decision points. Any role file without a model line falls back to Sonnet through the environment variable instead of following the lead.
Effort
What it is. The effort level (low, medium, high, xhigh, max) sets how much adaptive reasoning, verification and independent judgment Claude applies. It defaults to medium on Opus 5.5, Sonnet 5.5 and Haiku 5.5, xhigh on Opus 4.7 and high elsewhere. "The effort scale is calibrated per model", so high on Haiku isn't high on Opus.
How it resolves. For a session: CLAUDE_CODE_EFFORT_LEVEL, --effort or /effort → your saved level for that model (modelSettings) or effortLevel → the model default. For a subagent: the per-invocation effort parameter (v2.1.292+) → the frontmatter effort → the session level, with the environment variable beating both. Teammates inherit the lead's effort; an in-process teammate applies its definition's effort. max applies to the current session only unless it comes from the environment variable. maxEffortLevel (v2.1.267+) caps every source, frontmatter included. When several scopes set a cap, the lowest wins.
Every model is capped at high except Opus 5.5, which may run the occasional max audit. In managed settings this holds for the whole organization.
Why it matters. Effort is the cheapest routing lever, because it changes thoroughness without changing the model. The Claude Code team's own description: effort "was a great way of modulating how much verification and edgecase testing Claude did and how much of its own judgement it used", but "increasing effort tends to reduce failures due to missing edgecases... but does not fix when the model has the wrong approach" (Spending your effort). So route approach problems to a stronger planner or the advisor, and route thoroughness problems to effort.
How to apply it. Planner and reviewer at high, where missed edge cases are expensive. Builder at medium ("day-to-day engineering work with a clear scope"). Validator at low or medium, since it runs commands and reads output. Reserve max for hard problems Claude should work through without you, such as a vulnerability hunt, and test it first: max "may show diminishing returns and is prone to overthinking". For a single deeper turn, put ultrathink in the prompt. It's the only recognized keyword; "think hard" is ordinary text.
Pitfalls
One environment variable flattens the team.CLAUDE_CODE_EFFORT_LEVEL overrides every role's frontmatter effort. Don't export it in a shell where you run pipelines.
Unsupported levels fall back silently.xhigh runs as high on Opus 4.6.
Old settings don't carry over. A top-level effortLevel in your user settings doesn't count for Opus 5.5. Start new models at their default rather than carrying over the level you used on Opus 5.
Ultracode isn't a level. It's a setting that makes Claude plan a dynamic workflow for substantive tasks, at whatever effort the session runs. Since v2.1.284 it's its own toggle in /effort (Tab, or /effort ultracode [on|off]) that no longer forces xhigh and stays on at any effort level; launching with claude --effort ultracode still sets xhigh. With it on, the Large workflow warning doesn't appear (ultracode).
Cost and Speed
What it is. Every agent in a team pays for its own context: its system prompt, tools, CLAUDE.md, the spawn or delegation prompt, and every turn it takes. Parallelism buys wall-clock time and costs tokens. The docs are blunt: "Running several sessions or subagents at once multiplies token usage" (run agents in parallel), and "Agent teams use approximately 7x more tokens than standard sessions when teammates run in plan mode" (costs).
How it works.
List prices on the Anthropic API, per million input/output tokens: Opus 5.5 $4/$20, Sonnet 5.5 $2/$10, Haiku 5.5 $0.10/$0.50 (up to 100K prompt tokens), Fable 5.1 $10/$50. Cache reads cost 0.05× input on Opus 5.5 and Sonnet 5.5, 0.025× on Fable 5.1 and 0.1× elsewhere. Cache writes cost 1.25× (5-minute TTL) or 2× (1-hour TTL). Check the pricing page before you rely on these numbers. On a subscription, plan usage limits are what bind, and they're shared across all models.
Cache TTLs differ by role. On a subscription within plan usage, only the main conversation gets a 1-hour cache. Subagents, in-process teammates and workflow agents get 5 minutes unless subagentPromptCacheTtl is "1h", which bills each cache write at the higher rate. A teammate that waits more than five minutes on a dependency pays a full re-read on its next turn.
Forks are cheaper than fresh subagents for work that needs the same context, because a fork's first request reads the parent's cache. In a workflow fan-out, Claude Code holds sibling agents up to 5 seconds (CLAUDE_CODE_WORKFLOW_PREFIX_STAGGER_MS) so they read the first agent's cached prefix.
Speed levers: parallel agents for independent work; a smaller model for lookups; fast mode (/fast) for latency on the interactive session (turning it on invalidates the cache once per conversation).
Caps:--max-budget-usd and --max-turns on -p runs (the budget is checked against a client-side estimate and can overshoot by about one response), maxTurns per subagent and, for dynamic workflows, workflowSizeGuideline (v2.1.219+: small <5, medium <10, large <50 agents), which is advice to Claude rather than an enforced cap: a prompt that asks for a bigger run still gets one. A workflow shows a Large workflow warning past 25 agents (or past the count of a size guideline you chose) or 1.5M projected tokens.
Why it matters. The documented enterprise average is "around $13 per developer per active day", under $30 for 90% of users. A careless team setup can spend that in an hour. On a subscription, the same multiplier shows up as hitting your limit by lunch.
How to apply it. Measure first: run the pipeline once and read /usage, whose attribution breakdown shows the subagent share, or total_cost_usd and the per-model breakdown in -p --output-format json. Then cut where tokens don't buy quality: Haiku for search and log triage, smaller spawn prompts, teammates shut down when idle, and subagentPromptCacheTtl: "1h" only when agents really idle between 5 and 60 minutes.
Dynamic workflows on a shared account or on Bedrock
Set the workflow size to small. When many people fan out on one shared account at once, small workflows keep them from throttling it. Choose small for Dynamic workflow size in /config, run /config workflowSizeGuideline=small, or set "workflowSizeGuideline": "small" in a settings file, which takes precedence over /config (v2.1.219+). Claude then aims for fewer than 5 agents. A prompt that asks for more still overrides it (size guideline).
On Bedrock, pick tasks that don't need the web. "Amazon Bedrock doesn't expose the server-side web search tool" (tools reference). A code audit across a repository works well as a workflow. Deep research doesn't, and the bundled /deep-research workflow fans out web searches.
Eight tasks from one feature cycle. Choose a model and effort for each. The matrix scores fit (is capability matched to the task's difficulty and risk?) and estimates cost at Anthropic API list prices. Token counts per task are illustrative and caching is ignored, so read the totals as relative.
"All Opus, high" is safe but expensive. "All Haiku, low" is cheap and leaves the high-risk rows under-provisioned. The recommended policy spends on planning, building and review, and saves on lookups and routine checks, which matches the official guidance.
A toy model of total tokens for N parallel units of work. Each fresh agent pays a startup context. Teammates add coordination messages that grow with team size. A long single session re-sends a growing history. Gaps longer than the cache TTL force full re-reads. All numbers are illustrative.
Subagents and teams cost more than one session at small N, because every agent pays startup context. Teams pull further ahead as messages grow roughly quadratically. A 5-minute TTL with long waits turns cached re-reads into full-price ones.
Risk
What it is. Risk is the probability of a wrong action times its blast radius. In routing it works as an override: once a task's risk tier is known, it sets a floor on model and effort, picks the mechanism, and decides how many human gates surround the work. Cost optimization only happens above that floor.
Tier
Examples
Model · effort floor
Mechanism and permissions
Human gates
0 · read-only
Search, explain, summarize logs, draft docs
haiku or sonnet · low–medium
Subagent or background session, auto mode
None beyond reading the result
1 · contained
Tests, internal refactors behind tests
sonnet/opus · medium
Worktree, reviewer subagent
PR review
2 · user-facing or data
Public APIs, auth, migrations, billing logic
Planner and reviewer opus · high; advisor on
Plan mode first, validator, ownership guard
Plan approval and merge
3 · irreversible or external
Deploys, infra, data deletion, payments, secrets
Strongest available · high+
Agents prepare and humans execute; deny rules, sandbox
Every irreversible step
How to enforce it in Claude Code. Write the policy where every agent reads it (CLAUDE.md), set it in role files, and lock what must not vary in settings:
## Routing policy (project CLAUDE.md)
- Tier 2+ paths: src/auth/**, src/billing/**, db/migrations/**, infra/**.
- Any plan touching a Tier 2+ path needs my approval before building, and its review runs at high effort.
- Never run migrations, deploys or `terraform apply`; prepare the command and stop.
- Use the advisor before choosing an approach for Tier 2+ work.
The parameter ruleAgent(model:fable) makes Claude Code ask before Claude explicitly requests Fable for a subagent. It matches the literal value on the call, so a role file that sets model: fable in frontmatter doesn't trigger it. availableModels is the hard version: in managed settings, a model outside the list can't be selected for the main session, subagents, skills or the advisor, and a blocked teammate alias falls back to a permitted version or the lead's model.
Why it matters. Cost mistakes are linear and visible. Risk mistakes are rare, nonlinear and often silent: an under-reviewed auth change looks exactly like a well-reviewed one until it's exploited. A team multiplies the number of unsupervised actions, so the floor has to be enforced by configuration rather than remembered.
Pitfalls
Routing by task type alone. "Write tests" is Tier 1 until the tests are for the payment webhook. Route by the paths touched.
Treating auto mode as a risk control. "Auto mode reduces permission prompts but does not guarantee safety" (permission modes docs); in Anthropic's own evaluation it missed 17% of real overeager actions (Claude Code auto mode). Tier 3 needs deny rules and humans.
Relying on model in settings as enforcement. "The model setting is an initial selection, not enforcement." Use availableModels with enforceAvailableModels.
When does "cheap first, escalate on failure" pay?
Let c_s and c_l be the cost of a task on the small and large model, p the small model's success rate, and d the probability that a small-model failure is detected (by tests, a validator or a reviewer). A cascade costs E = c_s + (1 − p)·[d·c_l + (1 − d)·c_bug], where c_bug is the cost of a failure that ships. Going straight to the large model costs c_l (plus its own, smaller, residual bug cost).
With perfect detection (d = 1), the cascade wins when p > c_s / c_l. At list output prices Haiku 5.5 is 1/40 of Opus 5.5, so for lookups even modest success rates pay. For code, d is well below 1 and c_bug is large, so the (1 − d)·c_bug term dominates. That's the quantitative reason behind the cost post's "move down to Sonnet or Haiku for lookups, not for writing code".
The advisor is a different shape: E ≈ c_main + k·c_call, where k is the number of consultations and each call re-reads the transcript at the advisor's rates. It pays when a few decision points determine the outcome and most turns are routine, which is exactly the long-refactor case the docs describe.
What you build: a routing table you can defend. Each task in routing/tasks.json starts from its role's default (lookups and checks on Haiku, code on Sonnet or better, plans and reviews on Opus), moves up for risk and complexity, and is then clamped by the org caps (availableModels, maxEffortLevel). The lab says where each route lives in Claude Code (role frontmatter, the session's --model/--effort, a per-invocation override, opusplan), estimates cost against an all-Opus-at-high baseline, and writes one subagent file per role to out/routing/agents/. Offline by default; --real runs one read-only lookup through claude -p, capped at $0.05.
cd labs && python3 autonomy-3/routing.py
python3 autonomy-3/routing.py --max-effort medium --models sonnet,haiku # tighter org caps
python3 autonomy-3/routing.py --main-model opus # cost of mid-session /model switches
What to observe: the high-risk migration moves up to Opus at xhigh, while a typo fix stays on Sonnet at low (builders never drop to Haiku). The reviewer's route asks for Fable and is clamped back to Opus by availableModels. Run it with --models haiku and the builder routes show blocked: no allowed model sits at or above the Sonnet floor for writing code, so the lab refuses rather than routing code to Haiku. Section [3] shows why you route at session boundaries: switching the main session's model mid-task re-writes its whole cache, while a subagent starts from a small brief.
Exercise: write and test your team's routing table
For your own repository, list the six task types your team does most often, assign each a risk tier by the paths it touches, and write the model and effort for each role into the role files. Then run one representative task twice, once with your policy and once with every role on inherit under Opus, and compare /usage (or total_cost_usd from -p --output-format json) and the review outcome.
Show a reference table
Task
Tier
Role · model · effort
Codebase search, "where is X used"
0
custom searcher · haiku · low (built-in Explore would use the main model)
Feature plan
2
planner · opus · high
Implementation
1–2
builder · sonnet · medium for Tier 1, opus · medium for Tier 2; /advisor opus on a Sonnet lead
Review
by paths
reviewer · opus · high (Tier 2+), sonnet · medium otherwise
Run checks, summarize failures
0
validator · sonnet or haiku · medium
Docs and changelog
0
sonnet · low
Expect the policy run to cost noticeably less than all-Opus while producing the same review verdict on the code. If the verdict gets worse, the saving came from the wrong role: move capability back to the builder or reviewer before touching anything else.
Key takeaways
Set model and effort in every role file. Know the resolution orders: per-invocation → frontmatter → CLAUDE_CODE_SUBAGENT_MODEL → main for subagents; spawn prompt → definition → env → lead for teammates.
Spend capability where judgment and code are produced; move down to Sonnet or Haiku for lookups, not for writing code; use Sonnet for teammates that mostly coordinate.
opusplan switches models at the plan boundary. The advisor consults a stronger model at decision points, on the Anthropic API only.
Effort tunes thoroughness, not approach. CLAUDE_CODE_EFFORT_LEVEL overrides every role, and maxEffortLevel caps them all.
Teams multiply tokens (about 7× for teams in plan mode), and non-main agents get 5-minute caches. Risk sets a floor that cost optimization can't go below, enforced by deny rules, availableModels and human gates.
Supervision
Supervising a team means four jobs: seeing what each agent is doing, catching collisions before they become rework, stepping in with the lightest action that works, and keeping the irreversible decisions for yourself. Claude Code gives you a state API (claude agents --json), notification hooks, per-mechanism controls and a permission system in which no agent can approve on your behalf. Your job is to wire them into a routine you'll actually follow.
Play the hour or step it, click a blip to peek, then reply, stop, respawn or clear it to land on the runway, one merge at a time, in the order you choose. The states and the attach, stop and respawn actions are agent view's (agent view). The conflict ring, two sessions converging on the same file, is this course's collision rule, not a Claude Code feature. Sessions, positions and timings are illustrative.
Progress Visibility
What it is. Knowing, at a glance, which agents are working, which are blocked on you, which finished and which failed, plus enough detail to tell real progress from motion. Each mechanism has its own view:
Mechanism
Where you look
What it tells you
Background sessions
claude agents; claude agents --json --all; claude logs <id>
state (working, blocked, done, failed, stopped), status (busy, waiting, idle), waitingFor (permission prompt, input needed, sandbox request…), PR label
Agent team
Agent panel under the prompt; Ctrl+T task list; teammate transcripts (Enter)
Who's working or idle, task states and dependencies, each teammate's last answer
Subagents
/tasks; transcripts in ~/.claude/projects/{project}/{sessionId}/subagents/
Running and finished subagents, the model each ran on (v2.1.242+)
Dynamic workflows
/workflows
Per-agent progress and token usage; stop or resume
Cost by model and by subagent share; claude_code.cost.usage, claude_code.token.usage, subagent_completed events
How it works. Agent view rows are summarized by a Haiku-class model at each turn end, and refreshed from the session's own output at most every 15 seconds. claude agents --json "is the supported way to read session state from outside Claude Code". Poll it with --all so finished sessions stay listed. The Notification hook fires with type agent_needs_input or agent_completed while agent view is open, and with permission_prompt or idle_prompt in ordinary sessions.
#!/usr/bin/env bash
# Print background sessions that need you or have failed, once a minute.
while sleep 60; do
clear; date
claude agents --json --all | jq -r '
.[] | select(.kind == "background")
| select(.state == "blocked" or .state == "failed")
| [.state, (.name // .id), (.waitingFor // "-"),
(((now * 1000 - .startedAt) / 60000 | floor | tostring) + " min"), .cwd]
| @tsv' | column -t -s $'\t'
done
## In a background task's prompt
Every time you finish a step from the plan, append one line to
$CLAUDE_JOB_DIR/tmp/progress.md: "<time> step <n>/<total> <what> <evidence>".
Don't edit state.json.
Why it matters. The most expensive failure in a parallel team is the silent one: a session blocked on a permission prompt for an hour, a teammate that stopped after an error, a stale task status that froze three dependents. Each costs nothing to fix once seen, and everything if unseen.
How to apply it. Treat s:blocked in agent view (or the watch script) as an inbox you clear. Alert on blocked, failed, and "working for too long without a new summary". Measure progress by artifacts (commits, verdict lines, evidence blocks, PR checks), not by row text.
Pitfalls
A summary is a claim. Row summaries are written by a small model from the session's output. "Tests pass" in a summary isn't evidence; a green PR label or a validator's EVIDENCE block is.
Unstable files. Parsing ~/.claude/jobs/<id>/state.json breaks across versions. Use the JSON command.
Telemetry needs opting in. OTel is off until CLAUDE_CODE_ENABLE_TELEMETRY=1, and exporter variables in a repository's settings files are ignored.
A scripted replay of a busy hour. States, summaries and costs follow agent view's vocabulary; the alert rules are the ones suggested above. Use the controls to advance time, then pick an agent and choose an action. The numbers are illustrative.
Three alerts matter here: a session blocked on a permission prompt, a builder whose summary hasn't changed in 25 minutes, and a teammate whose task is still "in progress" after its PR merged. Each wants a different intervention.
Collision Detection
What it is. Finding the places where parallel agents interfere, as early as possible. Collisions come in six kinds: same-file edits; semantic conflicts (one agent changes a contract another consumes); duplicate work (two agents solve the same thing); shared runtime resources (ports, databases, caches, rate limits); git-level clashes (branch names, worktree locks); and instruction drift (two agents editing CLAUDE.md or a shared config).
How it works in Claude Code. Some collisions are prevented for you. Task claims use file locking, so two teammates can't claim the same task. Worktree isolation blocks edits and git commands that reach the main checkout. Agent view and claude rm refuse to delete a worktree another session is using. Agent teams don't isolate teammates ("Two teammates editing the same file leads to overwrites"), and nothing detects semantic conflicts. You build the rest from four timings, earliest first:
Plan time. Ownership in the plan and the briefs: each path prefix has exactly one writer.
Edit time. The PreToolUse ownership guard from the worked example denies an edit outside the role's paths the moment it's attempted.
Continuously. A PostToolUse hook logs each agent's file footprint to a file shared by every worktree, and a one-liner reports files touched from more than one worktree. For Bash, tool_response.bashEditDiff.changedFiles lists files a command changed (v2.1.269+, public beta). The docs say to use it "to find what to review, not to enforce a policy".
Merge time.git merge-tree --write-tree between branches, then the full suite on the merged result for semantic conflicts.
The cheapest collision is one the plan rules out. Bun's migration (case study under Merge Points) put 16 agents in each worktree, ran cargo check once before the fan-out and had "no git until the end".
#!/usr/bin/env bash
# PostToolUse on Edit|Write|NotebookEdit|Bash. Detection only, never enforcement.
# Appends repo-relative paths this agent touched to a log in the common .git dir,
# which every worktree of the repository shares.
input=$(cat)
cwd=$(jq -r '.cwd' <<<"$input")
common=$(git -C "$cwd" rev-parse --path-format=absolute --git-common-dir 2>/dev/null) || exit 0
top=$(git -C "$cwd" rev-parse --show-toplevel)
jq -c --arg top "$top/" '{
t: (now | floor), session: .session_id, agent: (.agent_type // "main"), checkout: $top,
files: ([.tool_input.file_path // .tool_input.notebook_path // empty]
+ (.tool_response.bashEditDiff.changedFiles // []) | map(ltrimstr($top)) | unique)
} | select(.files | length > 0)' <<<"$input" >> "$common/agent-footprints.jsonl"
exit 0
#!/usr/bin/env bash
# Files touched from more than one checkout since the log started.
log="$(git rev-parse --path-format=absolute --git-common-dir)/agent-footprints.jsonl"
jq -r '.files[] as $f | [$f, .checkout] | @tsv' "$log" | sort -u |
awk -F'\t' '{ n[$1]++; w[$1] = w[$1] "\n " $2 }
END { for (f in n) if (n[f] > 1) print "COLLISION " f w[f] }'
"async": true keeps the logger off the critical path. An async hook can't block anything, which is fine for a detector. bashEditDiff is recorded in every mode when the bashEditDiffEnabled setting turns it on; otherwise only in auto and bypassPermissions modes.
Why it matters. The cost of a collision grows with how late you find it. Caught at edit time, it costs one denied tool call and a message to the lead. Caught at merge, it costs a rebase and a second review. Caught after merge, it's a bug in main.
How to apply it. Put ownership in every plan. Install the guard for roles that write, and the footprint logger for every session. Before each merge, check overlap against the other open branches. Treat contract files (schemas, API types, shared config, lockfiles) as single-writer, and have the writer announce changes to the sessions that consume them.
What you build: a supervisor's board for a parallel team: a gift-cards feature split into build tasks T1–T5, each in its own worktree, plus a review task (T6). It reads the task board plus the events a PostToolUse hook logged, and raises five alerts: PLAN (two tasks claim a file and nothing orders them), DEPENDS (editing before a dependency completes), FOOTPRINT (an edit outside the task's files), COLLISION (two worktrees rewrite the same function, found with Python's ast) and STALLED. It then replays the kit's real PreToolUse footprint guard against the same edits and prints a merge plan. Offline by default.
cd labs && python3 autonomy-3/team_board.py # the board as of 11:20
python3 autonomy-3/team_board.py --at 10:15 # what the lead could see at 10:15
cp -r autonomy-3/team_board/kit/.claude <repo>/ # the hooks, settings and board template
What to observe: the PLAN alert for tinyapp/pricing.py appears before any session starts. At 10:14 two worktrees rewrite the same function, apply_discount: a COLLISION found by function, not just by file. The guard replay denies builder-b's 10:22 edit to a file another task owns, but it allows the pricing clash because the plan let both tasks own that file: fix the plan, not the guard.
Pick a session on the ring, then click a file in its footprint to cycle it through untouched → reads → edits. Every file two sessions share becomes a chord between them. The detector checks each pair of sessions for same-file edits, contract changes that another session reads, and hot files such as lockfiles, then proposes a merge order. The rework minutes are an illustrative toy model.
Two edits to the same file show up in every strategy. A contract changed by one session and read by another passes git cleanly, and only the plan-time ownership check or a post-merge test run finds it. On the ring that's the difference between a solid chord and a dashed one. Move detection earlier and watch the rework total shrink.
Intervention
What it is. Changing a running agent's course with the lightest action that works. The ladder, from lightest to heaviest: observe → steer (send a message) → interrupt (stop the current turn, keep the session) → stop (end the session, keep its transcript and worktree) → replace (a fresh agent with a better brief) → roll back (git) → escalate (a human decision, a stronger model or an abort).
Action
Subagent
Teammate (in-process)
Background session
Cloud session
Steer
Ask Claude to resume it with SendMessage
Select it, Enter, type
Space (peek) and reply, or claude attach
claude.ai/code, or claude -p "…" --cloud <id>
Interrupt
Esc interrupts the main turn
Esc while viewing it
Attach, then Esc
From the web UI
Stop
/tasks, or Claude's TaskStop
x on the row, or ask the lead to shut it down
Ctrl+X, claude stop <id>, /stop
Archive the session
Restart
Resume by name or ID
Message it: Claude Code brings a stopped in-process teammate back with its saved conversation (not after /resume)
claude respawn <id>
claude --teleport <id> to take over
How it works. Stopping a background session keeps its transcript and worktree; deleting it removes the worktree it created. Esc "keeps the work done so far". A subagent you stopped yourself won't auto-resume: "the message is refused and Claude is told the agent was cancelled". An in-process teammate that's no longer running is different: when Claude messages it, Claude Code brings it back in the same session with its saved conversation. Hooks give you automatic, deterministic interventions. TeammateIdle exit 2 keeps a teammate working until its artifact exists. TaskCompleted exit 2 keeps a task open until its checks pass. SubagentStop exit 2 keeps a subagent going. A Stop hook can force continuation, up to 8 consecutive blocks by default (CLAUDE_CODE_STOP_HOOK_BLOCK_CAP). The cap resets each time Claude calls a tool, so it doesn't bound a loop where Claude re-runs the tests between blocks. A hook guarded by stop_hook_active is a one-time nudge, and onFailure has no effect on Stop, SubagentStop, TaskCompleted or TeammateIdle hooks, so a crashing one fails open. CI stays the real gate. Auto mode has its own circuit breaker: after 3 classifier blocks in a row or 20 in total, it pauses and goes back to prompting.
Why it matters. Over-intervening wastes the context an agent built up. A stop-and-restart throws away its cache and history. Under-intervening lets a wrong direction compound. Matching the action to the symptom is most of the skill.
How to apply it. Prefer steering early. A one-line message at minute five (use the existing RateLimiter in src/lib) beats a rollback at minute fifty. For loops (the same failing test three times), interrupt and give a new brief, or let the advisor weigh in. Roll back with git, not checkpoints. /rewind undoes Bash changes only to files Claude had already edited with its file tools: "A file that only Bash commands changed isn't tracked and stays as it is." Subagent edits to other files usually aren't restored either (checkpointing limitations). Worktree branches make git rollback cheap.
Documented team failure modes and their fixes
The lead does the work itself → "Wait for your teammates to complete their tasks before proceeding".
The lead declares the team finished early → "tell it to keep going", or set /goal on the lead.
A teammate stopped after an error → message it with instructions, or spawn a replacement.
A task looks stuck → check whether the work is done, then update the status or nudge the teammate.
Too many permission prompts from teammates → pre-approve common operations before spawning.
Pick a symptom. The picker gives the lightest action that addresses it, the exact command or keystroke, what the action keeps and loses, and what to change so the symptom doesn't recur.
Notice how often the durable fix is a file (a brief, an ownership map, a hook) rather than a stronger intervention. Autonomy 5 turns these repeat fixes into an improvement loop.
Final Human Control
What it is. The decisions that stay with a human however capable the team gets: approving plans that touch high-risk areas, merging to protected branches, irreversible or external actions (deploys, migrations, deletions, payments), answering permission prompts, and giving consent. Final control means those decisions can't be made by an agent, even by accident and even under prompt injection, not merely that a human usually makes them.
Hover a gate or booth for what it checks; the barricaded shortcut is lit to start. Machine gates (hooks, the reviewer and validator, CI) catch what can be checked automatically and run on every change. Human gates sit only where judgment or irreversibility lives: the plan, the merge and the release. The barricaded shortcut is the path configuration closes: no agent pushes to main directly, and none can approve a prompt for you.
How it works in Claude Code.
Permission prompts belong to you. Teammate prompts surface in the lead session for you to answer. "No message from any agent counts as your approval for a pending permission prompt", and a denied teammate can't relay the action to another teammate.
Know which approvals aren't yours.Plan approval inside a team is granted automatically. The human plan gate has to happen before you spawn builders, as feature-lead.md does by waiting for your go-ahead.
Agents don't merge. Background sessions "never" push to main or master, force-push or merge. Add deny rules so that holds for every session. Remember that /autofix-pr replies post under your GitHub account.
The real boundary is server-side. The docs describe server-managed settings as "a client-side control, not a security boundary" on unmanaged devices, a user with local admin rights can edit file-based managed settings, and a Bash deny rule matches text. Branch protection, required reviews and CODEOWNERS on the remote are what make "only a human merges" true.
Bypass multiplies. "If the lead runs with --dangerously-skip-permissions, all teammates do too." Use bypass only inside an isolated container or VM as a non-root user, because it "offers no protection against prompt injection or unintended actions". Organizations can block it with permissions.disableBypassPermissionsMode: "disable".
managed-settings.json for a team that runs agent fleets:
Why it matters. Autonomy scales the number of decisions made without you. The decisions that matter most (what ships, what's irreversible, what's authorized) must not scale with it. A team you can trust is one whose worst possible action, given the configuration, is a bad pull request that you decline.
How to apply it. Keep exactly three human gates for Tier 2+ work: plan, merge and release. Make everything else a machine gate (hooks, the reviewer and validator, CI) so your attention goes only to those three. Audit the boundary periodically: try to push to main from an agent session, and confirm both the deny rule and branch protection refuse it.
Where each "human control" claim is actually enforced
Claim
Enforced by
Can an agent get around it?
"Only I merge to main"
Branch protection on the remote; deny rules locally
Locally, a rule matches text (git -C . push isn't matched), and deny rules are mod-proof only under managed settings or a Team/Enterprise login; otherwise an installed mod can approve a call a deny rule refuses. Remotely, no, unless the agent holds an admin token. Keep admin tokens out of agent environments.
"Agents can't approve prompts"
Claude Code's permission system: messages carry no consent
No, by design. In auto mode the classifier also treats relayed approvals as untrusted.
"I approve every plan"
Your lead's prompt and your own process
Yes inside a team: teammate plan approvals are automatic. Gate before spawning.
"No agent deletes data"
Deny rules plus the sandbox plus credentials scoped to read-only
Through any tool you didn't deny (an MCP server with write scope). Scope credentials, not just commands.
"Nobody uses bypass"
disableBypassPermissionsMode in managed settings
On unmanaged devices, a user can edit their own settings. It's a policy aid, not a boundary.
Exercise: a minimal supervision stack in 30 minutes
Install, in one repository: (1) the Notification hook, (2) watch-agents.sh in a spare terminal, (3) the footprint logger plus find-overlaps.sh, (4) the deny rules from the managed-settings example in your project settings. Then dispatch three background sessions with claude --bg, two of which you deliberately point at the same file. Answer one permission prompt from the watch output, run the overlap script, and try to have one session push to main.
Show what to expect
The watch script lists a session as blocked with waitingFor set to permission prompt within a minute, and the desktop notification fires while agent view is open. After the two sessions edit the shared file in their own worktrees, find-overlaps.sh prints COLLISION <file> with both checkout paths. Neither session conflicts until merge, because each has its own worktree; that's the point of logging footprints. The push attempt is refused by the Bash(git push * main) deny rule. If your remote has branch protection, try git -C . push origin main by hand from the worktree to see the second layer refuse it too. If any step doesn't behave this way, check that the hook scripts are executable and that jq is on the PATH Claude Code uses.
Key takeaways
Read state through supported interfaces: claude agents --json --all, the agent panel and task list, /tasks, /workflows, /usage, OTel. Alert on blocked, failed and stale.
Row summaries are claims. Artifacts (commits, verdict lines, evidence blocks, PR checks) are progress.
Detect collisions at the earliest timing you can afford: ownership at plan time, a guard at edit time, a footprint log continuously, merge-tree and tests at merge.
Intervene with the lightest action that works (steer, then interrupt, stop, replace) and roll back with git, not checkpoints. Encode repeat fixes as files and hooks.
Keep plan, merge and release as human gates. Team plan approvals are automatic, agent messages never carry consent, and the real merge boundary is server-side branch protection.
Session wrap-up
You now have a team you can commit to a repository: four role files with bounded tools, a lead that runs the loop, hooks that make roles and report contracts real, and a deny list that keeps main human. You can choose between subagents, agent teams, background sessions, dynamic workflows and /batch on documented capabilities rather than habit. You know where parallel work goes (worktrees, agent view, cloud) and that the merge point sets throughput. You route by capability, cost and risk with per-role model and effort, opusplan and the advisor. And you supervise through supported state, early collision detection, the intervention ladder and three human gates.
Forward:Autonomy 4 · Pipelines starts these teams from events (issues, PRs, schedules) instead of a prompt. Autonomy 5 · Optimization tunes roles, routing and briefs from the transcripts and interventions you'll now be collecting.
Labs in this session
Reads a task board and a PostToolUse event log for six parallel tasks and raises PLAN, DEPENDS, FOOTPRINT, COLLISION (same function, via ast) and STALLED alerts in the order they could have fired. It replays the kit's PreToolUse footprint guard on the same edits and prints a dependency-ordered merge plan with a check after each merge. Offline by default; --board/--events/--repo point it at your own hook log. Writes out/team_board/report.json.
Observe the final line (alerts: 2 COLLISION, 1 DEPENDS, 1 FOOTPRINT, 1 PLAN, 1 STALLED), then remove tinyapp/pricing.py from T2's footprint in board/board.json and see which alerts and guard decisions change. Walkthrough.
Routes a fixture task set by role default, risk and complexity, clamps every route with availableModels and maxEffortLevel, says where each route is set in Claude Code, and compares the cost with an all-Opus-at-high baseline. It also prices a mid-session /model switch against a subagent brief. Offline by default; --real makes one capped, read-only claude -p call.
cd labs && python3 autonomy-3/routing.py
python3 autonomy-3/routing.py --max-effort medium --models sonnet,haiku
Observe the total against the baseline, which routes the tighter caps clamp, and the generated files in out/routing/agents/. Then set "maxEffortLevel": "medium" in routing/policy.json and decide which clamped routes should move to a stronger model instead. Walkthrough.
Pick a real feature that spans at least two areas of your codebase. Use the worked example's files (adapted to your paths), plus the supervision stack from the last exercise. Run it end to end: plan gate, parallel builders in worktrees (or two builder teammates with strict ownership), reviewer and validator verdicts, your merge in a planned order. Keep a log of every intervention you make and every collision you detect, with the timing at which you caught it.
Show what a good capstone write-up contains
The roster with each role's tools, model and effort, and one sentence on why.
The task graph with its critical path, and whether contract-first changed it.
Cost: /usage (or total_cost_usd) for the run, and the subagent share.
Every intervention: symptom, action, what it preserved, and the durable fix (a brief, an ownership entry, a hook) you'd add next time.
Every collision: kind, when it was detected, and the rework it cost.
The three human gates and evidence that each one was enforced by configuration, not habit.
The most valuable part is usually the list of durable fixes. It's the input to Autonomy 5 · Distillation.
What to do next
Commit the four role files and the two hooks to one real repository, and run one feature through them this week.
Install the supervision stack (Notification hook, watch script, footprint logger, deny rules) before you scale beyond two parallel agents.
Write your routing table into CLAUDE.md and the role files, and compare one run's /usage against all-Opus.
Move on to Autonomy 4 to start these teams from repository events instead of prompts.