Skip to main content
Module 2: Multi-Agent 6 / 6
Intermediate S12 Worktree Isolation Git

Worktree Isolation

Run parallel Claude Code sessions in separate Git worktrees and clean them up safely.

March 20, 2026 15 min read

What You’ll Learn

Git worktrees let parallel Claude Code sessions edit separate checkouts and branches without touching one another’s files. Claude Code now exposes this isolation directly through CLI flags, in-session tools, and subagent configuration.

This session covers the supported lifecycle: create, initialize, work, resume, integrate, and clean up.

What a Worktree Isolates

A Git worktree is another working directory with its own checked-out files and branch. It shares the repository’s history and remotes with the main checkout.

repository
├── main checkout                 branch: main
└── .claude/worktrees/feature-auth
                                  branch: worktree-feature-auth

The isolation boundary is the filesystem checkout. While a session is isolated in a worktree, Claude Code also enforces that boundary: it blocks Edit, Write, and NotebookEdit calls that target the main checkout, and Bash or Monitor commands that run in the main checkout or redirect git into it (for example with git -C). It does not track which files a shell command writes, so a cp or shell redirect into the main checkout is governed only by your normal permissions and sandbox. (This enforcement covers every session type since Claude Code 2.1.222.)

Some state is still shared with the main checkout: the repository’s .git directory, project-scope plugins, and Bash approvals you save with “don’t ask again”, which since Claude Code 2.1.211 normally land in the main checkout’s .claude/settings.local.json and apply in every worktree. Worktrees don’t isolate external services, credentials, ports, databases, or package caches either. Coordinate those resources separately.

Worktrees also do not coordinate agents. Use subagents or Agent Teams for delegation and communication; use worktrees to prevent file edits from colliding.

Start an Isolated Session

Pass a name to --worktree or -w:

claude --worktree feature-auth
# equivalent
claude -w feature-auth

By default Claude Code creates .claude/worktrees/feature-auth/ and a branch named worktree-feature-auth; omit the name and Claude generates one. Use a different name in another terminal for another isolated session, and pass an existing name to reopen that worktree. Add the generated directory to your ignore rules:

.claude/worktrees/

When the repository has a remote, new worktrees branch from its default branch (origin/HEAD), not from the branch you have checked out, so your unpushed commits are not in them. Set worktree.baseRef to "head" when a worktree must start from your current local HEAD. To work on a pull request in isolation, pass its number instead of a name, quoted so the shell doesn’t treat # as a comment: claude --worktree "#1234".

You can also ask Claude to “work in a worktree” during an existing session. Claude Code enters one with its EnterWorktree tool and leaves with ExitWorktree; since Claude Code 2.1.206, entering a path outside .claude/worktrees/ asks for your approval first. You do not need to reproduce that transition with a custom event stream.

Initialize the Fresh Checkout

A worktree contains tracked files, not all local machine state. Install dependencies there and recreate any required local configuration.

For gitignored files that every Claude-created worktree needs, add a .worktreeinclude file at the repository root using .gitignore syntax:

.env.local
config/dev-secrets.json

Only matching files that are already gitignored are copied. Treat this as convenience, not a secrets policy: keep sensitive files minimal and review who can read the worktree.

For large repositories, two settings shape every new worktree:

{
  "worktree": {
    "symlinkDirectories": ["node_modules"],
    "sparsePaths": ["packages/my-app", "shared/utils"]
  }
}

symlinkDirectories links the listed directories from the main checkout instead of duplicating them, which means those directories are shared, not isolated. sparsePaths checks out only the listed directories plus root-level files.

Isolate a Custom Subagent

Ask Claude to use worktrees for agents, or make isolation part of a custom subagent definition:

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

Apply the requested refactor, run the affected tests, and report the commit.

Claude Code creates a temporary worktree for that subagent. Like --worktree, it branches from the default branch unless worktree.baseRef is "head"; either way it starts from a commit, so the subagent never sees your uncommitted changes. A worktree the subagent leaves unchanged is removed automatically; one containing changes remains until it can be cleaned without losing work.

With Agent Teams enabled (Session 9), a subagent that Claude spawns with a name launches as a teammate instead, and the frontmatter isolation value does not apply: the teammate runs in the main session’s working directory.

Background Sessions Isolate Themselves

A session you start with claude --bg or dispatch from agent view (claude agents) begins in your working directory and moves into its own worktree under .claude/worktrees/ before it edits files. A session you sent to the background with /background (/bg) keeps editing where it already was. In a repository where worktrees are impractical, set worktree.bgIsolation to "none" so background sessions edit the working copy directly.

Cleanup Is a State Decision

When an interactive worktree session exits, Claude Code checks for changed or untracked files, uncommitted work in checked-out submodules, and new commits.

StateInteractive behavior
Clean, session not namedWorktree and branch are removed automatically
Clean, named session (-n, /rename)Claude Code asks whether to keep it
Contains workClaude Code asks whether to keep or remove it
State can’t be verifiedClaude Code asks, naming what it couldn’t check
Non-interactive -p runNo exit prompt and no automatic cleanup

Removing a worktree that contains work deletes its directory and branch, including that work. Read the prompt and verify the target before accepting removal. When you keep one, Claude Code prints a claude --worktree <name> --resume command for returning to it.

For non-interactive runs or manual management, use Git’s public commands. A -p run leaves its worktree locked, so if git worktree remove refuses because of the lock, unlock it first:

git worktree list
git worktree unlock .claude/worktrees/feature-auth
git worktree remove .claude/worktrees/feature-auth
git worktree prune

Do not add --force unless you have deliberately decided to discard uncommitted or untracked work.

Background sessions follow the same rule from the shell. claude rm <id> deletes a session, and the worktree Claude created for it only when that is safe: it keeps a worktree with uncommitted changes, and when the worktree has unpushed commits it refuses and prints the exact claude rm <id> --discard-unpushed <commit>@<worktree-id> command to run if you really mean to discard them (Claude Code 2.1.260 and later). A separate --force-remove-worktree <worktree-id> value (2.1.268 and later) covers a worktree without uncommitted changes to tracked files that git or a WorktreeRemove hook failed to delete. Worktrees that Claude created for subagents and background sessions, and that hold no work, are swept automatically once they are older than cleanupPeriodDays.

Resume and Integrate

Resuming a session that ended inside a worktree returns it to that worktree when the directory still exists; if the directory is gone, Claude Code resumes in your launch directory and tells you. A fork with --fork-session starts from the directory where you launch Claude and leaves the original worktree unchanged.

Before integration:

  1. run the affected tests inside the worktree;
  2. inspect git status and git diff;
  3. commit the bounded change;
  4. merge, cherry-pick, or open a PR using your normal Git workflow;
  5. remove the worktree only after the work is safely integrated or intentionally discarded.

What Not to Assume

  • A new worktree starts from the remote default branch, not from your local work, unless worktree.baseRef says otherwise.
  • Worktrees are separate checkouts, but directories listed in worktree.symlinkDirectories are shared with the main checkout.
  • A clean filesystem does not prove external side effects are isolated.
  • Auto-cleanup rules differ between interactive sessions, subagents, background sessions, and -p runs.
  • Undocumented directory internals are not a stable orchestration API.

Official Sources

Next Session

Next, Session 13 covers the CLI control surface: print mode, JSON output, and resumable sessions.