Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 94 additions & 33 deletions .claude/scripts/gc-worktrees.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@
#
# Usage: gc-worktrees.sh [--dry-run] [--prune-branches]
# --dry-run report what would be removed; change nothing. Exit 0 either way.
# --prune-branches also `git branch -d` each freed branch (safe delete — git itself
# refuses if it is not merged; we only ever offer merged ones).
# --prune-branches also delete each freed branch (safe delete — we only ever offer
# branches classify() already confirmed merged: `git branch -D` when
# that confirmation came from authoritative GitHub PR state, since
# squash/rebase merges make git's own ancestry test unreliable
# (issue #2310); `git branch -d` when it came from the ancestry-test
# fallback itself, which has no more-authoritative signal to override it).
#
# REMOVAL RULE (all four must hold — fail-closed, never force):
# 1. SCOPE — the worktree path is under <repo-root>/.claude/worktrees/. The primary
Expand Down Expand Up @@ -93,23 +97,34 @@ fi
# back to the ancestor test per worktree — which under a squash-merge workflow collects
# almost nothing, so say so out loud rather than reporting a clean "0 collected".
# `gh --jq` uses gh's BUILT-IN jq, so this needs no external jq on PATH.
settled_heads=""; open_heads=""
settled_heads=""; open_heads=""; merged_heads_sha=""
gh_ok=0
if command -v gh >/dev/null 2>&1 \
&& all_prs="$(gh pr list --state all --limit 1000 --json headRefName,state \
--jq '.[] | "\(.state)\t\(.headRefName)"' 2>/dev/null)"; then
open_heads="$(printf '%s\n' "$all_prs" | sed -n 's/^OPEN\t//p')"
settled_heads="$(printf '%s\n' "$all_prs" | sed -n '/^OPEN\t/!s/^[A-Z]*\t//p')"
&& all_prs="$(gh pr list --state all --limit 1000 --json headRefName,state,headRefOid \
--jq '.[] | "\(.state)\t\(.headRefName)\t\(.headRefOid)"' 2>/dev/null)"; then
open_heads="$(printf '%s\n' "$all_prs" | sed -n 's/^OPEN\t\([^\t]*\)\t.*/\1/p')"
settled_heads="$(printf '%s\n' "$all_prs" | sed -n '/^OPEN\t/!s/^[A-Z]*\t\([^\t]*\)\t.*/\1/p')"
# branch\tSHA pairs for MERGED PRs specifically (not CLOSED-without-merging, which has
# no landed commit to pin against) — used to require an EXACT name-and-current-tip-SHA
# match before a branch is eligible for -D. A name-only match would wrongly treat a
# brand-new, never-merged local branch that happens to reuse an old merged PR's branch
# name as "confirmed merged," handing its real, un-landed commits to a force-delete —
# mirrors housekeep's Phase 4a fix for the identical gap (Greptile review, PR #2311).
merged_heads_sha="$(printf '%s\n' "$all_prs" | sed -n 's/^MERGED\t//p')"
gh_ok=1
else
echo "note: gh unavailable/unauthenticated — falling back to the ancestor test, which under" >&2
echo " a squash-merge workflow will collect almost nothing. Re-run with gh." >&2
fi

