↓ Skip to main content

Claude Code AI Agents Git

Claude Code Worktrees: Running Parallel Agents Without Collisions

How to use Claude Code worktrees: claude -w, .worktreeinclude for .env, node_modules, base ref and cleanup, and running parallel agents in tmux.

Claude Code Worktrees: Running Parallel Agents Without Collisions

To run Claude Code in a git worktree, start it with claude -w <name> (the long form is --worktree). Claude Code creates .claude/worktrees/<name>/ at the root of your repository, on a new branch called worktree-<name> cut from your default branch on the remote, and from then on the session can only edit files inside that folder. Run the same command with a different name in a second terminal and you have two agents that can’t touch each other’s files. The catch is that a worktree is a fresh checkout. Your .env, your node_modules and anything else git ignores aren’t there until you copy or install them, and nearly every worktree problem I’ve had came from exactly that.

I run a lot of agents in parallel, and I came to worktrees the hard way. This post covers how claude -w behaves (I tested it on version 2.1.328), what .worktreeinclude is for, what to do about node_modules, how I lay the sessions out in tmux, and when I still reach for plain git worktree add.

This post as an eight-minute film, if you’d rather watch than read. Some footage from Coverr.

Why one checkout doesn’t work for parallel agents
#

One day in September I had five Claude Code sessions working in the same checkout of my marketplace app, and two things went wrong. A one-line fix to a test config file survived four failed builds and was gone by the time it was ready to commit: git commit said the working tree was clean, and the file held another session’s version. Git keeps no record of a lost update like that. No reflog entry, no stash, just an ordinary modification time. The same day, a deploy script that builds from the working tree came close to shipping a different session’s unfinished work to production.

In October a third one turned up. A session committed its own files beside another session’s unstaged work, and the pre-commit hook stashed everything unstaged for the length of the hook. The other session’s edits vanished from disk while the hook ran, the type checker then failed on its new files, and the commit aborted. Every session commits under my name, too, so git log can’t tell you which one did what.

That’s the case for worktrees in one line: a working tree with several writers is a race, and the loser can’t see it happen. Give each agent its own working tree and the race goes away.

One repository, three working directories. History is stored once; files, HEAD and index are per worktree.

How claude -w works
#

A real run in a throwaway repo. Note the lock that’s still there after the session ended.

What the worktrees page in the docs says, and what I saw when I tried it:

  • Where and which branch. claude -w add-search creates .claude/worktrees/add-search/ on a new branch worktree-add-search. Leave the name out and you get a generated one like bright-running-fox. Add .claude/worktrees/ to your .gitignore, or the main checkout shows it all as untracked.
  • What it branches from. By default, worktree.baseRef is "fresh": the remote’s default branch, usually origin/main. Claude Code fetches it if the repository hasn’t been fetched in the last 24 hours, capped at five seconds. Set it to "head" and new worktrees start from your current local HEAD, unpushed commits and all. You can’t set it to a branch name; for a specific branch, use git worktree add yourself.
  • Pull requests. claude --worktree "#1234" fetches that PR’s head and creates .claude/worktrees/pr-1234. Quote it, or your shell treats # as a comment.
  • Trust. The first time, an interactive claude -w in a folder you’ve never opened Claude in fails with “Workspace trust not yet accepted”. Run plain claude there once and accept the dialog. claude -p -w skips the check.
  • The fence. While a session is in a worktree, Claude Code refuses edits to files in the main checkout, commands whose working directory is the main checkout, and git pointed back at it through git -C, --git-dir or GIT_DIR. The docs say plainly what it doesn’t catch: a cp or a shell redirect that writes into the main checkout isn’t refused by these checks.

What a worktree shares with the main checkout matters as much as what it doesn’t. Every worktree writes to the same .git, so commits and branches made in one are visible from all of them. Project-scope plugins load everywhere. And a “Yes, and don’t ask again” answered inside a worktree is saved to the main checkout’s .claude/settings.local.json, so the approval applies to every worktree and outlives the one it was given in. That’s convenient, and also one more reason to keep secrets out of the commands you approve.

