diff --git a/.claude/scripts/gc-worktrees.sh b/.claude/scripts/gc-worktrees.sh index d995b7ae6..45cdf0638 100644 --- a/.claude/scripts/gc-worktrees.sh +++ b/.claude/scripts/gc-worktrees.sh @@ -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 /.claude/worktrees/. The primary @@ -93,13 +97,20 @@ 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 @@ -107,9 +118,13 @@ else 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 @@ -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 `, 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 / HEAD / # branch |detached / locked. Parse the stanza rather than the human format, whose @@ -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 } @@ -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 <" git branch -D "" ``` - `-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 diff --git a/tests/unit/gc-worktrees-classify-2310.test.ts b/tests/unit/gc-worktrees-classify-2310.test.ts new file mode 100644 index 000000000..db4efecb5 --- /dev/null +++ b/tests/unit/gc-worktrees-classify-2310.test.ts @@ -0,0 +1,294 @@ +/** + * Regression test for issue #2310: `.claude/scripts/gc-worktrees.sh`'s + * `--prune-branches` step used `git branch -d` unconditionally for every + * branch `classify()` had already deemed "settled" via authoritative + * GitHub PR state. `-d`'s own internal check is an ancestry test — under a + * squash/rebase-merge workflow (this repo's own, confirmed live — #2309) a + * genuinely-merged branch's tip is never an ancestor of the squash commit + * on the default branch, so `-d` silently refused to delete it, and the + * branch survived every future `--prune-branches` run indefinitely. + * + * Fixing this by switching to `-D` unconditionally would introduce a worse + * bug: `classify()` originally matched a branch to a "settled" PR by name + * only. A branch name can be reused after its earlier PR merged or closed + * (a later run, or a human, creating a new branch of the same name for + * unrelated work) — matching by name alone would then hand that new, + * never-merged branch's real commits to `-D`. The fix requires an EXACT + * name-and-current-tip-SHA match against a PR GitHub reports MERGED before + * a branch is `-D`-eligible (mirroring housekeep's Phase 4a fix for the + * identical gap, Greptile review PR #2311); every other "settled" case + * (closed-without-merging, a reused name, or the ancestry-test fallback) + * still only gets `-d`, preserving its refusal-if-unmerged safety net. + * + * Extracts the real `classify()` function from the actual script (not a + * reimplementation) and exercises it with controlled inputs, mirroring + * fixer-skill-2g-queue-guard-2304.test.ts's extraction approach. + */ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; + +const REPO_ROOT = path.join(import.meta.dirname, '../..'); +const SCRIPT_PATH = path.join(REPO_ROOT, '.claude/scripts/gc-worktrees.sh'); + +/** Extract the body of a `name() { ... }` bash function, brace-matched (not regex-fragile). */ +function extractFunction(script: string, name: string): string { + const marker = `${name}() {`; + const start = script.indexOf(marker); + if (start === -1) { + throw new Error(`Function not found in gc-worktrees.sh: ${name}`); + } + let depth = 0; + let i = start + marker.length - 1; // position of the opening '{' + for (; i < script.length; i++) { + if (script[i] === '{') depth++; + else if (script[i] === '}') { + depth--; + if (depth === 0) break; + } + } + if (depth !== 0) { + throw new Error(`Unbalanced braces extracting function: ${name}`); + } + return script.slice(start, i + 1); +} + +const script = fs.readFileSync(SCRIPT_PATH, 'utf-8'); +const classifyFn = extractFunction(script, 'classify'); + +interface ClassifyInputs { + gh_ok: 0 | 1; + open_heads?: string; + settled_heads?: string; + merged_heads_sha?: string; + /** Only consulted when gh_ok=0: whether the ancestor test should report true. */ + ancestor: boolean; +} + +/** Run the real classify() against controlled inputs and return its exit code. */ +function runClassify(branch: string, head: string, inputs: ClassifyInputs): number { + // Stub `git` so the ancestor-test fallback (merge-base --is-ancestor) is + // controllable without a real repo — classify() only ever calls `git -C + // "$main_root" merge-base --is-ancestor ...` in that branch. + const gitStub = `git() { if [ "$3" = "merge-base" ]; then return ${inputs.ancestor ? 0 : 1}; fi; }`; + const script = ` + ${gitStub} + gh_ok=${inputs.gh_ok} + main_root="/tmp" + default_branch="main" + open_heads='${inputs.open_heads ?? ''}' + settled_heads='${inputs.settled_heads ?? ''}' + merged_heads_sha='${(inputs.merged_heads_sha ?? '').replace(/\\t/g, '\t')}' + ${classifyFn} + classify "${branch}" "${head}" + echo "EXIT:$?" + `; + const out = execFileSync('bash', ['-c', script], { encoding: 'utf8' }); + const match = out.match(/EXIT:(\d+)/); + if (!match) throw new Error(`Could not parse classify() exit code from: ${out}`); + return Number(match[1]); +} + +describe('gc-worktrees.sh classify() (#2310)', () => { + it('extracted a non-trivial classify() containing the merged_heads_sha check', () => { + expect(classifyFn).toContain('merged_heads_sha'); + expect(classifyFn).toContain('return 0'); + expect(classifyFn).toContain('return 3'); + }); + + it('returns 1 (keep, live work) for a branch with an open PR', () => { + const verdict = runClassify('feat/x', 'abc123', { + gh_ok: 1, + open_heads: 'feat/x', + ancestor: false, + }); + expect(verdict).toBe(1); + }); + + it('returns 0 (-D safe) when the branch name AND current tip SHA match a MERGED PR', () => { + const verdict = runClassify('feat/x', 'abc123', { + gh_ok: 1, + settled_heads: 'feat/x', + merged_heads_sha: 'feat/x\\tabc123', + ancestor: false, + }); + expect(verdict).toBe(0); + }); + + it('returns 3 (only -d safe), NOT 0, when the branch name matches a MERGED PR but the current tip SHA differs (reused branch name)', () => { + // This is the core safety fix: the branch name "feat/x" once merged as + // commit abc123, but the LOCAL branch's current tip is def456 — a + // different, never-merged commit sitting on a reused name. Verdict 0 + // here would hand real, un-landed work to -D. + const verdict = runClassify('feat/x', 'def456', { + gh_ok: 1, + settled_heads: 'feat/x', + merged_heads_sha: 'feat/x\\tabc123', + ancestor: false, + }); + expect(verdict).toBe(3); + }); + + it('returns 3 (only -d safe), NOT 0, for a CLOSED-without-merging PR (no landed commit to pin against)', () => { + const verdict = runClassify('feat/x', 'abc123', { + gh_ok: 1, + settled_heads: 'feat/x', + merged_heads_sha: '', + ancestor: false, + }); + expect(verdict).toBe(3); + }); + + it('returns 2 (orphan, report) when no PR exists for the branch at all', () => { + const verdict = runClassify('feat/x', 'abc123', { + gh_ok: 1, + ancestor: false, + }); + expect(verdict).toBe(2); + }); + + it('returns 3 (only -d safe) via the ancestor-test fallback when gh is unavailable', () => { + const verdict = runClassify('feat/x', 'abc123', { + gh_ok: 0, + ancestor: true, + }); + expect(verdict).toBe(3); + }); + + it('returns 1 (keep, inconclusive) via the ancestor-test fallback when the ancestor test fails', () => { + const verdict = runClassify('feat/x', 'abc123', { + gh_ok: 0, + ancestor: false, + }); + expect(verdict).toBe(1); + }); +}); + +/** + * Regression test for Greptile's findings across two rounds of review on PR #2469: + * + * Round 1: the original fix collected confirmed-`-D`-safe branch names into a list during + * the worktree walk, then deleted them all in a SEPARATE loop after the walk finished. That + * gap — the time the rest of the walk took — let a concurrent process recreate or advance a + * freed branch name before the deferred loop reached it; `-D` would then delete that NEW ref + * by name alone, with no re-verification. Fixed by moving deletion into `prune_branch()`, + * called immediately after each branch's own worktree removal. + * + * Round 2: that fix still re-read the branch's tip via a separate `rev-parse`, THEN called + * `git branch -D` in a second, distinct git invocation — leaving a narrower but still-real + * gap between the two commands. Fixed by replacing both with a single + * `git update-ref -d refs/heads/ ` call, which git performs as one + * atomic compare-and-delete: it deletes the ref only if it still points at the given SHA, + * with no window in between for a concurrent process to exploit. + */ +const pruneBranchFn = extractFunction(script, 'prune_branch'); + +interface PruneBranchOpts { + pruneBranches?: 0 | 1; + /** Whether the stubbed `git branch -d` should succeed (verdict-3 path only). */ + deleteOk?: boolean; + /** What the branch's ref is stubbed to ACTUALLY point at, simulating concurrent mutation. Defaults to `head` (no drift). */ + actualRefSha?: string; +} + +/** Run the real prune_branch() against controlled inputs; reports output text and every `git branch`/`git update-ref` invocation it made. */ +function runPruneBranch( + branch: string, + head: string, + verdict: number, + opts: PruneBranchOpts = {}, +): { output: string; gitCalls: string[] } { + const pruneBranches = opts.pruneBranches ?? 1; + const deleteOk = opts.deleteOk ?? true; + const actualRefSha = opts.actualRefSha ?? head; + const logFile = path.join( + os.tmpdir(), + `gc-worktrees-prune-branch-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.log`, + ); + // Stub `git` so both call shapes prune_branch() makes are controllable without a real + // repo: `git -C "$main_root" branch -d "$branch"` (arg $3 = "branch", verdict-3 path) and + // `git -C "$main_root" update-ref -d "refs/heads/$branch" "$head"` (arg $3 = "update-ref", + // verdict-0 path). update-ref is simulated with the same atomic compare-and-delete + // semantics the real command has: it succeeds only if the given old value ($6) matches + // this branch's stubbed actual ref value, mirroring how a concurrent mutation would make + // the real `git update-ref -d` fail closed rather than delete the wrong ref. + const gitStub = ` + git() { + if [ "$3" = "branch" ]; then + echo "branch $4" >> "${logFile}" + [ "${deleteOk ? 1 : 0}" = "1" ] && return 0 || return 1 + elif [ "$3" = "update-ref" ]; then + echo "update-ref $6" >> "${logFile}" + [ "$6" = "${actualRefSha}" ] && return 0 || return 1 + fi + } + `; + const runner = ` + ${gitStub} + main_root="/tmp" + prune_branches=${pruneBranches} + ${pruneBranchFn} + prune_branch "${branch}" "${head}" "${verdict}" + `; + const output = execFileSync('bash', ['-c', runner], { encoding: 'utf8' }); + let gitCalls: string[] = []; + if (fs.existsSync(logFile)) { + gitCalls = fs.readFileSync(logFile, 'utf8').split('\n').filter(Boolean); + fs.unlinkSync(logFile); + } + return { output, gitCalls }; +} + +describe('gc-worktrees.sh prune_branch() (#2310, Greptile rounds 1-2 on PR #2469)', () => { + it('extracted a non-trivial prune_branch() containing the atomic update-ref delete', () => { + expect(pruneBranchFn).toContain('update-ref'); + expect(pruneBranchFn).toContain('branch ref changed since classification'); + }); + + it('uses -d (not update-ref) for verdict 3 (settled, not name+SHA-confirmed)', () => { + const { output, gitCalls } = runPruneBranch('feat/x', 'abc123', 3); + expect(gitCalls).toEqual(['branch -d']); + expect(output).toContain('branch deleted'); + }); + + it('reports nothing (not an error) when -d refuses an unmerged verdict-3 branch', () => { + const { output, gitCalls } = runPruneBranch('feat/x', 'abc123', 3, { deleteOk: false }); + expect(gitCalls).toEqual(['branch -d']); + expect(output).not.toContain('branch deleted'); + }); + + it('deletes via update-ref for verdict 0 when the ref still matches the confirmed-merged SHA', () => { + const { output, gitCalls } = runPruneBranch('feat/x', 'abc123', 0, { actualRefSha: 'abc123' }); + expect(gitCalls).toEqual(['update-ref abc123']); + expect(output).toContain('branch deleted'); + }); + + it('atomically refuses the update-ref delete when the branch ref changed since classification', () => { + // This is the round-2 TOCTOU fix: classify() confirmed SHA abc123 merged, but by the + // time prune_branch() runs, refs/heads/feat/x actually points at def456 — a concurrent + // process recreated or advanced this exact branch name. The single update-ref call still + // fires (there is no separate pre-check to skip), but git's own atomic compare-and-delete + // refuses it in the same operation — never a two-step check-then-delete that a race could + // slip between. + const { output, gitCalls } = runPruneBranch('feat/x', 'abc123', 0, { actualRefSha: 'def456' }); + expect(gitCalls).toEqual(['update-ref abc123']); + expect(output).toContain('skip (branch ref changed since classification) feat/x'); + }); + + it('is a no-op when --prune-branches was not passed', () => { + const { output, gitCalls } = runPruneBranch('feat/x', 'abc123', 0, { + pruneBranches: 0, + actualRefSha: 'abc123', + }); + expect(gitCalls).toEqual([]); + expect(output).toBe(''); + }); + + it('is a no-op for a detached worktree (no branch name to delete)', () => { + const { output, gitCalls } = runPruneBranch('', 'abc123', 3); + expect(gitCalls).toEqual([]); + expect(output).toBe(''); + }); +});