# How to Orchestrate Multi-Agent Workflows in Claude Code

Multi-agent Claude Code workflows coordinate specialized agent instances across parallel tasks to accelerate complex refactoring and feature development. By pairing Claude Code agent teams with git worktrees and shared workspace rooms, engineering teams eliminate race conditions and direct file overwrites. This guide demonstrates how to configure autonomous teammate roles, manage shared task lists, and synchronize deliverables through persistent cloud workspaces.

Source: https://fast.io/resources/claude-code-multi-agent-orchestration/
Last reviewed: 2026-09-08

## Comparing Subagents, Agent Teams, and Parallel Worktrees

When two Claude Code instances execute parallel tasks against the same repository, they will overwrite each other's changes, scramble intermediate states, and create merge collisions that neither session can detect on its own. The core operational problem in multi-agent orchestration is not model reasoning, it is the absence of decoupled file boundaries and a shared synchronization substrate.

Multi-agent Claude Code orchestration is the concurrent execution of multiple specialized Claude Code sessions collaborating on a shared repository via synchronized workspace state and decoupled file scopes. Rather than forcing a single prompt thread to hold an entire system architecture in memory, multi-agent execution divides complex initiatives into focused workstreams. One session architects an interface, another implements backend routes, a third updates client components, and a fourth validates the test suite.

Claude Code provides three distinct mechanisms for parallel work. Choosing the right pattern depends on task dependencies and communication requirements:

