Agent worktrees with isolation:worktree not cleaned up when calling session ends
Summary
When the Agent tool is used with isolation: "worktree", Claude Code creates a git worktree and locks it with the calling process's PID. If the calling session ends before the agent completes (or before cleanup runs), the worktree is stranded — locked, never pruned, and orphaned forever.
Reproduction
- Launch an Agent with
isolation: "worktree"from a Claude Code session - End the session (context limit, crash, or manual exit) before the agent returns
- Start a new session in the same repo
- Run
git worktree list— orphaned locked worktrees appear
Observed state
Found 6 locked worktrees in .claude/worktrees/, all pointing to the same old commit, all locked with PID 197259 (long dead):
~/code/personal/boxy-green-thing/.claude/worktrees/agent-a1761c25a0d171d29 [locked]
~/code/personal/boxy-green-thing/.claude/worktrees/agent-a27eed21738882d75 [locked]
...
Lock reason string: claude agent agent-<id> (pid 197259) — the PID no longer exists.
Expected behavior
Claude Code should clean up orphaned agent worktrees on session start (or offer to). At minimum, a git worktree prune equivalent that checks whether the locking PID is still alive would clear stale locks automatically.
Workaround
git worktree remove -f -f .claude/worktrees/<name>
git worktree prune
git branch | grep worktree-agent | xargs git branch -D
Requires double --force because the lock explicitly blocks single --force removal.
Environment
- Platform: Linux (WSL2)
- Shell: zsh
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