Claude Code Git Worktree: How Parallel Agents Actually Work

A technical deep-dive into how Claude Code uses git worktrees to run parallel agents in isolation. Full lifecycle, communication protocol, merge strategy, and comparison with Codex and Cursor.

March 3, 2026 · 1 min read

Claude Code uses git worktrees to run multiple agents in parallel without file collisions. Each agent gets its own isolated branch and working directory, shared task list, and direct messaging. This is how the whole system works under the hood.

TL;DR

A git worktree is a second (or third, or fifth) working directory linked to the same repository. Claude Code creates one per parallel agent. Each agent writes to its own directory, checks out its own branch, and operates against a shared git object store. They share history but not file state.

When agents finish, branches get merged back manually or discarded. If agents edited different files, merges are clean. If they edited the same file, you get a standard three-way merge conflict.

The coordination layer runs entirely on disk: a shared task list of JSON files, a mailbox for peer-to-peer messages, and file locking to prevent two agents from claiming the same task simultaneously.

Experimental Feature

Agent teams (the multi-agent coordination layer) are experimental and disabled by default. Enable with CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 in settings.json or your shell environment. Git worktrees themselves (single-agent isolation) are stable.

What Are Git Worktrees?

A standard git repository has one working tree: one set of files on disk, one active branch, one staging index. When you run git checkout feature-branch, git swaps out the files in that single working tree.

Git worktrees extend this. The git worktree add command creates an additional working directory that checks out a different branch while sharing the same .git database — same object store, same refs, same remotes. You can have five branches checked out simultaneously in five directories, all pointing to the same history.

Basic git worktree commands

# Create a worktree at ../project-feature-auth checking out a new branch
git worktree add ../project-feature-auth -b feature-auth

# Create a worktree from an existing branch
git worktree add ../project-bugfix bugfix-123

# List all active worktrees
git worktree list
# /home/user/project              abc1234 [main]
# /home/user/project-feature-auth def5678 [feature-auth]
# /home/user/project-bugfix       ghi9012 [bugfix-123]

# Remove a worktree when done
git worktree remove ../project-feature-auth

Each worktree has its own .git file (not a directory) that contains a pointer back to the main .git directory. Tools that only look for .git will find it and work correctly. Each worktree also has its own index and HEAD, so staging and committing in one doesn't affect others.

One important constraint: you cannot check out the same branch in two worktrees simultaneously. Git tracks which worktree has which branch locked, and rejects duplicate checkouts. This is by design — it prevents the kind of state corruption that would happen if two processes wrote to the same index.

How Claude Code Uses Worktrees for Parallel Agents

Claude Code wraps git's worktree machinery with two additional behaviors: automated creation and cleanup, and integration with the agent coordination layer.

The --worktree Flag

Pass --worktree <name> (or -w <name>) when starting Claude. It creates a worktree at .claude/worktrees/<name> with a branch named worktree-<name>, then starts Claude with its working directory set to that path.

Starting Claude in isolated worktrees

# Worktree for a feature — creates .claude/worktrees/feature-auth/
claude --worktree feature-auth

# Worktree for a bugfix in a separate terminal
claude --worktree bugfix-payments

# Auto-generate a name (e.g., "bright-running-fox")
claude --worktree

# Same flag, short form
claude -w feature-auth

Worktrees branch from the default remote branch (usually main or master). If you want to branch from somewhere else, create the worktree manually with git worktree add and start Claude from that directory.

Subagent Worktree Isolation

Subagents can also run in isolated worktrees. You can request this conversationally ("use worktrees for your agents") or configure it in a custom subagent definition.

Subagent with worktree isolation (.claude/agents/refactor-agent.md)

---
name: refactor-agent
description: Refactors a module in isolation without affecting the main branch
tools: Read, Write, Edit, Bash, Glob, Grep
model: sonnet
isolation: worktree
---

You are a refactoring specialist. Work in your isolated worktree.
Complete the refactor, run tests, commit, and report back.
Do not push — the team lead will review your branch.

With isolation: worktree set, each invocation of this subagent gets its own worktree. When the subagent finishes without making changes, the worktree and its branch are removed automatically. This makes throwaway research subagents cheap: they spin up, search the codebase, and disappear.