Cleaning up, and the lock that stays behind
#

When you exit an interactive worktree session, Claude Code checks for anything removal would lose. An unnamed session with a clean worktree is removed automatically, branch and all. A named one asks first. If there’s work in it, you’re asked whether to keep it, and you can come back later with the claude --worktree <name> --resume command it prints.

Non-interactive runs are different, and it’s the one thing that caught me out when I tested this. claude -p has no exit prompt, so it doesn’t clean up. Claude Code also holds a git worktree lock on the worktree while the session runs, and after a -p run that lock is still there with a process ID that no longer exists. You can see it in the recording above: git worktree remove refuses with “cannot remove a locked working tree, lock reason: claude session add-search”. The docs describe exactly this: a later session’s stale-lock sweep releases it, or you run git worktree unlock first. It’s harmless once you know, and slightly alarming the first time.

.worktreeinclude: the files a fresh checkout doesn’t have
#

A worktree contains tracked files and nothing else. To bring gitignored files along, put a .worktreeinclude in the root of the repository. It uses .gitignore syntax, and Claude Code copies a file only if it matches a pattern and is gitignored, so tracked files are never duplicated:

# .worktreeinclude
.env
.env.local
config/secrets.json

It applies to every worktree Claude Code creates with git: claude -w, subagent worktrees and the desktop app’s parallel sessions. It doesn’t apply to worktrees you make with git worktree add, and it’s skipped entirely if you replace worktree creation with a WorktreeCreate hook.

I’d put more than .env in it, because the gitignored files you forget are rarely the ones that fail loudly. My app’s deploy script was changed to build from a clean worktree, so that other sessions’ uncommitted edits could never ship. The clean tree didn’t have the gitignored signing certificates that one feature needs, the image built anyway, and that feature failed in production for 13 days, until the script was changed to copy the certificates in and warn when one is missing. On another deploy from a worktree, a gitignored theme folder was missing, and the build failed only after a two-minute export had already dirtied the tree. Before you trust a worktree with anything that ships, run git status --short --ignored in your main checkout and ask which of those files the build reads.

node_modules: the expensive part
#

.worktreeinclude is for small files. It won’t help with node_modules, and nothing in Claude Code shares it between worktrees, so every worktree that needs to run your code needs its own.

Plain git worktrees in a demo repo: 84 KB until you install, then the full 45 MB again.

On a real project the numbers get serious. My mobile app’s repository has 19 worktrees beside the main checkout. I measured 12 of them: they range from 194 MB to 12 GB, and the four biggest were the four with their own node_modules. With my laptop’s disk at 96% this week, they’re the obvious place to start cleaning.

The options, from simplest to cleverest:

  1. Install per worktree. Ask the agent to run npm install first thing, or do it yourself. Slow, costs disk, never surprises you.
  2. Clone from a checkout with the same lockfile. On macOS, cp -c -R ../myapp/node_modules . uses APFS clones, which share data blocks until one side changes. Cloning the 45 MB demo took 0.8 seconds. I’ve used this for real deploys from worktrees. Only clone when the lockfiles match, and be careful with native build folders: my main checkout’s iOS Pods were built for an older SDK than the worktree’s branch, so those had to be installed fresh.
  3. Use pnpm. Its packages live in one store, and on macOS pnpm clones from the store before trying hard links (on Linux and Windows it hard-links first). A second worktree’s install of the demo took about five seconds.
  4. Install in a WorktreeCreate hook. The hook replaces Claude Code’s default git logic, so it could run git worktree add and then the install. I haven’t tried this one. If you do, remember .worktreeinclude stops being processed and the hook has to copy your .env too.

Parallel agents in tmux
#

