Run Parallel AI Coding Agents with Git Worktrees

Run Parallel AI Coding Agents with Git Worktrees

One AI coding agent is fast until it isn’t. The moment you hand it a task that takes twenty minutes, you are stuck watching it work while your other ideas sit idle. Run a second agent in the same folder and they stomp on each other: two sessions editing the same file, one overwriting the other’s half-finished changes. The result is a diff that makes no sense.

Git worktrees fix this without cloning the whole repo or juggling git stash. Each agent gets its own working directory and its own branch, but all of them share one .git history. You spin up three agents, they each build in isolation, and you merge the branches when they finish. This guide walks through the commands and the setup that actually makes parallel agents work.

Why a Shared Checkout Breaks

Most coding agents assume they own the project directory. Claude Code, Codex, and Cursor all read and write files directly. When two of them run in the same tree at the same time, three things go wrong fast.

File collisions are the obvious one: Agent A rewrites src/auth.ts while Agent B refactors the same file. Git only sees the last write. Context contamination is worse and quieter: an agent reads a file that another agent is halfway through editing and reasons about a state that never actually existed. Index corruption happens when two agents run git add at once. None of these are rare edge cases. They show up the first time you try two sessions on one repo.

The old workaround was git stash: stash your changes, switch branches, do the work, switch back, pop the stash. That is not parallel work. That is rapid context-switching, and you lose the agent’s place every time you swap branches.

What a Worktree Actually Gives You

A worktree is a linked working directory that points back to your main repo’s .git object database. Each worktree has its own checked-out branch and its own files on disk, but they all share the same commits, refs, and remotes. Creating one is nearly instant because Git does not copy the heavy objects. It writes a small .git file in the new worktree that says gitdir: /path/main/.git/worktrees/... and moves on.

That shared history is the whole point. You commit in a worktree, switch back to your main directory, and the branch is already there in your log. No push, no pull, no remote sync between agents. Integration is a local git merge.

ApproachSetup timeDisk overheadMerge complexityBest for
Git worktree~1 secondWorking tree onlyStandard gitParallel feature work
Full clone30-120 secondsFull repo copyManual remote syncLong-lived forks
Docker container10-60 secondsImage layersVolume mountsFull env isolation

The Manual Setup That Works Anywhere

Developer desk with two monitors and a laptop running code, ready for parallel agent work

The built-in git worktree command needs no extra tooling. Start from your main repo and create one worktree per task:

git worktree add ../feature-login -b feature/login main
git worktree add ../feature-payments -b feature/payments main

Each command checks out a fresh branch from main into its own folder. Now point an agent at each directory. With Claude Code the same step is one flag: claude --worktree feature-login creates the worktree, checks out a branch, and starts the session inside it. Codex CLI has no built-in flag, so the pattern is manual: git worktree add followed by codex --cd ../path. Cursor added first-class worktree support in its 2026.1 release, and Gemini CLI offers experimental worktree support behind a settings toggle.

One catch trips everyone up. A worktree only checks out tracked files. Anything in .gitignore does not carry over. Your fresh worktree has no node_modules, no .venv, no .env. Before the agent can run tests or a dev server, you install dependencies and copy your environment files. That two-minute setup cost pays for itself the first time an agent’s mistake stays in its own directory instead of corrupting your main branch.

Bootstrap Each Worktree Before You Launch

A clean checkout will not run until you bring its environment up to speed. For each worktree, install dependencies and assign a port so two agents do not fight over the same socket:

cd ../feature-login && npm install && echo "PORT=3101" > .env.local
cd ../feature-payments && npm install && echo "PORT=3102" > .env.local

Port collisions are the first friction most people hit. A worktree is a separate directory, not a separate machine. Two agents running npm run dev both reach for 3000, and one of them fails with EADDRINUSE. Deriving each worktree’s ports from its name keeps two agents from grabbing the same socket. The same logic applies to databases and Docker container names: prefix them with the worktree or branch name so parallel agents stay out of each other’s state.

If you use Claude Code, add isolation: worktree to a custom subagent’s frontmatter so every spawned agent provisioning happens automatically. Without that, subagents you launch with the Task tool share the main session’s working directory and can still overwrite each other.

Five Failure Modes to Design Around

Worktrees solve file conflicts. They do not solve everything else that breaks when agents run at once.

