All posts

Parallel AI Coding Agents and Git Worktrees: What They Miss

Devdatta Narawade11 min read

Run two AI coding agents in the same checkout and they will eventually step on each other. One agent rewrites a file while the other is halfway through editing it. The usual fix is a git worktree for each agent, and for the failure it targets, that fix works.

A worktree gives each agent its own working directory and branch while the repository history stays shared. That removes overwrites. It does not remove the harder problems: two diffs that merge cleanly but contradict each other, broken builds after a merge, and shared ports and databases. This post covers what worktrees solve, what they leave open, and the practices that close the gap when you run several parallel AI coding agents at once.

What worktrees isolate, and where isolation stops

A git worktree is a second checkout of the same repository. It has its own files, its own index and its own branch, while the object store and remote are shared. A new worktree costs little disk space and needs no second clone.

What it fixes: overwrites and index contention

Two agents cannot edit the same file on disk, because each edits its own copy. Each worktree has its own index, so git commands running in different directories do not contend for one index lock. An agent's view of the code also stays steady while it works, since nothing else changes its files underneath it.

What Claude Code does with worktrees

Claude Code's documentation describes the same model. Running claude --worktree <name> (or -w <name>) creates a worktree at .claude/worktrees/<name>/ under the repository root, on a new branch called worktree-<name>. The docs recommend adding .claude/worktrees/ to .gitignore, so the checkouts do not appear as untracked files in the main checkout.

A worktree is a fresh checkout, so untracked local files are missing from it. A .worktreeinclude file at the project root copies them in when Claude creates a worktree. The file uses .gitignore syntax, and only files that match a pattern and are also gitignored are copied, so tracked files are never duplicated.

Where isolation stops

The same documentation is clear that worktrees isolate file edits. Subagents split work inside one session, and cross-session messaging lets Claude pass findings between the sessions in your worktrees. Those are separate mechanisms that complement worktrees rather than replace them.

Isolation says nothing about which task each agent should do, which ports it may bind, or whether the branches will still work together. Those questions are where parallel runs usually fail, and the rest of this post covers them. The harness architecture is the layer where those limits belong, and it is worth designing before the first agent starts.

Clean merges can still break the build

Worktrees turn silent corruption into a conflict you can see. That is a real improvement, and it is also where the hard work starts. Git merges text. It does not know what each agent meant.

A clean merge is not clean code

Two agents can produce diffs that merge with no conflict markers and still break the build. One renames a helper while the other starts calling the old name. One changes a default timeout while the other adds a test that assumes the old value. The merge is clean, the suite fails, and git flags nothing. Parallel agents make this more likely because each one changes more code in the same period, so the chance that two sets of edits touch related logic goes up.

Intent conflicts are invisible to git

Two plans can contradict each other while their diffs merge cleanly. For example, agent A decides that session tokens expire after 15 minutes, while agent B, on a separate branch, decides refresh tokens should last 30 days. Neither diff touches the other's lines, yet the product now has two rules that cannot both hold.

No worktree catches this. Only a person who reads both plans, or a check that compares both against a shared specification, can. That is why the task definition matters as much as the isolation.

Serial merges stop the cascade

If you merge branches in whatever order they finish, one broken merge can hide the next. Merge in dependency order instead. Land the branch that others depend on first, re-run the suite, then move on.

Task contracts: the boundary worktrees do not draw

A worktree does not tell an agent what it is for, which files it may change, or whether another agent already owns the module. A task contract closes that gap.

Ownership and overlap

Before you start a batch, check that the tasks change different things. Split the work along file or module boundaries, and do not run two tasks whose plans touch the same module at the same time. Overlap is easy to catch before anything starts and hard to untangle after both branches have changed the same code.

Allowed and forbidden paths

Write a short file in each worktree that lists the goal, the allowed paths, the forbidden paths and the done condition. An agent asked to change one endpoint will otherwise tidy the neighbouring files, and those edits merge quietly into someone else's branch. The contract makes the boundary explicit for the agent and for the reviewer.

Enforcing the contract at review

A rule the agent can ignore is only a suggestion. A simple check can compare the diff against the allowed list and fail the run when a file outside it changed. Run that check before human review, so reviewers see only in-scope changes. The what an agent can reach applies the same principle to security: limit what the agent can touch, then verify it.

Ports, databases and caches are still shared

Isolated files do not give you isolated runtime resources. Two agents that each start a dev server on port 3000 will collide. Two test suites that write to one database produce results that depend on run order, and the failure looks like a code bug that points at neither branch.

Port ranges per worktree

Assign each worktree its own port range and write it into the task file. Agents should read their port from the contract rather than choose one at random. A check at the start of each run, confirming the port is free, catches most collisions before they cause confusing failures.

A database schema or container per task

Give each task its own database schema or container. If tests share one database, the results depend on run order, and the team can spend days chasing failures that are not in the code. Drop the schema when the task ends so stale data does not accumulate.

Fail loudly instead of killing processes

