Subagents & Orchestration
Updated
AdvancedWhat you'll learn
~26 min- Choose between one session, a subagent, a background agent, and parallel worktrees
- Apply the named orchestration patterns: fan-out, pipeline, supervisor, debate
- Run parallel agent sessions with git worktrees in any tool
- Hold several agent sessions side by side in tmux windows on Linux, WSL2 or macOS
Start here:
Research how our three payment providers handle refunds —use a subagent per provider and summarize the differences.You send that in Claude Code. Three subagents spin up — one scoped to Stripe’s docs, one to Braintree’s, one to PayPal’s. Each reads, searches, and summarizes independently. Your main window stays clean. Five minutes later you get a structured comparison. No dead-end tabs. No cross-contaminated context.
That is orchestration. The rest of this lesson names the patterns, maps them to the tools, and tells you when the overhead is worth it.
Why more than one agent?
There are exactly three reasons to involve a second agent. Know which one applies before you start:
Context isolation. A subagent doing exploratory research accumulates noise — dead links, false starts, discarded hypotheses. Running that work in a separate context window means none of it pollutes your main session. (This matters most when you have a carefully shaped context — see Context Engineering before using agents for research.)
Parallelism. Some work is genuinely independent. Three payment providers, four microservices, a dozen test files — if the tasks do not depend on each other, running them in sequence is waste. Wall-clock time drops proportionally; token spend rises proportionally. The tradeoff is real.
Specialization. Different agents can carry different system prompts, tool permissions, or roles. A security-review agent can have a skeptic’s lens. A documentation agent can have a style guide baked in. A debate opponent can be explicitly prompted to find flaws. Same model, different posture.
If none of these three apply, stay in one session. Orchestration adds latency, token cost, and coordination overhead. It earns its keep only when isolation, speed, or specialization actually matter.
The pattern vocabulary
Four named patterns have settled, and a fifth (swarm) is still emerging. Learn the names: you will see them in documentation, team postmortems, and your own commit messages.
Fan-out
Scatter independent work to multiple agents, then gather results. The parent decomposes the task, each agent handles one slice, the parent synthesizes.
Audit our API surface for these four concerns in parallel:authentication gaps, rate-limit enforcement, input validation,and error message leakage. Assign one concern per agentand merge the findings.Use fan-out when subtasks are independent and roughly equal in cost. The bottleneck is the slowest agent, not the sum.
Pipeline
Sequential stages where each agent’s output feeds the next agent’s input. The key property is that stage N cannot start until stage N-1 finishes.
Stage 1: Extract all TODO comments from the codebase.Stage 2: Triage each TODO by severity and owner.Stage 3: Draft GitHub issues for severity-high items.Use pipeline when work has a natural assembly line shape and intermediate outputs are worth inspecting between stages.
Supervisor
A lead agent decomposes a goal, delegates to specialist agents, and synthesizes their outputs. This is a common production shape: a lead agent with two or three delegates.
You are the lead architect. The goal is to add a real-timenotification system to this repo.
Delegate to three specialists:- Backend agent: design the WebSocket server and message schema- Frontend agent: design the React subscription hooks and UI- Testing agent: write integration tests for both sides
Synthesize their outputs into a single implementation plan,flagging any interface mismatches.The supervisor pattern earns its name: you shift from watching keystrokes to reviewing results. The lead agent does the coordination; you approve or redirect the plan. This is where human oversight is most important — set a plan-approval gate before the delegates execute.
Debate
Two or more agents take independent perspectives on the same question, then critique each other’s reasoning. Useful for architecture decisions, risk assessments, and any case where you want adversarial pressure before committing.
Agent A: argue for a serverless architecture.Agent B: argue against serverless for this workload.Each agent: read the other's argument and identify its threeweakest assumptions.Debate is computationally expensive and most valuable when the cost of a wrong decision is high. It seeds the council pattern covered in Lesson 8, which formalizes multi-model deliberation.
Swarm
Dynamic peers that self-assign tasks from a shared queue. Less structured than supervisor; useful when the task space is large and unpredictable. Still experimental where it exists: Claude Code’s agent teams, whose teammates self-claim work from a shared task list, are off by default as of November 2026. Each tool is at a different stage (as of 2026-11-07): Antigravity’s /teamwork is the one shipped without a flag, on paid plans only; Copilot CLI’s /fleet runs parallel subagents but is not a team of peers; Codex has no named team feature. Mention it to your team, but do not build on it for production yet.
The escalation ladder in Claude Code
Claude Code offers a ladder of agent parallelism. This lesson covers four rungs, each with more power and more cost:
1. Inline subagent
The default. Delegate a task with its own clean context window. By default a subagent can spawn subagents of its own, up to three layers below your main conversation (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH changes the limit). To create a custom one, ask Claude or write the file yourself; /agents no longer opens a wizard.
Use a subagent to audit src/auth/ for JWT handling issues.Report findings here when complete.Custom agent definitions are markdown files in .claude/agents/ (this project) or ~/.claude/agents/ (all your projects). Their frontmatter gives the subagent a name, a description, a tool set, and optionally a model.
2. Background agent
Run work without holding your terminal. The session continues asynchronously.
claude --bg "Refactor all CSS modules to use our new design tokens"Or run /background (alias /bg) from inside a session to detach it and free your terminal. Ctrl+B is different: it moves one running command or subagent to the background while you stay in the session. claude agents opens agent view (still a research preview), which lists your background sessions and dispatches new ones. Background agents are right for long-running tasks where you want to context-switch and check in later.
3. /batch with parallel worktrees
Type /batch followed by the change you want, for example /batch migrate src/ from JavaScript to TypeScript. It researches the codebase, splits the work into 5 to 30 independent units, and shows you the plan. Once you approve, each unit runs as a background subagent in its own worktree, runs the tests, and opens a PR or reports what happened. This is the highest-throughput pattern Claude Code offers for repository-scale work.
The merge step is yours to own: /batch opens the PRs, and you review and merge them.
Dynamic workflows sit beside /batch for multi-step jobs that are not one mechanical change. Ask Claude to orchestrate the job and it writes a rerunnable orchestration script, which you watch with /workflows; /effort ultracode makes Claude reach for one on its own. They are on every paid plan (on Pro, turn them on in /config).
4. Agent Teams (EXPERIMENTAL)
Agent Teams require the environment variable CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 to be set. The API and behavior may change without notice. Do not rely on this in production pipelines.
When the env flag is set, a team lead can spawn teammates with their own context windows. Unlike subagents, teammates coordinate through two mechanisms: a shared task list (file-locked claiming, so two agents do not grab the same work) and a mailbox for peer-to-peer messages.
By default all teammates run inside your one terminal; split-pane display, one pane per teammate, needs tmux or iTerm2. Teammates can plan before they implement, but the lead approves those plans, not you, so review the lead’s plan before it spawns the team.
Documented limits: one team per session, and no nested teams (teammates cannot spawn teammates). Token use is significantly higher than a single session, because each teammate is a separate Claude instance. Do not start a team without a rough cost estimate.
When does a team justify the cost? When tasks are tightly interdependent, require back-and-forth negotiation between agents, and the time savings are significant relative to the subscription tier you are on.
Git worktrees: the tool-agnostic pattern
Every CLI tool covered in this course — Claude Code, Antigravity, Copilot, Codex — can run parallel sessions if each session has its own working directory. Git worktrees give you that.
# Create two worktrees for parallel feature workgit worktree add ../proj-auth feature/authgit worktree add ../proj-payments feature/paymentsEach worktree is a full checkout of the same repo, tracking its own branch. Open one CLI session per worktree. They share the git object store and history but do not interfere with each other’s files.
A realistic two-agent scenario:
You are adding auth and payments to the same app. They touch different layers: auth is middleware and session handling, payments is a third-party SDK integration. Neither depends on the other being done first. Start one session in each worktree, switch each to plan mode, and give each its job in a sentence or two:
Add JWT auth middleware, login and logout endpoints, and session storage. Follow ARCHITECTURE.md.Integrate Stripe for one-time payments: a /checkout endpoint and a /webhook handler. Follow ARCHITECTURE.md.Approve each plan, and both agents build at the same time. When both branches are ready:
git checkout maingit merge feature/authgit merge feature/payments# Resolve any conflicts, then:git branch -d feature/auth feature/paymentsgit worktree remove ../proj-authgit worktree remove ../proj-paymentsThe merge step is manual and intentional. You review both branches before they land. If you have not already, review the branching fundamentals in Module 7 — worktrees assume you are comfortable with branches and merges.
A desk for parallel agents: tmux over worktrees
Worktrees give each agent its own folder. Something still has to hold the sessions so you can move between them. Desktop apps do it with tabs or a sidebar of sessions. In a terminal on Linux, WSL2 or macOS, tmux does it: one tmux window per worktree, each split into panes for the agent and for a plain shell where you run tests and read diffs. Sessions keep running when you close the terminal window or an SSH connection drops, and you reattach where you left off.
This four-command script opens the layout for the scenario above. Run it from the main checkout:
tmux new-session -d -s build -n auth -c "$PWD/../proj-auth"tmux split-window -h -t build:auth -c "$PWD/../proj-auth"tmux new-window -t build -n payments -c "$PWD/../proj-payments"tmux attach -t buildThe keys you need, all after the tmux prefix Ctrl+B:
| Keys | What they do |
|---|---|
Ctrl+B then c | New window |
Ctrl+B then n / p | Next / previous window |
Ctrl+B then % | Split the window into left and right panes |
Ctrl+B then arrow key | Move between panes |
Ctrl+B then d | Detach; everything keeps running. tmux attach -t build brings it back |
tmux takes the first Ctrl+B, so a tool shortcut on the same keys (Claude Code’s Ctrl+B sends a running command to the background) needs Ctrl+B pressed twice inside tmux.
The working rhythm: give the agent in one window its task, approve its plan, and move to the next window while it builds. Come back when it finishes, check its work in the shell pane beside it, and merge from the main checkout. With three or four windows you are reviewing one agent’s result while the others work, which is where the parallel time saving comes from; token spend still rises with every agent you add.
This terminal setup is the course author’s own daily one (why, and why it is optional). A desktop app’s parallel sessions reach the same result. tmux asks you to learn a few keys, and in return costs no extra windows, works the same over SSH on a remote machine, and can be scripted as above. Choose the setup that suits how you like to work.
The same rungs in each tool
The manual git worktree add above works in all four tools. Beyond it, each tool has its own subagents, background work and worktree commands (as of 2026-11-07):
| Tool | Subagents | Background and parallel work | Native worktrees |
|---|---|---|---|
| Claude Code | On by default; custom ones in .claude/agents/*.md; built-in Explore and Plan | claude --bg, /background, /tasks; claude agents (research preview) | claude -w [name]; subagent isolation: worktree |
| Codex CLI | On by default; custom ones in .codex/agents/*.toml; /subagents | codex agents, codex queue; /ps lists background terminals | codex --worktree, /worktree (on by default since 0.156.0) |
| Antigravity CLI | Custom ones in .agents/agents/<name>.md; built-in browser; /agents | /tasks; subagents run asynchronously | No worktree command; a subagent’s branch workspace mode gives it its own worktree |
| Copilot CLI | Custom agents in .github/agents/<name>.agent.md, run via /agent or --agent <name> | /fleet runs a prompt as parallel subagents; /tasks; /delegate (or a prompt starting with &) hands the session to the cloud agent, which opens a draft PR (paid plans; see Lesson 6, Level 5) | /worktree, /fork worktree |
OpenAI’s list of common mistakes with Codex includes “Running live tasks on the same files without using Git worktrees”; the warning applies to every tool here. Check each tool’s /help before scripting against these commands, as they move between releases.
Choosing your level
| Scenario | Right choice |
|---|---|
| One focused task, normal session length | Single session |
| Research that might dead-end; you want a clean main context | Subagent |
| Long-running work; you want to context-switch | Background agent (--bg / /background) |
| Large change across multiple independent modules | /batch or manual worktrees |
| Tightly coordinated team work with peer messaging | Agent Teams (experimental, opt-in) |
| You are not sure | Start with a subagent; escalate if needed |
When not to parallelize: tasks with tight sequential dependencies (output of step 1 is the input of step 2), tasks where a mistake early invalidates all parallel work downstream, or any task where the coordination overhead exceeds the parallelism benefit. A two-minute task does not justify a five-minute orchestration setup.
You need to add a new feature that requires: (1) a database migration, (2) a new API endpoint that depends on the migration, and (3) frontend components that call the API. What is the right orchestration approach?
Your team wants to use Claude Code Agent Teams for a large refactor. What is the first thing you should verify?
When should you NOT use parallel agents?
Key takeaways
- Three reasons to orchestrate: context isolation, parallelism, specialization. If none apply, stay in one session.
- Four named patterns: fan-out (parallel independent work), pipeline (sequential stages), supervisor (lead + delegates, a common production shape), debate (adversarial critique). Swarm is still emerging.
- Claude Code escalation ladder: subagent → background agent (
--bg//background/claude agents) →/batchworktrees → Agent Teams (experimental,CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1). - Git worktrees are the universal pattern.
git worktree addgives any CLI tool parallel checkouts; Claude Code, Codex and Copilot can also create them for you. The merge step is yours. - tmux holds the sessions. One window per worktree, a shell pane beside each agent, and detach/reattach that survives a closed terminal or a dropped SSH link. A desktop app’s parallel sessions are the no-terminal route to the same place.
- Parallelism multiplies token spend. Supervision shifts from watching keystrokes to reviewing results. Build in approval gates before delegates execute.
Next: Headless Agents & CI — running agents without a terminal, in pipelines, and on schedules.