Home › Rules › Claude Code worktrees

Claude Code worktrees: run sessions side by side, pick the base branch, copy your .env, and clean up

From Anthropic's Claude Code docs (worktrees, desktop app, hooks, settings, subagents, agent view), checked Nov 16, 2026. Sources below.

Short answer: run claude --worktree <name> (or -w) and Claude Code makes a separate checkout of your repo under .​claude/​worktrees/ on its own branch, then works there, so two sessions never edit the same files. New worktrees start from your remote's default branch; set worktree.​baseRef to "head" to start from where you are, or pass "#1234" to start from a pull request. List gitignored files like .​env in a .​worktreeinclude file so they come along. Put isolation: worktree in a subagent's file to give that subagent its own copy. When you exit, a clean worktree from an unnamed session goes away on its own; otherwise Claude Code asks first.

Our Claude Code multi-agent setup page has the short version next to subagents, agent view and agent teams. This page is everything else: base branch, pull requests, where the folders go, what gets copied and what's shared, cleanup, the desktop toggle, hooks for other version control systems, and fixes for the errors you're most likely to hit.

Worktree vs branch

People mix these up because Claude Code makes both at once. A branch is a named line of commits. A worktree is a folder on disk with one branch checked out. Your normal repo folder is already one worktree; git worktree add makes more. Anthropic's one-line version: each worktree has "its own files and branch", sharing the same history and remote as your main checkout.

Branches in one folderOne worktree per branch
Folders on diskOne. You switch branches in placeOne per worktree, each with its own files
Two Claude sessions at the same timeThey edit the same files and trip over each otherEach edits its own folder
History, commits, remoteSharedShared: every worktree uses the same .​git
Same branch in two placesn/aGit refuses unless you force it (git worktree add --force)
Gitignored files (.​env, node_​modules)Already thereMissing in a new worktree until you copy, link or install them

So "worktree vs branch" isn't really a choice: in Claude Code you get a branch inside a worktree. Use a worktree whenever more than one session (or subagent) edits the repo at once. For one session at a time, a plain branch is fine.

Start Claude in a worktree

A worktree is a fresh checkout, so set it up like a new clone: ask Claude to install dependencies, or run your setup script in the new folder. Add .​claude/​worktrees/ to your .​gitignore so the worktrees don't show up as untracked files in your main folder.

Our example (VibeKits): worktree commands
# Terminal 1 and terminal 2: one task each, no collisions
claude --worktree fix-login
claude -w update-docs

# Start from pull request 1234 (quote it, or the shell eats the #)
claude --worktree "#1234"

# Same idea, opened in its own tmux session
claude -w fix-login --tmux

# Pick up a worktree you kept when you exited
claude --worktree fix-login --resume

# What's on disk, and removing one by hand
git worktree list
git worktree remove .claude/worktrees/update-docs

Which commit a new worktree starts from (worktree.baseRef)

This is the setting behind the "claude code worktree base ref" searches. It takes two values, and you can't give it a branch name:

With "fresh", Claude Code fetches the default branch if the repo hasn't been fetched in the last 24 hours, gives up after five seconds, and never stops to ask for a password or passphrase. If there's no remote at all, it falls back to your local HEAD. To start from a particular existing branch, skip the setting and make the worktree yourself: git worktree add ../​myapp-hotfix hotfix-2, then cd there and run claude.

Start a worktree from a pull request

Pass --worktree a PR number with a # in front, a GitHub PR link, or a GitLab merge request link. Quote the # version so your shell doesn't treat it as a comment. Claude Code fetches that PR's head commit from origin and puts the worktree in .​claude/​worktrees/​pr-1234. It only reads the number from a link, and always fetches from origin: pull/<number>/​head on github.com, merge-requests/<number>/​head on gitlab.com, and both in turn on other hosts. GitLab links need Claude Code v2.1.233 or later.

If the fetch would need a password, a key passphrase or a new-host confirmation, it fails with Failed to fetch PR/​MR #<number> instead of asking. Load your key into ssh-agent and run git fetch once by hand first.

Where worktrees go

.worktreeinclude: bring your .env and other ignored files

