The practical rule is simple: give each coding agent its own branch, its own Git worktree, and a clearly bounded task. A worktree is a separate checkout attached to the same repository. It gives every agent an independent working directory and index while reusing the repository’s shared Git data. That separation prevents one agent’s checkout, staging, or uncommitted edits from silently changing another agent’s environment.
Worktrees do not make parallel work conflict-free. Two agents can still change the same behavior on different branches, and shared services or caches can still collide. Pair filesystem isolation with ownership rules, validation, and one controlled integration point.
Git-specific behavior in this article was checked against the official Git documentation on 2026-07-23.
1. Why agents collide in one checkout
Multiple agents in one working directory share too much mutable state. One agent may switch branches while another is reading files. A formatter can rewrite a file outside its assigned task. One process may stage changes created by another. Generated files, lockfiles, build output, and test databases can change between an agent’s inspection and its edit.
These are not ordinary merge conflicts. They happen before Git has a clean branch boundary from which to explain what changed. Common symptoms include:
- an agent reports edits that disappear after another checkout;
git statuscontains a mixture of unrelated work;- one agent commits another agent’s files;
- tests pass against generated output from a different task;
- cleanup removes files or processes another task still needs;
- reviewers cannot tell which prompt or agent produced a line.
A linked worktree addresses the checkout-level problem. Git supports one main worktree and zero or more linked worktrees, each associated with the same repository. In normal use, each linked worktree checks out a different branch. Git refuses to add a branch that is already checked out elsewhere unless a force option overrides the safeguard. Keep that safeguard: assigning the same branch to two agents defeats the isolation model.
Worktrees are not security sandboxes. An agent that can access parent directories, credentials, the network, or other worktrees may cross the boundary. Use stronger isolation for untrusted code, and follow How to Review AI-Generated Code before integrating sensitive changes.
What a worktree isolates—and what it does not
Git’s glossary draws an important boundary: linked worktrees share most repository metadata, while each worktree keeps its own working tree, index, HEAD, and worktree-specific references. That is enough to isolate normal checkout and staging activity, but not every runtime resource an agent can touch.
| Layer | Separate by default? | Practical control |
|---|---|---|
| Checked-out files | Yes | One worktree path per task |
Index and HEAD | Yes | One branch per worktree |
| Git objects and most repository metadata | No | Treat repository-wide maintenance as integration-owner work |
| Dependencies, build output, ports, and databases | Tool-dependent | Give each task separate mutable state |
| Credentials, network, and parent-directory access | No | Use a sandbox and explicit permissions |
| Merge decisions | No | Use one integration owner and recorded acceptance checks |
Use worktrees for development isolation, then add a real security boundary when the agent or repository content is not fully trusted. How to Sandbox an AI Coding Agent Safely covers that separate layer.
2. Create one worktree per task
Start from a clean integration branch in the main checkout. Fetching remote changes may be appropriate for your workflow, but do not mix network operations into an automated agent bootstrap unless they are explicitly authorized.
Choose a short task identifier and create both a branch and worktree explicitly:
git worktree add -b agent/parser-timeouts ../wt-parser-timeouts main
git worktree add -b agent/docs-errors ../wt-docs-errors main
The last argument is the start point. Replace main with the reviewed commit or integration branch from which both tasks should begin. Explicit branch names are clearer than Git’s convenience behavior, which can derive a branch name from the destination directory.
Confirm the result before launching agents:
git worktree list
git -C ../wt-parser-timeouts status --short --branch
git -C ../wt-docs-errors status --short --branch
Start each agent with its worktree as the working directory. Its assignment should name the task, allowed files, prohibited actions, required tests, and completion evidence. State the observable behavior it must change and what it must leave alone.
For automation, git worktree list --porcelain -z provides a stable, machine-readable form. Avoid parsing the column-aligned human output. Also avoid --force during setup. A refusal usually identifies a real branch or path collision that the orchestrator should resolve rather than bypass.
Use a machine-readable status format in scripts as well:
git -C ../wt-parser-timeouts status --porcelain=v1 -z
Git documents porcelain v1 as stable across versions and user configuration; -z terminates path records with a NUL byte, avoiding ambiguous newline parsing. Human-facing --short --branch remains useful at the terminal, but it is not the best automation contract.
If a worktree is on storage that may be temporarily unavailable, git worktree lock --reason "active agent task" <path> prevents pruning and normal move or removal operations. Ordinary local worktrees usually do not need locking.
3. Assign file ownership and branch rules
Filesystem separation removes accidental shared edits; task design reduces intentional overlap. Before agents start, write a small ownership manifest:
| Task | Branch | Primary ownership | May read | Must not edit |
|---|---|---|---|---|
| Parser timeout | agent/parser-timeouts | src/parser/**, focused tests | entire repository | docs, deployment, unrelated lockfiles |
| Error docs | agent/docs-errors | docs/errors.md | parser and tests | runtime code, package metadata |
Ownership should be exclusive where possible. If two tasks need the same file, either sequence them or assign one agent as the file owner and make the other return a proposed change instead of editing it. A worktree makes overlapping edits safe to store, not cheap to reconcile.
Use one branch per agent task and one integration owner. Agents should not commit to the integration branch, rewrite shared history, delete other branches, remove worktrees, or push unless the workflow explicitly assigns those actions. Give each commit one coherent purpose and require a clean git status at handoff.
Define completion in evidence, not confidence. A useful handoff includes:
- branch name and worktree path;
- commit identifier, or a clear statement that changes remain uncommitted;
- exact files changed;
- tests and checks run, with outcomes;
- known failures and skipped checks;
- assumptions, migrations, generated files, and cleanup needs.
If a task requires an out-of-scope file, the agent should stop that part and propose the smallest ownership change. Silent scope expansion couples supposedly independent branches.
Put stable repository-wide rules—authoritative commands, protected paths, and proof-of-completion requirements—in How to Write an AGENTS.md File That Coding Agents Can Follow. Keep task-specific branch, path, and acceptance details in the individual assignment so the shared guide does not become a queue of temporary work.
4. Share dependencies without sharing edits
All linked worktrees reuse the repository’s Git object store and references, so creating them is usually lighter than making independent clones. Their checked-out files and indexes remain separate. Application dependencies need a more deliberate policy.
Prefer shared immutable caches, separate mutable installations. Package-manager download caches can often be reused because they are content-addressed or otherwise designed for concurrent access. In contrast, a single dependency directory symlinked into several worktrees may contain mutable install state, native build artifacts, or tool-specific metadata. One agent reinstalling packages can then break another agent’s tests.
A conservative layout gives each worktree its own:
- dependency installation directory;
- build output and temporary directory;
- test database or schema;
- local port allocation;
- environment file containing only task-safe values;
- process identifiers and logs.
Share only resources documented as concurrency-safe: download caches, container image layers, compiler caches with safe locking, and read-only datasets. Pin dependencies through the repository’s existing lockfile. If one task must update that lockfile, make it the explicit owner; unrelated agents should not regenerate it.
Assign ports deterministically and give each test run a unique database or namespace. Do not copy production credentials into every worktree. Generated code should have one owner or a reproducible step; each worktree should generate its own uncommitted output instead of reading stale output from the main checkout.
5. Integrate and resolve conflicts deliberately
Integration is a separate job, not the last agent to finish. Keep one checkout reserved for the integration owner. Review each branch independently before combining them:
git log --oneline main..agent/parser-timeouts
git diff --stat main...agent/parser-timeouts
git diff main...agent/parser-timeouts
Run the task’s focused checks in its own worktree first. Then integrate one branch at a time using the repository’s chosen merge, rebase, or cherry-pick policy. After each integration, run the checks that cover the combined behavior. Two branches can pass independently yet fail together because they change assumptions, schemas, types, or generated artifacts.
Begin integration from a clean checkout. Git’s merge documentation warns that git merge --abort may be unable to reconstruct pre-merge changes when a merge starts with non-trivial uncommitted work. A clean integration worktree also makes it easier to attribute every resulting change to the branch being reviewed.
Resolve conflicts by intent. Do not accept “ours” or “theirs” mechanically. Read both task briefs, identify the invariant each change protects, and create a combined implementation. Integrate foundational interfaces before their consumers, and return conflicts when domain knowledge is missing.
Machine checks should gate, not merely annotate, the integration. The approach in Machine Gates for AI Output applies here: define the required commands, fail on missing evidence, and keep human review for semantics and risk. Record which branch introduced a failure rather than asking all agents to revise simultaneously.
6. Clean up safely
Do not delete a worktree directory manually. First verify that the task has been integrated or intentionally abandoned and that no valuable changes remain:
git -C ../wt-parser-timeouts status --short
git log --oneline main..agent/parser-timeouts
git worktree list
If the worktree is locked, unlock it only after confirming why it was locked:
git worktree unlock ../wt-parser-timeouts
git worktree remove ../wt-parser-timeouts
git branch -d agent/parser-timeouts
git worktree remove normally refuses an unclean worktree, and git branch -d normally refuses to delete a branch that is not fully merged under Git’s applicable merge check. Those refusals are useful review gates. Do not turn --force or -D into routine cleanup. If the task is being discarded, capture the decision and inspect the diff before using any destructive override.
If someone already deleted a linked directory outside Git, inspect stale metadata without changing it:
git worktree prune --dry-run --verbose
Run git worktree prune only after the dry run matches the intended cleanup. If a worktree was moved, use git worktree repair instead. The main worktree cannot be removed with git worktree remove.
7. Reusable multi-agent runbook
Use this sequence for every parallel batch:
- Freeze the base. Select one reviewed start commit and record it.
- Decompose the work. Create tasks with independently testable outcomes and minimal file overlap.
- Assign ownership. Give every file and shared resource one primary owner.
- Create branches and worktrees. Use explicit names and paths; never bypass a collision with force.
- Provision isolated runtime state. Separate installs, outputs, ports, databases, logs, and secrets; share only concurrency-safe caches.
- Launch agents with bounded instructions. Include allowed files, prohibited operations, tests, and the required handoff.
- Inspect continuously. Use
git worktree listand per-worktreegit status; stop a task that crosses ownership boundaries. - Validate each branch. Review its diff and run focused checks inside its worktree.
- Integrate serially. One owner combines branches in dependency order and runs checks after each addition.
- Clean up through Git. Confirm integration and cleanliness, remove the worktree, then delete the merged branch.
- Record exceptions. Preserve why a force operation, skipped test, conflict, or abandoned branch was necessary.
The useful unit is not “one agent per idea,” but one agent per isolated, reviewable change with an owner and acceptance test. Add worktrees only while tasks remain genuinely independent.
FAQ
Can two worktrees use the same branch?
Not in the normal workflow. Git generally refuses to check out a branch that is already checked out in another worktree. Do not bypass that protection for parallel agents; create a separate task branch instead.
Is a Git worktree better than a separate clone for each agent?
Use worktrees when agents can safely share one repository’s Git data and you want lightweight local checkouts. Use separate clones—or stronger sandboxed environments—when repository-level separation, distinct credentials, or independent network and storage boundaries matter more than disk reuse.
How many agent worktrees should run at once?
There is no Git-defined optimum. Limit the batch to tasks with distinct ownership and enough CPU, memory, ports, and test capacity to validate them independently. If agents repeatedly touch the same files or wait on the same integration point, reduce concurrency or sequence those tasks.
Should dependencies be shared between worktrees?
Share only caches documented as concurrency-safe. Keep mutable dependency installations, build output, test databases, and generated files separate unless the tool explicitly guarantees safe concurrent use.
Can I delete a worktree folder after merging?
Use git worktree remove <path> rather than deleting the directory manually. First confirm a clean status and that the branch is integrated or intentionally abandoned; then remove the worktree and delete the branch separately.
Official sources
Primary sources used in this article:
- Git worktree documentation — checked 2026-07-23: linked worktrees,
add, branch checkout safeguards, stable list output, locking, moving, repairing, removing, and pruning. - Git branch documentation — checked 2026-07-23: deleting merged branches and restrictions on changing a branch checked out in another worktree.
- Git glossary — checked 2026-07-24: which repository metadata is shared and which state is maintained per worktree.
- Git status documentation — checked 2026-07-24: stable porcelain output and NUL-delimited
-zrecords for scripts. - Git merge documentation — checked 2026-07-24: pre-merge cleanliness and the limits of reconstructing uncommitted changes with
git merge --abort.