An agent that hits "port already in use" should stop and report the conflict. It should not kill the process holding the port, because that process may belong to a sibling agent. Put the stop-and-report rule in the contract, so a collision becomes a visible failure rather than silent interference.

Verifying and rolling out parallel work

Parallel work needs serial integration. Without it, a fast pipeline becomes a fast way to break main.

Test each pair before merging

Before either branch lands in main, run the suite on the merged result of each pair of agent branches. Git 2.38 and later support git merge-tree --write-tree, which computes a merge without touching your working copy. You can script the pairwise check against that command. It produces the merged tree but does not run tests, so you still need to run the suite against that result, for example in a temporary worktree.

Merge in dependency order and re-verify

Land one branch, re-run the suite on main, then move to the next. Skipping the re-run is how a green branch turns main red. If a merge fails, stop the batch and resolve it before anything else lands.

Clean up at exit

When you exit an interactive Claude Code session in a worktree that Claude created with git, Claude checks for changed or untracked files, uncommitted work inside checked-out submodules, and new commits. For an unnamed session, a clean worktree and its branch are removed automatically. A named session prompts you first so you can keep the worktree for later. If the worktree has work in it, Claude prompts you to keep or remove it, and removing deletes the directory and branch along with that work.

Gitignored files such as .env do not count as work, so you can lose them at exit. Copy out anything you need first. Non-interactive -p runs have no exit prompt, so remove those worktrees yourself with git worktree remove. In your own setup, clear finished worktrees and their branches on a schedule so stale branches do not pile up.

A setup for two to four agents

For a small team, run parallel agents in three stages and cap concurrency at two to four. Each extra agent adds reviews, and the review queue is usually where parallel work stalls, so add agents one at a time and watch how long branches wait before you add the next.

Prepare one contract per task

Write one task file per agent, with the goal, allowed paths, forbidden paths, port range, database schema and done condition. Check overlap before you start. If two tasks touch the same module, run them one after the other. Create one worktree per task, with one branch and one recorded base commit.

Run and test pairs before merging

Run each agent against its contract, and reject out-of-scope diffs before human review. Then test each pair of branches with the in-memory merge check. A clean merge that fails the suite goes back to the agent, not into main.

Merge in order and clean up

Merge one branch at a time in dependency order, and re-run the suite after each merge. When the batch is done, remove the finished worktrees and their branches. The how coordinating many agents is organised covers the same coordination problem at larger scale, and the cost side of spreading work across subagents covers the token spend that comes with running more agents.

AutoCoder runs on your own Windows machine with your own DeepSeek key. It works one ticket end to end on your machine and hands back the diff with the token cost of the run. One bounded task per run matches the contract approach above: one branch, one scope, one cost report. When you compare batches, measure cost per completed task rather than cost per run, so a run that fails and is retried is counted honestly.

Parallel runs do not remove conflicts. Worktrees reduce one class of failure. Overlap checks, task contracts, pairwise merge tests and serial integration are still your responsibility, and that is where most of the real engineering effort sits. Treat the tooling as a way to run disciplined parallel work, not as a substitute for the discipline.

Try AutoCoder.dev free on one bounded task with a task file, and compare its cost and merge result with your last batch.

FAQ

Do git worktrees stop AI coding agents from conflicting?

They stop agents from overwriting each other's files on disk. They do not stop intent conflicts, where two diffs merge cleanly but contradict each other, or merges that break the build. Those need overlap checks, pairwise merge tests and serial integration.

How many AI coding agents should run in parallel?

Start with two. Keep the number at two to four, and add agents only when the review queue can keep up. Beyond that, reviewers become the bottleneck and the time saved by parallel generation is lost.

What is a task contract for an AI agent?

It is a short file that sits with the worktree and lists the goal, the allowed paths, the forbidden paths, any port or database assignment and the done condition. A contract is only useful when a check enforces it, so reject diffs that touch paths outside the allowed list.

Does Claude Code support git worktrees?

Yes. Running claude --worktree <name> creates a worktree under .claude/worktrees/<name>/ on a new branch named worktree-<name>. The official docs also cover subagent isolation, a .worktreeinclude file for copying gitignored files such as local config, and the checks Claude runs at exit.

How do I check that parallel branches will merge safely?

Run the test suite on the merged result of each pair of agent branches before merging either one into main. Git 2.38 and later support git merge-tree --write-tree, which computes the merge without changing your working copy. Then merge serially and re-run the suite after each merge.

AutoCoder Premium Brief · daily at 07:00 IST

One AI-coding story a day. Explained.

Every issue starts from a post like this one and condenses it to the part you can act on today — the mechanism, the sources, and what to do about it.

  • The one release, advisory or benchmark that changes how you build
  • The mechanism in four minutes, with every source linked
  • One thing to do today

One email with a full sample issue and the plans. Nothing else unless you subscribe.

Then $9 / 30 days or $90 / year · in India ₹299 / 30 days or ₹2,499 / year · See the plans

TaggedAI Coding AgentsGit WorktreesParallel AgentsAgent OrchestrationMerge ConflictsTask ContractsClaude CodeAgentic Engineering

Related reading