# Classify this worktree's work. $1 = branch name ("" when detached), $2 = HEAD sha.
# 0 = settled -> collect
# 0 = merged, name+SHA confirmed via GitHub PR state -> collect, -D the branch
# 1 = open PR -> live work, keep quietly
# 2 = no PR -> orphan, keep but REPORT
# 3 = settled, but not a name+SHA-confirmed merge (closed-without-merging, a merge whose
# branch name was since reused, or the ancestry-test fallback) -> collect the
# worktree, but only -d the branch — retains git's own ancestry check as the sole
# safety net for exactly the cases that lack a more authoritative one
classify() {
local branch="$1" head="$2"
if [ "$gh_ok" -eq 1 ] && [ -n "$branch" ]; then
Expand All @@ -120,24 +135,75 @@ classify() {
# first match, the producer takes SIGPIPE, and the pipeline reports 141 — so a settled
# branch would read as unsettled. A here-string has no pipe and no such failure mode.
grep -qxF "$branch" <<<"$open_heads" && return 1
grep -qxF "$branch" <<<"$settled_heads" && return 0
if grep -qxF "$branch $head" <<<"$merged_heads_sha"; then
return 0
fi
grep -qxF "$branch" <<<"$settled_heads" && return 3
return 2
fi
# Detached HEAD, or no gh: fall back to the ancestor test. A detached worktree has no
# name to pin, so keeping it costs nothing when the test is inconclusive.
# name to pin, so keeping it costs nothing when the test is inconclusive. Distinct
# return code (3, not 0) from the gh-confirmed case above: this branch's "settled"
# verdict has no authority beyond git's own ancestry test, so the deletion step below
# must not treat it the same as a gh-confirmed merge (issue #2310).
if git -C "$main_root" merge-base --is-ancestor "$head" "origin/$default_branch" 2>/dev/null; then
return 0
return 3
fi
return 1
}

# Delete a branch classify() already ruled settled, choosing -D vs -d by $3's verdict.
# Split out of flush() so it can be extracted and unit-tested in isolation, the same way
# classify() itself is (tests/unit/gc-worktrees-classify-2310.test.ts).
#
# $1 = branch name, $2 = HEAD sha captured from `git worktree list --porcelain` BEFORE this
# call, $3 = classify()'s verdict for this branch (3 or 0 — flush() never calls this for 1/2).
prune_branch() {
local branch="$1" head="$2" verdict="$3"
[ "$prune_branches" -eq 1 ] && [ -n "$branch" ] || return 0
if [ "$verdict" -eq 3 ]; then
# -d, not -D: this branch was classified "settled" but without an exact name+SHA
# match against a MERGED PR — either it's a CLOSED-without-merging PR (no landed
# commit exists to pin against; deleting its branch with -D could destroy real,
# never-merged work), a MERGED PR whose branch name has since been reused for
# different commits, or the git-ancestry-test fallback (no gh available, or a
# detached worktree). None of these have a more-authoritative signal than git's own
# ancestry check, so -d's refusal-if-unmerged behavior is exactly the safety net to
# keep here — unlike the exact-merge-confirmed branches below.
if git -C "$main_root" branch -d "$branch" >/dev/null 2>&1; then echo " branch deleted $branch"; fi
return 0
fi
# -D, not -d: classify() already confirmed this branch's CURRENT tip SHA matches a
# MERGED PR's exact recorded head via authoritative GitHub PR state, not git
# ancestry. Under a squash/rebase-merge workflow (this repo's own, confirmed live —
# issue #2309) the local branch tip is never an ancestor of the squash commit on the
# default branch, so -d's own ancestry check would silently refuse a genuinely
# merged branch here — exactly the fix already applied to housekeep's Phase 4d/1e
# (issue #2309) for the identical reason. The name+SHA (not name-only) requirement
# additionally guards against a reused branch name aliasing an old, unrelated merged
# PR (Greptile review, PR #2311) — a name-only match would hand -D a brand-new,
# never-merged branch's real commits just because an old PR once used the same name.
#
# `update-ref -d <ref> <oldvalue>`, not a separate `rev-parse` check followed by
# `branch -D`: those are two distinct git invocations, and a concurrent process could
# mutate the ref in the gap between them — narrower than the original deferred-batch
# gap, but not closed. `update-ref -d` takes the expected old value as part of the SAME
# command and refuses atomically if the ref no longer matches, so there is no window at
# all between "confirm" and "delete" (Greptile review, PR #2469, round 2).
if git -C "$main_root" update-ref -d "refs/heads/$branch" "$head" 2>/dev/null; then
echo " branch deleted $branch"
else
echo " skip (branch ref changed since classification) $branch"
fi
}

# Directories that no longer exist on disk: git's own bookkeeping handles these.
[ "$dry_run" -eq 1 ] || git -C "$main_root" worktree prune

# These are newline-delimited STRINGS, not arrays: `${#arr[@]}` on an empty array trips
# `set -u` on bash 3.2, which this script still targets for portability.
removed=0; skipped_dirty=0; skipped_open=0; skipped_orphan=0; skipped_locked=0
freed_branches=""; orphan_branches=""
orphan_branches=""

# `git worktree list --porcelain` emits stanzas: worktree <path> / HEAD <sha> /
# branch <ref>|detached / locked. Parse the stanza rather than the human format, whose
Expand Down Expand Up @@ -183,19 +249,24 @@ flush() {

if [ "$dry_run" -eq 1 ]; then
echo " would remove $label"
else
if git -C "$main_root" worktree remove "$path" 2>/dev/null; then
echo " removed $label"
else
echo " skip (git refused the remove) $label — $path"
return 0
fi
return 0
fi
removed=$((removed + 1))
if [ -n "$branch" ]; then
freed_branches="${freed_branches}${branch}
"
if ! git -C "$main_root" worktree remove "$path" 2>/dev/null; then
echo " skip (git refused the remove) $label — $path"
return 0
fi
echo " removed $label"
removed=$((removed + 1))

# Deletion happens HERE, immediately after this branch's own worktree removal — not
# deferred to a batch loop run after the whole worktree walk finishes. Deferring it (the
# original design) left a window, for however long the rest of the walk took, in which a
# concurrent process could recreate or advance this exact branch name before the deletion
# loop got to it; `-D` would then delete that NEW ref by name with no revalidation. Doing
# it inline collapses that window to the next statement, and prune_branch()'s own SHA
# re-check (for the -D path specifically) closes what's left of it outright (Greptile
# review, PR #2469).
prune_branch "$branch" "$head" "$verdict"
return 0
}

Expand All @@ -209,16 +280,6 @@ while IFS= read -r line; do
done < <(git -C "$main_root" worktree list --porcelain)
flush

if [ "$prune_branches" -eq 1 ] && [ "$dry_run" -eq 0 ] && [ -n "$freed_branches" ]; then
while IFS= read -r b; do
[ -n "$b" ] || continue
# -d (not -D): git refuses if the branch is somehow not merged after all.
if git -C "$main_root" branch -d "$b" >/dev/null 2>&1; then echo " branch deleted $b"; fi
done <<EOF
$freed_branches
EOF
fi

# Orphans get named, not just counted. Folding them into the in-flight total is what lets
# a repo report itself healthy while dozens of dead worktrees pin their branch names.
if [ "$skipped_orphan" -gt 0 ]; then
Expand Down
2 changes: 1 addition & 1 deletion .claude/skills/housekeep/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ git worktree prune
git worktree remove "<path>"
git branch -D "<branch>"
```
`-D`, not `-d`: this worktree was already classified "stale" via Phase 1c's GitHub-PR-state check, not git ancestry, so `-d`'s own ancestry test would wrongly refuse a genuinely squash/rebase-merged branch here — see Phase 4d's identical fix for why `-d` is the wrong tool once a more authoritative source already confirmed the merge (issue #2309). Phase 1c's classifier currently matches by branch name only (not name-and-SHA the way Phase 4a now does), so this inherits the same reused-branch-name gap Phase 4a closed — tracked separately in issue #2310 since the fix belongs in `gc-worktrees.sh`, not here.
`-D`, not `-d`: this worktree was already classified "stale" via Phase 1c's GitHub-PR-state check, not git ancestry, so `-d`'s own ancestry test would wrongly refuse a genuinely squash/rebase-merged branch here — see Phase 4d's identical fix for why `-d` is the wrong tool once a more authoritative source already confirmed the merge (issue #2309). `gc-worktrees.sh`'s own `classify()` (which Phase 1c delegates to) now requires the same name-**and**-current-tip-SHA match against a MERGED PR that Phase 4a uses before treating a branch as `-D`-safe, closing the identical reused-branch-name gap here too (issue #2310).

**For bloated (non-stale) worktrees:**
- List them with a per-artifact size breakdown
Expand Down
Loading
Loading