Worktree sessions can edit files in the parent main checkout with no guardrail
Summary
When a Claude Code session is launched inside a git worktree, the harness sets the working directory to the worktree, announces "You are operating in a git worktree" in the system prompt, and includes the worktree path. But it does not prevent the agent from issuing Edit/Write/NotebookEdit calls against absolute paths that point into the parent main checkout (outside the worktree).
The result: an agent can dirty the working tree on whatever branch the main checkout has checked out (typically master/main), bypassing the branch isolation the worktree was supposed to provide. There is no prompt, no warning, no confirmation β the edit just lands.
Repro
- From a main checkout on
master(clean), launch a Claude Code session inside a worktree:<repo-root>/.claude/worktrees/<wt-name>/ - Ask the agent to edit a source file. The agent, working from
cd-style context or absolute paths, can call:
instead ofEdit { file_path: "<repo-root>/io_utils.py", ... }Edit { file_path: "<repo-root>/.claude/worktrees/<wt-name>/io_utils.py", ... } - The harness accepts the call.
git statusin the main checkout now showsmodified: io_utils.pyonmaster.
Expected
One of:
- Block
Edit/Write/NotebookEditcalls whose resolved absolute path is inside the parent main checkout but outside the active worktree, with a clear rejection message. - At minimum, prompt the user for confirmation (similar to the existing prompts for sensitive paths).
The detection is simple: git rev-parse --show-toplevel vs git rev-parse --git-common-dir differ inside a worktree; the worktree root and main-checkout root are both knowable.
Why this matters
The whole point of EnterWorktree / running a session in a worktree is branch isolation β keep the agent's edits on a feature branch, ship a PR, leave master clean. Today that guarantee is advisory only: it relies on the agent's good behavior and absolute-path discipline. Users currently have to write their own PreToolUse hooks to enforce what the harness implies but doesn't enforce.
Workaround (for other users hitting this)
A PreToolUse hook on Edit/Write/NotebookEdit that compares the resolved file_path against git rev-parse --show-toplevel and rejects anything outside the worktree but inside the parent main checkout. Roughly 20 lines of Python. But this should be a harness-level guarantee, not a per-user patch.
Environment
- Platform: Windows 11, PowerShell + Git Bash
- Worktrees managed via the built-in worktree workflow (
.claude/worktrees/<name>/) - Reproduces with both Sonnet and Opus
Found 2 possible duplicate issues:
- https://github.com/anthropics/claude-code/issues/58772
- https://github.com/anthropics/claude-code/issues/59019
This issue will be automatically closed as a duplicate in 3 days.
- If your issue is a duplicate, please close it and π the existing issue instead
- To prevent auto-closure, add a comment or π this comment
π€ Generated with Claude Code
Confirming the repro pattern on macOS too (not just Windows) β the agent will happily write to the parent main checkout via absolute path even though it correctly identifies that it is "operating in a worktree" in its own status output. The advisory-vs-enforced gap you describe is exactly right.
A few notes from running into this in production:
-
area:sandboxis the right framing. It belongs next to the same machinery that enforces other path-based permission rules β anything less means every worktree user has to hand-roll the hook. -
The detection logic you sketched works in practice. I've been running a
PreToolUsehook along those lines and it's been reliable. Rough shape:- Resolve
file_pathto an absolute, normalized path. - Compare against
git rev-parse --show-toplevel(worktree root) andgit rev-parse --git-common-dir(main repo's.git, from which the main checkout root is derivable). - Reject if the path falls under the main checkout root but outside the worktree root.
The catch is that the hook fires per-call, so on a big multi-file edit run the latency is noticeable. A native check inside the harness would be O(1) per call against pre-computed roots.
- Resolve
-
One edge case worth flagging: the agent will sometimes legitimately want to read shared files from the parent checkout (e.g., a common
requirements.txtor a CI config). A blanket reject on edits/writes outside the worktree is correct, but a blanket reject on reads would break some workflows. The block should be scoped toEdit/Write/NotebookEditonly (which matches the issue body β good catch). -
Symlinks and junctions. On Windows the worktree directory is sometimes implemented with NTFS junctions; on macOS people occasionally symlink worktrees onto external volumes. Whatever the harness does for path comparison should resolve symlinks before deciding "inside vs outside the worktree", or there's a trivial bypass.
-
For the "at minimum, prompt the user" fallback: if it goes that route, the prompt should include both paths (the resolved target and the worktree root) so the user can see at a glance that the write is crossing the boundary. A bare "Are you sure?" doesn't help when the agent is the one driving and the user is reviewing five edits a minute.
Overall, +1 to making this a harness-level guarantee. Worktree-as-isolation is a load-bearing assumption for a lot of multi-agent setups, and the current advisory-only behavior means every team builds the same hook.
Root Cause + Proposed Fix
The worktree isolation is advisory only β the system prompt tells the agent it is in a worktree, but the harness does not enforce path-level restrictions on Edit/Write/NotebookEdit tool calls.
Detection Logic
git rev-parse --show-toplevel β worktree root
git rev-parse --git-common-dir β main repo .git dir (from which main checkout root is derivable)
If resolved file_path falls under main checkout root but outside worktree root β cross-boundary write.
Proposed Fix
1. Harness-level path enforcement (Recommended)
Add a pre-check in the tool handler for Edit, Write, and NotebookEdit:
- Resolve
file_pathto absolute normalized path (resolve symlinks/junctions viafs.realpathSync()) - Get worktree root via
git rev-parse --show-toplevel - Get main checkout root via
git rev-parse --git-common-dir - If resolved path is under main checkout root but NOT under worktree root β reject with clear error
2. Edge cases to handle
- Symlinks/junctions: On Windows, worktrees may use NTFS junctions; on macOS, symlinks to external volumes. Must resolve all symlinks before path comparison.
- Read vs Write: Reads from parent checkout are legitimate (shared configs, CI files). Block should be scoped to
Edit/Write/NotebookEditonly. - User prompt fallback: If full enforcement is too aggressive, at minimum prompt: "β οΈ Edit targets file outside worktree: [target path] vs worktree root: [worktree path]. Continue?"
3. Why this matters
The whole point of worktrees is branch isolation. Currently every team has to hand-roll PreToolUse hooks. A harness-level guarantee is a load-bearing assumption for multi-agent setups.
Confirming on macOS with quantified impact + worker-prompt root cause
Confirming this bug on macOS 26 / Claude Code (2026-05 vintage). Adding hard numbers from a single 24-hour orchestration window and identifying the upstream mechanism in the parent session.
Quantified impact: single day
Scan of one day's subagent transcripts (~/.claude/projects/<slug>/<parent-uuid>/subagents/agent-*.jsonl):
- 42 subagent sessions spawned via
Agenttool withisolation: "worktree". - 153 Edit/Write/MultiEdit calls across those workers.
- 37 of those calls (24%) wrote to
file_pathinside the parent main checkout, outside the worker's worktree. - 116 correctly targeted the worker's worktree.
So roughly 1-in-4 writes from isolation: worktree workers contaminate the parent's working tree under normal orchestration load.
Concrete trace: one worker writing to the wrong tree
Worker agent-a8b191a1a01af85c4, cwd = <repo>/.claude/worktrees/agent-a8b191a1a01af85c4. Selected Edit calls in order:
line 155: file_path='<repo>/lib/core/providers/permission_providers.dart' β MAIN
line 158: file_path='<repo>/lib/features/admin/state/user_access_aggregator_provider.dart' β MAIN
line 160: file_path='<repo>/lib/features/admin/state/user_access_aggregator_provider.dart' β MAIN
...
line 227: file_path='<repo>/packages/b2m_shared/lib/core/default_module_access.dart' β MAIN
line 279: file_path='<repo>/.claude/worktrees/agent-a8b191a1a01af85c4/packages/b2m_shared/lib/core/default_module_access.dart' β worktree (self-corrected)
line 283+: ...worktree paths from here on
15 incorrect writes, then the worker self-corrected β likely after a Read returned content it didn't expect, or after a parent intervention.
Root cause: the worker's prompt embeds the main-repo path
The parent session constructs the worker's first message with a hardcoded main-repo absolute path. Example opening (taken verbatim from the worker's transcript):
"You are creating a new PR on the B2M Hub repo (
<repo-root>). Franz's directive: β¦"
That <repo-root> is the main checkout path, not the worktree. The worker has:
- cwd = worktree (set correctly by harness)
- prompt body = main-repo path (set by parent, not rewritten)
- system prompt = mentions "operating in a git worktree" but doesn't override the path the parent gave it
- Edit/Write tools = accept any absolute path, no sandbox
When the worker resolves "where do I edit lib/foo.dart?", it concatenates the path from its prompt + the relative file, producing a main-repo absolute path. The harness accepts it.
This means the bug is not purely in the worker
The worker is doing the reasonable thing β it followed the path its parent gave it. Three fix surfaces:
- Harness PreToolUse sandbox (what this issue proposes): block writes outside the worktree when
isolation: worktreeis active. Correct and sufficient. I shipped this locally and 100% of worker contamination stops. - Harness prompt-rewrite: when
isolation: worktreeis active, scan the worker's prompt for<main-repo>and rewrite to<worktree>. Compositional, but fragile (false positives on user-quoted text). - Parent-session discipline: parent must explicitly write worktree paths in worker prompts. Convention-based, breaks first time someone forgets.
(1) is the only one that scales. The detection logic is exactly what this issue describes:
# inside the PreToolUse path-check
import subprocess
def in_worktree_sandbox(cwd, file_path):
if "/.claude/worktrees/" not in cwd:
return True # not in a worktree, no constraint
abs_path = file_path if file_path.startswith("/") else f"{cwd}/{file_path}"
return abs_path == cwd or abs_path.startswith(cwd + "/")
Or via git: git -C <cwd> rev-parse --show-toplevel vs the resolved path.
Why patch+stash recovery is insufficient
Per the parent session: when the worker reports "done", the parent runs git diff in main checkout, discovers contamination, runs git stash, applies the stash patch into the worker's worktree, then continues. This costs:
- Real risk of contamination escaping into the parent's next commit if the parent doesn't notice.
- 2-5 minutes per recovery, multiple times per session.
- Cognitive overhead: the parent has to remember to check the main checkout's
git statusbefore every commit.
A harness-level sandbox eliminates all three.
Reads should NOT be sandboxed
The proposed fix should block writes, not reads. Workers legitimately need to read shared assets, package configs, parent CLAUDE.md, etc. A read-side sandbox would break legitimate workflows. The write-side sandbox is the minimum necessary intervention.
Suggested escape hatch
For the rare case where a worker genuinely needs to write outside its worktree (e.g., updating a shared cache, writing to a deploy artifact dir), an explicit env var works:
CLAUDE_WORKTREE_WRITE_ALLOW=/path/one:/path/two
Default-deny + opt-in allowlist matches the spirit of every other sandbox primitive (chroot, Docker bind mounts, npm workspaces).
TL;DR
- 24% contamination rate in a real 1-day orchestration load.
- Root cause: parent embeds main-repo path in worker prompt; worker obeys.
- Fix: PreToolUse write-sandbox keyed to
isolation: worktreecwd. Reads unrestricted. Escape hatch via env var. - Locally shipped this hook; works as designed; should not be a per-user patch.
+1 with fresh data β reproduces 2026-06 on Linux with Opus, top-level (non-subagent) session.
The system prompt explicitly said "This is a git worktree⦠Do NOT cd to the original repository root." Every Read/Edit/Write/Bash call across many turns still used <repo>/packages/... instead of <repo>/.claude/worktrees/<name>/packages/.... Bash cd went to <repo>. Worktree stayed clean; primary clone ended up with 22 modified + 7 new files + a generated Drizzle migration on an unrelated branch (joel/pdf-autoscroll-fix). "Shell cwd was reset to <worktree>" reminders after each Bash call didn't stop subsequent absolute paths from escaping.
Two beyond-file-leakage notes worth flagging:
- Near-miss on destructive infra. Generated the migration from the wrong checkout and ran
bun db:migrate(drizzle-kit push) from the primary clone. It connects to the shared DB regardless of worktree and was one interactive prompt away from applying schema computed against the wrong branch state. - Recovery is hard when branch bases differ. Worktree's base had migrations the primary clone didn't, so my generated
.sqlfilename collided andpackage.jsonexports had drifted β patch neededgit apply --3way+ a manual conflict resolution. Had there been real WIP onjoel/pdf-autoscroll-fix, thegit checkout -- .recovery step would have destroyed it.
Strongly endorse the PreToolUse path-containment fix in this issue / #62547 / #64322 β one git rev-parse --show-toplevel check on writes would have prevented every escape.
Our claude-code-cache-fix project just shipped a PreToolUse hook workaround for this issue.
What it does: intercepts Edit / Write / MultiEdit / NotebookEdit calls and refuses them if the target path's realpath falls outside the active git worktree root. Pass-through (no-op) when the session is launched from a regular checkout rather than a linked worktree.
Why it can help here: addresses the exact data-loss path this issue describes β agent writes inside a worktree session reaching files in the parent main checkout. The hook fires client-side via ~/.claude/settings.json hooks config, doesn't touch the API request path, ships without any proxy dependency.
Install β single hook script + one settings.json entry:
{
"hooks": {
"PreToolUse": [
{ "matcher": "Edit|Write|MultiEdit|NotebookEdit",
"hooks": [{ "type": "command", "command": "<path-to>/worktree-edit-guard.py" }] }
]
}
}
Script + docs + install steps: hooks/examples/worktree-edit-guard.py (docs at docs/hooks/worktree-edit-guard.md). Released in v3.9.0 β npm install -g claude-code-cache-fix ships the script at <npm-prefix>/lib/node_modules/claude-code-cache-fix/hooks/examples/worktree-edit-guard.py.
Containment is strict β also catches symlink-escape paths via realpath resolution on both existing targets and not-yet-existing targets (parent-dir realpath). 20 unit + integration tests, also catches the directive's two highest-risk cases (existing symlink file targets + symlinked parent dir).
This is client-side β it doesn't replace an upstream fix from Anthropic; it gives operators a lever to use today.
β AI Team Lead