Worktree Cleanup
You are cleaning up a git worktree and its associated local branch after the feature has been merged or is no longer needed.
Steps
Determine which worktree to clean up.
If the user provides an argument, use it as the worktree name or branch name.
If no argument is provided, first check if the current working directory is inside a worktree:
# Get the main repo root and current working directory MAIN_ROOT=$(git worktree list | head -1 | awk '{print $1}') CWD=$(pwd)If
CWDis inside a.claude/worktrees/path (i.e., we're currently in a worktree), extract the worktree name and ask the user: "You're currently in worktree<name>— clean up this one?" If they confirm, use it. If they decline, fall through to the list.If not in a worktree (or user declined), list all worktrees and ask the user which one to remove:
git worktree listExclude the main worktree (the first entry, which is the primary repo checkout).
If there are no worktrees to clean up, tell the user and stop.
Check if we're currently inside the worktree being removed (i.e., it was created with
EnterWorktreein this session).If inside the worktree: Call
ExitWorktreewithaction: "remove"anddiscard_changes: true. This cleanly releases the directory lock, removes the worktree, and switches the session back to the main repo. Then skip to step 4 (branch deletion) — the worktree directory is already gone.If NOT inside the worktree (cleaning up a worktree from a previous session or one created manually):
a. Make sure
pwdis not inside the worktree path. If it is,cdto the main repo root first.b. Remove the worktree using git's worktree command:
git worktree remove <path> --forceIf that fails due to permissions (common on Windows), fall back to manual removal:
rm -rf <path> git worktree pruneDelete the local branch if it exists. Determine the branch name from the worktree or the user's input:
git branch -d <branch-name>If
-dfails because the branch isn't merged to HEAD (but is merged to its remote tracking branch), use-Dafter confirming with the user.Prune stale worktree references:
git worktree pruneShow a summary of what was cleaned up:
- Worktree path removed
- Branch deleted (if applicable)
- Confirmation that everything is clean
Important
- Always check we're not inside the worktree before removing it.
- The worktree directory lives under
.claude/worktrees/<name>by convention. - The branch name is typically
feature/<name>where<name>matches the worktree directory name. - If the worktree directory doesn't exist but the git worktree ref is stale,
git worktree prunehandles it. - Never delete the
main,dev, ormasterbranches.