Git worktrees are the isolation layer under the method in shipping a SaaS product with a fleet of AI coding agents. Once more than two agents work at the same time, one shared checkout stops working: an agent’s half-written file breaks another agent’s build, a branch switch pulls the floor out from under a running process, and nobody can tell whose change broke the tests. The fix is one worktree per agent, plus the four resources that travel with it.
What is a git worktree and why use it for agents?
A git worktree is a second working directory attached to the same repository, with its own checked-out branch. Git describes it as a worktree “linked to the current repository, sharing everything except per-worktree files such as HEAD, index, etc.” (git-worktree documentation).
For agents, three properties matter:
- Separate files. Each agent edits its own directory. Uncommitted work in one cannot appear in another.
- Separate branches. Each agent commits to its own branch, so the lead can review, merge or discard one agent’s work without touching the others.
- A guard against sharing. By default git refuses to create a worktree for a branch that is already checked out in another worktree, unless forced. A mistake that would corrupt shared state becomes an error message.
The playbook behind this fleet makes worktrees the default for anything above two agents. File ownership still matters, but a worktree turns “agents can clobber each other’s half-written files” into “agents commit on their own branches, and merging is the lead’s job”.
How do you create a worktree for each agent?
Create one from the main branch per agent, with a new branch name, then prepare it the way a fresh clone would be prepared. The excerpt below is generic; paths and names are placeholders.
# per agent: its own checkout, branch, scratch dir
git -C /abs/repo worktree add /abs/repo-wt-<name> -b fix/<name> main
cd /abs/repo-wt-<name>
ln -s /abs/repo/.env .env # shared env; never paste secrets into briefs
pnpm install --frozen-lockfile # plus codegen your project needs
mkdir -p /abs/scratch/<name> # scratch OUTSIDE the repo
Each line carries a decision:
-b fix/<name>creates a fresh branch, which also avoids the already-checked-out refusal formain.- A symlinked env file shares configuration without copying secrets into a brief or a commit.
- A frozen lockfile install gives each worktree an identical dependency tree, and the codegen step covers anything generated, such as an ORM client.
- A scratch directory outside the repo is where screenshots, test scripts and mail output go. It keeps scratch files out of commits, which is one of the failure modes in reviewing agent output.
Cleanup is the reverse: after the lead merges a branch, git worktree remove takes the directory away and the branch can be deleted.
What does every agent get besides a directory?
Every agent gets five things, written into its brief, and each exists to prevent a specific collision.
| Resource | Example | Collision it prevents |
|---|---|---|
| Worktree path and branch | /abs/repo-wt-api, fix/api |
Two agents editing one checkout |
| Dev-server port | 3041, 3042, … | Two servers fighting for one port |
| Scratch directory | /abs/scratch/<name>/ |
Screenshots and scripts landing in commits |
| Test database names | Derived from the worktree name | False failures from shared test data |
| File ownership list | “You own exactly these files” | Conflicting edits on different branches |
The brief also states what the agent must not do: it commits on its branch and never pushes, merges, rebases or touches another worktree. A second rule covers shared services: create your own test accounts, and never truncate or wipe shared tables. The full brief layout is in writing briefs AI coding agents can’t misread.
Why do worktrees not replace file ownership?
Worktrees protect against overwriting; ownership protects against conflicting. Two agents on two branches can both edit the same helper, and each branch is internally consistent. The conflict appears at merge, or worse, merges cleanly and behaves wrongly.
The rule is one owner per file, and any change an agent needs in a file it does not own goes under a “needs from others” heading in its result file. The lead applies those at merge time. In the fleet record, six branches from one round merged with zero conflicts because ownership was strict (from the delegation playbook).
Dependencies add a sequencing rule. Land the foundation first (schema, shared helpers, the auth wrapper), merge it to main, then branch the dependent worktrees from the new main. Work that only consumes a public contract can start early against a mock: the MCP server and external connectors in the same build were briefed to “build against a mock HTTP server” and ran alongside the foundation instead of after it.
One more instruction belongs in every brief: do not git checkout another branch inside a worktree while an agent is running in it.
How should merges work?
The lead merges into an integration branch with --no-ff, one branch at a time, and runs the tests after each. The --no-ff flag keeps a merge commit per agent branch, so a bad branch can be reverted as one unit. Running tests after each merge means a failure points at the last branch merged, not at a pile of six.
A hand-resolved conflict deserves extra suspicion. Two earlier merges in the same project show why: a hand-resolved conflict in a settings registry dropped a secret: true flag and caused a syntax error that took down most web test suites in one verify run, and a CSS conflict resolved by deleting the markers dropped two closing braces both sides shared. Every test passed and the page did not render. After any hand-resolved conflict, run the build, and for UI, open the page (from the playbook’s review notes).
How do you isolate test databases per worktree?
Give each worktree its own test databases, named from the worktree, and reset them on every full verify. This is the failure that looks least like an isolation problem, because it presents as flaky tests.
The mechanics from the fleet’s verification scripts:
- A suffix per worktree. A variable such as
TEST_DB_SUFFIX=<name>derives the database names. Hyphens in the name are converted to underscores because Postgres identifiers cannot hold them unquoted. - No sharing. Parallel agents sharing one test database produced false failures: one agent’s fixtures appeared in another’s assertions.
- Reset on a full verify. A reset flag drops and recreates the databases. A persistent test database slowly filled past a row cap, and 9 worker tests that pass on a fresh database started failing. It looked like a regression from the latest merge and was not (from the playbook’s verification notes).
The same lesson shows up when comparing a failure count to a baseline. In one Claude-subagent run, an agent reported 8 test failures as “probably unrelated”. Running the suite on the base commit showed they were test database contention, not regressions. Always compare against the base commit before believing or dismissing a failure count.
How do you run verification away from the laptop?
Past about ten worktrees, a laptop cannot run every agent’s tests and builds, so verification moved to a spare Linux box reached over ssh (from the playbook, November 2026 fleet notes). Two small scripts did the work: one runs a single command against a given worktree’s branch on the box, and one pulls main and runs typecheck, every package’s tests, lint and the production build, then prints only the summary lines. The same fleet pattern is described in running AI coding agents on remote Linux machines.
The script failure worth copying is the quiet one. A locally modified lockfile on the box blocked git pull, and verification kept testing a stale commit for several rounds while reporting green. The script now discards that file first and prints PULL-FAILED on any pull error. The rule that follows is cheap to apply: the first line of the verify output must be the commit hash you expect. If it is not, nothing below it is evidence.
How do you know which agent is still working?
Use one background check-in instead of polling. A script wakes the lead when any agent stops, or every 15 minutes with a snapshot, and for each agent it prints whether the process is running, how many commits sit ahead of main, how many files are uncommitted and how many were touched in the last 15 minutes.
How to read a snapshot:
| Reading | Meaning |
|---|---|
| Stopped, 1 commit, 0 uncommitted, done line printed | Clean finish |
| Stopped, 0 commits, files uncommitted | Died with work: relaunch with a continuation brief |
| Running, zero files touched for two heartbeats | Stalled |
Two additions earned their place: end every snapshot with the remaining quota line, so the trend sits next to the fleet state (quota gates and stall detection), and mark an agent as handled after merging so a finished agent does not hide a stalled one in a long list.
How do Claude Code subagents fit in?
Claude Code subagents run the same pipeline without the external engine. They are defined as Markdown files with a system prompt, tool access and permissions, each runs in its own context window, and they can run in the background while the main session keeps working (Claude Code subagents).
The playbook’s record is a site cleanup done with Claude models only: Sonnet subagents for the work, the lead orchestrating and doing the visual checks.
| Subagent task | Model | Wall clock |
|---|---|---|
| Navigation menus and footer, every link must resolve | Sonnet | 3 min |
| Read-only live-site audit (crawl, hubs, metadata, counts, CTAs) | Sonnet | 4.5 min |
| Homepage demo layout and reduced motion | Sonnet | 7 min |
| Site polish, eight numbered fixes | Sonnet | 5 min |
| Gallery weight (4.4 MB to 280 KB) and 76 thin pages | Sonnet | 16 min |
What carried over unchanged: the brief format, one worktree per agent, merges by the lead. What changed: subagents notify on completion, so the PID waiter and the check-in script are unnecessary. What did not change: review still found problems. One agent edited a file it did not own, for a good reason, but the edit had to be checked. And the read-only audit agent was the best value of the five: one crawl of 382 URLs produced the real backlog, and confirmed what was fine, so nothing was re-checked by hand (all from the playbook’s subagent-mode record).
Which isolation approach should you use?
| Shared checkout | Separate clones | Worktrees | |
|---|---|---|---|
| Setup cost | None | Full clone each, separate object stores | One command, shared objects |
| Uncommitted work isolated | No | Yes | Yes |
| Same branch checked out twice | Not possible | Possible and confusing | Refused by default |
| Branch visible across agents | Yes | Only after fetch | Immediately |
| Fits a fleet of more than two | No | Heavy | Yes |
Which should you choose? Use worktrees for any fleet above two agents, and add ownership, ports, scratch space and per-worktree databases. For one or two agents on clearly separate files, a shared checkout with strict ownership is enough, and a worktree is optional.
What broke and what we changed
Parallel agents shared one test database. The result was false failures that disappeared on rerun. Each worktree now gets its own databases, derived from its name, with hyphens converted to underscores.
A persistent test database drifted. It filled past a row cap and made 9 worker tests that pass on a fresh database fail, which looked like a regression from the latest merge. Full verifies now reset the databases.
The build box tested a stale commit. A modified lockfile blocked the pull and the script carried on silently for several rounds. The script now discards the file, prints PULL-FAILED on any pull error, and the first output line is checked against the expected hash.
A hand-resolved conflict passed every test and broke the page. Two dropped closing braces left the build green and the page unrendered. Hand-resolved merges now get a build and a visual check.
Laptop capacity ran out. Seven local QA agents plus a dev server crashed the machine. Fleets above four or five agents now run on a Linux box, covered in remote agent fleets.
A finished agent hid a stalled one. With 20 or more agents over a night, the snapshot filled with completed work. Handled agents are now marked and skipped.
Related
Frequently asked questions
What is a git worktree?
A git worktree is an additional working directory linked to the same repository. It shares the object store and history, but has its own checked-out branch, HEAD and index, so two directories can hold two branches at once without a second clone.
Why use worktrees instead of separate clones for AI agents?
Worktrees share one object database, so creating one is fast and cheap, and branches created in any of them are visible to all. Git also refuses to check out the same branch in two worktrees by default, which turns an easy mistake into an error.
Do worktrees stop agents from editing the same file?
They stop agents from overwriting each other's uncommitted work, but not from producing conflicting changes. Two agents can still edit the same file on different branches and conflict at merge. File ownership in the brief is what prevents that.
How should parallel agents handle databases?
Give every worktree its own test databases, named from the worktree with hyphens converted to underscores, and reset them on every full verification. A shared test database causes false failures, and a persistent one drifts until tests fail for reasons unrelated to the code.
When do Claude Code subagents replace worktree agents?
When the external engine is unavailable or the owner asks for Claude-only work. The pipeline is the same: briefs, worktrees, lead-owned merges. Subagents run in the background and notify on completion, so the PID waiter and check-in script are not needed.
