Running Parallel AI Agents with Git Worktree
Running multiple AI coding agents at the same time can dramatically speed up development, but only if each agent has its own isolated workspace. Git worktree provides that isolation by letting you check out multiple branches simultaneously, each in its own directory. This guide covers the architecture, tooling, and best practices for multi-agent parallel development.
Why Parallel Agents Need Worktrees
AI coding agents work by reading files, reasoning about changes, and writing modified files back to disk. When two agents run in the same directory, their file operations collide:
- Write conflicts:Agent A saves a file, then Agent B overwrites it with a different version. Agent A's changes are lost.
- Read inconsistency: Agent B reads a file while Agent A is in the middle of modifying it, leading to partial or corrupted context.
- Build interference: Both agents trigger builds or test runs that compete for the same output directories and ports.
Git worktrees solve all three problems by giving each agent its own working directory. Each directory has its own copy of the source files on its own branch, so agents cannot interfere with each other's reads or writes.
Architecture Overview
The parallel agent architecture has three layers:
┌─────────────────────────────────────────────────────────┐
│ Git Repository │
│ (shared .git store) │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Worktree 1 │ │ Worktree 2 │ │ Worktree 3 │ │
│ │ branch: │ │ branch: │ │ branch: │ │
│ │ feat/auth │ │ fix/perf │ │ refactor/ │ │
│ │ │ │ │ │ db-layer │ │
│ │ ┌───────┐ │ │ ┌───────┐ │ │ ┌───────┐ │ │
│ │ │Agent 1│ │ │ │Agent 2│ │ │ │Agent 3│ │ │
│ │ │Claude │ │ │ │Cursor │ │ │ │Codex │ │ │
│ │ └───────┘ │ │ └───────┘ │ │ └───────┘ │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Orchestration Layer │ │
│ │ (tmux / script / CI pipeline) │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Merge & Review │ │
│ │ (git merge / pull requests / code review) │ │
│ └─────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘The key insight is that every agent operates in its own worktree on its own branch, but all worktrees share a single git object store. This means branches are visible across worktrees, disk usage is minimized, and merging happens through standard git workflows.
Setting Up the Infrastructure
The fastest way to spin up parallel agents is a shell script that creates worktrees and launches agents in tmux panes:
#!/bin/bash
# parallel-agents.sh - Spin up parallel AI agents in git worktrees
# Usage: ./parallel-agents.sh task1 task2 task3
SESSION="parallel-agents"
REPO_DIR=$(pwd)
TOOL="${AI_TOOL:-claude}" # Default to claude, override with AI_TOOL env var
if [ $# -eq 0 ]; then
echo "Usage: $0 <task1> <task2> [task3] ..."
exit 1
fi
# Create worktrees
for task in "$@"; do
branch="agent/$task"
worktree="../$(basename $REPO_DIR)-$task"
if [ ! -d "$worktree" ]; then
git worktree add "$worktree" -b "$branch"
echo "Created worktree: $worktree (branch: $branch)"
# Install dependencies if needed
if [ -f "$worktree/package.json" ]; then
(cd "$worktree" && npm install --silent)
fi
fi
done
# Launch tmux session with agents
tmux new-session -d -s $SESSION
FIRST=true
for task in "$@"; do
worktree="../$(basename $REPO_DIR)-$task"
if [ "$FIRST" = true ]; then
tmux send-keys -t $SESSION "cd $worktree && $TOOL" Enter
FIRST=false
else
tmux split-window -t $SESSION
tmux send-keys -t $SESSION "cd $worktree && $TOOL" Enter
tmux select-layout -t $SESSION tiled
fi
done
echo "Launching tmux session '$SESSION' with $# agents..."
tmux attach-session -t $SESSIONThis script works with any AI tool. Set the AI_TOOL environment variable to use a different tool:
# Use with Claude Code
./parallel-agents.sh auth-api search-feature caching-layer
# Use with Cursor
AI_TOOL="cursor" ./parallel-agents.sh auth-api search-feature
# Use with OpenCode
AI_TOOL="opencode" ./parallel-agents.sh auth-api search-featureManaging Multiple Sessions
Once your agents are running, you need to monitor their progress and manage the sessions effectively:
tmux Navigation
# Switch between panes
Ctrl-b + arrow keys # Move to adjacent pane
Ctrl-b + q # Show pane numbers, then press number to switch
Ctrl-b + z # Toggle zoom on current pane (fullscreen/split)
# Pane management
Ctrl-b + x # Close current pane
Ctrl-b + ! # Move pane to its own window
# Session management
Ctrl-b + d # Detach from session (agents keep running)
tmux attach -t parallel-agents # Reattach laterMonitoring Progress
Keep a terminal available (outside tmux or in its own tmux window) to check on the state of all worktrees:
# See all worktrees and their branches
git worktree list
# Check what each agent has committed
for branch in $(git branch --list 'agent/*' --format='%(refname:short)'); do
echo "\n=== $branch ==="
git log --oneline main..$branch
done
# See uncommitted changes in a specific worktree
git -C ../my-project-auth-api statusMerging Results Back
After all agents finish, you need to review and merge their work. There are several strategies depending on your workflow:
Strategy 1: Sequential Merge
Merge each agent's branch one at a time, resolving any conflicts as they come up:
# Review each branch's changes
git diff main..agent/auth-api
git diff main..agent/search-feature
git diff main..agent/caching-layer
# Merge sequentially
git checkout main
git merge agent/auth-api
git merge agent/search-feature
git merge agent/caching-layerStrategy 2: Pull Request Per Agent
Push each branch and create a pull request for it. This lets you review each agent's work independently and run CI checks:
# Push all agent branches
for branch in $(git branch --list 'agent/*' --format='%(refname:short)'); do
git push origin $branch
done
# Create PRs (using GitHub CLI)
gh pr create --base main --head agent/auth-api --title "feat: auth API"
gh pr create --base main --head agent/search-feature --title "feat: search"
gh pr create --base main --head agent/caching-layer --title "feat: caching"Strategy 3: Integration Branch
Create an integration branch where you merge all agent branches together, test the combined result, and then merge the integration branch into main:
# Create integration branch
git checkout -b integrate/sprint-42 main
# Merge all agent work
git merge agent/auth-api
git merge agent/search-feature
git merge agent/caching-layer
# Run tests on the combined result
npm test
# If everything passes, merge to main
git checkout main
git merge integrate/sprint-42Orchestration Tools
Beyond tmux and shell scripts, several tools and patterns help manage parallel agents:
Claude Code /worktree Skill
Claude Code has a built-in /worktree skill that creates a worktree and spawns a sub-agent inside it from your current session. This is the simplest way to spin up parallel agents without leaving your editor.
Docker Compose
For Codex and other container-based agents, Docker Compose lets you define multiple agent services, each mounted to its own worktree directory, and start them all with a single command.
CI/CD Pipelines
Some teams run AI agents as CI jobs. Each job creates a worktree, runs an agent, and pushes the result branch. GitHub Actions, GitLab CI, and other platforms support this pattern.
Custom Orchestrators
For larger teams, a custom script or service can manage the lifecycle of agent sessions: creating worktrees, dispatching tasks, monitoring progress, and collecting results.
Best Practices for Multi-Agent Development
Assign Non-Overlapping Tasks
The biggest source of merge pain is two agents editing the same files. Divide work so each agent touches a different part of the codebase: one on the API layer, another on the frontend, a third on tests. This minimizes merge conflicts when combining results.
Keep Tasks Small and Focused
Small, well-defined tasks produce better results from AI agents and are easier to review. Instead of "refactor the entire backend," try "extract the authentication logic into a middleware."
Start from the Same Base
Create all agent worktrees from the same commit on main. This ensures all agents start with the same codebase and reduces the likelihood of conflicts when merging.
Review Before Merging
Never merge agent work without reviewing it. AI agents can produce code that compiles and passes tests but contains subtle issues, from security vulnerabilities to architectural decisions that conflict with your project's conventions.
Clean Up After Each Sprint
Remove completed worktrees and delete merged branches promptly. Stale worktrees consume disk space and clutter git worktree list output:
# Remove all agent worktrees
git worktree list | grep 'agent/' | awk '{print $1}' | xargs -I{} git worktree remove {}
# Delete merged agent branches
git branch --list 'agent/*' | xargs git branch -d
# Clean up stale references
git worktree pruneLimit Concurrency
More agents is not always better. Each agent consumes API credits, system resources, and review time. Two to four parallel agents is a practical sweet spot for most teams. Scale up only when you have the review capacity to match.
Summary
Git worktrees are the foundation for running AI agents in parallel. They provide the file-level isolation that prevents agents from interfering with each other, while keeping everything in a single repository for easy merging. Whether you use Claude Code, Cursor, Codex, or another tool, the pattern is the same: create worktrees, launch agents, and merge the results. Start with the setup script above, adapt it to your workflow, and scale up as you build confidence in the process.