Your gitignored files (keys in .​env, local certificates) aren't in a fresh checkout, which is the usual reason an app "works in my folder but not in the worktree". A .​worktreeinclude file at the project root fixes that. The rules, from Anthropic's page:

  1. It uses .​gitignore syntax.
  2. A file is copied only if it matches a line and is gitignored, so files git tracks are never copied twice.
  3. It runs for every worktree Claude Code creates with git: --worktree sessions, subagent worktrees and desktop worktree sessions.
  4. It does not run when a WorktreeCreate hook makes the worktree. Copy the files in your hook instead.
  5. A pattern starting with **/ only reaches into a wholly ignored folder if that folder matches, or if the first name after **/ is in the folder's path. To be safe, name the folder: vendor/**/​config.​json rather than **/​config.​json. (This changed in v2.1.239.)
Our example (VibeKits): .worktreeinclude
# .gitignore syntax. A file is copied only when it
# matches a line here AND your .gitignore ignores it.
.env
.env.local
.env.development.local
certs/localhost.pem

Don't list node_​modules here: copying a whole dependency folder into every worktree is slow and big. Use symlinkDirectories below, or let Claude install dependencies in the worktree.

Big repos: symlinkDirectories and sparsePaths

Two more worktree settings make worktrees cheaper on disk:

Our example (VibeKits): worktree settings
{
  "worktree": {
    "baseRef": "head",
    "symlinkDirectories": ["node_modules"],
    "sparsePaths": [".claude", "apps/web", "packages/ui"]
  }
}

Our example starts worktrees from your current work, links one shared node_​modules, and checks out only a web app and its UI package. Our note: a linked folder really is the main checkout's folder, so installing a different package version in one worktree changes it for all of them. If your sessions need different dependencies, leave symlinkDirectories out. The desktop app doesn't use baseRef, sparsePaths or symlinkDirectories for the worktrees its Code tab creates.

isolation: worktree for subagents

A subagent normally edits the same files as your session. Give it its own worktree in one of two ways: ask Claude to "use worktrees for your agents", or add isolation: worktree to the subagent's frontmatter so it always gets one. What Anthropic's pages say happens:

Our example (VibeKits): dependency-bumper.md
---
name: dependency-bumper
description: Upgrades one outdated package in its own worktree, runs the tests and reports back. Use when asked to update dependencies.
tools: Read, Edit, Bash, Grep, Glob
model: sonnet
isolation: worktree
---

Upgrade only the package you were given, to the version you were given.
Fix whatever breaks because of the upgrade, then run the full test suite.
Commit on your worktree's branch when the tests pass.
Report back: old and new version, files changed, test result, branch name.
Don't touch other packages, and never push to main.

Every other subagent field, with seven more to copy: Claude Code subagents examples. /​batch uses this too: it breaks a large change into 5 to 30 units and gives each unit a background subagent, every one in its own worktree.

What a worktree shares with your main folder

ThingIn a worktree
Git history (.​git)Shared. A commit in a worktree lands in the same repository
Project-scope pluginsShared; no need to reinstall per worktree
"Yes, and don't ask again" for a Bash commandWritten to .​claude/​settings.​local.​json in the main checkout, so it applies everywhere and outlives the worktree. On Windows it stays with that one worktree
Untracked skills, agents and commandsIf the worktree has no .​claude/​skills of its own (for example because it's gitignored), the main checkout's load instead. Same for .​claude/​agents and .​claude/​commands. Skills need v2.1.277+
Hooks${CLAUDE_​PROJECT_​DIR} still points at the folder where the session started; the cwd field in the hook input is the worktree. Read cwd when a hook needs the worktree's path
Gitignored filesNot there, unless .​worktreeinclude copies them or symlinkDirectories links them
Desktop worktree sessionsSettings, hooks, skills, agents, commands and .​mcp.​json come from the main checkout's root; CLAUDE.​md and .​claude/​rules/ come from the worktree

The first four rows hold whether Claude Code made the worktree or you did with git worktree add.

How Claude Code keeps a session inside its worktree

While a session (or any subagent it starts) is isolated in a worktree, Claude Code refuses four kinds of tool call: file edits aimed at the main checkout, commands whose working folder is the main checkout, git commands pointed back at it (git -C, --git-dir, GIT_​DIR, GIT_​WORK_​TREE, or a cd first), and commands whose git use it can't read from the text. You can't turn that last check off. Claude sees the refusal as an error that says how to redo the command.

The catch, in Anthropic's words: none of these checks "tracks which files a shell command writes", so a cp or a shell redirect into the main folder isn't stopped by them. Your normal permission and sandbox settings still apply.

Matching kit: MVP Spec-to-Build Pack ($7)

The free rules set the boundaries. The MVP pack gives you the build order: a 1-page spec to fill in first, then 7 prompts in sequence (skeleton, review, login, database, security, one feature at a time, polish), plus a "did I leak user data?" checklist.

See the MVP Spec-to-Build Pack ($7) →

Instant download. 7-day refund, no questions asked.

Cleanup: what gets removed, and when

By hand: git worktree list shows them all, git worktree remove <path> removes one (--force if it has uncommitted or untracked files), and git worktree unlock <path> comes first if git says it's locked.

Desktop app: the Worktree toggle

In a project that's a git repo, turn on Worktree before you start a session. It's off by default, so Claude works in the project folder itself until you do.

Location and branch prefix are covered above. .​worktreeinclude works in the desktop app too.

Hooks: worktrees without git

Worktrees need a git repo, and --worktree in a folder that isn't one stops with Can only use --worktree in a git repository. For SVN, Perforce, Mercurial or anything else, a WorktreeCreate hook replaces Claude Code's git logic, and a WorktreeRemove hook cleans up.

Anthropic's SVN examples, create + remove together
{
  "hooks": {
    "WorktreeCreate": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"
          }
        ]
      }
    ],
    "WorktreeRemove": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'p=$(jq -er .worktree_path) && rm -rf -- \"$p\"'"
          }
        ]
      }
    ]
  }
}

