Skip to content
Documentation GitHub
Workflow Issues

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

Terminal window
# 1. FIRST: Navigate to the main repository root
cd /path/to/main/repo
# 2. Merge the worktree branch into main
git checkout main
git merge <branch-name>
# 3. Run full test suite to verify merge
<project-specific test command>
# 4. ONLY AFTER cd'ing out: Remove the worktree
git worktree remove .claude/worktrees/<worktree-name>
# 5. Clean up stale worktree references
git worktree prune

Anti-Pattern (Unrecoverable Failure)

Terminal window
# ❌ NEVER do this — CWD is still inside the worktree
git worktree remove .claude/worktrees/<name> # Directory deleted, shell dies
git checkout main # Never executes

Where This Is Enforced

  • commands/workflow/execute.md — “Worktree Cleanup” section in session handoff
  • skills/workflow-guide/SKILL.md — “Parallel Execution Workflow” step 6
  • Project MEMORY.md — “Worktree cleanup CWD trap” pattern entry

Prevention

  1. The cd to main repo root MUST be the very first command in any cleanup sequence
  2. Merge and test verification happen AFTER the cd but BEFORE the removal
  3. git worktree prune at 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.

Was this page helpful?