Port and service collisions come first: explicit .env.local per worktree is the fix. Shared external state is second: databases, Redis instances, and Docker volumes are still shared, so two agents running migrations against one dev database will corrupt it. Separate schemas or containers per worktree handle that. Loose task boundaries are third: if you let two agents touch the same module, you get a conflict neither anticipated. Assign file ownership before you launch. Uncommitted state is invisible across worktrees: Agent B cannot see Agent A’s in-progress edits until A actually commits. Review becomes the bottleneck last: worktrees make it cheap to start many agents, but reading many diffs is still expensive, so keep task scope narrow and merge one branch at a time.

There is also a quiet trap with git stash. The stash ref lives in the shared repo, so if one agent stashes in a worktree, another worktree can apply it in the wrong place. Rule: never stash with parallel agents. Use commits on your own branch only.

A Real Example: Bugfix While a Feature Ships

The clearest case for worktrees is the interrupt. You are mid-feature when a production bug lands. Without isolation you stash, switch to main, fix it, switch back, and your agent loses the thread of what it was doing. With a worktree the feature branch never moves.

Create a worktree off main, fix the bug there, open a PR, and merge it. Your feature agent keeps working in its own directory the entire time. When both are done, you merge the feature branch into main and run one combined test pass. The bugfix and the feature never shared a working directory, so there was nothing to untangle.

This also works for throwaway experiments. Want an agent to try a risky refactor or a new library without touching your real branch? Give it a worktree. If the experiment fails, git worktree remove discards the directory and branch. If it works, you merge it like any other change. The experiment is disposable, but your main branch stays clean either way.

Recombine Without the Headache

The hardest part of parallel agent work is not isolation, it is putting the pieces back together. Four strategies work in practice.

Sequential integration is safest: merge one worktree into main, fix conflicts, then merge the next. Rebase before PR keeps history linear and is the most recommended convention for parallel worktree development. Pre-merge conflict detection tools run git merge-tree between worktree pairs without touching the repo, catching overlaps before agents sink hours into conflicting edits. Cherry-pick selection fits the ensemble pattern, where several agents solve the same problem and you keep the best commits from each.

Two facts keep integration cheap. Branches that diverge for a long time and touch the same central interface produce the worst conflicts, so merge sooner and keep tasks small. And review, not git, becomes the ceiling: most teams find three to five concurrent worktrees is the sweet spot before coordination overhead eats the speed gain.

Key Takeaways

  • One shared checkout with two agents causes file collisions, context contamination, and index corruption. Worktrees separate files and branches while sharing one .git history.
  • Setup is one command per task: git worktree add. Claude Code shortens it to claude --worktree; Codex needs the manual pattern.
  • Every worktree needs its own dependencies and a unique port. A fresh checkout has no node_modules, .env, or build cache.
  • Worktrees isolate the filesystem, not the database, ports, or Docker daemon. Solve shared services at the service layer.
  • Merge sequentially with tests between merges. Keep three to five worktrees before review becomes the bottleneck.

Final Thoughts

Git worktrees have become the default baseline for multi-agent coding in 2026, not an advanced trick. The commands are simple, the isolation is real, and the cleanup is just git worktree remove plus git worktree prune. Start with one extra agent on a risky refactor you would otherwise avoid. When that works, add a second. The speed is in the parallelism, but the safety is in the boundaries.

Want more hands-on agent workflows? Our vibe coding guide for solo developers covers the daily loop, and our rules files guide shows how to keep every agent on the same conventions. New to agents? Start with building custom MCP servers to wire your tools in.

Irfan is a Creative Tech Strategist and the founder of Grafisify. He spends his days testing the latest AI design tools and breaking down complex tech into actionable guides for creators. When he’s not writing, he’s experimenting with generative art or optimizing digital workflows.

Leave a Reply

Your email address will not be published. Required fields are marked *

You might also like
Run AI Workflows in Isolated Docker Containers: A Guide

Run AI Workflows in Isolated Docker Containers: A Guide

Script GitHub CLI to Automate Repo Workflows

Script GitHub CLI to Automate Repo Workflows

How to Connect MCP Servers to Your Coding Agent

How to Connect MCP Servers to Your Coding Agent

Claude Code Subagents vs Copilot Coding Agent

Claude Code Subagents vs Copilot Coding Agent

AI Coding Agents on Large Codebases Without Breaking Things

AI Coding Agents on Large Codebases Without Breaking Things

Claude Code vs Cursor vs Copilot: Which Coding Agent Ships

Claude Code vs Cursor vs Copilot: Which Coding Agent Ships