Coding agents · Git · Multi-agent systems

Run Parallel Coding Agents Safely with Git Worktrees

Give each coding agent an isolated branch and working directory, then integrate changes through explicit ownership, verification, and cleanup.

Published
Updated
Code examples
Illustrative
Reading time
7 minutes

Run each coding agent in its own Git worktree on its own branch, created from the same immutable base commit. Assign non-overlapping files or interfaces when possible, isolate ports and mutable dependencies, verify each patch independently, and merge through one integration branch. Worktrees prevent agents from sharing a working directory; they do not provide a security sandbox or eliminate semantic conflicts.

This guide is for trusted automation on one repository. If generated commands may be hostile, place every worktree inside a stronger execution boundary; see Sandbox Untrusted Agent Code.

Understand what a worktree isolates

A normal repository has one working tree. Git's git worktree documentation explains that linked worktrees attach additional working trees to the same repository. They share repository data but have per-worktree files such as HEAD and index.

That gives each agent separate:

  • checked-out files;
  • current branch and HEAD;
  • staging index;
  • untracked files within its directory.

It does not automatically separate:

  • the object store and repository configuration;
  • hooks or other shared Git administration;
  • dependency caches outside the worktree;
  • databases, queues, cloud resources, ports, or environment variables;
  • files an agent can reach outside its directory;
  • logical ownership of APIs, schemas, or generated artifacts.

Treat a worktree as a concurrency primitive. Use operating-system or virtualized isolation for security.

Start every task from one recorded base

Resolve the integration branch to a full commit identifier before delegation. Then create a unique branch and path for each task. The commands below are illustrative; choose paths outside the primary working tree and compatible with your cleanup policy.

git rev-parse --verify main^{commit}
git worktree add -b agent/search ../worktrees/search <base-commit>
git worktree add -b agent/billing ../worktrees/billing <base-commit>
git worktree list --porcelain

The worktree manual documents add, list --porcelain, lock, remove, prune, and repair. Porcelain output is intended for scripts; do not scrape the decorative human format.

Git normally refuses to check out one branch in multiple worktrees. Keep that protection. A branch-per-agent makes ownership, review, and cleanup explicit.

Record a manifest before execution:

baseCommit: 0123456789abcdef
integrationBranch: integrate/checkout-redesign
agents:
  - id: search
    branch: agent/search
    path: ../worktrees/search
    owns:
      - src/search/**
      - tests/search/**
  - id: billing
    branch: agent/billing
    path: ../worktrees/billing
    owns:
      - src/billing/**
      - tests/billing/**

Ownership is policy, not a Git feature. Your orchestrator must compare the final changed paths with the manifest.

Partition work by contract, not just directory

The easiest parallel tasks have a narrow output and a stable boundary: one migration plan, one test fixture, one adapter, or one documentation section. Two agents can edit different files and still conflict if both change the same public type, database table, generated schema, or user flow.

Before starting, write each task as:

  • objective and acceptance criteria;
  • allowed and denied paths;
  • input interfaces and expected output interfaces;
  • commands the verifier will run;
  • dependencies on other tasks;
  • conditions that require escalation.

Use a dependency graph. If task B consumes an interface invented by task A, either run A first or freeze that interface in an integration commit before B starts. Parallelism helps only when work is genuinely independent; Make Agent Swarms Faster and Cheaper with Bounded Parallelism covers the scheduling tradeoff.

Avoid having every agent update central registries, snapshots, lockfiles, generated clients, or changelogs. Assign those shared artifacts to one integration task after leaf changes land.

Isolate the environment around each worktree

Most parallel failures happen outside Git. Give every agent distinct mutable resources:

ResourceSafe default
Development portderive from agent ID or allocate from a broker
Test databaseunique database or schema per run
Queue/topicunique namespace
Temporary directoryunique absolute path
Browser storagefresh context and state file
Build outputinside the worktree or unique cache key
Dependency cacheread-only shared cache or concurrency-safe manager
Credentialsshort-lived, minimum scope, absent unless required

Do not symlink one mutable node_modules, virtual environment, build directory, or generated output tree into every worktree. Package managers and compilers may write metadata during otherwise read-only-looking commands. Prefer immutable caches plus per-worktree installations or a tool's documented concurrency-safe store.

Never copy the primary worktree's .env by default. If a test needs configuration, generate a run-specific file containing synthetic endpoints and narrowly scoped credentials.

Capture and gate each patch

After an agent stops, inspect its worktree rather than trusting its summary:

git -C ../worktrees/search status --porcelain=v1
git -C ../worktrees/search diff --check
git -C ../worktrees/search diff --binary <base-commit>

git status describes porcelain formats, and git diff documents --check and binary patch output. Include untracked files in your own capture logic; a plain diff does not serialize them.

Reject or escalate if the observed patch:

  • touches a denied or unowned path;
  • changes submodule pointers unexpectedly;
  • edits workflow, ownership, secrets, or deployment policy;
  • modifies a shared interface without the declared dependency;
  • contains generated output without its source;
  • exceeds file-count or byte limits;
  • removes or weakens acceptance tests.

Commit only after the patch passes policy and trusted checks. The commit message should carry the task ID and base commit so integration can trace provenance.

Verify in two stages

Run a fast task-specific verifier in the agent worktree, then rerun integration checks after combining branches. A green leaf branch does not prove the combined system works.

Leaf verification should include:

  1. path and patch policy;
  2. formatter or generated-file checks;
  3. tests closest to the changed behavior;
  4. typecheck and lint for the affected package;
  5. build or security checks appropriate to risk.

Integration verification should include:

  1. clean merge or cherry-pick of approved commits;
  2. regeneration of intentionally centralized artifacts;
  3. cross-package and end-to-end tests;
  4. database or API compatibility checks;
  5. a full repository status check for unexpected files.

Run these commands from trusted configuration, not a list rewritten by an agent. Preserve exit code and logs. Distinguish a test failure from a timeout or infrastructure failure.

Choose an integration strategy deliberately

Cherry-picking reviewed commits onto a fresh integration branch provides a simple audit trail and lets the integrator control ordering. Merging each agent branch preserves branch topology. Either can work; consistency and verification matter more than the choice.

Integrate lower-level contracts before their consumers. If two branches conflict, do not ask a third agent to mechanically select both sides. Restate the invariant, inspect both patches, and make one owner responsible for the resolution plus new tests.

Do not continually rebase active agent worktrees onto a moving integration branch. It destroys the shared experimental base and makes comparative evaluation harder. For long tasks, stop at a checkpoint, record the old state, then start a new task from a new base.

Recover and clean up safely

Check the worktree registry before deleting a directory:

git worktree list --porcelain
git worktree remove ../worktrees/search
git worktree prune --dry-run

Use git worktree remove for normal cleanup. The worktree documentation notes that a dirty worktree requires force and that locked worktrees cannot be removed; inspect why before overriding either condition. Use lock for a worktree stored on removable or intermittently mounted storage. Use repair when administrative links are stale after paths move.

Never make a broad recursive deletion part of the ordinary agent prompt. The orchestrator should resolve an exact registered path, verify it is beneath a dedicated worktree parent, confirm the task is terminal and artifacts are retained, and then invoke the narrow Git cleanup operation.

Pruning removes stale administrative information, not a branch. Delete branches only under a separate retention policy after their commits are merged or intentionally abandoned.

Know when not to parallelize

Use one agent when tasks share the same core files, requirements are still ambiguous, verification is slow and global, or the work is a single ordered migration. Parallel worktrees add setup, compute, review, and integration overhead.

Good parallel candidates are independent tests, adapters behind a frozen interface, documentation pages, or separate packages with explicit contracts. Start with two agents, measure successful-task lead time and reviewer burden, then raise concurrency only if integration remains cheaper than the time saved.

Operational checklist

  • All branches start at one recorded base commit.
  • Each agent has a unique branch, path, task ID, and resource namespace.
  • Allowed paths and interface ownership are recorded before execution.
  • Shared mutable dependencies, ports, and databases are isolated.
  • Credentials are absent by default and never copied from the primary worktree.
  • Git independently captures tracked, untracked, and submodule changes.
  • Leaf checks pass before integration.
  • Combined checks pass on a fresh integration branch.
  • Conflict resolution has one accountable owner.
  • Cleanup uses the registered exact path and preserves audit artifacts.