Skip to content

A Git worktree gives each parallel coding agent task its own working directory and branch while sharing one Git object store. Developers and tech leads use worktrees—paired with per-stream port blocks, development-only config allowlists, overlap checks, and safe cleanup—to run two to four concurrent streams in Claude Code, Codex, or Cursor without file collisions.

You open three terminals in the same checkout. Agent one’s formatter rewrites a file agent two is editing, agent two’s dev server silently grabs the next free port, and agent three’s end-to-end tests pass against agent two’s running server. All three report “done”, yet none proved which code actually passed.

When parallel worktrees pay off—and when to serialize

Section titled “When parallel worktrees pay off—and when to serialize”

Parallel streams multiply output only when tasks touch disjoint files and each has a machine-checkable gate. Your bottleneck is almost always review capacity rather than model concurrency; two to four active streams keep verification and integration manageable for one developer.

SituationExecution patternRationale
2–4 fixes or features in disjoint modules, each with testsParallel worktrees, one stream per taskIndependent diffs and independent gates
One tricky design with two competing architecturesSame spec in two worktrees; keep the cleaner passing diffObjective comparison against identical tests
Two tickets modifying the same API, schema, or shared configSingle stream, executed sequentiallyParallel edits guarantee semantic conflicts and rework
Read-only codebase investigation or PR auditScoped subagent inside one sessionNo separate checkout or branch overhead needed

For broader choices across worktrees, subagents, and background queues, see orchestration patterns.

What a worktree isolates—and what remains shared

Section titled “What a worktree isolates—and what remains shared”

Every worktree owns its working tree, staging index, and checked-out branch, while sharing .git history, refs, and git config. Everything outside Git stays shared unless your setup isolates it:

ResourceIsolated by Git worktree?Failure mode if ignored
Tracked files and branchYesSolved natively by worktrees
Gitignored files (.env, dependencies)Absent in fresh worktreeBuilds fail or the agent invents placeholder config
Dev-server and test portsNoSilent port fallback causes cross-stream test contamination
Local database, cache, queuesNoConcurrent migrations or seeds corrupt shared state
git configNoWriting config inside one worktree mutates every worktree
Cloud credentials, secrets, deploysNoAny stream can still reach shared remote resources

Native worktrees across Claude Code, Codex, and Cursor

Section titled “Native worktrees across Claude Code, Codex, and Cursor”

All three tools support isolated worktrees natively, differing in where checkouts live and what ignored files carry over. Consult official docs for current flags and UI flows:

Claude Code supports built-in worktree sessions and subagent worktree isolation, copying gitignored development files listed in a root .worktreeinclude allowlist. Add its worktree directory to .gitignore, keep .worktreeinclude restricted strictly to local dev files (never production secrets), and note that non-interactive runs leave worktrees behind for explicit cleanup. See the Claude Code docs.

Encode the isolation contract in repository scripts

Section titled “Encode the isolation contract in repository scripts”

Native tool commands create isolated files, not port blocks or safe cleanup. Commit a thin repository wrapper (bin/wt new <slug> and bin/wt cleanup <slug>) so every developer and agent follows the exact same contract:

  1. Create with explicit base and port block (wt new): Fetch origin, branch agent/<slug> from the default branch, assign the lowest free port index (stride 10 so accidental fallbacks stay inside the stream’s block), record WT_INDEX, WT_BASE, APP_PORT, and DB_PORT into a gitignored .wt-env, copy only an explicit allowlist of development config files, and install dependencies cleanly.
  2. Bind servers and tests strictly to .wt-env: Read APP_PORT from .wt-env inside your dev server and E2E configuration, enabling strict port mode so the server exits instead of silently shifting ports:
playwright.config.ts
import { readFileSync } from 'node:fs';
import { defineConfig } from '@playwright/test';
const wtEnv = (() => {
try { return readFileSync('.wt-env', 'utf8'); } catch { return ''; }
})();
const port = /^APP_PORT=(\d+)$/m.exec(wtEnv)?.[1] ?? '4321';
const baseURL = `http://localhost:${port}`;
export default defineConfig({
use: { baseURL },
webServer: {
command: `pnpm dev --port ${port} --strictPort`,
url: baseURL,
reuseExistingServer: !process.env.CI,
},
});
  1. Remove safely (wt cleanup): Refuse removal if git status --porcelain is non-empty, if a port from .wt-env still has a live listener, or if the branch contains commits missing from origin.
  1. Partition independent tasks first. Before creating checkouts, verify candidate tickets touch disjoint files and public contracts; serialize any overlapping work.
  2. Spawn 2–4 streams via your wrapper script. Start one agent session inside each worktree directory with explicit path boundaries and its .wt-env port contract.
  3. Require local gates inside each worktree. Each agent finishes only when typecheck, lint, and tests exit 0 inside its own checkout—ideally enforced by a Stop hook.
  4. Integrate sequentially and rebase. Merge one PR at a time, rebase remaining active branches onto updated main, re-run gates, and clean up merged worktrees with your safe cleanup script (review queue).

Verify parallel streams without reading every diff

Section titled “Verify parallel streams without reading every diff”

Check four mechanical proofs before opening or reviewing pull requests:

  • Overlap check across active stream branches: Run from the main checkout; any printed filename means two streams collided and one must pause until the other merges and rebases:
Terminal window
for b in $(git for-each-ref --format='%(refname:short)' refs/heads/agent/ 'refs/heads/worktree-*'); do
git diff --name-only "origin/main...$b"
done | sort | uniq -d
  • Checkout and port verification: Confirm git merge-base HEAD origin/main matches the intended base and confirm any running server on APP_PORT belongs to that worktree directory.
  • Automated Station 4 audit: Run npx @wondelai/harness-audit to verify Station 4 (Graph) checks worktree scripts, .worktreeinclude hygiene, and port/state isolation (harness audit guide).
  • Evidence bundle: Attach exact commands, exit codes, and changed file lists to each PR (evidence bundle).
  • Tests pass against a neighbour’s server. Missing strictPort or hardcoded E2E URLs mask broken code. Stop all dev servers, bind servers and test URLs strictly to .wt-env, and discard earlier unproven green results.
  • Fresh worktrees fail to build. Missing dev configs or dependencies stall the agent. Add dev-only files to your wrapper allowlist or .worktreeinclude and automate dependency installation during worktree creation.
  • Commits vanish after cleaning up a detached HEAD. Rescue commits via git reflog before pruning, and require every stream prompt to check git branch --show-current and create a named branch before editing.
  • Two streams pass independently but break after merging. They edited an implicit shared contract. Rebase the second stream onto updated main, re-run its full check suite, and record that contract in your task-splitting checklist.
  • Headless runs abandon locked worktrees. Inspect status to preserve wanted commits, unlock and remove stale worktrees cleanly, and run git worktree prune periodically.

Review current worktree commands, .worktreeinclude semantics, and multi-agent UI workflows in official docs: Claude Code docs, OpenAI Codex docs, and Cursor docs.

Did this guide help you?

One tap, no sign-in.

not at all a lot

Frequently asked questions

What do Git worktrees isolate when running parallel coding agents, and what extra isolation is needed?

Git worktrees give each parallel agent task its own working directory and branch while sharing repository history. Because worktrees isolate files only, each stream also needs its own port block, local state, dev-only configuration allowlist, and independent verification gate.

How many parallel agent streams should a developer run in Git worktrees?

Two to four isolated streams balance throughput against human review capacity, provided each stream passes its own automated check gate and cleanup protects unpushed commits.