·16 min read·ai-cli-tools

Multi-Agent Development with Git Worktree — Complete Setup Guide

The definitive guide to running multiple AI coding agents in parallel using git worktrees. Covers git worktree fundamentals, Claude Code's built-in --worktree flag, step-by-step setup for 3 parallel agents, conflict resolution, merge strategy, and cleanup. Includes a practical example with auth, API, and test agents working simultaneously.

DH
Danny Huang

The Core Problem: AI Agents Fight Over Your Working Directory

You have Claude Code refactoring the authentication module. Midway through, you want a second agent working on the API layer. You open another terminal, start a new Claude Code session in the same repo, and within minutes both agents are editing overlapping files, overwriting each other's changes, and producing a codebase that compiles for neither of them.

This is the fundamental constraint of single-directory development. Git tracks one working tree per repository by default. Every staged change, every modified file, every uncommitted edit is shared across all processes reading that directory. Two AI agents writing to the same directory is no different from two developers editing the same file on the same machine without version control — except the agents work faster, so they create conflicts faster.

Git worktrees eliminate this problem entirely.

What Git Worktree Is and Why It Exists

A git worktree creates an additional working directory linked to the same repository. Each worktree has its own checked-out branch, its own staged changes, and its own working files — but they all share the same .git history, the same remotes, and the same refs.

# Your main repo is at ~/project
# Create a worktree for a feature branch
git worktree add ../project-feature-auth feature/auth

# Now you have two directories:
# ~/project              → main branch
# ~/project-feature-auth → feature/auth branch

The key insight: worktrees are not clones. A git clone copies the entire repository, creating a separate .git directory with its own history. A worktree shares the original .git directory. This means:

  • Disk usage is minimal. A worktree only stores working files, not a duplicate of the entire git object database. For a 2 GB repo, a clone uses 2 GB. A worktree uses only the size of the checked-out files.
  • Branches stay synchronized. Commits made in any worktree are immediately visible to all other worktrees. Push from one, pull from another — the underlying repo is the same.
  • No remote configuration. Worktrees inherit the origin remote, authentication, and hooks from the parent repository. Nothing to set up.

The limitation: each worktree must be on a different branch. You cannot check out the same branch in two worktrees simultaneously. This is actually a feature for multi-agent work — it forces each agent onto its own branch, which is exactly what you want.

Why Git Worktree Is Perfect for AI Agents

AI coding agents have three properties that make worktrees the ideal isolation mechanism:

Agents modify files aggressively. A single Claude Code prompt can touch 15 files across your project. Two agents sharing a directory will inevitably edit the same file, and neither agent is aware of the other's changes. Worktrees guarantee filesystem-level isolation — agent A literally cannot see agent B's modifications.

Agents work faster than humans. A human developer context-switches slowly enough that two developers on one machine rarely collide. An AI agent writes, reads, compiles, and iterates in seconds. The collision window is measured in seconds, not hours. Worktrees close that window completely.

Agents benefit from parallelism more than humans. A human can only focus on one task at a time. Running three agents in parallel on three different features is genuine 3x throughput — each agent gets your full codebase context and works at full speed. The bottleneck shifts from agent speed to your ability to monitor and merge.

Claude Code's Built-in Worktree Support

Claude Code added native worktree support in February 2026, with the --worktree (or -w) flag. This is the simplest path to running parallel agents.

The --worktree Flag

# Start Claude Code in a new worktree
claude --worktree feature-auth

# Short form
claude -w feature-auth

This single command does three things:

  1. Creates a new git worktree at .claude/worktrees/feature-auth/
  2. Creates and checks out a new branch named feature-auth
  3. Starts a Claude Code session inside that worktree

If you omit the name, Claude Code generates a random one automatically:

claude --worktree
# Creates something like .claude/worktrees/jade-fox-42/

Running Multiple Agents in Parallel

Open three terminals. Start three worktrees:

# Terminal 1
claude -w feature/auth

# Terminal 2
claude -w feature/api-layer

# Terminal 3
claude -w tests/integration

Each agent gets its own branch, its own directory, and its own working files. They can all read, write, compile, and run tests simultaneously without any awareness of each other. The overhead per worktree is negligible — on a typical 500 MB project, each worktree adds roughly 500 MB of disk usage (the working files), while the git object database stays shared.

Worktree Cleanup

When you exit a worktree session, Claude Code handles cleanup based on what happened:

  • No changes made: The worktree and branch are removed automatically. Zero manual cleanup.
  • Changes or commits exist: Claude Code prompts you to keep or remove the worktree. Keeping preserves the directory and branch for later. Removing deletes the worktree directory and its branch, discarding all uncommitted changes and local commits.