Storage Layout

Claude stores worktrees inside the repository under .claude/worktrees/. The official docs recommend adding this to .gitignore to prevent worktree checkouts from showing up as untracked files in the main repository.

Add to .gitignore

.claude/worktrees/

Agent Lifecycle: Spawn to Merge

Here is the full sequence from team creation to merged branches.

Step 1: Enable Agent Teams

settings.json

{
  "env": {
    "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
  }
}

Step 2: Team Lead Creates the Team

Tell Claude to create an agent team in natural language. The lead uses the TeamCreate tool internally, which creates a team config at ~/.claude/teams/<team-name>/config.json and initializes a task directory at ~/.claude/tasks/<team-name>/.

Team creation prompt

Create an agent team to add rate limiting to the API.
Spawn three teammates:
- backend: implement the rate limiting middleware
- tests: write integration tests for the new middleware
- docs: update the API documentation

Use worktrees so each teammate works in isolation.

Step 3: Tasks Are Created and Assigned

The lead creates tasks using TaskCreate. Each task is a JSON file in ~/.claude/tasks/<team-name>/. Tasks have a subject, description, status (pending, in_progress, completed), and optional dependency links.

Task dependency chain

Task 1: Implement rate limiting middleware     [pending]
Task 2: Write integration tests               [pending, blocked by Task 1]
Task 3: Update API docs                       [pending, can run in parallel]

Step 4: Teammates Claim Work with File Locking

Each teammate calls TaskList to find available tasks, then TaskUpdate to set status to in_progress and set the owner field. This write uses file locking to prevent two agents from claiming the same task simultaneously — last writer wins is not the behavior here.

When Task 1 completes, the dependency system unblocks Task 2 automatically. The tests teammate doesn't need to poll or wait — it will see Task 2 available the next time it calls TaskList.

Step 5: Parallel Work in Isolated Worktrees

With worktrees active, each teammate's working directory is .claude/worktrees/<teammate-name>/. The backend agent writes to its directory. The docs agent writes to its directory. Their file writes never touch each other.

Filesystem state during parallel work

project/                          # main worktree (team lead)
project/.claude/worktrees/
  backend/                          # teammate 1's isolated checkout
    src/middleware/rate-limit.ts    # new file — only visible here
    worktree-branch: worktree-backend
  tests/                            # teammate 2's isolated checkout
    src/middleware/rate-limit.test.ts
    worktree-branch: worktree-tests
  docs/                             # teammate 3's isolated checkout
    docs/api-reference.md           # updated — only visible here
    worktree-branch: worktree-docs

Step 6: Agents Commit and Report

Agents commit to their worktree branches normally. When done, they mark their tasks completed and send the team lead a message with branch names and a summary of what changed.

Step 7: Team Lead Merges Branches

The lead merges each worktree branch back to main. If the branches touched different files (which they should, given proper task assignment), all merges are clean. Then the lead cleans up the team.

Merging worktree branches

# From the main worktree
git merge worktree-backend    # adds rate-limit.ts
git merge worktree-tests      # adds rate-limit.test.ts
git merge worktree-docs       # adds doc changes

# Remove worktrees after merge
git worktree remove .claude/worktrees/backend
git worktree remove .claude/worktrees/tests
git worktree remove .claude/worktrees/docs

Communication Protocol

The entire coordination layer runs on disk. No message broker. No database. No network calls. Two mechanisms: the task list and the mailbox.

Task List: The Coordination Backbone

Tasks live at ~/.claude/tasks/<team-name>/. Each task is a JSON file. The schema includes id, subject, description, status, owner, blockedBy, and blocks arrays. Agents poll this directory to find work.

Task JSON structure

{
  "id": "task-3",
  "subject": "Implement rate limiting middleware",
  "description": "Add express-rate-limit to src/middleware/. Limit: 100 req/min per IP. Return 429 with Retry-After header.",
  "status": "in_progress",
  "owner": "backend",
  "blocks": ["task-4"],
  "blockedBy": [],
  "activeForm": "Implementing rate limiting"
}

