Claude Code is not just a coding assistant. It is an orchestrator. The main session decomposes work, spawns teammate agents, manages shared task lists, routes typed messages between agents, and synthesizes results. Anthropic proved this at scale: 16 agents, 2,000 sessions, 100,000 lines of compiler code. This guide covers the concrete protocols, JSON structures, and patterns that make Claude Code orchestration work.
What a Claude Orchestrator Is
A Claude orchestrator is a Claude Code session acting as team lead. It does not write code. It creates tasks, spawns teammates, routes messages, enforces quality gates, and synthesizes results. The teammates do the implementation. The orchestrator coordinates.
This is distinct from the subagent pattern. Subagents report results back to the parent and cannot talk to each other. Every insight routes through one bottleneck. The orchestrator removes that bottleneck: teammates share a task list, claim work independently, and communicate directly through typed message protocols.
Enable orchestration by setting CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 in your settings.json. The session that creates the team becomes the lead. Teammates are separate Claude Code instances, each with their own context window, that the lead spawns and coordinates.
The orchestrator mental model
Think of the orchestrator as a project manager who never touches the codebase. It reads reports, assigns work, mediates conflicts, and ensures quality. The moment the lead starts implementing tasks itself, coordination quality drops. Use delegate mode to enforce this separation.
Inter-Agent Communication Protocols
Three primitives power all agent coordination in Claude Code: TaskCreate for work queues, SendMessage for typed messaging, and worktree isolation for parallel file safety.
TaskCreate: The Work Queue
TaskCreate writes JSON files to ~/.claude/tasks/{team-name}/. Each task has a unique ID, subject, description, status, owner, and dependency edges. The description field is the prompt: whatever the lead writes there is what the teammate reads and executes.
TaskCreate JSON structure
{
"subject": "Refactor auth middleware to use JWT validation",
"description": "Rewrite src/middleware/auth.ts to validate JWT tokens using jose library. Keep existing session interface. Add token expiry check. Write tests in tests/auth/jwt.test.ts.",
"status": "pending",
"owner": null,
"blocks": ["task-004"],
"blocked_by": ["task-001"]
}Tasks have three states: pending, in-progress, and completed. Dependency graphs use blocks and blocked_by relationships. When a teammate completes task-001, task-003 (which was blocked by task-001) auto-unblocks. File locking prevents race conditions when multiple teammates try to claim the same task simultaneously.
SendMessage: Typed Inter-Agent Messaging
Messages land in ~/.claude/teams/{team-name}/inboxes/{name}.json and are picked up automatically. No polling required.
SendMessage JSON structure
{
"from": "security-reviewer",
"text": "Found SQL injection in src/api/users.ts line 47. The query interpolates user input directly. Use parameterized queries.",
"summary": "SQL injection found in users API",
"timestamp": "2026-03-10T14:22:05.123Z",
"read": false
}message
Direct message to one specific teammate. Use for targeted coordination: 'Security reviewer, I fixed the SQL injection you flagged. Please re-check src/api/users.ts.'
broadcast
Sends to all teammates simultaneously. Use sparingly since costs scale linearly with team size. Best for critical blockers that affect everyone.
shutdown_request
Asks a teammate to gracefully exit. The teammate can approve (exits) or reject with an explanation of why it needs to continue working.
plan_approval_response
Lets the lead approve or reject a teammate's plan before implementation begins. Rejected teammates stay in plan mode and revise based on feedback.
Worktree Isolation
Each teammate gets its own git worktree via the --worktree flag. This creates a separate working directory with its own files and branch while sharing the same repository history. Agent A can rewrite src/auth.ts while Agent B rewrites the same file with a different approach. Zero interference. Changes merge back through normal git workflows.
Without worktrees, two agents editing the same file leads to overwrites regardless of coordination quality. Worktree isolation is what makes parallel orchestration safe.
Parallel Coding Workflows
Anthropic's C compiler project is the most complete public demonstration of parallel orchestration. 16 agents, each in its own Docker container with a worktree-like clone, coordinated through a central repository. Parallelism enabled specialization: one agent coalesced duplicate code, another optimized compiler performance, a third focused on efficient compiled output.
Orchestrator prompt for parallel feature implementation
Create an agent team with 3 teammates for the billing dashboard:
- Backend agent: owns src/api/billing/ and src/db/migrations/.
Create API endpoints and database schema. Commit when done.
- Frontend agent: owns src/components/billing/ and
src/app/dashboard/billing/. Blocks on backend completing
the API schema task before starting UI work.
- Test agent: owns tests/billing/. Blocks on both backend
and frontend completing their implementation tasks.
Use Sonnet for each teammate. Require plan approval
before any teammate makes changes.The key principle: each agent owns a different set of files. The backend agent never touches src/components/. The frontend agent never touches src/db/. File ownership boundaries prevent conflicts even without worktree isolation, though worktrees add a safety net.
| Metric | Single Agent | 3-Agent Team | 16-Agent Team |
|---|---|---|---|
| Token cost | 1x baseline | ~3x baseline | ~16x baseline |
| Wall-clock time | Baseline | ~40% of baseline | ~15% of baseline |
| File conflict risk | None | Low (with ownership) | Moderate (needs worktrees) |
| Coordination overhead | None | Low | Significant |
| Best for | Sequential tasks | Cross-layer features | Large-scale rewrites |
The Agent Tool Deep Dive
The Agent tool (formerly Task tool) spawns subagents within a single session. Unlike agent teams, subagents cannot talk to each other. They report results back to the parent and terminate. Each subagent starts with approximately 20,000 tokens of context overhead before your actual work begins.
Claude Code includes three built-in subagents: Explore (Haiku, read-only, for codebase search), Plan (inherited model, read-only, for planning research), and general-purpose (inherited model, all tools, for complex multi-step tasks). Custom subagents are Markdown files with YAML frontmatter stored in .claude/agents/ (project) or ~/.claude/agents/ (user-level).
Custom subagent definition
---
name: security-reviewer
description: Reviews code for security vulnerabilities
tools: Read, Grep, Glob, Bash
model: sonnet
isolation: worktree
memory: user
---
You are a security reviewer. Focus on:
- SQL injection and input validation
- Authentication and session management
- Secrets exposure and API key handling
- OWASP Top 10 vulnerabilities
Format findings by severity: Critical, Warning, Info.| Subagents (Agent Tool) | Agent Teams (Orchestrator) | |
|---|---|---|
| Communication | Report to parent only | Message each other directly |
| Context | Own window; results return to caller | Own window; fully independent |
| Coordination | Parent manages everything | Shared task list, self-coordination |
| Overhead per agent | ~20K tokens | Full session context |
| Can spawn nested agents | No (subagents cannot spawn subagents) | No (only lead manages team) |
| Best for | Quick, focused tasks | Complex parallel coordination |
CLAUDE.md and AGENTS.md as Orchestration Config
Teammates do not inherit the lead's conversation history. This is the most common mistake in multi-agent orchestration: assuming teammates know what the lead knows. They do not. Whatever context they need must come from three sources: the spawn prompt, CLAUDE.md, or AGENTS.md.
CLAUDE.md
Loaded automatically by every teammate at startup. Contains project context: tech stack, file structure, coding conventions, environment variables, build commands. This is the source of truth that all agents share.
AGENTS.md
Configures agent-specific behavior: roles, file ownership boundaries, communication protocols, escalation paths. Defines the organizational chart that shapes how agents coordinate. Some teams use this for workflow definitions (the HOW) while per-task overlays define the WHAT.
CLAUDE.md orchestration context
# Project Context for All Agents
## Tech Stack
- Next.js 15 with App Router, TypeScript, Tailwind CSS
- PostgreSQL with Drizzle ORM
- Auth: Clerk. Payments: Stripe.
## File Ownership Rules
- Backend agents: src/api/, src/lib/db/
- Frontend agents: src/components/, src/app/
- Test agents: tests/
## Communication Protocol
- Report blocking issues via SendMessage immediately
- Update task status when starting and completing work
- Use broadcast only for critical cross-cutting discoveriesContext engineering replaces prompt engineering
With multi-agent systems, the challenge is not getting agents to write code. It is ensuring each agent sees the right information at the right time. A teammate that starts work without knowing about a constraint discovered by another teammate will produce code that has to be thrown away. Put shared context in CLAUDE.md. Put agent-specific context in spawn prompts. Use SendMessage for real-time coordination.
Hooks as Coordination Primitives
Claude Code exposes 12 lifecycle hook events. For orchestration, six matter most. Hooks fire at specific moments in the agent lifecycle and can modify behavior based on exit codes: exit 0 allows the operation, exit 2 blocks it and sends feedback to the agent.
TeammateIdle
Fires when a teammate is about to go idle. Exit code 2 forces it to keep working. Use this to prevent premature completion when the shared task list still has unclaimed work.
TaskCompleted
Fires when a task is being marked complete. Exit code 2 prevents completion and sends feedback. Use this as a quality gate: run tests, check linting, verify the deliverable before accepting the task.
PreToolUse
Fires before a tool executes. Use to validate operations: block writes to protected files, enforce read-only access for reviewer agents, validate database queries are SELECT-only.
PostToolUse
Fires after a tool returns a result. Use for cleanup: run formatters after file edits, trigger test suites after code changes, log operations for audit trails.
SubagentStart
Fires when a subagent begins execution. Matcher targets specific agent types by name. Use for setup: initialize database connections, configure environment variables, prepare test fixtures.
SubagentStop
Fires when a subagent completes. Use for teardown: clean up temporary files, close connections, aggregate results across multiple subagent runs.
TaskCompleted hook as quality gate
// settings.json
{
"hooks": {
"TaskCompleted": [
{
"hooks": [
{
"type": "command",
"command": "./scripts/validate-task.sh"
}
]
}
]
}
}
// validate-task.sh reads JSON from stdin,
// runs tests, exits 0 (accept) or 2 (reject with feedback)Orchestrator Patterns
Three patterns account for most orchestration use cases. The choice depends on whether you need parallel execution, quality verification, or adversarial exploration.
Planner-Worker-Judge
The lead decomposes work into tasks with dependency graphs (planner). Teammates claim and execute tasks in their own worktrees (workers). TaskCompleted hooks enforce quality gates before accepting results (judge). This is the default orchestration pattern.
Competing Hypotheses
Multiple teammates investigate the same problem from different angles simultaneously. They challenge each other's theories via SendMessage. The theory that survives adversarial scrutiny is more likely to be the actual root cause. Prevents anchoring bias from sequential debugging.
Delegation Mode
The lead is restricted to coordination only. It cannot read code, write files, or run tests. It can only create tasks, send messages, and review results. This forces proper task decomposition and prevents the lead from doing implementation work that should go to teammates.
Competing hypotheses prompt
Users report the app exits after one message.
Spawn 5 teammates to investigate different hypotheses:
- WebSocket timeout theory
- Auth token expiration theory
- Memory pressure / OOM theory
- Race condition in message handler theory
- Client-side reconnection bug theory
Have them talk to each other to try to disprove each
other's theories. Update findings.md with whatever
consensus emerges.| Capability | Claude Code Orchestrator | Codex CLI | Cursor |
|---|---|---|---|
| Agent communication | Direct inter-agent messaging + shared tasks | Agents SDK + MCP protocol | Cloud-based subagent system |
| Max parallel agents | No hard limit (3-5 recommended) | Multiple (via Agents SDK) | Multiple (cloud-based) |
| File isolation | Git worktrees per agent | Git worktrees per agent | Cloud sandbox |
| Quality gates | TaskCompleted + TeammateIdle hooks | Custom pipeline steps | Background agent review |
| Coordination model | Shared task list + messaging | MCP + deterministic workflows | Cloud handoff |
| Cost model | Per-token (each agent has context) | Per-token | Subscription tier |
When Claude Code IS the Orchestrator vs When It's a Teammate
The same Claude Code binary serves both roles. The role is determined by whether the session creates or joins a team.
| As Orchestrator (Team Lead) | As Teammate | |
|---|---|---|
| Created by | User starts a session and requests a team | Lead spawns it with a prompt |
| Responsibilities | Decompose work, assign tasks, route messages, synthesize | Claim tasks, implement, report findings |
| Tools available | TaskCreate, SendMessage, TeammateTool + all standard tools | Standard tools + SendMessage |
| Context source | User conversation + CLAUDE.md | Spawn prompt + CLAUDE.md (no lead history) |
| File access | Full (but should use delegate mode) | Own worktree only |
| Lifecycle | Persists until user ends session | Persists until task complete or shutdown_request |
Use Claude Code as orchestrator when the task requires decomposition, parallel exploration, or quality verification across multiple agents. Use it as a single agent (no team) for sequential tasks, single-file edits, or when token cost matters. The coordination overhead of orchestration is real: 3 teammates consume roughly 3x the tokens of a single session. The benefit comes from wall-clock time savings and specialization, not token efficiency.
The 3-agent starting point
Start with 3 teammates for most workflows. Give each teammate 5-6 tasks to keep them productive without excessive context switching. If you have 15 independent tasks, 3 teammates is the right starting point. Scale up only when the work genuinely benefits from more parallelism. Three focused teammates consistently outperform five scattered ones.
Frequently Asked Questions
What does "Claude orchestrator" mean?
A Claude orchestrator is a Claude Code session acting as team lead. It decomposes work into tasks, spawns teammate agents, manages a shared task list stored as JSON files, routes typed messages between agents, and synthesizes results. The orchestrator coordinates without implementing. Enable it with CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1.
How do Claude Code agents communicate with each other?
Through three primitives: SendMessage for typed messaging (direct, broadcast, shutdown, plan approval), TaskCreate for shared work queues with dependency tracking, and worktree isolation for safe parallel file editing. Messages are stored as JSON in ~/.claude/teams/{team-name}/inboxes/ and picked up automatically.
What is the difference between a Claude orchestrator and subagents?
Subagents report results back to the parent and cannot talk to each other. An orchestrator (agent team lead) enables direct inter-agent communication through shared task lists and messaging. Use subagents for quick focused tasks where only the result matters. Use the orchestrator pattern when agents need to share findings, challenge each other, and coordinate autonomously.
How does worktree isolation work in Claude Code?
Each teammate gets its own git worktree via --worktree. This creates a separate working directory with its own files and branch while sharing the same repository history. Parallel file edits never collide. Changes merge back through normal git workflows. Without worktrees, two agents editing the same file leads to overwrites.
What hooks does Claude Code provide for orchestration?
Twelve lifecycle events. The most relevant for orchestration: TeammateIdle (force agents to keep working), TaskCompleted (quality gates before accepting work), PreToolUse/PostToolUse (validate and cleanup around tool execution), SubagentStart/SubagentStop (setup and teardown for subagent lifecycles). Exit code 2 blocks the operation and sends feedback.
How did Anthropic test orchestration at scale?
Sixteen agents built a 100,000-line Rust-based C compiler across 2,000 sessions ($20,000 in API costs). The compiler builds Linux 6.9 on x86, ARM, and RISC-V. Claude Code Review, launched March 2026, dispatches parallel agents to review pull requests. It flags problems in 84% of changes over 1,000 lines, averaging 7.5 issues per change with a false positive rate below 1%.
Orchestrating Agents Generates More Code. Apply It Reliably.
Multi-agent orchestration produces parallel code edits across multiple worktrees. Morph's Fast Apply model merges LLM-generated edits deterministically at 10,500+ tokens per second. The reliability layer your agent pipeline needs.