You can also clean up manually at any time:

# List all worktrees
git worktree list

# Remove a specific worktree
git worktree remove .claude/worktrees/feature-auth

# Prune stale worktree references
git worktree prune

Subagent Worktree Isolation

Claude Code's subagent system also supports worktree isolation. When a subagent needs to make changes that could conflict with the main agent, you can configure it to use its own worktree:

# In a custom agent definition (.claude/agents/refactor-agent.md)
---
isolation: worktree
---

With isolation: worktree, the subagent gets its own worktree automatically. When the subagent completes its task without changes, the worktree is cleaned up silently. When changes exist, they stay on the subagent's branch for you to review and merge.

Step-by-Step: Running 3 Agents on Auth, API, and Tests

Here is a concrete walkthrough. You are building a new user management feature that requires changes to authentication, the API layer, and integration tests. Instead of handling this sequentially, you run three Claude Code agents in parallel, each in its own worktree.

Step 1: Verify Your Starting State

# Make sure your main branch is clean
git status
# On branch main
# nothing to commit, working tree clean

# Verify no existing worktrees
git worktree list
# /Users/you/project  abc1234 [main]

Step 2: Create Worktrees and Start Agents

Open three terminal windows or panes. In each one:

# Terminal 1 — Auth agent
claude -w feature/user-auth
# Prompt: "Implement JWT-based user authentication with refresh token
# rotation. Add login, logout, and token refresh endpoints. Use the
# existing User model in prisma/schema.prisma."

# Terminal 2 — API agent
claude -w feature/user-api
# Prompt: "Create CRUD API endpoints for user profile management:
# GET /api/users/:id, PATCH /api/users/:id, DELETE /api/users/:id.
# Add input validation with zod. Follow the existing route patterns
# in app/api/."

# Terminal 3 — Test agent
claude -w feature/user-tests
# Prompt: "Write integration tests for the user management feature.
# Cover authentication flows (login, logout, token refresh),
# profile CRUD operations, and error cases (invalid tokens,
# missing fields, unauthorized access). Use the existing test
# setup in tests/setup.ts."

Each agent now works independently. The auth agent creates middleware and token logic. The API agent builds route handlers. The test agent writes test cases based on the existing codebase patterns.

Step 3: Monitor Progress

This is where running three agents simultaneously gets interesting — you need to watch all three. Each terminal shows its agent's progress, file modifications, and any questions the agent asks.

Three parallel terminals is exactly the scenario where a proper terminal layout pays for itself. You need all three agents visible simultaneously, with the ability to resize whichever terminal needs attention. Termdock lets you drag and resize terminal panes freely — three agents side by side, or two on top and one on the bottom, rearranged on the fly as your attention shifts between agents.

Try Termdock Drag Resize Terminals works out of the box. Free download →

Step 4: Review Each Agent's Output

Once all three agents complete their work, review what each one produced:

# Check what the auth agent changed
cd .claude/worktrees/feature/user-auth
git log --oneline main..HEAD
git diff main --stat

# Check the API agent
cd .claude/worktrees/feature/user-api
git log --oneline main..HEAD
git diff main --stat

# Check the test agent
cd .claude/worktrees/feature/user-tests
git log --oneline main..HEAD
git diff main --stat

Step 5: Merge the Results

The merge order matters. Start with the changes that other branches depend on:

# Go back to main
cd ~/project

# Merge auth first (API and tests depend on auth types)
git merge feature/user-auth

# Merge API second
git merge feature/user-api

# Merge tests last (tests reference both auth and API code)
git merge feature/user-tests

If the agents worked on genuinely separate areas, these merges complete without conflicts. When they touched the same files — which is likely for shared types or configuration — you get standard git merge conflicts that resolve in minutes.

Conflict Resolution Strategy

Three parallel agents will sometimes produce conflicting changes. This is expected. The resolution strategy depends on the type of conflict.

Type 1: Import and Dependency Conflicts

The most common conflict. Agent A adds import { AuthToken } from '@/types' and agent B adds import { UserProfile } from '@/types' at the same line.

Resolution: Keep both imports. These are additive changes that do not conflict semantically — git just cannot auto-merge them because they touch the same line.

Type 2: Shared Configuration Conflicts

Multiple agents modify the same config file — package.json, prisma/schema.prisma, or a shared constants file.

