Worktree Isolation
- Entity ID:
ent-20260410-da00b9227e1a - Type:
service - Scope:
shared - Status:
active - Aliases: worktree, git worktree, worktree isolation
Description
Worktree Isolation is a filesystem-level isolation mechanism built on top of git worktree. When activated -- either via the --worktree CLI flag at session startup, the EnterWorktree tool mid-session, or the isolation: "worktree" parameter on the Agent tool -- Claude Code creates a new git worktree inside .claude/worktrees/<slug> with a dedicated branch based on the default remote branch (typically origin/main). Each worktree gets its own working directory, staging area, and HEAD pointer while sharing the .git/objects/ store with the main repository, so history is stored once regardless of how many worktrees exist. This means multiple agents can write to the same codebase concurrently without stepping on each other's files.
The system supports three distinct usage patterns. First, session worktrees created at startup with --worktree (optionally combined with --tmux for a detached terminal session) set the worktree as the session's project root for the entire session. Second, mid-session worktrees created via the EnterWorktree tool let a user switch into an isolated workspace during an ongoing conversation and return via ExitWorktree. Third, agent worktrees are created automatically when the Agent tool is invoked with isolation: "worktree" -- each spawned subagent gets its own ephemeral worktree (slug pattern agent-a<7hex>), works in isolation, and the worktree is automatically cleaned up if no changes were made. Agents that produce commits leave their worktree and branch intact so the work can be reviewed and merged through standard pull requests.
Cleanup follows a layered strategy. On explicit exit, the ExitWorktree tool offers keep (preserve worktree and branch on disk) or remove (delete both, with a safety check for uncommitted files and unmerged commits that requires discard_changes: true to override). If a session ends while inside a worktree, the WorktreeExitDialog component prompts the user to keep or remove. For ephemeral agent worktrees that leak due to process termination (Ctrl+C, crashes), a periodic background sweep (cleanupStaleAgentWorktrees) scans .claude/worktrees/ for directories matching ephemeral slug patterns (agents, workflows, bridges), checks that they are older than 30 days, have no uncommitted changes, and have no commits unreachable from remotes, then removes them with git worktree remove --force followed by git worktree prune.
Key claims
- Branch naming convention is
worktree-<slug>-- the functionworktreeBranchName()prependsworktree-to the flattened slug (forward slashes replaced with+to avoid git D/F conflicts). The branch is created withgit worktree add -B worktree-<slug> <path> <base>, where-Bresets any orphaned branch from a previously removed worktree without requiring a separategit branch -D. -
Evidence:
worktree.tslines 221-223 (worktreeBranchName), line 328 (-Bflag inaddArgs). -
Worktrees are stored under
.claude/worktrees/<flat-slug>-- theworktreePathFor()function joins the repo root with.claude/worktrees/and the flattened slug. Nested slugs likeuser/featureare flattened touser+featurefor both the directory name and branch name to prevent directory nesting conflicts. -
Evidence:
worktree.tslines 204-227 (worktreesDir,flattenSlug,worktreePathFor). -
Agent worktrees auto-clean when unchanged -- after an agent completes,
AgentTool.tsxcallshasWorktreeChanges()which checks bothgit status --porcelain(uncommitted changes) andgit rev-list --count <original>..HEAD(new commits). If both are clean,removeAgentWorktree()runsgit worktree remove --forceandgit branch -Dto delete the worktree directory and branch. If changes exist, the worktree is kept and its path and branch are returned in the agent's result. -
Evidence:
AgentTool.tsxlines 666-684 (cleanupWorktreeIfNeeded),worktree.tslines 1144-1173 (hasWorktreeChanges), lines 961-1020 (removeAgentWorktree). -
Post-creation setup propagates settings, hooks, symlinks, and gitignored files -- the
performPostCreationSetup()function copiessettings.local.jsoninto the worktree, configurescore.hooksPathto point at the main repo's.huskyor.git/hooksdirectory, symlinks directories listed insettings.worktree.symlinkDirectories(e.g.,node_modules) to avoid disk bloat, and copies gitignored files matched by.worktreeincludepatterns. It also supports sparse checkout viasettings.worktree.sparsePathsfor large monorepos. -
Evidence:
worktree.tslines 506-624 (performPostCreationSetup), lines 321-366 (sparse checkout ingetOrCreateWorktree),settings/types.tslines 438-457 (settings schema). -
Hook-based worktrees extend isolation to non-git VCS -- when
WorktreeCreate/WorktreeRemovehooks are configured insettings.json, the system delegates worktree creation and cleanup to those hooks instead of usinggit worktree. This allows worktree isolation with Mercurial, Perforce, or other version control systems. The hook-based path skips git-specific operations (branch management, change detection) and always keeps the worktree on exit since it cannot detect VCS-level changes. - Evidence:
worktree.tslines 715-728 (hook-based branch increateWorktreeForSession), lines 825-835 (hook-based cleanup incleanupWorktree),EnterWorktreeTool.tsprompt lines 20-21.
Relations
rel-20260410-5f8c6cc6: ent-20260409-cdc5e105d192 --[uses]--> ent-20260410-da00b9227e1arel-20260410-71c8b466: ent-20260409-381bd95a1693 --[contains]--> ent-20260410-da00b9227e1arel-20260410-e7a1b200: ent-20260410-da00b9227e1a --[exposes]--> EnterWorktree toolrel-20260410-e7a1b201: ent-20260410-da00b9227e1a --[exposes]--> ExitWorktree toolrel-20260410-e7a1b202: ent-20260410-da00b9227e1a --[used_by]--> Agent tool (isolation: "worktree")rel-20260410-e7a1b203: ent-20260410-da00b9227e1a --[depends_on]--> git worktree (or WorktreeCreate/WorktreeRemove hooks)
Sources
src-20260409-a14e9e98c3cd
C:\Dev\notebooklm\code\src\utils\worktree.ts-- core worktree lifecycle: creation, cleanup, slug validation, branch naming, stale sweep, agent worktrees, tmux integration, sparse checkout,.worktreeincludefile copyingC:\Dev\notebooklm\code\src\tools\EnterWorktreeTool\EnterWorktreeTool.ts-- mid-session worktree entry toolC:\Dev\notebooklm\code\src\tools\ExitWorktreeTool\ExitWorktreeTool.ts-- mid-session worktree exit tool with keep/remove actions and change safety checksC:\Dev\notebooklm\code\src\tools\AgentTool\AgentTool.tsx-- agent-level worktree isolation viaisolation: "worktree"parameter, auto-cleanup on agent completionC:\Dev\notebooklm\code\src\components\WorktreeExitDialog.tsx-- session exit UI prompting keep/remove when active worktree existsC:\Dev\notebooklm\code\src\setup.ts----worktreeCLI flag handling at session startupC:\Dev\notebooklm\code\src\utils\worktreeModeEnabled.ts-- feature gate (unconditionally enabled)C:\Dev\notebooklm\code\src\utils\cleanup.ts-- periodic stale worktree cleanup integration