Two coding agents are pointed at the same repository on the same machine. Agent A is renaming a function across forty files. Agent B is fixing a flaky test and, as its first step, runs git checkout -b fix/flaky-test. The checkout succeeds because git is happy to carry uncommitted changes onto a new branch, so Agent B is now standing on a branch that contains half of Agent A's rename. B runs the test suite, sees new failures it did not cause, and "fixes" them. A, meanwhile, runs git stash to get a clean tree for a rebase, and B's edits vanish into the stash with no notice. Neither agent did anything unreasonable. They shared a mutable resource without knowing it.
Humans avoid this by habit: one person, one working copy. Agents do not have that habit and multiply cheaply, so the question becomes how to give each one a private working copy without paying for a full clone each time. Git has had a built-in answer since version 2.5: git worktree. This article covers what a worktree actually is, how to run a worktree-per-task lifecycle, what worktrees do not isolate (a long list), and how to bring the parallel results back together without trading file collisions for merge chaos.
1. What goes wrong when agents share one checkout
A git checkout is not one piece of state but four, and each can be corrupted by a second writer.
The working tree
The files on disk. Two agents editing the same file produce interleaved, last-writer-wins results, and even edits to different files interact: a half-finished rename in one corner breaks the build for everyone else.
The index
The staging area, stored in a single file. Git guards it with a lock file (index.lock), so two simultaneous git add or git commit calls produce the familiar "Unable to create index.lock: File exists" error. An agent that sees this error often does the worst possible thing: deletes the lock file and retries, possibly while the other process is mid-write.
HEAD and the current branch
One checkout has one HEAD. When agent A switches branches, agent B's idea of "the branch I am on" changes underneath it. Commits then land on the wrong branch, which is hard to notice and tedious to untangle.
Tool state that lives beside the code
Build output directories, dependency folders, test databases, lock files from package managers, language server caches. These are not git's business but they are part of the checkout, and parallel builds that write to the same output directory corrupt each other's artifacts.
The common reactions are unattractive. Serialising agents wastes the parallelism you wanted. Telling agents "do not touch files outside your task" relies on a prompt to enforce a filesystem property. Cloning the repo per task works but copies the entire object database every time, which for a large repository costs minutes and gigabytes. Worktrees sit between the extremes.
2. How a worktree is built
A repository normally has one .git directory holding the object database (commits, trees, blobs), the refs (branches and tags) and configuration, plus one working tree. git worktree add creates an additional working tree elsewhere on disk that shares the repository's object database and refs but has its own HEAD, its own index and its own checked-out files.
Mechanically: the new directory contains a small .git file (not a directory) whose single line points at .git/worktrees/<name> inside the main repository. That per-worktree administrative directory holds the worktree's HEAD, index and a few other private files. Everything else (objects, refs, hooks, config) is read from the common directory. Because objects are shared, creating a worktree writes only the checked-out files, which is why it takes seconds even for a big repository, and a commit made in one worktree is immediately visible to all the others.
| Resource | Shared across worktrees? | Consequence for parallel agents |
|---|---|---|
| Object database (commits, blobs) | Shared | Cheap to create; a commit in one is visible in all |
| Branches and tags (refs) | Shared | A branch can be checked out in only one worktree at a time |
| HEAD | Private | Each agent has its own current branch |
| Index (staging area) and its lock | Private | No more index.lock fights between agents |
| Working files | Private | Edits and build output are separate on disk |
| Repository config and hooks | Shared by default | A config change or hook affects every agent |
| Stash | Shared | The stash is one stack; avoid git stash in agent workflows |
| Untracked and ignored files (.env, node_modules) | Not present in a new worktree | Each worktree needs its own setup |
The one-branch-per-worktree rule is a feature. Git refuses to check out a branch that is already checked out elsewhere (unless you force it), which turns "two agents on the same branch" from a silent hazard into an immediate error.
3. A worktree-per-task lifecycle
The pattern has five steps: pick a base, create a worktree on a new branch, run the agent inside it with its working directory pinned there, verify, then integrate and remove. Here is a script that handles creation, setup and cleanup for one task. It assumes it runs from inside the repository and that main is the integration branch.
#!/usr/bin/env bash
# spawn-task.sh <task-slug> -- create an isolated worktree for one agent task
set -euo pipefail
SLUG="$1"
REPO_ROOT="$(git rev-parse --show-toplevel)"
WT_ROOT="$(dirname "$REPO_ROOT")/worktrees" # outside the main checkout
WT_DIR="$WT_ROOT/$SLUG"
BRANCH="agent/$SLUG"
mkdir -p "$WT_ROOT"
git fetch origin main --quiet
# 1. New branch from a known base commit, in its own directory.
git worktree add -b "$BRANCH" "$WT_DIR" origin/main
# 2. Untracked setup that git does not carry over.
[ -f "$REPO_ROOT/.env.local" ] && cp "$REPO_ROOT/.env.local" "$WT_DIR/.env.local"
(cd "$WT_DIR" && npm ci --silent)
# 3. Give each task its own port range so dev servers do not collide.
PORT_BASE=$(( 4000 + ( $(printf '%s' "$SLUG" | cksum | cut -d' ' -f1) % 500 ) * 10 ))
echo "PORT_BASE=$PORT_BASE" > "$WT_DIR/.task.env"
# 4. Protect the worktree from an accidental prune while the agent runs.
git worktree lock --reason "agent task $SLUG in progress" "$WT_DIR"
echo "$WT_DIR"
And the cleanup half, which should run whether the task succeeded or not:
#!/usr/bin/env bash
# finish-task.sh <task-slug> -- remove the worktree after its branch has been pushed or merged
set -euo pipefail
SLUG="$1"
WT_DIR="$(dirname "$(git rev-parse --show-toplevel)")/worktrees/$SLUG"
git worktree unlock "$WT_DIR"
# Refuses if there are uncommitted changes. That refusal is information, so read it.
git worktree remove "$WT_DIR"
git worktree prune
git worktree list
Details that save you later
- Name branches and directories from the task id. When something goes wrong,
git worktree listbecomes a table of what is running and who owns it. - Base every task on an explicit commit. Branching from
origin/mainafter a fetch means every task starts from the same known point instead of whatever the shared checkout happened to have. - Pin the agent's working directory. The worktree only protects you if the agent's shell, file tools and test runner all start inside it. An agent whose tools use absolute paths into the main checkout bypasses the isolation entirely, so give it paths relative to its own root and check the first command it runs.
- Keep worktrees outside the main checkout. A worktree nested inside the main working tree shows up as untracked content there and confuses tools that scan the directory.
- Use
--detachfor throwaway reads. For tasks that only inspect a revision, a detached worktree avoids creating branches that need cleaning up.
4. What worktrees do not isolate
This is where most disappointments come from. Worktrees isolate files and git state. Everything else that your project touches is still shared unless you separate it too.
Network ports and local services
Two worktrees both running a dev server on port 3000 will collide. Allocate a port range per task, as in the script above, and make the project read its ports from environment variables rather than hard-coding them.
Databases and caches
If every worktree points at the same local database, parallel test runs will see each other's rows. Give each task its own database name or schema, or run tests against an ephemeral database created per run.
Dependencies and build caches
Each worktree has its own dependency directory, so the first setup repeats an install. Package managers with a content-addressed global store make that cheaper, and build tools with a shared remote or local cache can reuse compiled outputs, but you must verify that the cache keys do not depend on absolute paths. A cache that is keyed by path and shared across worktrees can serve stale artifacts.
Untracked configuration and secrets
A new worktree contains only tracked files. .env files, local certificates and editor settings are not there. Copying them in is the usual answer, but treat it as a secrets-handling decision: the agent in that worktree can now read them. Give it only the credentials its task needs, preferably short-lived ones.
Shared repository state
Config, hooks and the stash live in the common directory. A hook installed for one task runs for all. Garbage collection can run in the background and take locks that briefly block other worktrees. git gc and git prune operate on the shared object database, so be careful with aggressive pruning while others are mid-operation. If you need per-worktree config, git supports it through an opt-in extension; the documentation for extensions.worktreeConfig explains the details.
Submodules
Support for submodules inside linked worktrees has historically been incomplete. If your repository relies on them, test the full lifecycle (add, checkout, remove) before building an agent pipeline on top.
5. Integration: parallel work still has to merge
Worktrees remove collisions in the working directory. They do nothing about semantic conflicts, which appear when two tasks change related code in compatible-looking but incompatible ways. Agent A renames a function, Agent B adds a call to the old name, both branches pass their own tests, and main breaks after both merge. Isolation moves the conflict from "while editing" to "at integration", which is a better place for it, but you still have to handle it.
- Partition by ownership before starting. Decompose work so tasks touch mostly disjoint files. Two tasks that both need to edit the same module are one task, or a sequence.
- Integrate one at a time. Merge or rebase each finished branch onto the current main, rerun the verification suite, then move to the next. Parallel work, serial integration.
- Verify after the merge, not only before. Passing tests on a branch tells you the branch works against its old base. The check that matters runs on the integrated result.
- Keep branches short-lived. A branch that lives for hours diverges from main by less than one that lives for days. Smaller tasks yield smaller conflicts.
- Let the integrator, not the task agent, resolve cross-task conflicts. The agent that finished first lacks the context of the other task. A dedicated integration step, with both diffs in view, resolves them better.
A worked example with three tasks
Suppose a service has three tickets open: add pagination to a list endpoint, fix a timezone bug in the report exporter, and upgrade a logging library. Pagination touches the API layer and its tests. The timezone fix touches the exporter. The logging upgrade touches a dependency manifest and, through renamed imports, a few files in both of the other areas. A sensible plan starts all three in separate worktrees from the same base commit, but lists the logging upgrade as the last to integrate, because it is the one most likely to conflict with the others.
Pagination and the exporter fix finish first. The integrator merges pagination into main and runs the full suite, then rebases the exporter branch onto the new main, reruns its tests and merges it. Only then does the logging branch get rebased. Its conflicts are now visible against code that is already in main, and the person or agent resolving them can see exactly which import changed and why. Had all three merged blindly in finish order, the failure would have surfaced as a confusing build break with three suspects. Serial integration turns it into a conflict with one suspect.
6. Choosing an isolation strategy
Worktrees are the right default for parallel code changes on one machine, but they are not the only option. The table compares the main choices on qualitative properties.
| Strategy | Isolates files and git state | Isolates ports, databases, processes | Setup cost | Best used for |
|---|---|---|---|---|
| Shared checkout | No | No | None | A single agent, one task at a time |
| Branches in one checkout | No (one working tree) | No | Very low | Sequential tasks only |
| Git worktrees | Yes | No, you add it | Low: seconds, little extra disk beyond checked-out files | Parallel code changes on one machine |
| Separate clones | Yes, plus separate objects and config | No | Medium to high for large repos | Strong separation of hooks, config and gc |
| Containers or VMs per task | Yes | Yes | Highest | Untrusted code, heavy services, reproducible environments |
A practical stack combines them: a worktree for the files, a container for the processes, and per-task environment variables for ports and database names. Choose the lightest layer that stops the failure you actually have.
7. Failure modes and cleanup
Orphaned worktrees
If an agent crashes or the machine reboots, the directory may remain, or it may disappear while git still lists it. git worktree list shows entries marked prunable when the directory is gone, and git worktree prune removes the stale records. Worktrees on a removable or temporary filesystem can vanish wholesale, so do not store unmerged work only there; push the branch before you consider the task done.
"Branch is already checked out"
This is the guard working. The fix is to pick another branch name or finish with the other worktree, not to pass the force flag. Forcing re-creates the exact shared-HEAD hazard you were avoiding.
Dirty worktree on removal
git worktree remove refuses when there are uncommitted or untracked changes. An unattended pipeline that responds by forcing removal will occasionally delete work. Make the pipeline commit to a rescue branch or fail loudly.
Disk growth
Each worktree adds its checked-out files plus its own dependency directory and build output. With dozens of long-lived worktrees on a large monorepo, disk use becomes real. Cap the number of concurrent tasks, set a time-to-live for idle worktrees and clean them in a scheduled job.
Locks that never release
A stale index.lock inside a worktree's administrative directory usually means a process died mid-operation. Check that no git process is still running there before deleting it, and prefer to tear the whole worktree down and recreate it.
8. Decision checklist and common mistakes
Checklist
- Will more than one agent write to this repository at the same time? If yes, give each its own worktree.
- Is each task's working directory pinned inside its worktree for the shell, file edits and test runs?
- Are ports, databases and caches separated per task?
- Do secrets reach each worktree deliberately and in the narrowest form?
- Is integration serial, with verification on the merged result?
- Is there a cleanup job and a rule for unmerged work?
Common mistakes
- Creating worktrees but letting the agent's tools keep absolute paths into the original checkout.
- Assuming worktrees isolate databases and ports.
- Forcing branch checkouts or worktree removal to get past an error without reading it.
- Letting two tasks edit the same files and expecting git to sort it out afterward.
- Using
git stashin an agent workflow when the stash is shared. - Declaring a task done because its branch tests pass, without testing the merge result.
9. FAQ and what to do Monday
Do worktrees work with every git host? They are a local feature of git. The remote only sees branches and commits.
How many can I run at once? The practical limit is disk, memory for the processes inside them, and the integration bandwidth of whoever merges the results, rarely git itself.
Is a worktree safe against a malicious agent? No. It is a convenience boundary, not a security boundary. A process with your user's permissions can read and write any path you can. For untrusted code, add a container or VM and restrict filesystem access at the operating system level.
Should the main checkout be used at all? Treat it as read-mostly: a place to fetch, inspect and run the integration step, not a place where agents do their work.
What to do Monday
Take the next two tasks you would normally hand to agents one after the other and run them in parallel. Write the two short scripts above for your own repository, including whatever your project needs for dependencies, ports and environment files. Run the tasks, then integrate them one at a time with the full test suite after each merge. Note every place the isolation leaked (a port, a cache, an absolute path) and fix those in the script rather than in the agent's prompt. After two or three rounds the leaks become rare, and the setup scales to more agents without more surprises.