# Run parallel agents in isolated worktrees

URL: https://developertoolkit.ai/en/workflows/harness/git-worktrees/
Description: Run two to four parallel coding agents safely in Git worktrees across Claude Code, Codex, and Cursor with port blocks, overlap checks, and safe cleanup.

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

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](/en/claude-code/automate/custom-subagents/) inside one session | No separate checkout or branch overhead needed |

For broader choices across worktrees, subagents, and background queues, see [orchestration patterns](/en/workflows/automate/orchestration-patterns/).

## 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 |

**A worktree is never a security sandbox**

Every local worktree inherits your workstation's network, cloud sessions, and credentials. Enforce hard containment with [permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/), and move tasks needing dedicated databases or service stubs into [ephemeral environments](/en/workflows/harness/ephemeral-environments/).

## 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**

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](https://code.claude.com/docs).

**Codex**

Codex creates managed worktrees via CLI or in-session commands ([isolated Codex worktrees](/en/codex/automate/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](https://developers.openai.com/codex).

**Cursor**

Cursor supports Worktrees alongside its Agents Window for side-by-side execution ([Cursor Agents Window](/en/cursor-ide/build/agents-window/) · [Cursor docs](https://cursor.com/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

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:

```ts title="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,
  },
});
```

3. **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`.

## Run parallel streams from split to merge

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](/en/workflows/harness/agent-hooks/).
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](/en/teams/review-queue/)).

**Copy-paste prompt: verify stream independence before branching**

```text
Read issues #412, #415, and #418 without editing code. For each issue list:
- Expected files and modules modified
- Shared contracts touched (API routes, DB schema, exported types, configs)
- Executable test or acceptance check proving completion
Output a table marking each issue "parallel" or "after #<id>" so no two parallel
worktrees edit the same file or shared contract.
```

## 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:

```bash
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](/en/workflows/harness/harness-audit-guide/)).
- **Evidence bundle:** Attach exact commands, exit codes, and changed file lists to each PR ([evidence bundle](/en/workflows/ship/evidence-bundle/)).

## When parallel worktrees break

- **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.

## Official docs and next steps

Review current worktree commands, `.worktreeinclude` semantics, and multi-agent UI workflows in official docs: [Claude Code docs](https://code.claude.com/docs), [OpenAI Codex docs](https://developers.openai.com/codex), and [Cursor docs](https://cursor.com/docs).

- [Ephemeral environments](/en/workflows/harness/ephemeral-environments/) — Add per-task databases, service stubs, and teardown when file isolation is not enough.
- [Orchestration patterns](/en/workflows/automate/orchestration-patterns/) — Choose between worktrees, subagents, and background queues by task shape.
- [Isolated Codex worktrees](/en/codex/automate/worktrees/) — Handle managed Codex worktrees, branches, and cleanup cleanly.
- [Review queues](/en/teams/review-queue/) — Prevent parallel agent streams from turning pull-request review into a bottleneck.
