Worktree Cleanup CWD Trap: Shell CWD Inside Deleted Worktree Is Unrecoverable
Worktree Cleanup CWD Trap
Problem
When Claude Code (or any CLI agent) operates inside a git worktree and then removes that worktree, the shell’s current
working directory (CWD) becomes a dangling reference to a non-existent path. All subsequent shell commands fail with “no
such file or directory” and the session cannot recover — even cd / requires a functioning Bash invocation, which fails
because the CWD is gone.
Symptoms
- Agent completes work in a worktree successfully
- User requests merge + cleanup
- Agent runs
git worktree remove .claude/worktrees/<name>while CWD is inside that worktree - Every subsequent Bash tool call fails
- Session is effectively dead — no recovery path within the session
Root Cause
Unix shells resolve commands relative to CWD. When CWD is deleted (by removing the worktree directory), the kernel returns ENOENT for any operation that needs CWD resolution, including spawning new processes. Claude Code’s Bash tool creates new shell processes for each invocation, all of which inherit the broken CWD from the parent process.
Solution
Always change directory to the main repository root BEFORE removing a worktree.
Safe Cleanup Sequence
# 1. FIRST: Navigate to the main repository rootcd /path/to/main/repo
# 2. Merge the worktree branch into maingit checkout maingit merge <branch-name>
# 3. Run full test suite to verify merge<project-specific test command>
# 4. ONLY AFTER cd'ing out: Remove the worktreegit worktree remove .claude/worktrees/<worktree-name>
# 5. Clean up stale worktree referencesgit worktree pruneAnti-Pattern (Unrecoverable Failure)
# ❌ NEVER do this — CWD is still inside the worktreegit worktree remove .claude/worktrees/<name> # Directory deleted, shell diesgit checkout main # Never executesWhere This Is Enforced
commands/workflow/execute.md— “Worktree Cleanup” section in session handoffskills/workflow-guide/SKILL.md— “Parallel Execution Workflow” step 6- Project MEMORY.md — “Worktree cleanup CWD trap” pattern entry
Prevention
- The
cdto main repo root MUST be the very first command in any cleanup sequence - Merge and test verification happen AFTER the
cdbut BEFORE the removal git worktree pruneat the end catches any stale references
First Encountered
2026-02-21 — Session completed INK-252/INK-254 work in worktrees but crashed during cleanup when the worktree was removed with CWD still inside it. Work was completed but never merged to main.
Wave-Based Sentinel Test Remediation Patterns Next
Worktree Ownership Boundary: Never Remove Worktrees You Didn't Create
Was this page helpful?
Thanks for your feedback!