Topics
Recent articles

Developer Tools

Git Worktrees for Parallel AI Coding Agents

Use Git worktrees to give parallel coding agents isolated files and branches without cloning the same repository for every task.

Table of Contents11 sections
Two computer monitors on a developer desk showing code
Parallel coding agents need separate working directories and branches, not simultaneous edits in one checkout.

Running two coding agents against the same repository sounds efficient until both touch the same checkout. One agent switches branches while another is still editing. Generated files appear unexpectedly. A formatter rewrites code another task is reviewing. Even when the agents are solving unrelated problems, they are competing for one mutable working directory.

The practical fix is to give each active task its own Git worktree and branch.

A Git worktree lets one repository expose multiple working directories at the same time. The worktrees share the repository’s Git object database, but each linked worktree has its own HEAD, index, and checked-out files. That makes worktrees a useful isolation boundary for parallel coding agents without requiring a full independent clone for every task.

Worktrees do not eliminate merge conflicts or coordination. They solve a narrower problem: keeping concurrent agents from trampling the same checkout.

Why One Checkout Becomes a Shared Mutable Resource

A normal repository checkout assumes one active filesystem state.

Consider two agents:

Agent A: refactor authentication
Agent B: fix checkout validation

If both operate in the same directory, they can interfere even when their intended file sets barely overlap. A branch switch changes the files underneath both processes. git reset, cleanup commands, dependency installation, code generation, and formatters can also affect the shared workspace.

This is different from a merge conflict. A merge conflict happens when Git combines incompatible histories. Shared-checkout interference happens earlier, while work is still being produced.

That distinction matters in autonomous workflows. The safest handoff process cannot compensate for a workspace that changed underneath the agent. The RayLabs guide to AI agent handoffs and context recovery covers continuity between agents; worktrees address isolation while agents are active at the same time.

The Basic Worktree Pattern

Suppose the main checkout is:

/srv/shop-app

Keep it as the integration workspace, then create one linked worktree per task:

cd /srv/shop-app

git fetch origin

git worktree add -b agent/auth-refactor \
  /srv/worktrees/shop-app-auth \
  origin/main

git worktree add -b agent/checkout-fix \
  /srv/worktrees/shop-app-checkout \
  origin/main

The resulting layout is:

/srv/shop-app            main integration checkout
/srv/shop-app-auth       agent/auth-refactor
/srv/shop-app-checkout   agent/checkout-fix

Agent A receives only /srv/shop-app-auth. Agent B receives only /srv/shop-app-checkout.

Git’s worktree documentation describes linked worktrees as separate working trees attached to the same repository. Per-worktree state such as HEAD and the index is separate, while repository data and most refs are shared.

That is exactly the boundary a parallel agent runner needs.

Use One Branch Per Agent Task

Do not create multiple worktrees that conceptually represent the same mutable task.

A simple naming convention is enough:

agent/<ticket-or-purpose>

For example:

agent/login-timeout
agent/payment-tests
agent/update-readme

The branch should describe the unit of integration, not the model or vendor executing it. An agent may be replaced halfway through a task, but the branch still represents the same change.

This also makes handoff easier. A replacement agent can inspect:

git status
git log --oneline --decorate -5
git diff origin/main...HEAD

The state is anchored in Git instead of depending on a long chat transcript.

Why Worktrees Are Better Than Copying the Folder

A manual folder copy looks similar on disk but has worse semantics.

shop-app-copy-1/
shop-app-copy-2/

Those directories may contain duplicated build output, stale untracked files, different remotes, or changes that never become commits. It is also easy to forget which copy is authoritative.

Worktrees remain explicitly registered with Git:

git worktree list

That command shows each linked directory, commit, and checked-out branch. The repository therefore has a machine-readable inventory of active workspaces.

A full clone still has valid uses. If an agent needs a completely independent Git configuration, object store, network boundary, or disposable container image, a clone may be cleaner. Worktrees are most attractive when tasks run on the same host and should share one repository while isolating filesystem state.

Worktrees Share More Than You May Expect

Filesystem isolation does not mean total isolation.

Most refs are shared across worktrees. Repository configuration is also shared by default. That means an agent can still create branches, tags, or configuration changes that are visible from another worktree.

Treat the worktree as a working-directory boundary, not a security sandbox.

A good agent contract should therefore restrict destructive Git operations. In particular, avoid giving ordinary task agents permission to rewrite shared branches, force-push integration branches, delete unrelated refs, or modify repository-wide configuration.

If separate configuration is required, Git supports worktree-specific configuration through the extensions.worktreeConfig mechanism and git config --worktree. Use that deliberately rather than assuming every config value is already local.

A Safer Parallel Agent Flow

