Mastery Module 19 · Agentic Engineering

Subagents & Orchestration

Last reviewed

Advanced

What you'll learn

~22 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

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

The industry has settled on four named patterns as of 2026. 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 agent
and 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 the production default in 2026 — most real agentic workflows are supervisors with two or three delegates.

You are the lead architect. The goal is to add a real-time
notification 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 three
weakest 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 in most tools as of mid-2026 — mention it to your team but do not build on it for production yet.

The escalation ladder in Claude Code

Claude Code exposes four levels of agent parallelism, each with increasing power and cost:

1. Inline subagent

The default. Delegate a task with its own clean context window. One level deep — subagents cannot spawn subagents. Managed via /agents.

Use a subagent to audit src/auth/ for JWT handling issues.
Report findings here when complete.

Custom agent definitions are markdown files that give the subagent a specific role, tool set, and constraints. Check /help for the current syntax.

2. Background agent

Run work without holding your terminal. The session continues asynchronously.

Terminal window
claude --bg "Refactor all CSS modules to use our new design tokens"

Or use /background (Ctrl+B) from inside a session. claude agents lists and dispatches active background sessions. Background agents are right for long-running tasks where you want to context-switch and check in later.

3. /batch with parallel worktrees

Decompose a large change into parallel git worktrees. Each worktree gets its own checkout; each runs an independent CLI session. Results merge back as branches. This is the highest-throughput pattern Claude Code offers for repository-scale work.

The merge step is yours to own — /batch does not resolve conflicts automatically.

4. Agent Teams (EXPERIMENTAL)

Experimental feature — requires opt-in

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.

Visualization uses split-pane display via tmux or iTerm2. Plan-approval gates are available — use them.

Documented limits: one team at a time, no nested teams. Token use is materially higher than single-agent sessions. 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.

Terminal window
# Create two worktrees for parallel feature work
git worktree add ../proj-auth feature/auth
git worktree add ../proj-payments feature/payments

Each 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 + session handling, payments is a third-party SDK integration. Neither depends on the other being done first.

Terminal 1 — auth worktree:

Terminal window
cd ../proj-auth
claude "Implement JWT auth middleware, login/logout endpoints,
and session storage. See ARCHITECTURE.md for conventions."

Terminal 2 — payments worktree:

Terminal window
cd ../proj-payments
claude "Integrate Stripe for one-time payments. Add a /checkout
endpoint and a /webhook handler. See ARCHITECTURE.md."

Both agents run concurrently. When both branches are ready:

Terminal window
git checkout main
git merge feature/auth
git merge feature/payments
# Resolve any conflicts, then:
git branch -d feature/auth feature/payments
git worktree remove ../proj-auth
git worktree remove ../proj-payments

The 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.

Antigravity CLI note: /agent dispatches async subagents and is a headline feature of the tool. Copilot CLI offers /fleet and /delegate for similar patterns — consult /help or the current docs for their exact semantics, as these interfaces evolve.

Choosing your level

ScenarioRight choice
One focused task, normal session lengthSingle session
Research that might dead-end; you want a clean main contextSubagent
Long-running work; you want to context-switchBackground agent (--bg / Ctrl+B)
Large change across multiple independent modules/batch or manual worktrees
Tightly coordinated team work with peer messagingAgent Teams (experimental, opt-in)
You are not sureStart 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.

KNOWLEDGE CHECK

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?

KNOWLEDGE CHECK

Your team wants to use Claude Code Agent Teams for a large refactor. What is the first thing you should verify?

KNOWLEDGE CHECK

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, the 2026 default), debate (adversarial critique).
  • Claude Code escalation ladder: subagent → background agent (--bg / Ctrl+B / claude agents) → /batch worktrees → Agent Teams (experimental, CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1).
  • Git worktrees are the universal pattern. git worktree add gives any CLI tool parallel checkouts. The merge step is yours.
  • 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.

Search lessons