Git Worktrees for Multiple Coding Agents: Isolation, Integration, and Cleanup
A practical operating model for running Claude Code, Codex, Cursor, and other coding agents in parallel with Git worktrees, bounded scopes, dependency-aware integration, and verifiable cleanup.
Git Worktrees for Multiple Coding Agents: Isolation, Integration, and Cleanup
Git worktrees let multiple coding agents use isolated directories and branches from one repository, so each task has a separate filesystem, diff, checkpoint, and validation surface. They prevent accidental working-tree collisions, but they do not replace task boundaries, dependency planning, evidence handoffs, or integration ownership.
Decompose and approve the work before allocating directories. Task Decomposition for Multiple Coding Agents shows how to stabilize shared contracts, identify producer-consumer edges, and decide which task nodes are ready for isolated execution.
If Claude Code changes an API while Codex regenerates a client and Cursor updates the UI in one checkout, all three processes can alter the index, dependency tree, generated files, and build output at the same time. Even when their intended source files do not overlap, their tools may.
A worktree gives each writer a real boundary:
repository/ integration checkout
worktrees/avatar-api/ agent/avatar-api
worktrees/avatar-client/ agent/avatar-client
worktrees/avatar-ui/ agent/avatar-ui
This guide focuses on the isolation and lifecycle layer. For the broader coordination contract, start with How to Manage Multiple Coding Agents in One Repository. For transferring state between agents or sessions, use the Coding-Agent Handoff Template.
What a worktree isolates—and what it does not
A Git worktree creates another checkout connected to the same repository. Each worktree has its own checked-out branch, working files, and index. The worktrees share Git objects and repository history, so they are lighter than separate clones.
| Concern | Worktree provides | Worktree does not provide |
|---|---|---|
| Working files | separate directory | safe task scope |
| Git index | separate staged state | correct commit boundaries |
| Branch | one checked-out branch per worktree | dependency ordering |
| Build output | separate if generated inside the worktree | isolated external services or ports |
| Dependencies | separate local tree such as node_modules | deterministic versions unless locked |
| Agent context | repository files visible in that checkout | shared authority or instruction precedence |
| Integration | inspectable commits and diffs | conflict ownership or combined proof |
The distinction matters: workspace isolation makes collisions observable; repository orchestration decides whether the work is valid.
The safe worktree lifecycle
The lifecycle begins before git worktree add. The task packet defines why the worktree exists, what it may change, and which proof must come back. A directory without a bounded task is only another place for ambiguity to accumulate.
1. Start from a clean, current integration branch
Use one checkout as the integration control surface. It should not be an agent’s scratch space.
git switch main
git fetch origin
git status --short
git log --oneline --decorate -5
Decide whether tasks start from local main, origin/main, or a named integration commit. Record the exact base in every task packet. “Latest main” is not reproducible after the next push.
A useful allocation record is:
## Allocation
- Task: avatar API contract
- Base: `origin/main@8bf2...`
- Branch: `agent/avatar-api`
- Worktree: `../worktrees/avatar-api`
- Write scope: `packages/api/avatar/**`, `openapi/avatar.yaml`
- Depends on: none
- Produces: stable API contract for client generation
- Validation: `scripts/validate-api avatar`
2. Name worktrees after tasks, not models
Create the branch and worktree together:
mkdir -p ../worktrees
git worktree add -b agent/avatar-api ../worktrees/avatar-api origin/main
git worktree add -b agent/avatar-client ../worktrees/avatar-client origin/main
git worktree add -b agent/avatar-ui ../worktrees/avatar-ui origin/main
Task names are more durable than claude-1, codex-2, or cursor-new. A task may move between tools, but its scope and dependency identity should remain stable.
Inspect the allocation:
git worktree list --porcelain
Before starting an agent, verify three facts inside its directory:
git branch --show-current
git status --short
git rev-parse HEAD
The branch, clean state, and base revision should match the task packet.
3. Give each agent a bounded write surface
A worktree isolates files physically, but two branches can still make incompatible changes. Write boundaries prevent hidden semantic overlap.
| Task | Write scope | Read-only dependency | Must not change |
|---|---|---|---|
| Avatar API | packages/api/avatar/**, OpenAPI source | storage decision | generated clients, UI |
| Client generation | generated/** | stabilized OpenAPI commit | source schema, server behavior |
| Avatar UI | packages/web/avatar/** | generated client commit | API source, generator config |
The important field is Produces for downstream work. Parallel agents should know whether they can start immediately or must wait for a stable upstream checkpoint.
Do not manufacture parallelism across a strict dependency chain. The client task may prepare fixtures or inspect the generator while the API contract is unstable, but it should not generate from an imagined final schema.
4. Isolate more than Git state
Build systems and development services can collide outside Git.
Check these shared surfaces:
- ports and local service names;
- Docker Compose project names;
- temporary directories outside the worktree;
- caches that are unsafe under concurrent writes;
- test databases and schema names;
- browser profiles;
- generated artifacts written to absolute paths;
- credentials and account-sensitive operations;
- package-manager locks and daemon state.
A task packet can assign runtime identity:
Task avatar-api
port: 4311
compose project: agent-avatar-api
test database: app_agent_avatar_api
temp root: .tmp/avatar-api
Task avatar-ui
port: 4312
browser profile: .tmp/browser-avatar-ui
Worktrees solve repository filesystem isolation. They do not sandbox the machine.
5. Require a stable checkpoint and evidence handoff
An agent should not return “done” with an uncommitted tree and a prose summary. It should produce a coherent checkpoint:
git status --short
git diff --check
scripts/validate-api avatar
git add packages/api/avatar openapi/avatar.yaml
git commit -m "feat(api): add avatar upload contract"
git status --short
git rev-parse HEAD
The handoff should identify:
- outcome and completion state;
- exact branch, commit, base, and working-tree state;
- changed and untouched contracts;
- commands and observed results;
- relevant checks not run;
- assumptions and residual risks;
- downstream dependency unlocked;
- recovery checkpoint.
Use the full coding-agent handoff template when the work crosses a tool, owner, session, or approval boundary.
6. Integrate in dependency order, not completion order
Suppose the tasks form this graph:
avatar-api
-> avatar-client
-> avatar-ui
-> combined integration proof
If the UI agent finishes first against a guessed client, its completion time is irrelevant. The integrator should accept work only when its dependencies are stable and named.
A conservative integration sequence is:
git switch integration/avatar
git merge --no-ff agent/avatar-api
git merge --no-ff agent/avatar-client
git merge --no-ff agent/avatar-ui
scripts/validate-api avatar
scripts/validate-client avatar
scripts/validate-web avatar
scripts/smoke-avatar-upload
Cherry-picking can be appropriate when each branch has focused commits and the repository prefers linear integration. Merging can preserve task boundaries and review context. Choose one policy before agents start; do not improvise based on whichever history is easiest to force through.
Rebase only when the dependency plan requires it
If a downstream task needs the exact integrated upstream contract, update it deliberately:
git -C ../worktrees/avatar-client fetch origin
git -C ../worktrees/avatar-client rebase agent/avatar-api
Before rebasing, preserve a clean checkpoint and update the handoff. Do not run background rebases against active agent worktrees. Rebase changes the state the agent and its evidence referred to.
7. Separate worker proof from integration proof
Each worktree proves local claims. The integrated candidate proves cross-task behavior.
| Gate | Owner | Evidence |
|---|---|---|
| Worker | task agent | focused tests, lint, typecheck, generator cleanliness |
| Dependency | upstream/downstream owners | exact contract revision and compatibility check |
| Integration | designated integrator | combined build, cross-package tests, smoke or end-to-end flow |
| Release | maintainer or automation | packaging, install, migration, rollback, release proof |
A green API worktree does not prove the client. A green UI worktree does not prove the merged schema. Validation must broaden as work combines.
This is why branches alone are not an orchestration system. A branch preserves a diff; a repository harness pattern maps claims to executable proof.
8. Retire worktrees without losing state
List the current worktrees and inspect the task branch before cleanup:
git worktree list
git -C ../worktrees/avatar-api status --short
git branch --merged main
git log main..agent/avatar-api --oneline
If the work is integrated and the tree is clean:
git worktree remove ../worktrees/avatar-api
git branch -d agent/avatar-api
git worktree prune
git worktree list
If the branch is not merged, do not use force as a reflex. Decide whether to integrate it, preserve a patch, archive an evidence handoff, or explicitly abandon it. The cleanup record should state which outcome occurred.
Never delete the directory manually as the primary cleanup method. Git may retain stale worktree metadata, and the missing directory hides whether useful uncommitted state was destroyed.
A copyable worktree runbook
# Multi-agent worktree runbook
## Before allocation
- [ ] integration checkout is clean
- [ ] exact base revision recorded
- [ ] task outcome and acceptance defined
- [ ] write scope and forbidden paths defined
- [ ] dependencies and integration order defined
- [ ] runtime resources assigned where needed
## Allocate
- [ ] task branch and worktree created together
- [ ] branch, HEAD, and clean status verified inside worktree
- [ ] canonical AGENTS.md and scoped instructions discoverable
- [ ] agent starts from the task packet, not an improvised prompt
## Execute
- [ ] agent stays within write scope
- [ ] dependency changes are reported instead of guessed
- [ ] focused validation runs inside the worktree
- [ ] stable checkpoint created before handoff
- [ ] exact commands, results, omissions, and risks recorded
## Integrate
- [ ] dependency revisions are compatible
- [ ] commits reviewed in planned order
- [ ] conflicts are resolved by the designated integrator
- [ ] combined validation runs after all relevant changes land
- [ ] durable corrections move to canonical repository sources
## Retire
- [ ] useful state is integrated or preserved
- [ ] worktree is clean
- [ ] handoff is archived or closed
- [ ] worktree removed through Git
- [ ] merged branch deleted according to policy
- [ ] stale metadata pruned
Common failure modes
Several agents share one checkout
The index, generated files, dependencies, and formatter output become shared mutable state. Give every concurrent writer a separate worktree.
Worktrees are created without task packets
Isolation makes the branches easier to inspect but does not tell agents what they own. Pair every worktree with an outcome, scope, dependency, validation, and handoff contract.
Agents branch from different unknown bases
Their changes may appear independent while relying on incompatible contracts. Record the base commit and integration graph before execution.
Tool names become branch identities
codex-task-2 says nothing about the change after another agent takes over. Use task-based identities.
Shared services still collide
Two worktrees both start port 3000, write the same test database, or use one Docker project. Assign runtime resources explicitly.
The integrator merges in notification order
The first “done” message wins even when its dependency is unstable. Integrate by the declared graph.
Validation stops at the worker branch
Every isolated change is green, but the combined candidate fails. Define integration proof before parallel work starts.
Worktrees accumulate forever
Stale directories obscure active ownership and preserve outdated branches. Make retirement a required lifecycle state, not optional housekeeping.
When worktrees are unnecessary
Use a normal branch and one checkout when:
- only one writer is active;
- the task is small and finishes in one short session;
- other agents are read-only;
- the repository tooling cannot safely run twice on the same machine;
- the coordination overhead exceeds the cost of serial execution.
Use separate clones instead when you need stronger separation of Git configuration, object storage, credentials, large-file behavior, or repository-level hooks. Use containers or virtual machines when the threat or dependency model requires process and operating-system isolation.
Worktrees are a lightweight coordination primitive, not a security boundary.
Make isolation part of the repository contract
A durable repository should explain how parallel work is allocated, validated, integrated, and retired. Put the stable rules in root instructions or an operations guide:
## Concurrent coding-agent work
- Every concurrent writer uses a task branch and separate Git worktree.
- Worktrees are named after tasks, not tools.
- The task packet records base revision, write scope, dependencies, and proof.
- Agents do not rebase active worktrees without an explicit integration decision.
- Ready means a stable checkpoint plus an evidence handoff.
- One integrator owns dependency order, conflicts, and combined validation.
- Worktrees are removed only after useful state is integrated or preserved.
The rule is short because detailed commands belong in a linked runbook or script. Root instructions should route agents to the right controller, not become a complete Git manual.
Isolation is the beginning, not the operating system
Git worktrees make parallel coding-agent work observable. Each agent receives a separate directory, branch, diff, and checkpoint. That removes accidental filesystem interference and gives reviewers a stable unit to inspect.
Reliability still comes from the surrounding harness: canonical instructions, bounded task packets, explicit dependencies, validation contracts, evidence handoffs, integration ownership, and safe cleanup.
repository-harness provides a starting structure for turning those controls into repository-visible operating context for Claude Code, Codex, Cursor, and other coding agents.
Related pages
- How to Integrate Changes from Multiple Coding Agents Safely
- How to Manage Multiple Coding Agents in One Repository
- Coding-Agent Handoff Template
- Repository Harness Patterns
- How to Migrate an Existing Repository to a Coding-Agent Harness
- How to Audit a Repository for Agent-Readiness
- How to Prepare Your Repository for Claude Code
- How to Prepare Your Repository for Codex
- repository-harness on GitHub
FAQ
Why use Git worktrees for multiple coding agents?
Git worktrees give each coding agent an isolated directory and branch while sharing one repository object database. That prevents agents from overwriting each other’s working files and makes every task’s diff, checkpoint, validation evidence, and cleanup independently inspectable.
Should every coding agent get its own worktree?
Every concurrent writer should get its own worktree and branch. Read-only research agents may share a clean checkout, but any agent that edits files, runs generators, changes dependencies, or creates build artifacts should work in an isolated directory.
Do Git worktrees prevent merge conflicts between coding agents?
No. Worktrees prevent filesystem collisions, not semantic conflicts. Agents can still change the same contract on separate branches. Prevent that with explicit write scopes, declared dependencies, one integration order, and an integrator who owns conflict resolution and combined validation.
How should I name coding-agent worktrees and branches?
Use task identities rather than model names, for example branch agent/avatar-api and worktree ../worktrees/avatar-api. Task-based names remain meaningful if a different tool resumes the work and make ownership, dependency, and cleanup easier to audit.
Can Claude Code and Codex work in separate worktrees of the same repository?
Yes. Create one task branch and worktree for each tool, give both the same canonical repository instructions, and assign non-overlapping scopes or an explicit dependency order. Each tool should return a stable commit and evidence handoff before integration.
When should I remove a coding-agent worktree?
Remove a worktree only after its useful commits are integrated or preserved, its branch state is understood, its handoff and evidence are archived where needed, and the directory is clean. Run git worktree remove and then git worktree prune; delete the branch only after confirming it is merged or intentionally abandoned.
Are Git worktrees enough to run coding agents safely in parallel?
No. Worktrees provide workspace isolation. Safe parallel execution also needs canonical instructions, bounded task packets, source-of-truth ownership, validation contracts, evidence handoffs, dependency-aware integration, approval boundaries, and a recovery path.