Resolution: Merge carefully. For package.json, combine the dependency additions from both agents. For Prisma schema, ensure model definitions from different agents do not conflict. Use git mergetool or resolve manually — these conflicts are mechanical, not logical.

Type 3: Architectural Conflicts

Agent A and agent B made different architectural decisions about the same system boundary. Agent A expects authentication via middleware, agent B implements inline auth checks in each route handler.

Resolution: Pick one approach and ask a single agent to reconcile. This is where you start a new Claude Code session with the merged state:

claude "The auth agent used middleware-based authentication but the API
agent added inline auth checks. Standardize on middleware-based auth
across all routes. Remove the inline checks and ensure every route
uses the auth middleware."

Prevention: Reduce Conflicts Before They Happen

The best conflict resolution is conflict prevention. Before starting parallel agents:

  1. Define interfaces first. Create shared types and interfaces on main before branching. If all agents import from the same types file, their implementations are more likely to be compatible.
  2. Assign non-overlapping directories. Auth agent works in lib/auth/ and app/api/auth/. API agent works in app/api/users/. Test agent works in tests/. Minimal overlap means minimal conflicts.
  3. Use explicit prompts. Tell each agent what the other agents are doing: "The auth agent is implementing JWT middleware in lib/auth/middleware.ts. Build your API routes assuming that middleware exists and exports a requireAuth function."

When to Merge: The Decision Framework

Not every worktree needs to be merged immediately. Here is the decision framework.

SituationActionWhy
Agent completed a self-contained featureMerge to main immediatelyReduces drift from other branches
Agent produced a draft that needs iterationKeep the worktree, iterate furtherMerging incomplete work creates noise
Two agents have conflicting architectural choicesMerge one, rebase the otherEstablish the pattern before merging the follower
Agent work depends on another agent's outputMerge the dependency first, rebase the dependentStandard dependency-order merge
Agent produced garbageRemove the worktree and branchgit worktree remove cleans up completely

Summary: merge complete, self-contained work immediately. Keep worktrees open for incomplete work. Always merge dependencies before dependents.

The general principle: short-lived worktrees. The longer a worktree diverges from main, the harder the merge. Aim to merge within hours, not days.