TaskCreate / TaskUpdate / TaskList: The API

Agents interact with the task system through three tools:

  • TaskCreate: write a new JSON file to the task directory with status pending.
  • TaskUpdate: update fields in an existing task file (status, owner, blocks, blockedBy). Uses file locking.
  • TaskList: read all task files in the directory and return a summary. Agents check this before claiming work.

Mailbox: Direct Agent Messaging

The team config at ~/.claude/teams/<team-name>/config.json contains a members array with each teammate's name and agent ID. Agents use this to discover each other.

The SendMessage tool delivers a message directly to a specific teammate's inbox. Message delivery is automatic — recipients don't poll. There's also a broadcast mode for team-wide announcements, but the docs explicitly warn it's expensive: N teammates = N separate message deliveries.

SendMessage usage (agent perspective)

// Direct message to team lead
SendMessage({
  type: "message",
  recipient: "team-lead",
  content: "Rate limiting middleware complete. Branch: worktree-backend. Added express-rate-limit@7.2.0. Tests pass locally.",
  summary: "Rate limiting implementation complete"
})

// Shutdown response
SendMessage({
  type: "shutdown_response",
  request_id: "abc-123",
  approve: true
})

Idle Notifications

When a teammate finishes work and goes idle, it automatically sends the team lead a notification. The lead doesn't have to poll — it gets an interrupt when any teammate stops. This is the mechanism that lets the lead synthesize results as they arrive rather than waiting for everyone to finish.

Three Patterns for Parallel Work

Three configurations cover most real-world use cases. The right choice depends on whether agents need to communicate with each other.

Pattern A: Parallel Independent (Manual Worktrees)

You run multiple Claude sessions manually. Each gets its own worktree via the --worktree flag. No agent team. No coordination layer. You act as the coordinator — you start each session, monitor them yourself, and merge branches yourself.

Best for: working on three unrelated features simultaneously where you want full control. Low overhead. No experimental features.

Pattern A: Three independent sessions

# Terminal 1
claude --worktree feature-auth
> Add OAuth2 login to the auth module

# Terminal 2
claude --worktree bugfix-payments
> Fix the null pointer in the payment processor

# Terminal 3
claude --worktree docs-update
> Update the README with the new deployment steps

Pattern B: Full Agent Team (Coordinated)

A team lead spawns multiple teammates, assigns tasks, and coordinates via the shared task list and mailbox. Agents report to each other directly. The lead synthesizes results.

Best for: complex features that need parallel exploration with cross-agent communication — competing hypotheses, security + performance + tests all reviewing the same PR simultaneously, or large migrations where agents can question each other's approaches.

Pattern B: Agent team with coordination

Create an agent team to investigate why the checkout flow is slow.
Spawn 3 teammates:
- database: profile slow queries in the checkout path
- frontend: check bundle size and render timing
- network: audit API response times and payload sizes

Have them share findings with each other and challenge each other's
theories. Update findings.md with whatever consensus emerges.

Pattern C: Subagent Research Pool (Read-Only)

The team lead spawns multiple read-only subagents in isolated worktrees for parallel research. Each subagent searches a different aspect of the codebase. Results return to the lead. Worktrees auto-clean because no changes were made.

Best for: understanding a large, unfamiliar codebase quickly. Ten read-only subagents exploring ten different subsystems in parallel is dramatically faster than one agent reading sequentially.

Pattern C: Parallel research subagents

I need to understand the payment system before refactoring it.
Use worktrees for your agents.
Spawn 4 research agents:
- one traces the checkout flow from frontend to database
- one maps all external payment API calls
- one identifies all error handling paths
- one finds all places that touch the Order model

Each agent reads only. Compile their findings into a single
architecture doc.
PatternCoordinationAgent CommunicationBest For
Parallel IndependentManual (you)NoneUnrelated features, full control
Full Agent TeamAutomated task list + mailboxDirect peer-to-peerComplex tasks needing cross-agent discussion
Subagent Research PoolLead spawns subagentsResults back to lead onlyParallel codebase exploration

Worktree vs Cloud Sandbox vs Background Agent

Claude Code, Codex, and Cursor all run multiple parallel agents, but their isolation models are fundamentally different.