Both commands are Anthropic's own examples from the worktrees and hooks pages, put in one file. Swap in your repository URL, and add a copy step for .​env inside the create command if you need it, since .​worktreeinclude doesn't run with a hook. They need jq installed.

Worktree not working: 12 things to check

  1. Can only use --worktree in a git repository. Run git init, make a first commit, and try again, or set up a WorktreeCreate hook. To just work in the folder, start Claude without --worktree.
  2. --worktree exits and talks about trust. Run claude once in that folder and accept the trust prompt.
  3. Claude says it has no EnterWorktree tool. permissions.​blockWritesOutsideWorkingDirectories is on, which removes both worktree tools. Start with claude --worktree instead (or claude --bg --worktree for background sessions), or remove the key from every settings file /​status lists and restart.
  4. The app fails in the worktree. Usually a missing .​env or dependencies: add the file to .​worktreeinclude, and install dependencies or link node_​modules with symlinkDirectories.
  5. The worktree doesn't have my latest commits. It started from the remote's default branch. Push first, or set worktree.​baseRef to "head".
  6. Large files show up as tiny text "pointer" files. You set up Git LFS with git lfs install --local; Claude Code skips filter drivers from the repo's own config when it makes a worktree. Run git lfs pull inside the worktree.
  7. Failed to fetch PR/​MR #<number>. The fetch needed a password, passphrase or host confirmation. Load your key into ssh-agent and run git fetch once by hand.
  8. belongs to a different repository or is a leftover worktree. Common after copying or moving a project. Use a different worktree name.
  9. Creation fails on a symlinked path. .​claude, .​claude/​worktrees or the worktree folder is a symlink. Remove the symlink and retry.
  10. Refusing to use <path> as an isolation worktree. Most often you launched Claude from inside the worktree: launch from the main checkout instead. Read the end of the message; Anthropic's page lists a fix for each ending, and the folder is left in place in case it holds work.
  11. A resumed session isn't in its worktree. If the message starts Your worktree <path> no longer exists, the folder was deleted and nothing else is needed. Could not verify: resume again. Did not re-enter or Could not re-enter: match the refusal message from the step above.
  12. git worktree remove refuses. If it's locked, a session may still be running; check, then git worktree unlock and remove. Add --force if it has uncommitted files you don't need.

Where Anthropic's pages don't line up

  1. Which keys the worktree setting takes. The settings reference describes worktree as an object "with baseRef, symlinkDirectories, sparsePaths, and bgIsolation", but the same page also documents worktree.​location.
  2. Two "location" settings. The desktop page has a Worktree location setting for local sessions, while the worktree.​location key is only for desktop SSH sessions and is ignored by --worktree. Not a mistake, but easy to mix up.
  3. Settings that skip the desktop app. The desktop page says worktree.​baseRef, sparsePaths and symlinkDirectories are "not used for the worktree that the Code tab creates", which the worktrees page doesn't mention. .​worktreeinclude does work there.
  4. When WorktreeCreate runs. The hooks page also lists workflow agents and claude remote-control in worktree mode; the worktrees page only names --worktree, subagents and background sessions.