Manual Worktree Setup (Without Claude Code's --worktree)

Claude Code's --worktree flag is the fastest path, but any AI CLI tool works with manual worktrees. Gemini CLI, Codex CLI, aider — any agent that operates on a local directory can run inside a worktree.

Create Worktrees Manually

# From your main repo directory
git worktree add ./worktrees/feature-auth -b feature/auth
git worktree add ./worktrees/feature-api -b feature/api
git worktree add ./worktrees/feature-tests -b feature/tests

Start Agents in Each Worktree

# Terminal 1 — Claude Code in auth worktree
cd ./worktrees/feature-auth && claude

# Terminal 2 — Gemini CLI in API worktree
cd ./worktrees/feature-api && gemini

# Terminal 3 — Any agent in test worktree
cd ./worktrees/feature-tests && aider

This mixed-agent setup is powerful. You can run Claude Code on the complex auth work, Gemini CLI on the straightforward API routes (saving your Claude Code budget), and aider on test generation. Each agent in its own directory, on its own branch. The dual-tool strategy applies naturally here — assign agents to worktrees based on task complexity, not tool loyalty.

Cleanup Manual Worktrees

# List all worktrees
git worktree list

# Remove a worktree (keeps the branch)
git worktree remove ./worktrees/feature-auth

# Remove a worktree AND delete the branch
git worktree remove ./worktrees/feature-auth
git branch -d feature/auth

# Clean up stale references after manual deletion
git worktree prune

Monitoring Multiple Agents: The Real Bottleneck

The technical setup of worktrees and agents is straightforward. The actual bottleneck is attention management. Three agents running in parallel means three streams of output, three sets of file changes, three potential points where the agent asks a clarifying question and blocks until you answer.

Effective monitoring requires three things:

Visibility. All agent terminals must be visible simultaneously. Tabbed terminals defeat the purpose — if you cannot see agent B's question while focusing on agent A, agent B sits idle. A tiled layout where all three agents are visible at once is the minimum viable setup.

Quick switching. When agent C finishes and needs your review, you need to resize that pane larger without losing sight of agents A and B. Fixed-size panes do not work because attention requirements shift constantly.

Git status awareness. Each worktree has its own branch, its own staged changes, and its own commit history. Keeping track of three branches across three directories manually is error-prone. Integrated status — seeing which worktree is ahead of main, which has uncommitted changes, which has merge conflicts — saves real time.

This three-agent monitoring pattern is the core design problem that Termdock solves. Drag any terminal border to resize on the fly. See workspace-level Git status across all worktrees. Drop files directly into whichever agent terminal needs them. The full landscape of terminal setups and AI CLI tool configurations is covered in the 2026 AI CLI Tools Complete Guide.

Advanced: Worktree Configuration for Large Repos

For repositories over 5 GB or monorepos with deep node_modules, worktree creation can be slow because git copies the entire working tree. Two optimizations help.

Sparse Checkout in Worktrees

If each agent only needs a subset of the repo:

# Create a worktree with sparse checkout
git worktree add --sparse ./worktrees/feature-auth -b feature/auth

# Configure which directories to include
cd ./worktrees/feature-auth
git sparse-checkout set src/auth src/types tests/auth package.json tsconfig.json

The auth agent now sees only the files it needs. Worktree creation is faster, disk usage is lower, and the agent has less irrelevant context to process.

For Node.js projects, node_modules in every worktree wastes disk space and installation time:

# Install dependencies once in the main repo
cd ~/project && npm install

# Symlink node_modules into each worktree
ln -s ~/project/node_modules ./worktrees/feature-auth/node_modules
ln -s ~/project/node_modules ./worktrees/feature-api/node_modules

This works as long as agents are not modifying package.json with different dependencies. If they are, each worktree needs its own npm install.

Common Mistakes to Avoid

Checking out the same branch in two worktrees. Git prevents this, but developers sometimes try to work around it. Do not. Each worktree gets its own branch — that is the whole point of the isolation.

Forgetting to prune stale worktrees. If you delete a worktree directory manually (with rm -rf instead of git worktree remove), git keeps a stale reference. Run git worktree prune periodically, or use Claude Code's built-in cleanup which handles this automatically.

Letting worktrees diverge too long. A worktree that has not been merged for a week will have painful merge conflicts. Merge early, merge often. If you need to keep a worktree open for days, rebase it on main daily:

cd ./worktrees/feature-auth
git rebase main

Not telling agents about each other. If agent A creates a new type that agent B needs, and you do not mention this in agent B's prompt, agent B will either invent an incompatible type or fail to compile. Include cross-agent context in your prompts — "the auth agent is creating a JWTPayload type in src/types/auth.ts, use that type in your API handlers."

Running too many agents at once. Three parallel agents is a sweet spot. Five or more becomes difficult to monitor effectively, and the merge complexity grows quadratically. Start with two, move to three when comfortable, and rarely go beyond four.

Quick Reference

CommandWhat It Does
claude -w feature-authCreate worktree + branch + start Claude Code
claude --worktreeCreate worktree with auto-generated name
git worktree add ./path -b branchCreate worktree manually
git worktree listShow all worktrees
git worktree remove ./pathRemove a worktree
git worktree pruneClean up stale references
git branch -d branch-nameDelete the branch after worktree removal

Summary: claude -w is the one-command shortcut. git worktree add/remove/list/prune gives you full manual control.

Checklist: Your First Multi-Agent Worktree Session

  1. Verify prerequisites. Git 2.20+ (worktree features stabilized), Claude Code installed, clean main branch.

  2. Pick a task with 2-3 parallel subtasks. Ideal: a feature with auth, API, and test components. Not ideal: a single-file bug fix (just use one agent).

  3. Define shared interfaces first. Create any shared types on main before branching. This reduces merge conflicts significantly.

  4. Start worktrees. claude -w subtask-a, claude -w subtask-b, claude -w subtask-c in separate terminals.

  5. Write explicit prompts with cross-agent context. Tell each agent what the others are building. Mention shared types, expected function signatures, and directory boundaries.

  6. Monitor all agents visually. Tile your terminals so all agents are visible. Resize as needed when one agent requires more attention.

  7. Merge in dependency order. Base modules first, dependent modules second, tests last. Resolve conflicts immediately.

  8. Clean up. Verify merged branches are removed. Run git worktree prune to clear stale references. Run the full test suite on main after all merges.

This workflow scales from solo developers running 2-3 agents to teams where each member runs their own set of parallel agents. The git worktree primitives are the same at any scale — what changes is the merge coordination. For the complete picture of how AI CLI tools fit into parallel development workflows, see the 2026 AI CLI Tools Complete Guide.

DH
Free Download

Ready to streamline your terminal workflow?

Multi-terminal drag-and-drop layout, workspace Git sync, built-in AI integration, AST code analysis — all in one app.

Download Termdock →
#git-worktree#multi-agent#claude-code#parallel-development#ai-cli#workflow

Related Posts