PropertyClaude Code (Worktrees)Codex (Cloud Sandboxes)Cursor (Background Agents)
Where agents runLocal machineCloud containersCloud (Cursor servers)
Isolation mechanismGit worktree per agentSeparate container per taskIsolated cloud worktrees
Network access during agent workFull (your machine)Disabled by defaultLimited
Local tool accessYes — your shell, scripts, envNoNo
Codebase copyGit worktree checkoutFull repo clone per taskWorktree per agent
Merge strategyManual git mergeManual review + mergeDiff review UI
Agent communicationMailbox + task listNot nativeLimited
Max parallel agentsNo hard limit (resource-bound)Depends on planUp to 8 (Cursor v2.5)
Cost modelClaude API tokens onlyCodex subscriptionCursor subscription

Why Local Worktrees Beat Cloud Sandboxes for Most Workflows

Codex's cloud sandboxes are the more isolated option — no network access, full container separation, harder to break out of. If you're running untrusted code or need strong security guarantees, that matters.

For typical development work, local worktrees win on capability. Agents can run your actual test suite. They can call local services. They can access your environment variables, scripts, and build tools. A Claude Code agent running in a worktree can run npm test against your real local database. A Codex sandbox agent cannot.

Cursor's cloud agents are closer to Codex — remote, isolated, limited access. The tradeoff is the diff review UI, which makes it easy to inspect and selectively accept agent changes.

The Storage Location Difference

Claude Code agent teams store state locally: team config in ~/.claude/teams/, tasks in ~/.claude/tasks/, worktrees in .claude/worktrees/ inside the repo. Everything is readable with standard unix tools. No opaque state in external services.

Merge Conflicts and Resolution

The Root Cause: File Overlap

Parallel agents in separate worktrees produce separate branches. Merging two branches that touched the same file in different ways produces a conflict. This is standard git — no different from two human developers editing the same file on separate branches.

The difference with AI agents is volume: an agent might touch 40 files in a single session. If you spawned four agents and didn't plan file ownership carefully, you might have 20 conflicting files to resolve.

Prevention: Assign File Ownership Upfront

The most effective strategy is preventing conflicts before agents start. When creating tasks, explicitly partition the codebase:

Task assignment with explicit file ownership

Create tasks for migrating from Express to Fastify:
- routes-agent: owns src/routes/**  only
- middleware-agent: owns src/middleware/**  only
- tests-agent: owns src/**/*.test.ts  only (read src/routes, src/middleware)
- docs-agent: owns docs/**  only

Each agent should not touch files owned by other agents.
If a change requires cross-boundary edits, block the task on
the owning agent completing their work first.

Detection: Clash and git merge-tree

Clash is an open-source tool that detects conflicts between worktrees before they happen. It runs git merge-tree (three-way merge simulation) between all worktree pairs without touching your working directories. If Clash finds a conflict, it warns before the agent writes the file — not after.

Clash integration with Claude Code hooks

# Clash hooks into Claude Code's PreToolUse event
# Before any file write, it checks if the target file
# conflicts with another active worktree

# Manual check:
clash check --worktrees .claude/worktrees/

# Output example:
# CONFLICT: src/auth/middleware.ts
#   worktree-backend wants to modify lines 45-67
#   worktree-auth also modified lines 52-60
#   Run: git merge-tree main worktree-backend worktree-auth

Resolution: Standard git Workflow

When conflicts do occur, resolve them after agents finish with the standard merge workflow. The advantage of worktrees: each branch is clean and complete. You're merging well-defined units of work, not half-finished edits.

Conflict resolution workflow

# Merge first branch cleanly (no conflicts)
git merge worktree-routes

# Second branch conflicts on src/auth/middleware.ts
git merge worktree-auth
# CONFLICT (content): Merge conflict in src/auth/middleware.ts
# Automatic merge failed; fix conflicts and then commit the result.

# Open the file, review both changes, resolve manually
vim src/auth/middleware.ts

# Alternatively: ask Claude to resolve
# "Help me resolve this conflict. Branch 1 adds rate limiting,
#  Branch 2 adds JWT validation. Both need to stay."

git add src/auth/middleware.ts
git merge --continue

Best Practice

If the task genuinely requires two agents to touch the same file, sequence them: block Agent B on Agent A completing first. Then Agent B reads Agent A's output as its starting point. This eliminates the conflict entirely.

Resource and Cost Implications

Running parallel agents is not free. Here are the real numbers.

3-5x
Token multiplier for a typical agent team
5-6
Recommended tasks per teammate
3-5
Recommended team size for most workflows

Token Costs Scale Linearly

Each teammate is a separate Claude instance with its own context window. A 3-agent team uses roughly 3x the tokens of a single session doing the same work sequentially. The Anthropic docs are explicit: "Agent teams use significantly more tokens than a single session."

Where the multiplier is worth paying:

  • Competing hypotheses. Three agents independently investigating a bug root cause often find the answer faster than one agent serializing through the same hypotheses.
  • Large independent modules. Five agents migrating five independent services in parallel versus one agent doing them sequentially. Wall-clock time drops proportionally.
  • Parallel review. Security + performance + test coverage review happening simultaneously on the same PR is worth 3x the tokens compared to sequential review.

Where the multiplier is not worth paying:

  • Sequential-by-nature tasks. If step 2 needs step 1's output, running them in parallel gives you nothing. Use subagents or a single session.
  • Same-file edits. Two agents editing app.ts will conflict. Run them sequentially.
  • Small tasks. Coordination overhead (team setup, task creation, mailbox messages) costs tokens too. For a 10-minute task, a single session is always cheaper.

Disk and Memory

Each worktree checkout costs disk space proportional to the working tree size (not the full git object store — that's shared). For a typical web app at 50MB, five worktrees add 250MB of disk usage. Node.js node_modules are not shared: each worktree needs its own npm install. This can dominate disk costs on large projects.

Memory: each claude process is a separate Node.js process. Five agents = five processes. On a machine with 16GB RAM, this is fine. On a machine with 8GB running other development tools, it can cause pressure.

Real-World Walkthrough: Three-Agent Code Review

This is a full walkthrough of a realistic use case: reviewing a pull request with three agents checking different concerns simultaneously.

The Setup

PR #142 adds a new file upload endpoint to a Node.js API. You want security review, performance review, and test coverage review done in parallel.

Step 1: Enable Teams and Start

Create the review team

Create an agent team to review PR #142.
Spawn 3 reviewers with worktrees for isolation:
- security: check for path traversal, file type bypass, upload size bypass,
            SSRF via file contents, authentication gaps
- performance: check for blocking I/O, missing streaming, unnecessary
               file reads, memory allocation patterns
- tests: identify untested paths, missing edge cases, gaps in error
         handling coverage

Each reviewer should produce a structured report:
  file:line | severity | finding | fix

Share findings with each other. If security finds something that
tests missed, security should message tests directly.

Step 2: Agents Claim Tasks and Start Work

The lead creates three tasks in ~/.claude/tasks/pr-review-142/. Each agent calls TaskList, finds an unclaimed task, and calls TaskUpdate to claim it. All three work simultaneously in their own worktrees.

The security agent reads the upload endpoint, traces the file path construction, and finds that the original filename is used directly without sanitization — a path traversal vulnerability. It messages the tests agent:

Cross-agent message

SendMessage({
  type: "message",
  recipient: "tests",
  content: "Found path traversal in uploadFile(). The filename parameter flows directly into path.join(uploadDir, req.file.originalname) without sanitization. Check if your test suite covers filenames like '../../../etc/passwd' or '../../.env'.",
  summary: "Path traversal found — check test coverage"
})

Step 3: Tests Agent Responds and Updates Its Findings

The tests agent receives the message, checks the test file, confirms no path traversal tests exist, and adds that finding to its report. It also updates its task to flag the dependency.

Step 4: All Three Complete and Notify Lead

Each agent marks its task completed and sends an idle notification with its findings. The lead receives three reports within minutes of each other.

Step 5: Lead Synthesizes

The lead compiles a combined review comment, deduplicates findings (the path traversal appeared in both security and tests reports), and posts it to the PR. Total wall-clock time: roughly the same as running one review, not three sequential reviews.

This is exactly the use case where agent teams pay for their token cost: three independent review lenses running in parallel, with cross-agent communication catching the gap between security findings and test coverage.

Limitations and Gotchas

Known Limitations (March 2026)

  • No session resumption with in-process teammates. /resume and /rewind do not restore in-process teammates. After resuming, the lead may message teammates that no longer exist. Spawn replacements.
  • Task status lag. Teammates sometimes fail to mark tasks completed, blocking dependent tasks. Check manually and update status if needed.
  • One team per session. A lead manages one team at a time. Clean up before starting a new one.
  • No nested teams. Teammates cannot spawn their own sub-teams. Only the lead can manage the team.
  • Permissions set at spawn time. All teammates inherit the lead's permission mode. You can change individual modes after spawning, but not at creation time.
  • Split-pane mode requires tmux or iTerm2. Does not work in VS Code integrated terminal, Windows Terminal, or Ghostty.
  • node_modules are not shared. Each worktree needs its own dependency install. On large Node.js projects this is slow and eats significant disk space.
  • Cannot check out the same branch in two worktrees. Standard git constraint. Each agent's worktree must have its own unique branch.

When Not to Use Agent Teams

The Anthropic docs identify these patterns clearly. Avoid agent teams when:

  • Tasks must run sequentially (step N needs step N-1's output)
  • Multiple tasks edit the same file
  • The task is small — coordination overhead exceeds the parallelism benefit
  • You need deterministic, reproducible output — agent teams introduce non-determinism from parallel execution order

For sequential tasks or tasks that don't need peer communication, use subagents instead. Subagents are cheaper, simpler, and don't require the experimental feature flag.

Frequently Asked Questions

What is a git worktree in Claude Code?

A git worktree is a separate working directory linked to the same git repository. Each worktree has its own branch, working files, and git index, but shares the object store and history with the main repository. Claude Code creates one per parallel agent so agents edit different directories and can't overwrite each other's work.

How do I start Claude Code in a worktree?

Run claude --worktree feature-name to create a worktree at .claude/worktrees/feature-name/ with a new branch named worktree-feature-name. Omit the name (claude --worktree) to auto-generate one. You can also say "work in a worktree" during a session.

How do Claude Code agents communicate with each other?

Two mechanisms: a shared task list at ~/.claude/tasks/<team-name>/ (JSON files on disk) and a mailbox system via the SendMessage tool. Tasks use file locking to prevent race conditions when multiple agents try to claim the same task. Messages are delivered automatically — no polling.

What happens to a worktree branch when an agent finishes?

No changes: Claude removes the worktree and its branch automatically. Changes exist: Claude prompts you to keep (preserves directory and branch) or discard (deletes both, including uncommitted work).

How does Claude Code handle merge conflicts from parallel agents?

Conflicts are prevented through upfront task design — assign agents to non-overlapping files. When conflicts do occur, resolve them with standard git merge workflow after agents finish. Tools like Clash can detect conflicts between worktrees before agents write files.

How does Claude Code worktree differ from Codex cloud sandboxes?

Claude Code worktrees run locally with full access to your tools, environment, and credentials. Codex sandboxes run in isolated cloud containers with network access disabled. Codex is better for security-sensitive or untrusted code execution. Claude Code worktrees are better when agents need your local environment — build tools, test runners, local services.

Can subagents use worktrees?

Yes. Add isolation: worktree to a custom subagent's YAML frontmatter in .claude/agents/. Each invocation gets its own worktree. Auto-cleanup happens when the subagent finishes without changes.

What is the token cost of agent teams with worktrees?

Token costs scale linearly with team size. A 3-agent team uses roughly 3x the tokens of a single session. The Anthropic docs recommend 3-5 teammates with 5-6 tasks each for most workflows. Agent teams are cost-effective when tasks are truly parallelizable and the work would otherwise take proportionally longer sequentially.

Sources

Add Fast Code Search to Any Agent

WarpGrep gives parallel agents instant codebase search — 4 turns, 8 parallel tool calls, no embeddings. Works with Claude Code, Cursor, or raw API. No index setup.