A reliable workflow has four roles even if one orchestration process performs several of them.

1. Coordinator assigns the task

The coordinator starts from an agreed base commit and creates the branch plus worktree.

BASE=$(git rev-parse origin/main)

git worktree add \
  -b agent/payment-tests \
  /srv/worktrees/shop-app-payment-tests \
  "$BASE"

Recording the base SHA matters. If main moves while the agent works, reviewers can still tell exactly what the task started from.

2. Agent edits only its worktree

The agent runs tests, changes files, and commits on its own branch.

It should not switch the main checkout to its branch. It should not enter another agent’s worktree to “help.” Isolation is valuable only if the orchestrator preserves it.

3. Reviewer evaluates the branch

Review the committed diff, not a summary generated by the same agent.

git diff origin/main...agent/payment-tests

Run the repository’s real validation commands in the task worktree or a clean verification environment.

This separation follows the same principle as deciding between AI agents and deterministic workflow automation: use agent reasoning where judgment is useful, but keep integration gates explicit and reproducible.

4. Integrator merges in a controlled order

Two successful agents can still modify overlapping code. Worktrees do not make those changes automatically compatible.

Merge or rebase one task at a time, then rerun validation after integration. If the second branch conflicts with the first, resolve the conflict as an integration problem rather than allowing both agents to mutate the same directory.

Do Not Let Every Agent Merge to Main

Parallel execution and parallel integration are different concerns.

Agents can work concurrently:

             +--> worktree A --> branch A
origin/main -+
             +--> worktree B --> branch B
             +--> worktree C --> branch C

But final integration should pass through a serialized gate:

branch A --+
branch B --+--> review --> test --> integrate --> main
branch C --+

This is especially important when automated agents can push. A green branch-level test only proves that branch against its tested base. It does not prove that three independently green branches remain green after being combined.

For small teams, the integration gate can simply be a pull request queue and CI. For a local orchestrator, it can be a coordinator that merges one approved branch, updates the base, and validates before accepting the next.

Common Failure Modes

Reusing the same branch in two worktrees

Git normally refuses to check out a branch that is already checked out in another worktree. Do not routinely bypass that safeguard with --force. Give each task its own branch.

Deleting a worktree directory manually

If you remove the directory without using Git, administrative metadata can remain behind.

Prefer:

git worktree remove /srv/worktrees/shop-app-payment-tests

If stale metadata already exists, inspect first:

git worktree list
git worktree prune --dry-run

Then prune deliberately.

Treating worktrees as containers

Processes in different worktrees can still share host-level resources such as ports, caches, emulators, databases, credentials, and background daemons.

Two agents starting the same development server on port 3000 will still collide.

Assign per-task ports and disposable external resources where needed.

Sharing generated dependency state blindly

Some ecosystems create large dependency or build directories inside each worktree. That can consume significant disk space.

Do not solve this by symlinking every mutable build directory between agents. Shared writable caches can reintroduce cross-task interference. Prefer ecosystem-supported caches that are designed for concurrent access, and keep task-specific outputs isolated.

Cleaning up before the task is recoverable

A worktree is disposable only after its useful state is committed or intentionally discarded.

Before removal, check:

git -C /srv/worktrees/shop-app-payment-tests status

Git refuses to remove a dirty linked worktree without force in normal cases. Treat that refusal as protection, not inconvenience.

A Minimal Lifecycle Script

The orchestration logic does not need to be elaborate.

Creation:

TASK=payment-tests
PATH_TO_TREE="/srv/worktrees/shop-app-$TASK"
BRANCH="agent/$TASK"

git fetch origin
git worktree add -b "$BRANCH" "$PATH_TO_TREE" origin/main

Inspection:

git worktree list --porcelain
git -C "$PATH_TO_TREE" status --short

Cleanup after the branch is safely integrated or abandoned:

git worktree remove "$PATH_TO_TREE"
git branch -d "$BRANCH"
git worktree prune

Do not automate branch -D as the default cleanup path. A branch that Git considers unmerged deserves inspection.

The Right Mental Model

A worktree is not a copy of the repository in the organizational sense. It is another checked-out workspace attached to the same repository.

For parallel coding agents, that gives a useful division of responsibility:

worktree = filesystem isolation
branch   = change isolation
commit   = recoverable checkpoint
CI       = verification
merge    = integration

Keeping those responsibilities separate makes multi-agent development easier to reason about.

If two agents only need to discuss a design, worktrees add no value. If they need to edit the same codebase concurrently, separate worktrees are a lightweight way to stop the filesystem itself from becoming the first source of conflict.

The rule is simple: one active task, one branch, one worktree, then one controlled integration path back to main.

Continue Exploring

You Might Also Like

View all articles