* **Subagents**: Focused worker agents dispatched inside a single parent conversation. Each subagent operates in its own isolated context window, executes a specific exploration or verification task, and returns a concise summary to the calling session. The intermediate tool calls, compiler dumps, and file reads remain inside the worker's temporary context, protecting the main thread from context exhaustion.
* **Agent Teams**: A coordinated collection of full Claude Code sessions managed by an autonomous team lead. Enabled through the `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` flag, teammates operate with independent context windows, communicate directly via peer mailboxes, and self-claim tasks from a shared task list. Teammates can challenge each other's findings, propose competing hypotheses, and synchronize status without routing every interaction through the user. Review the [Claude Code documentation on agent teams](https://code.claude.com/docs/en/agent-teams) for specific flag specifications.
* **Parallel Sessions in Git Worktrees**: Fully independent terminal sessions launched manually or via scripts, isolated into dedicated working directories through the `--worktree` flag. Each session operates on its own branch and file tree while sharing repository history and remote pointers. Consult the [git worktree documentation](https://git-scm.com/docs/git-worktree) for underlying repository mechanics.

| Execution Model | Context Isolation | Communication Mechanism | File System Boundary | Primary Operational Fit |
| :--- | :--- | :--- | :--- | :--- |
| **Subagents** | Isolated context; summary returns to caller | Parent-child request and response | Shared working directory or isolated worktree | Targeted research, file discovery, or localized test execution |
| **Agent Teams** | Fully independent context per teammate | Peer-to-peer mailboxes and shared task list | Shared working directory by default | Multi-layered feature builds, competing bug hypotheses, code reviews |
| **Parallel Worktrees** | Separate sessions across terminals | Optional cross-session messaging over local sockets | Dedicated filesystem directory and branch per session | Large independent refactors, long-running migrations, multi-repo tasks |

Most failed multi-agent experiments stem from running agent teams directly against a single local checkout without file boundaries. Because teammates in an agent team share the active working tree by default, two teammates modifying overlapping modules will corrupt each other's work mid-turn. Reliable multi-agent orchestration requires pairing session-level task coordination with strict filesystem isolation and a persistent workspace layer for non-code artifacts.

## How to Initialize and Control Claude Code Agent Teams

Claude Code agent teams coordinate multiple autonomous instances working under a unified team lead. The lead session decomposes high-level requests into discreet tasks, tracks dependencies, assigns responsibilities, and synthesizes final deliverables.

Follow these seven steps to initialize an agent team with isolated task boundaries and structured workspace synchronization:

1. **Enable experimental agent teams**: Set the environment variable `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` in your shell configuration or within `~/.claude/settings.json`.
2. **Define specialized teammate roles**: Author subagent definitions in `.claude/agents/` to preconfigure role prompts, model tiers, and tool restrictions.
3. **Launch the team lead session**: Start Claude Code in interactive mode from your project root.
4. **Enter plan mode for initial decomposition**: Switch the lead session to plan mode before spawning workers so architecture and task boundaries are verified prior to code edits.
5. **Spawn the team with explicit scope**: Prompt the lead to instantiate named teammates with distinct responsibilities (such as architect, backend developer, frontend developer, and test engineer).
6. **Select the terminal display mode**: Choose between in-process terminal cycling and split panes (using tmux or iTerm2) based on your monitoring needs.
7. **Monitor the shared task list**: Track progress as teammates claim unblocked tasks, exchange peer messages, and post completion notices.

### Enabling Agent Teams

Agent teams are disabled by default. To enable them across your projects, add the flag to your user settings:

```json
{
  "env": {
    "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
  }
}
```

When agent teams are enabled, any named subagent invoked by Claude Code launches as a full teammate rather than a basic subagent. Spawning teammates requires an interactive terminal session; non-interactive runs with the `-p` flag will fall back to standard subagents.

### Choosing a Display Mode

Claude Code supports two operational display modes for agent teams:

* **In-process mode (default)**: All teammates execute inside your primary terminal window. Use the up and down arrow keys in the agent panel below the prompt input to highlight a specific teammate, press `Enter` to open that teammate's transcript, and type to send direct instructions. Press `x` to stop a selected worker, and press `Ctrl+T` to toggle the shared task view.
* **Split-pane mode**: Each teammate runs in its own visible pane, allowing you to observe parallel execution in real time. This mode requires either tmux or iTerm2 with the `it2` CLI.

To set split-pane mode automatically whenever tmux is active, configure your settings:

```json
{
  "teammateMode": "auto"
}
```

Alternatively, pass the flag at launch:

```bash
claude --teammate-mode auto
```

### Enforcing Plan Mode Before Implementation

Unsupervised parallel agents can write hundreds of lines of code before an architectural flaw is noticed. To prevent premature implementation, place the team lead in plan mode before asking for teammates:

```text
/plan
```

Once in plan mode, instruct the lead to spawn planning teammates:

```text
Spawn an architect teammate to design the database migration schema and an API specialist to draft endpoint specifications. Have them plan their approaches and coordinate dependencies before any files are modified.
```

Teammates spawned while the lead is in plan mode operate in read-only analysis mode. When a teammate finishes its technical plan, it transmits a plan approval request back to the lead. The lead approves the plan, allowing the teammate to exit plan mode and begin execution.

## How to Eliminate Race Conditions with Git Worktrees

The primary vulnerability in multi-agent workflows is the shared working directory. In a default agent team, every teammate executes commands within the same checkout. If teammate A refactors an authentication function inside `src/auth/session.ts` while teammate B updates imports across `src/auth/session.ts`, the second agent will overwrite the first agent's edits mid-stream, breaking the syntax tree and producing confusing test failures.

Eliminating race conditions requires decoupling the file scopes using git worktrees. A git worktree is a linked working tree that shares the repository's `.git` metadata and branch history but lives in a separate directory on disk.

### Launching Isolated Parallel Sessions

You can launch independent Claude Code sessions in isolated worktrees using the `--worktree` (or `-w`) flag:

```bash
claude --worktree feature-auth-backend
```

Claude Code automatically creates a linked working tree at `.claude/worktrees/feature-auth-backend/` on a new branch named `worktree-feature-auth-backend`. Running a second command in another terminal tab isolates the next agent:

```bash
claude --worktree feature-auth-ui
```

Add `.claude/worktrees/` to your project's `.gitignore` to keep worktree directories from appearing as untracked files in your primary checkout.

### Automated Environment Replication with Worktreeinclude

Because a fresh worktree contains only tracked files, untracked configuration like local environment variables, API secrets, and local certificates are missing. To replicate these files automatically whenever Claude Code provisions a worktree, create a `.worktreeinclude` file in your repository root:

```text
.env
.env.local
config/secrets.json
```

Claude Code evaluates `.worktreeinclude` using standard gitignore patterns, copying matching untracked files directly into every newly spawned worktree.

### Enforcing Worktree Isolation on Subagents

When creating reusable subagents for your team, you can enforce worktree isolation directly in the agent's frontmatter definition inside `.claude/agents/`:

```markdown
---
name: schema-migrator
description: Applies database migrations and validates table schemas
tools: Read, Write, Edit, Bash, Glob, Grep
model: sonnet
isolation: worktree
---

Execute the requested database schema changes in your isolated worktree.
Verify all migrations against the local test database before committing.
```

When Claude Code spawns a subagent configured with `isolation: worktree`, it provisions a dedicated temporary worktree for that run. Claude Code enforces four strict safety boundaries on isolated workers:

* **File writes**: Edits and writes targeting paths in the primary repository checkout are blocked.
* **Working directory validation**: Shell commands that resolve to or move into the parent checkout are refused.
* **Git redirection blocking**: Commands attempting to redirect git operations to the main checkout using `git -C` or `--git-dir` are intercepted.
* **Command shape inspection**: Shell syntax that obscures the execution target is rejected until rewritten cleanly.

### Cross-Session Messaging Across Worktree Boundaries

When running parallel sessions across worktrees, agents must still communicate milestones, such as notifying a frontend session when a backend API schema has landed. Claude Code provides cross-session messaging using Unix domain sockets (or named pipes on Windows), exposed via the `CLAUDE_CODE_MESSAGING_SOCKET` environment variable.

Claude Code discovers live peers using the `ListAgents` tool and delivers notifications using `SendMessage`. An agent in one worktree can message another directly:

```text
Let @feature-auth-ui know that the authentication endpoints have been implemented and committed on branch worktree-feature-auth-backend.
```

The message arrives in the recipient session as an unblock notice between tool turns, allowing parallel sessions to coordinate without touching each other's disk files.

## Why Multi-Agent Workflows Require Persistent Coordination Rooms

Local terminal messaging and git branches resolve source code isolation on a single developer machine. However, production software development requires coordinating non-code artifacts across multi-agent pipelines: architecture decision records, database migration dumps, OpenAPI schemas, performance benchmarks, and human sign-off briefs.

When parallel Claude Code instances finish tasks, their outputs often remain stranded inside ephemeral worktrees or local scratch paths. Teammates running on other computers, automated CI agents, or peer tools like Codex and Cursor cannot inspect those assets.

Bridging this gap requires a shared workspace layer. Consumer file sharing tools such as Google Drive, Dropbox, or Box were designed for human file sync rather than autonomous agent pipelines. Background sync daemons lock files unpredictably during rapid writes, rate-limit automated API requests, and lack structured Model Context Protocol (MCP) connectivity.

[Fast.io Coordination Rooms](/product/rooms/) provide neutral ground for multi-agent workflows. A Coordination Room is a persistent, shared workspace where agents running in Claude Code, Codex, Cursor, or custom scripts post messages, exchange files, and hand off deliverables, while human engineers maintain visibility, set direction, and review work. Explore the developer architecture in the guide to [storage for AI agents](/storage-for-agents/).

```
+-----------------------------------------------------------------------+
|                       Fast.io Coordination Room                       |
|          Persistent Workspace, Version History, Audit Log            |
+-----------------------------------------------------------------------+
              ^                            ^                       ^
              | (MCP /mcp)                 | (MCP /mcp)            | (Web UI)
              v                            v                       v
+----------------------------+  +--------------------+  +---------------+
| Claude Code: Lead Session  |  | Claude Code Worker |  | Human Lead    |
| (Architect / Plan Mode)    |  | (Backend / Tests)  |  | (Review & Dir)|
+----------------------------+  +--------------------+  +---------------+
```

### Neutral Ground for Heterogeneous Agents

Modern engineering teams rarely rely on a single agent framework. A common setup pairs Claude Code for terminal refactoring with Codex for automated code reviews and Python scripts for data extraction. Fast.io serves as the common substrate for all of them through a remote MCP endpoint:

* **Streamable HTTP Endpoint**: Fast.io provides remote MCP connectivity at `https://mcp.fast.io/mcp`, as well as authenticated access at `https://mcp.fast.io/mcp/key` using Bearer tokens. Review `https://fast.io/llms.txt` for machine-readable connection details.
* **Zero Local Dependencies**: Because the MCP server is hosted remotely, agents do not need local package managers, Python runtimes, or Node daemons to access workspace storage.
* **Standardized Tools**: Agents interact using action-based MCP tools to read files, write deliverables, search workspace context, and post updates into coordination rooms. Read the tool definitions in `https://mcp.fast.io/skill.md` or review the [storage for AI agents](/storage-for-agents/) overview.

To connect your Claude Code sessions to a Fast.io Coordination Room, declare the server in your project's `.mcp.json`:

```json
{
  "mcpServers": {
    "fastio": {
      "type": "http",
      "url": "https://mcp.fast.io/mcp/key",
      "headers": {
        "Authorization": "Bearer YOUR_FASTIO_API_KEY"
      }
    }
  }
}
```

### Tangible Artifact Handoffs

Instead of treating an agent handoff as an ephemeral terminal log, multi-agent pipelines structure handoffs as concrete file deliverables inside a shared room.

Consider an API refactor workflow:

1. The **Lead Architect** drafts an interface contract and uploads `specs/auth-v2.json` to the Fast.io workspace room via MCP.
2. The **Backend Teammate** reads `specs/auth-v2.json` directly from the [Fast.io workspaces](/product/workspaces/) layer, implements the endpoint logic in its local worktree, and uploads an execution log with test results to `artifacts/backend-test-results.json`.
3. The **Frontend Teammate** receives notification of the uploaded spec, pulls the interface definitions, and constructs corresponding UI forms.
4. A **Human Engineer** inspects the versioned artifacts in the Fast.io web interface, comments on the specification, and approves the deployment.

### Version History and Audit Trails

When multiple autonomous agents write to a shared repository or storage bucket, tracking provenance is essential. Fast.io automatically maintains per-file version history for every write. If an agent writes a flawed schema or overwrites a critical specification, prior versions can be inspected and restored instantly.

Every action taken by an agent or human is permanently recorded in an append-only audit log. The audit log records which agent ID modified a file, the exact timestamp, and the target workspace path. This auditability ensures engineering teams maintain strict governance over automated agent activities without impeding development speed.

Access is governed by granular permissions scoped at the organization, workspace, folder, and file level. Coordination room invite links can be restricted to specific team members and set to expire after designated time windows.

Every organization starts with a 14-day free trial, which requires a credit card. | Plans are Starter at $29/mo, Business at $99/mo, and Growth at $299/mo. Detailed tier breakdowns and seat allowances can be verified on the [Fast.io pricing](/pricing/) page.

## Steps to Coordinate Full-Stack Refactoring with Specialized Roles

To illustrate multi-agent orchestration in practice, consider a complete full-stack refactoring workflow. In this scenario, an engineering team refactors an authentication system from single-tenant passwords to multi-tenant organization switching.

The team coordinates four specialized roles across decoupled file scopes and a shared Fast.io Coordination Room:

* **Architect (Team Lead)**: Decomposes tasks, designs interface contracts, and enforces quality gates.
* **Backend Engineer**: Implements database schema updates and API handlers in an isolated worktree.
* **Frontend Engineer**: Builds UI components and state management hooks in an isolated worktree.
* **Integration Tester**: Executes end-to-end test suites and publishes test coverage reports.

```
+-------------------------------------------------------------------------+
|                     Team Lead (Interactive Session)                     |
|             1. Define tasks & post contracts to Fast.io Room           |
+-------------------------------------------------------------------------+
                   |                                  |
                   v                                  v
+-----------------------------------+  +----------------------------------+
|      Backend Teammate             |  |      Frontend Teammate           |
|  Worktree: .claude/worktrees/api  |  |  Worktree: .claude/worktrees/ui  |
|  - Migrates database models       |  |  - Builds workspace picker       |
|  - Pushes schema to Fast.io       |  |  - Subscribes to API schema      |
+-----------------------------------+  +----------------------------------+
                   \                                  /
                    v                                v
+-------------------------------------------------------------------------+
|                       Integration Test Teammate                         |
|                 - Pulls branches & runs test suites                     |
|                 - Uploads audit report to Fast.io Room                  |
+-------------------------------------------------------------------------+
```

### Phase 1: Planning and Contract Definition

The human developer launches Claude Code and initiates plan mode:

```text
/plan
I need to refactor our authentication system to support multi-tenant organization switching.
1. Analyze our existing session handling in src/auth/.
2. Draft an OpenAPI specification for organization switching endpoints.
3. Save the specification to our Fast.io workspace under /contracts/auth-v2.yaml using MCP.
4. Break down implementation tasks for backend and frontend teammates.
```

The lead evaluates the codebase, writes `auth-v2.yaml`, and uploads it to the Fast.io Coordination Room. Because the specification lives in a central workspace, every subsequent agent and human reviewer references the identical contract.

### Phase 2: Parallel Worktree Implementation

With the plan established, the lead populates the task list and assigns implementation roles. The backend teammate and frontend teammate operate concurrently in isolated git worktrees. Launch the backend worker in its dedicated directory:

```bash
claude --worktree auth-backend-service
```

In a separate terminal window, launch the frontend worker:

```bash
claude --worktree auth-frontend-ui
```

The backend agent implements the database migration, updates the user model, and exposes the tenant switching endpoint. Once local tests pass, the backend agent commits to its branch (`worktree-auth-backend-service`) and uses `SendMessage` to notify the frontend agent:

```text
SendMessage to @auth-frontend-ui: Backend endpoints verified on branch worktree-auth-backend-service. Updated OpenAPI contract uploaded to Fast.io workspace.
```

Meanwhile, the frontend agent consumes the contract from the Fast.io workspace, implements the organization switcher dropdown, and updates client-side session tokens in `src/components/OrgSwitcher.tsx`. Because both agents work in separate worktree directories, neither agent experiences git lock collisions or file overwrite conflicts.

### Phase 3: Enforcing Quality Gates with Hooks

To prevent agents from marking tasks complete prematurely, the team configures Claude Code hooks in `.claude/settings.json`:

```json
{
  "hooks": {
    "TaskCompleted": [
      {
        "type": "command",
        "command": "npm test"
      }
    ],
    "TeammateIdle": [
      {
        "type": "command",
        "command": "npm run lint"
      }
    ]
  }
}
```

When a teammate attempts to mark a task as complete, the `TaskCompleted` hook executes the test suite. If the tests fail, the hook exits with status code 2, rejecting task completion and feeding the compiler errors back into the teammate's context to trigger automated fixes.

### Phase 4: Synthesis and Deliverable Handoff

Once all tasks on the shared task list are marked complete, the integration tester runs the full end-to-end test suite against both branches. The tester compiles a markdown verification summary and uploads it to the Fast.io Coordination Room along with test logs.

The team lead requests graceful teammate shutdowns:

```text
Ask the backend, frontend, and integration teammates to shut down.
```

Each teammate completes pending I/O operations and exits gracefully. The human lead reviews the branch diffs, inspects the verification report in the Fast.io Coordination Room, and merges the completed feature branches into main.

## How to Troubleshoot and Safeguard Multi-Agent Claude Code Sessions

Running multi-agent Claude Code workflows introduces distinct failure modes that do not occur in single-agent terminal sessions. Understanding these failure states ensures your orchestration remains stable.

### Lagged Task Status and Stalled Workers

Teammates occasionally complete their code modifications but fail to mark their assigned task as finished in the shared task list. Because dependent tasks remain blocked until prerequisites complete, this causes dependent teammates to sit idle.

* **Diagnosis**: Check the task list by pressing `Ctrl+T` in the lead session. If a task shows `in_progress` while its assigned teammate is idle, the worker missed the completion call.
* **Remedy**: Message the teammate directly by selecting its row in the agent panel and pressing `Enter`. Instruct it explicitly: `Mark task #3 as completed.` Alternatively, instruct the team lead: `Update task #3 to completed and unblock the frontend teammate.`

### In-Process Session Resumption Limitations

Claude Code supports session resumption via `/resume` and `--continue` for standard conversations. However, in-process teammates are ephemeral and do not persist across session restarts.

If you terminate the team lead session and later resume it, the lead's conversation history may contain references to teammates that no longer exist on disk. Attempting to message those teammates will result in delivery errors.

To recover:
1. Launch the resumed session.
2. Instruct the lead: `Previous teammates have exited. Clear stale member records and spawn new teammates for remaining incomplete tasks.`
3. The lead reads the persisted task list from `~/.claude/tasks/{team-name}/` and reassigns incomplete work items to newly spawned workers.

### Managing Stale Worktree Locks and Tmux Panes

If a background agent terminates unexpectedly during a system reboot or shell interruption, it can leave behind locked git worktrees or detached tmux sessions.

* **Releasing worktree locks**: If git refuses to remove an abandoned worktree with the error `fatal: '...' is locked`, run:
 

```bash
  git worktree unlock .claude/worktrees/stale-branch-name
  git worktree remove .claude/worktrees/stale-branch-name --force
 

```
* **Cleaning orphaned tmux sessions**: List active sessions and kill orphaned agent panes:
 

```bash
  tmux ls
  tmux kill-session -t claude-team-session-id
 

```

### Controlling Token Consumption and Cache Windows

Multi-agent sessions consume tokens rapidly because each teammate maintains an independent context window. When five teammates ingest a large codebase simultaneously, token consumption multiplies by five.

To optimize token economy:

* **Route lightweight tasks to smaller models**: In subagent definitions or spawn instructions, assign exploratory and verification tasks to `haiku` while reserving `sonnet` or `opus` for architectural reasoning.
* **Extend prompt cache TTL**: In-process teammates operate outside the primary conversation's cache bucket, defaulting to a five-minute cache TTL. If your teammates work on long-running tasks, set `subagentPromptCacheTtl` to `1h` in your settings to keep cached repository context warm across turns. Note that 1-hour cache writes incur higher initial write rates on the API.
* **Scope repository context**: Keep `CLAUDE.md` concise and modular. Teammates automatically load `CLAUDE.md` on startup; bloated guidelines consume thousands of tokens on every teammate instantiation.

## Frequently asked questions

### Can Claude Code run multiple agents simultaneously?

Claude Code can run multiple agents simultaneously through three distinct patterns. Subagents execute focused tasks inside a single session and return summaries. Agent teams allow a lead session to spawn and supervise multiple autonomous teammates that communicate through peer mailboxes and a shared task list. Parallel sessions in git worktrees let developers run independent Claude Code instances in separate terminal tabs with isolated file trees.

### How do you coordinate multiple Claude Code instances on one codebase?

Coordinating multiple Claude Code instances requires decoupling file scopes and synchronizing task state. Use git worktrees (`claude --worktree <name>`) so each session operates on an independent branch and directory, preventing file overwrite collisions. Coordinate high-level progress using cross-session messaging over local domain sockets, and store shared artifacts, schemas, and research briefs in a centralized Fast.io Coordination Room accessible via remote MCP.

### What is the difference between Claude Code subagents and multi-agent sessions?

Claude Code subagents are lightweight workers spawned inside a single conversation that execute a task in an isolated context window and return a summary to the caller. Multi-agent sessions, such as agent teams or parallel worktree instances, are full, independent Claude Code processes with their own execution environments, capable of peer-to-peer messaging, independent tool usage, and parallel file modifications.

### How do you prevent file race conditions when running parallel Claude Code sessions?

To prevent file race conditions, isolate each parallel agent inside a dedicated git worktree using the `--worktree` flag or by setting `isolation: worktree` in subagent definitions. This ensures each agent writes to its own isolated filesystem branch. For agent teams operating in a single checkout, partition task assignments so no two teammates modify the same files concurrently.

### How does Fast.io support multi-agent Claude Code workflows?

Fast.io provides a neutral collaboration room where multiple Claude Code instances, peer agents like Codex or Cursor, and human developers coordinate. Connected via a remote MCP endpoint (`https://mcp.fast.io/mcp`), Fast.io stores shared specifications, schemas, and test deliverables with per-file version history, granular permissions, and an append-only audit trail.

## About Fast.io

Fast.io provides shared workspaces where people and AI agents work on the same files, with built-in semantic search and citation-backed chat over what they hold. Agents reach it through a remote MCP server at https://mcp.fast.io/mcp, a REST API at https://api.fast.io/current/, and a command line client published on npm as @vividengine/fastio-cli.