I already live in tmux (the day-to-day post has the layout), so worktrees slot straight in: one window, or one pane, per worktree. Here are three agents started at the same moment, each told to change the same file:

Three agents, one file, no collisions. The main checkout ends up clean, and each change waits in its own branch.

Two of them edited src/index.js at the same time and neither noticed the other, because each one’s src/index.js was a different file on disk. The main checkout stayed clean. What you get at the end is three branches to review and merge, which is the work worktrees can’t do for you: if two agents change the same lines, you still get a merge conflict. It just arrives in a merge, where you can see it, instead of as a silent overwrite.

In VS Code, a worktree is just a folder: code .claude/worktrees/add-search opens it in its own window, on its own branch.

A worktree is a snapshot
#

Worktrees age. On 19 November an over-the-air update went out from a worktree that had been prepared two or three days earlier, and it quietly reverted two fixes that had shipped from elsewhere in the meantime. It was caught and replaced the same day. The worktree was perfectly isolated, and that was the problem: it never saw those fixes. A git one-liner would have caught it before release:

The check to run before shipping from any worktree that isn’t freshly cut.

baseRef: "fresh" keeps new worktrees current. Nothing keeps old ones current, so check before you release from one.

Subagents and hooks
#

You don’t need a terminal per agent to get this isolation. A custom subagent with isolation: worktree in its front matter always runs in a temporary worktree of its own:

---
name: refactorer
description: Applies mechanical refactors across many files
isolation: worktree
---

Apply the requested refactor across every affected file, then run the tests
and report the results.

That’s the example from the docs. The worktree is removed when the subagent finishes without changes. One with changes stays until a periodic sweep can remove it without losing work. One subtlety: a subagent in a worktree under .claude/worktrees/ takes its instructions from your main conversation and doesn’t load the CLAUDE.md at the worktree’s root.

WorktreeCreate and WorktreeRemove hooks replace the git logic entirely. They’re meant for other version control systems, or for putting worktrees somewhere other than .claude/worktrees/, and they’re also the place for setup steps like the install above.

When plain git worktree add is the better tool
#

Here’s the confession: the .claude/worktrees folder in my app’s repository is empty. All 19 of its worktrees were made with plain git worktree add, all of them in the past month, and half of them sit on a detached HEAD. Other repositories on my laptop have 40, 40, 18, 10, 3, 2 and 2 more. And most of the time it isn’t me making them: 85 of the 638 Claude Code transcripts on this laptop have an agent running git worktree add, 336 times in all.

Plain git is better when:

  • You need a specific existing branch, such as a release branch kept for hotfixes. baseRef can’t do that.
  • You want to ship exactly one fix. Other sessions had committed work to main that hadn’t been deployed yet, so a detached worktree at the commit running in production, with my fix cherry-picked into it, was the way to deploy that fix and nothing else.
  • You’re briefing agents yourself. When I start several agents on one repository, each brief says to work in its own git worktree add --detach "$TMPDIR/<task>-wt" refs/remotes/origin/main, push with git push origin HEAD:main, and rebase on conflict.
  • You want it kept. Claude Code’s sweep never removes a worktree you created with git worktree add.

claude -w is better when you’re starting a session by hand and want the branch, the .env copy, the fence around the main checkout and the cleanup handled for you. The two mix fine: Claude Code treats any worktree as a worktree, including the main-checkout sharing described above.

The short version
#

Use claude -w <name> for each parallel session, and add .claude/worktrees/ to .gitignore. List every gitignored file your build needs in .worktreeinclude, not just .env. Plan for node_modules, whether that means installing per worktree, cloning or pnpm. After a -p run, expect a lock you may need to git worktree unlock. Before you ship from a worktree that isn’t new, check it contains what’s already live. Worktrees stop agents overwriting each other’s files; they don’t stop them disagreeing, so you’ll still be reviewing three branches at the end.

Further reading
#

On this site:

Elsewhere: