Run parallel agents in isolated worktrees
PLA 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.
| Situation | Execution pattern | Rationale |
|---|---|---|
| 2–4 fixes or features in disjoint modules, each with tests | Parallel worktrees, one stream per task | Independent diffs and independent gates |
| One tricky design with two competing architectures | Same spec in two worktrees; keep the cleaner passing diff | Objective comparison against identical tests |
| Two tickets modifying the same API, schema, or shared config | Single stream, executed sequentially | Parallel edits guarantee semantic conflicts and rework |
| Read-only codebase investigation or PR audit | Scoped subagent inside one session | No 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:
| Resource | Isolated by Git worktree? | Failure mode if ignored |
|---|---|---|
| Tracked files and branch | Yes | Solved natively by worktrees |
Gitignored files (.env, dependencies) | Absent in fresh worktree | Builds fail or the agent invents placeholder config |
| Dev-server and test ports | No | Silent port fallback causes cross-stream test contamination |
| Local database, cache, queues | No | Concurrent migrations or seeds corrupt shared state |
git config | No | Writing config inside one worktree mutates every worktree |
| Cloud credentials, secrets, deploys | No | Any 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.
Codex creates managed worktrees via CLI or in-session commands (isolated Codex worktrees). Managed worktrees often start on a detached HEAD without gitignored files, so switch to a named branch before committing and provision local config explicitly—or launch Codex inside a worktree created by your repository’s wrapper script. See the OpenAI Codex docs.
Cursor supports Worktrees alongside its Agents Window for side-by-side execution (Cursor Agents Window · Cursor docs). When your stack requires deterministic port blocks and environment setup, create the checkout with your repository wrapper script and open that folder directly in its own Cursor window.
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:
- Create with explicit base and port block (
wt new): Fetchorigin, branchagent/<slug>from the default branch, assign the lowest free port index (stride 10 so accidental fallbacks stay inside the stream’s block), recordWT_INDEX,WT_BASE,APP_PORT, andDB_PORTinto a gitignored.wt-env, copy only an explicit allowlist of development config files, and install dependencies cleanly. - Bind servers and tests strictly to
.wt-env: ReadAPP_PORTfrom.wt-envinside your dev server and E2E configuration, enabling strict port mode so the server exits instead of silently shifting ports:
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, },});- Remove safely (
wt cleanup): Refuse removal ifgit status --porcelainis non-empty, if a port from.wt-envstill has a live listener, or if the branch contains commits missing fromorigin.
Run parallel streams from split to merge
Section titled “Run parallel streams from split to merge”- Partition independent tasks first. Before creating checkouts, verify candidate tickets touch disjoint files and public contracts; serialize any overlapping work.
- Spawn 2–4 streams via your wrapper script. Start one agent session inside each worktree directory with explicit path boundaries and its
.wt-envport contract. - 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
Stophook. - 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:
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/mainmatches the intended base and confirm any running server onAPP_PORTbelongs to that worktree directory. - Automated Station 4 audit: Run
npx @wondelai/harness-auditto verify Station 4 (Graph) checks worktree scripts,.worktreeincludehygiene, and port/state isolation (harness audit guide). - Evidence bundle: Attach exact commands, exit codes, and changed file lists to each PR (evidence bundle).
When parallel worktrees break
Section titled “When parallel worktrees break”- Tests pass against a neighbour’s server. Missing
strictPortor 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
.worktreeincludeand automate dependency installation during worktree creation. - Commits vanish after cleaning up a detached
HEAD. Rescue commits viagit reflogbefore pruning, and require every stream prompt to checkgit branch --show-currentand 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 pruneperiodically.
Official docs and next steps
Section titled “Official docs and next steps”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.
What will you do with it?
How did it read?
What got in the way? Pick any that apply
Your role?
Thanks. I read every answer. Michał Jaskólski
Did this guide help?
One tap each. Close whenever you like.
no sign-in
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.