FAQ

What does claude --worktree do?

It makes a new git worktree, a second folder of your repo on its own branch, and starts Claude Code inside it, so its edits can't collide with another session's. By default the folder is .claude/worktrees/<name>/ at the repo root and the branch is worktree-<name>. Leave the name off and Claude Code picks one. The short form is -w.

Where does Claude Code put worktrees?

In .claude/worktrees/ at the root of your repository, so add that folder to your .gitignore. The command line has no setting to move it; a WorktreeCreate hook can create worktrees anywhere, or you can make one yourself with git worktree add and start claude inside it. The desktop app has a Worktree location setting for local sessions and a Worktree folder setting on SSH connections.

What's the difference between a worktree and a branch?

A branch is a line of commits. A worktree is a folder on disk where one branch is checked out. With plain branches you have one folder and switch between them; with worktrees each branch has its own folder, so two Claude sessions can work at the same time. All worktrees share the same history, and git won't check out the same branch in two worktrees unless you force it.

How do I get my .env file into a Claude Code worktree?

Add a .worktreeinclude file at your project root and list .env in it, using .gitignore syntax. Claude Code copies a file only when it matches that list and is also gitignored. It works for --worktree sessions, subagent worktrees and desktop worktree sessions, but not when a WorktreeCreate hook makes the worktree; then copy the file in your hook.

Does Claude Code delete worktrees automatically?

Sometimes. When you exit a worktree session with nothing changed, it removes the worktree and its branch, but it asks first if you named the session. If there is work in it, it asks whether to keep or remove it. Worktrees made for subagents and background sessions are swept once they are older than your cleanupPeriodDays setting, unless they still hold changes or unpushed commits. Runs with -p are never cleaned up at exit.

Can I start a Claude Code worktree from a specific branch?

Not through the worktree.baseRef setting: it only takes fresh (your remote's default branch, the default) or head (your current local HEAD). To use an existing branch, create the worktree yourself with git worktree add, then run claude in that folder. To start from a pull request, pass its number with a # or its URL to --worktree.

Related setups

Worktrees go with running things in parallel: Claude Code multi-agent setup compares subagents, agent view, agent teams and workflows, and subagents examples has files to copy. Agent teams don't use worktrees, so read Claude Code agent teams before you let teammates edit the same repo. For hooks beyond worktrees, see Claude Code hooks examples. Sessions in worktrees still follow your project rules: CLAUDE.md examples.

Next step for Claude Code: Agent Skills

Skills are folders your AI coding agent loads only when the job comes up, and Claude Code, Cursor and OpenAI Codex all read the same SKILL.md format. The Vibe Coder Skills Pack ($9) is 6 ready-to-copy SKILL.md skills (fix-one-bug, stop-the-loop, leak-check, ship-check, explain-project, builder-handoff) for Claude Code, Cursor and OpenAI Codex. Also included in the 6-kit bundle.

Get the Skills Pack for $9 on Gumroad → See what's inside

One .zip of skill folders plus one markdown file. 7-day refund, no questions asked.

Best value

All 6 kits for $29 — or $20.30 with code WELCOME30 (through Nov 30)

Worktrees keep parallel work apart, but each session still needs to know what to build. The kits give your AI the plan for a whole project, step by step: a small game, a Discord bot, an email-triage agent, an MVP, or a cleanup of messy code.

Get all 6 kits for $29 → See what's in each kit

$29 instead of $48 for the six kits bought separately; WELCOME30 takes 30% off that at checkout ($20.30). Instant download from Gumroad. 7-day refund, no questions asked.

Related

Sources

Every command, setting, version number and error message here was checked Nov 16, 2026 on Anthropic's own Claude Code docs. Claude Code updates often and its worktree pages change with it, so run claude --version and check Anthropic's page if something looks different. If something here no longer matches, tell us at [email protected].

Free rules starter pack for Cursor, Claude Code, Codex and Antigravity

One shared AGENTS.md that works across Cursor, Claude Code, Codex, Copilot and Antigravity, plus database and test rules in each tool's format. Unzip it into your project and fill in two sections. I'll email you the link.

After that, an occasional email when I publish a new guide or rules file.

Free. No spam. Unsubscribe anytime. See our privacy note.