TODO: Worktree cleanup after agent merge

todo-worktree-cleanup Todo

todo done

TODO: Worktree cleanup after agent merge

Problem

Every dev agent spawned with isolation: "worktree" creates a worktree at .claude/worktrees/agent-{hash} and a branch worktree-agent-{hash}. Claude Code only auto-cleans worktrees where the agent made no changes. Since dev agents always make changes, the worktrees and branches accumulate forever.
Discovered 2026-03-02: 24 stale worktrees and 30 stale branches in pal-e-docs alone. Manually nuked. This will happen in every repo that agents touch.

Root Cause

  • worktree-workflow SOP describes manual worktree creation with explicit cleanup after merge, but doesn't address Claude Code's auto-created worktrees from isolation: "worktree"
  • pr-lifecycle SOP has no "clean up worktree after merge" step
  • No hook exists to auto-prune stale worktrees after PR merge
  • Betty Sue (main session) doesn't have a post-merge cleanup step in her workflow

Options

Option Mechanism Pros Cons
<strong>A: Post-merge hook</strong> Hook on PR merge event that removes the worktree + branch Automatic, tied to the right lifecycle event No obvious Claude Code hook event for "PR merged". Would need a Woodpecker CI step or Forgejo webhook.
<strong>B: Session-start cleanup script</strong> Script in session start hook that prunes worktrees whose branches are merged to main Catches everything, runs naturally Adds latency to session start (already slow with N+1 problem)
<strong>C: Manual SOP step</strong> Add "clean up worktree" to <code>pr-lifecycle</code> after merge Simple, explicit Betty Sue has to remember. Will be forgotten.
<strong>D: Periodic cron/script</strong> Script that finds worktrees whose branches are fully merged, removes them Decoupled from session lifecycle Another thing to maintain
Recommendation: Option B (session-start cleanup) is the most natural. A lightweight script that runs git worktree list, checks each worktree branch against origin/main, and removes merged ones. Add to the existing session-start hook. Cost: ~1 second.

Cleanup Script Sketch

Scope

This affects every repo where agents are spawned with isolation: "worktree". Currently that's pal-e-docs, but will grow as more repos get agent work. The cleanup script should be repo-agnostic (run in whatever repo the session starts in).
  • worktree-workflow — SOP that needs updating
  • pr-lifecycle — SOP that needs a cleanup step
  • project-ai-agency — claude-config project