Skip to content

Add gh pr-review gc, the --doctor paths and one section on where reviews run - #18

Merged
catalan-adobe merged 35 commits into
mainfrom
review-gc
Nov 30, 2026
Merged

catalan-adobe merged 35 commits into
mainfrom
review-gc

Conversation

@catalan-adobe

@catalan-adobe catalan-adobe commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

PR 3d of review tracking: gh pr-review gc, the --doctor paths, and one README section on where reviews run. This is Task 5 and steps 1–2 of Task 6 of docs/superpowers/plans/2026-11-26-review-tracking-pr3-local-worktrees.md. The plan predates #16's six review rounds, so it follows #16's code: the refs, worktree and lock paths keyed by <host>/<owner>/<repo>/<N>, the locks, and the path checks. Two plan steps are left out on purpose: the real run and its timings (Task 6 steps 3–4) come in a follow-up, because they call the model.

After round 3 flagged this PR as churning and too big, it was split: gc here removes review worktrees and refs only and keeps the review history. Deleting history (--purge) moves to a separate PR.

gh pr-review gc [--dry-run] [-u <login>]

  • Which PRs: every PR folder in the state folder with a pr.json, including dot-named repos such as .github. Folders without one are passed over, and GitHub isn't asked about them. gc asks GitHub for each PR's state with this account: -u, else the one in pr.json, else GH_PR_REVIEW_USER, else the active one, chosen as a review run chooses it. Open PRs are kept.
  • Merged or closed: under the PR's lock, then the clone's lock for the PR:
    • The review worktree is removed only when it is clean, with git worktree remove and no --force. Clean means all of these:

      • git status with untracked and ignored files and submodule changes prints nothing. The fsmonitor and untracked cache are off, and the stat data is checked in full.
      • No file is flagged assume-unchanged or skip-worktree.
      • No .git is below it other than its own. For each folder, the check asks the file system for <folder>/.git, as git does, so .GIT on a case-insensitive volume counts.
      • Each submodule entry's folder is absent or empty.
      • No rebase, merge, cherry-pick, revert or bisect is in progress.
      • It references no commit that would be lost: every commit named by its HEAD, its reflogs or its own refs (refs/worktree, refs/bisect, refs/rewritten) is either a PR head the run checked out or reachable from a ref that stays.
        • PR heads the run checked out: the commit it made the worktree at (worktree_sha in pr.json), and the new values of the reflog entries it labels.
        • Refs that stay: every ref except refs/pr-review/* and symbolic refs, plus the main worktree's HEAD and the HEADs of worktrees outside .reviews. Nothing gc may delete counts.
      • An emptiness check asks whether an entry exists; it never decides from file names as text.

      It must also pass the run's path checks: owned_worktree, the exact <clone>.reviews/<host>/<owner>/<repo>/<branch>/<N> layout, reviews_check, and no overlap with the state folder or the PR's folder.

    • When the worktree is left: the line names what was found (for lost commits, all their IDs) and the command that removes it anyway (git -C <clone> worktree remove --force <path>). The PR keeps its refs and pr.json, so a later gc can finish.

    • A worktree whose folder was deleted outside git: that one registration is removed when its recorded path still leads where the run puts it and its leftover git folder (worktrees/<id>) passes the same commit and operation checks. gc never runs git worktree prune, which would drop the registrations of your offline worktrees.

    • Refs: refs/pr-review/<host>/<owner>/<repo>/<N>/* (head, base and round pins) are deleted in one update-ref --no-deref --stdin transaction, with old values checked.

    • Empty folders: those left in .reviews and .locks are removed with rmdir only, and so is .reviews itself when it is empty.

  • History stays: the PR's state folder (run folders, pr.json, loop-check.md) is kept. The README says how to delete it by hand.
  • --dry-run prints what gc would do and changes nothing. It runs the same checks, including the locks, through the read-only lock check that the run's lock code also uses (lock_state / lock_probe in lib/state.sh, clone_lock_path / clone_lock_check in lib/worktree.sh).
  • Skipped, with the reason: a PR whose review is running (either lock held), or whose clone isn't there (deleted, or on an unmounted volume).
  • Folders gc can't list are named, and the folders beside them are still checked.
  • Exit code: 1 when a PR failed (something was left), its state couldn't be read, or a folder couldn't be listed; 0 otherwise.
  • Never touched: your clone's branches, HEAD, index, stash, config and other worktrees, and the cache clones.

State and lock changes

  • One lock policy: lock_take decides by lock_state after each failed atomic claim. lock_probe and lock_check give the same verdict and message without changing anything. clone_lock is split into path checks, a read-only check, and the take.
  • Clone lock: it makes <clone>.reviews 0700 by stripping the known /.locks/<pr-key> suffix.
  • Temp names: runs write their temporary files as .pr.json.tmp.<pid> and .loop-check.md.tmp.XXXXXX.
  • What the run records: when it creates the review worktree, it saves the commit in pr.json (worktree_sha). When it checks out the PR head in a reused worktree, it labels the reflog entry gh-pr-review: checkout of the PR head. Both let gc tell the PR heads the run checked out from commits made there.
  • Worktrees made by earlier versions have neither record. They are removed only when all their commits are reachable from a ref that stays, which is usually the case for a PR merged with a merge commit once the clone has fetched it.
  • Locks: lock_claim, lock_remove, lock_state and lock_probe tell "empty" and "only pid" with find, so names that end in a newline can't fool them.

--doctor

It now also prints the state folder (with a note when it isn't writable or searchable), the config file (or "none"), and the clone roots (or "none" for []), without scanning. An invalid config file fails the check, since every run that looks up a clone stops on it. clone_roots (in lib/clones.sh) now reads the roots for both --doctor and find_clone.

README

The parts that grew over #16's rounds are now one "Where reviews run" section:

  • the clone lookup;
  • the review worktree and private refs;
  • the state folder;
  • locks;
  • --clone/--fresh;
  • the config file, with an example;
  • cleaning up.

gc is in Usage, and Troubleshooting covers:

  • skipped clones;
  • a refused .reviews;
  • a refused lock and its rm -rf command;
  • exit 4.

Tests

tests/gc.sh: 211 checks, with real git and stub gh. Worktrees are made by the run's own code. Preview/run pairs compare the lines and the exit code, and check what survives. Cases:

  • Basics: --dry-run; -u and an unknown login; open, merged and closed PRs; a state that can't be read.
  • Paths and locks: worktrees that aren't the tool's or sit in the wrong place; held and read-only locks; a folder deleted outside git; a .reviews symlink.
  • Leftovers that keep a worktree: a dirty, ignored or nested-.git (or .GIT) worktree; assume-unchanged, skip-worktree and core.ignoreStat files; files in an unpopulated submodule's folder; a stopped rebase; a commit on its HEAD, only in its reflog, or on refs/worktree/*; a commit kept only by a PR's private ref, or shared by two review worktrees; a worktree remade at the saved path from a local branch; a deleted folder whose registration still holds a commit or a stopped rebase; a file named with a newline. Each check confirms the file or commit is still there afterwards.
  • Controls: multi-round worktrees made by the run's own code, including force-pushed and --no-post heads, are removed. So are an earlier version's worktree whose heads were merged, and a run-made worktree whose folder was deleted.
  • Refs and folders: symbolic refs; rmdir failures; unlistable folders; tidying beside an open PR.

tests/state.sh: a table of lock kinds, including names that end in a newline. Each is checked for the probe verdict, that nothing changed, and that it matches a real lock_take.

tests/flow.sh: the --doctor lines.

@catalan-adobe catalan-adobe left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approach

What it does: Adds gh pr-review gc to remove review worktrees and private refs for merged or closed PRs. --dry-run previews cleanup; local review history stays unless --purge is passed. --doctor and the README now show where those files live.

Fit with the repo: docs/superpowers/plans/2026-11-26-review-tracking-pr3-local-worktrees.md names lib/gc.sh, and gh-pr-review already dispatches gc to cmd_gc. Cleanup reuses the two existing locks and the worktree ownership checks. It adds no GC branch to the review flow.

Strongest case for the approach as built: The PR says “gc never runs git worktree prune.” That departure from the original plan is justified: #16’s lib/worktree.sh deliberately preserves unrelated worktree registrations when a volume is offline. Removing only the recorded review worktree honors the same promise.

Alternatives: Keep pr.json as the cleanup inventory. It names only the last clone used for a PR, but requires no new bookkeeping. If cleanup must also find artifacts in previously used clones, I’d record each clone used rather than scan for deletion candidates.

Questions for the author: None.
Missing context: The planned live review and timings are deferred; neither is needed to judge where cleanup belongs.

Approach: Sound

Strengths

  • [tests/gc.sh:260] — The tests check the promise that matters to a clone owner: unrelated branches, worktrees, stash and config survive cleanup. The separate assertion that an offline worktree stays registered is especially valuable.
  • [lib/gc.sh:112] — Deleting refs in one transaction with their observed object IDs avoids partially deleting a PR’s pins if a ref changes concurrently. That transaction is worth keeping.
  • [lib/clones.sh:236] — Sharing clone_roots between lookup and --doctor keeps the diagnostic accurate without scanning the filesystem.

Issues

🚨 Critical (Must Fix Before Merge)

  • [lib/gc.sh:220] — --purge recursively deletes user files that merely resemble run artifacts. round-notes.md, pr.json.backup, and even a user directory named loop-check.md all reach rm -rf. None is a run folder produced by lib/state.sh.

    • Match the writer’s actual names and types: numbered round directories, timestamped run/preview directories with their optional collision suffix, and known metadata files. Preserve ambiguous entries rather than recursively deleting them.
  • [lib/gc.sh:118] — The ref transaction can delete a branch outside the PR namespace. If a ref under refs/pr-review/<key>/ is symbolic and points to a local branch, %(objectname) supplies the target’s object ID and update-ref dereferences the symbolic ref by default. The old-value check therefore does not protect the branch.

    • Use no-dereference semantics for every delete, or refuse symbolic refs without changing their targets. Add a real-Git assertion that the target branch survives.
  • [lib/gc.sh:83] — The worktree check protects only the state root of the current gc invocation. A second review can run --fresh with GH_PR_REVIEW_STATE=./state from inside the first review’s worktree. When the first PR closes, gc using the default state root can force-remove that worktree, including the second review’s history, checkout and lock.

    • Make nested state recognizable independently of the caller’s environment and refuse removal when found. Cover two distinct state roots and PRs; neither lock for the first PR protects the second one.

⚠️ Important (Should Fix)

  • [lib/gc.sh:302] — With --purge, a four-component directory name is enough to select a PR even without pr.json or any evidence of a review. With the supported GH_PR_REVIEW_STATE=., an unrelated empty github.com/org/repo/7/ is removed, along with empty parents, if GitHub says PR 7 is closed.

    • Keep support for --fresh history, but require a recognizable run artifact before treating a directory without pr.json as tool-owned. Validate the candidate’s path before taking its lock, not only later in gc_purge.
  • [lib/gc.sh:64] — The missing-worktree path can report successful cleanup without checking the recorded registration. For example, if a branch directory was replaced by a symlink and the leaf is absent, the resolved path can fail gc_shape; the function returns success, leaving the old registration in Git and allowing --purge to erase the inventory. When the shape does match, this path skips the parent reviews_check that the existing-worktree path performs.

    • Distinguish “confirmed absent and unregistered” from “cannot safely resolve the recorded path.” Report the latter as left, keep pr.json, and apply the parent-path checks before removing a registration or tidying its ancestors.
  • [lib/gc.sh:415] — The discovery glob skips dot-prefixed repositories, including the explicitly supported .github repo. I checked a temporary state tree containing github.com/org/.github/7/pr.json: gc --dry-run reported “No PRs.” Its worktree, pins and history would never be collected.

    • Include hidden path components during enumeration while retaining PR-key validation. Add .github to the GC fixture.
  • [lib/gc.sh:233] — Every failed rmdir is reported as “holds other files,” even when the directory is empty. If the PR directory is writable but its parent is read-only, purge can delete all its contents, fail to remove the empty directory, and exit 0 with holds other files (). gc_tidy similarly discards removal errors at lines 133–142.

    • Treat confirmed nonempty directories as expected; report other removal failures and return 1. Delete pr.json after the run artifacts so an earlier removal failure preserves the clone and account needed for a retry.
  • [lib/gc.sh:216] — --dry-run --purge reports that it would remove the state folder without inspecting what would remain. In a temporary fixture it said this both for a PR containing notes.txt and for one whose lock/ contained a non-PID file. The real run keeps the directory in the first case and refuses the lock before cleanup in the second.

    • Share read-only candidate selection and lock validation between preview and execution. The preview need not predict races, but it should describe the outcome for an unchanged filesystem.

💡 Minor (Nice to Have)

  • [gh-pr-review:412] — --doctor checks directory write permission but not search permission. A mode-0600 state directory was reported without a warning, although the process cannot create a PR directory inside it. Check -x as well as -w on the existing directory or nearest existing parent.

Recommendations

Keep the real-Git fixtures and add paired preview/execution cases: for the same initial state, assert what survives, what remains retryable, and the exit code. Sharing the ownership checks between those two paths would address several of the discrepancies above without adding a GC branch to the review flow.

Assessment

Ready to merge? No

Reasoning: The transaction and targeted worktree removal are sound choices, but the current deletion rules can cross the advertised boundary into user files, branch refs and another review’s state. Those are merge blockers for a cleanup command.


Review generated by gh pr-review · model: azure-openai-direct/gpt-6.2-astra

@catalan-adobe

Copy link
Copy Markdown
Owner Author

Thanks for round 1. All nine items are fixed, one commit each, each with tests that failed on the code before its fix (controls that pass on both are labelled). The recommendation is in too: paired preview/execution cases check that, from the same starting files, the --dry-run lines (with "would remove" read as "removed") and exit code equal the real run's.

Critical

  • lib/gc.sh:220 (--purge deletes look-alikes): 843f165. New gc_artifact decides by name and type, matching exactly what the writers make, and never matches a symlink:

    • regular files pr.json and loop-check.md;
    • their temp files pr.json.<pid> (pr_json_set writes $file.$$) and loop-check.md.XXXXXX (mktemp);
    • folders round-<K> (K ≥ 1), and run-/preview- followed by <UTC YYYYmmddTHHMMSS>, with an optional -<n> (run_dir_new).

    Anything else stays and is named in the line. Tests: round-notes.md, pr.json.backup, a folder named loop-check.md, a round-1 symlink, a file named run-<time>, round-0 and run-latest all survive.

  • lib/gc.sh:118 (a symbolic ref deletes a branch): 69d6e96. The transaction runs update-ref --no-deref --stdin, so a symbolic ref under the PR's namespace is deleted itself, and the branch it points at survives. Checked with real git 2.55 and 2.43. The old-value check still refuses a mismatch. Tests: a symref to a local branch, and one to another ref of the same PR.

  • lib/gc.sh:83 (another run's state inside the worktree): 0783a16.

    • pr_state_mkdir writes <state root>/.gh-pr-review-state, mode 0600, once (noclobber), and only for a PR folder under that root. A failed write doesn't stop the run.
    • gc refuses a worktree that holds, anywhere in it:
      • that marker;
      • a pid file of a live process;
      • a state folder from before the marker: a <N> folder at least 4 levels deep holding pr.json, lock/pid or a run folder (by the patterns above).
    • The search is find -print0, and it doesn't follow symlinks. If find fails, the worktree is refused.
    • Tests: two state roots and two PRs, the second root inside the first PR's worktree. Closing the first PR, gc leaves that worktree, and the second root's history and lock survive. The same holds for a root made before the marker, and for a live lock. A review run on an older root adds the marker and goes on.

Important

  • lib/gc.sh:302 (--purge without pr.json): 8ee370d. Such a folder counts only when it holds a run folder (by the patterns above) or its state root has the marker; otherwise it is passed over, and gh isn't asked. A symlink on the path fails the PR before its lock is taken. Tests: an empty github.com/org/repo/7/ and one holding look-alikes are left, together with their parents.

  • lib/gc.sh:64 (a missing worktree path): 4b8a695. The registration is looked up under both the recorded and the resolved path:

    • Not registered: nothing to remove. The parent folders are tidied only when the checks pass.
    • Registered: removed only when the resolved path equals the recorded one, fits the layout, and passes reviews_check on its parent. Otherwise it is left with the reason, and pr.json stays (no purge).

    Tests cover the case you describe: a branch folder replaced by a symlink, with the leaf absent.

  • lib/gc.sh:415 (hidden repo names): 8346847. New gc_walk lists *, .[!.]* and ..?*; the PR-key check is unchanged. h/o/.github/1 is now in the main fixture: found by --dry-run, removed, and its state folder purged.

  • lib/gc.sh:233 (rmdir failures): f903649. New gc_rmdir takes a confirmed non-empty folder as expected and names what is in it. Any other failure is "could not remove the folder X: ", and the PR fails (exit 1), in gc_tidy and in purge alike. pr.json is now deleted last. Tests: a read-only parent keeps pr.json and exits 1.

  • lib/gc.sh:216 (--dry-run --purge mispredicts): f404908.

    • Dry-run makes the run's checks without changing anything. gc_lock_check gives each refusal lock_take would make, with the same text, for both locks.

    • gc_purge_plan, shared by both modes, refuses up front, deleting nothing, when:

      • a folder on the path is a symlink;
      • the state folder overlaps the clone;
      • the PR folder can't be read, written and searched;
      • the folder would be left empty in a parent that can't be changed.

      It predicts the kept files and the parents it would remove.

    • A preview can't foresee a run folder rm fails to delete, an rmdir failure inside .reviews, or a git failure; the README says so.

Minor

  • gh-pr-review:412 (--doctor and search permission): 7488f82. It checks -w and -x on the state folder, or on its nearest existing parent. Tests: a 0600 state folder, and one in a 0600 parent.

9679ee3 and bb11b2e only rewrap the README and lib/gc.sh comments. The README's gc section is rewritten to match, and the state-folder section names the marker.

Results on bb11b2e:

  • CI (run, ubuntu-26.04): passes, 1777 checks, 0 FAIL (2 case-alias checks skipped on its case-sensitive volume).
  • macOS bash 5.3 (git 2.55): every file passes, tests/gc.sh with 144 checks; flow.sh and worktree.sh each skip one case-alias check.
  • macOS /bin/bash 3.2: gc 144, state 135 and flow 355 pass.
  • Ubuntu 26.04 (git 2.53): every file passes, and lint is clean. The lock stress test gave 900 entered with 0 overlaps, and tests/clones.sh passed 20 of 20 runs.
  • ubuntu:24.04 (git 2.43): tests/gc.sh 144 ok.

@catalan-adobe catalan-adobe left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 2 · since round 1

5 fixed · 4 still open · 5 new (3 in the new commits) · open blocking: 7 (was 8) · loop: early

Approach

What it does: Adds gh pr-review gc to remove closed PRs’ review worktrees and private refs. History stays unless --purge is passed.

Fit with the repo: The command still belongs in lib/gc.sh, as docs/superpowers/plans/2026-11-26-review-tracking-pr3-local-worktrees.md specifies. Two decisions since round 1 change my verdict. First, gc_lock_check now predicts refusal and takeover rules owned by lib/state.sh; gc_clone_lock also repeats path checks from lib/worktree.sh. A lock-policy change now needs two implementations to keep preview accurate. Second, gc_runs_left accepts a PR-shaped directory when “its state root has the marker.” With GH_PR_REVIEW_STATE=., one review proves the root contains review state, not that every matching directory under it belongs to the tool.

Strongest case for the approach as built: Preview takes no locks, and the root marker lets GC protect another review’s nested state before removing a worktree. Both are worth keeping.

Alternatives: Share read-only lock checks with the lock implementations, leaving atomic acquisition and rechecks there. That costs a contained refactor. Keep the root marker as a reason not to delete, but require per-PR evidence to purge. That leaves ambiguous empty directories behind; if collecting them matters, mark each PR directory when it is created.

Questions for the author: None. Those two changes would restore my round-1 verdict.
Missing context: None for this decision.

Approach: Questionable

Strengths

  • [lib/gc.sh:246] — The ref transaction now uses --no-deref and retains the old-object checks. tests/gc.sh:419 verifies the important outcome: the symbolic ref is gone, but the user’s branch still points to the same commit.
  • [lib/gc.sh:179] — For a missing worktree, GC checks both the recorded and resolved paths against Git’s registrations. The tests at tests/gc.sh:520 verify that an unsafe registration and the pr.json needed to retry both survive.
  • [tests/gc.sh:609] — Comparing preview and execution from the same starting state, including exit status, is a useful regression test for a destructive command.

Issues

🚨 Critical (Must Fix Before Merge)

  • F1 · [lib/gc.sh:357] — Purge still selects user backups and directories the writer cannot produce. loop-check.md.backup matches the six-character temporary-file suffix. run-20260101T000000-1 also matches, although run_dir_new starts collision suffixes at -2. I checked both with gc_artifact; it accepted both. The latter is then deleted recursively.

    • Preserve ambiguous legacy temp files, give new temp files a tool-specific naming convention, and restrict collision suffixes to the writer’s actual format. Add both names to the preservation test.
  • F3 · [lib/gc.sh:126] — The marker protects the tested nested state root, but the fallback still misses real review state. A stopped --check can leave only loop-check.md (gh-pr-review:528); a root created before the marker has no other evidence. I checked that gc_state_in reports no state for that layout. There is also a current path to losing full rounds: if another state root’s repo directory points into the worktree, its root marker is outside, and its completed PR history can be shallower than the four levels required at lib/gc.sh:150.

    • Mark the physical per-PR directory as well as the root, and recognize the legacy loop-check-only layout before force-removing a worktree.
  • [lib/gc.sh:474] — Purging a --fresh run bypasses the nested-state check entirely. A second PR can use GH_PR_REVIEW_STATE=./state from the first PR’s archived preview-…/repo. Purging the closed first PR recursively removes the second PR’s marked state, history and even a live lock. Round 1 examined the linked-worktree deletion path; the --fresh checkout is deleted by this separate rm path.

    • Check all candidate run directories for nested state before deleting the first artifact. On a match, report the path and retain the inventory for retry.
  • [lib/gc.sh:222] — A different Git worktree nested inside the review worktree is not protected. For example, a developer can have a linked dependency checkout with uncommitted work under the review checkout. The outer worktree passes owned_worktree, and the new scan looks for review state, not nested checkouts. Force-removing the outer directory removes the inner files while leaving their registration behind. Round 1 checked sibling and offline worktrees, not descendants.

    • Refuse removal when the target contains another worktree; exclude the target’s own .git entry from that check. Test that both the nested checkout’s dirty file and its registration survive.

⚠️ Important (Should Fix)

  • F4 · [lib/gc.sh:385] — A root marker still authorizes purging an unrelated PR-shaped directory. With GH_PR_REVIEW_STATE=., one genuine review marks the shared root. A sibling github.com/org/repo/7 with no review evidence then qualifies: GC can remove it and its empty parents, or delete a user’s loop-check.md there. tests/gc.sh:500 currently expects the empty sibling to be deleted.

    • Require evidence in the candidate PR directory. Keep the root marker as a reason to protect a tree, not permission to purge its descendants. Reverse the marked-sibling test and assert that no GitHub lookup occurs.
  • F8 · [lib/gc.sh:55] — Preview still approves locks execution cannot take on an unchanged filesystem. I checked an empty mode-0500 PR lock: gc_lock_check accepts it because the listing is empty, but lock_claim cannot create pid. The clone equivalent at lib/gc.sh:301 skips the creation check altogether when the lock is absent, including when its nearest existing parent is read-only.

    • Share a read-only lock feasibility check with acquisition and cover both cases in the paired test. Neither discrepancy requires predicting a race or a Git failure.
  • [lib/gc.sh:634] — Discovery treats an unreadable directory as an empty one. With a real h/o/r/7/pr.json below a non-listable r/, gc --dry-run printed No PRs and exited 0. A batch can therefore report success while omitting an entire repository.

    • Distinguish a missing state root from a directory that cannot be enumerated. Name the unreadable path, continue with readable siblings, and retain exit 1 even when the number of discovered PRs is zero.

💡 Minor (Nice to Have)

  • [lib/gc.sh:274] — A nonempty worktree ancestor now returns from all of gc_tidy, rather than just ending that ancestor walk. If an open PR remains in the same repo, GC can leave the closed PR’s empty .locks hierarchy behind. End the worktree walk with break, then tidy the independent lock path.
  • [lib/gc.sh:139] — Any regular file named pid containing a live PID is reported as a held lock. A tracked test fixture containing 1 is enough to prevent cleanup, despite no process holding a lock there. Check a recognizable lock layout and bound the amount read from a candidate PID file.
Fixed since the last round (5)
  • F2 — Ref deletion no longer dereferences a symbolic ref into a user branch.
  • F5 — A registered missing worktree behind a changed symlink or .git ancestor is refused, with pr.json retained.
  • F6 — Discovery includes dot-prefixed repositories, with .github covered through preview, cleanup and purge.
  • F7 — Unexpected rmdir failures are reported, and an earlier artifact-removal failure preserves pr.json.
  • F9 — --doctor checks search as well as write permission on the state directory or nearest existing parent.

Recommendations

Use the existing paired-test pattern to check what survives, not just whether preview and execution agree. In particular, put one unrelated directory beside a real PR under a marked root, and one independently owned checkout or state root inside each kind of recursive deletion target.

Assessment

Ready to merge? No

Reasoning: The ref and missing-registration fixes protect the clone in the cases they target. The remaining deletion paths can still erase user backups, another PR’s history, or uncommitted files in another worktree; a successful dry run does not rule those out.


Review generated by gh pr-review · model: azure-openai-direct/gpt-6.2-astra

… remove without --force, and keeps the PR's refs when it leaves the worktree
…d gc --purge removes a PR's folder only with evidence in it: that marker, pr.json or a run folder, never the state folder's marker
….json.tmp.<pid>, .loop-check.md.tmp.XXXXXX), and gc --purge deletes only those and the run folders' exact suffixes; earlier versions' temporary files stay, named
…anything in a PR's folder: a --fresh checkout must be clean, and no other checkout or state folder may be in one
…cide what a lock is and what lock_take would do, lock_take decides by lock_state, and gc --dry-run uses lock_check and clone_lock_check (lib/worktree.sh) instead of repeating them
…he others, and exits 1, even when it found no PR; a state folder that is not there still holds no PR
… ends that walk only, and the PR's emptied .locks folders are still removed
@catalan-adobe

Copy link
Copy Markdown
Owner Author

Thanks for round 2. Your two design points are adopted as you proposed them. Most of the remaining findings had one shape: something that isn't the tool's sits inside a folder gc deletes recursively. So this round closes that class instead of the listed cases. gc now deletes only what it can prove is the tool's and clean, and leaves the rest with the command to remove it by hand. Seven commits, b3b3a71…194439d, each with tests that failed on bb11b2e (controls that pass on both are labelled).

Approach

  • One lock policy (3457236): lib/state.sh now has lock_state <dir>, read only. It reports free, empty, cannot, notlock, nopid, live <pid> or dead <pid>.
    • What uses it: lock_take decides by it after each failed atomic claim, for the lock and while waiting on the takeover lock. Claims, rechecks under lock.takeover, removal and messages are unchanged.
    • The preview: lock_probe adds what lock_take would do with the takeover lock, and lock_check is lock_probe plus lock_take's message. gc --dry-run calls only that.
    • Removed from gc: gc_lock_check. clone_lock (lib/worktree.sh) is split into its path checks, a read-only clone_lock_check and the take, so gc_clone_lock no longer repeats lib/worktree.sh's checks.
    • Tests: tests/state.sh builds 18 kinds of lock. For each it checks the verdict, that nothing changed, and that lock_check gives the exit code and first error of a real lock_take.
  • The root marker protects; only per-PR evidence permits a purge (72fcdd5). A run also writes <PR folder>/.gh-pr-review-pr (the PR's <host>/<owner>/<repo>/<N>, 0600, once). --purge takes a folder as the tool's only with a marker, a regular pr.json or an exact run folder in it. The root marker is no longer permission.

Critical

  • F1, lib/gc.sh:357 (backups and impossible names): f5a5d94.
    • New temp names: writers use .pr.json.tmp.<pid> and .loop-check.md.tmp.XXXXXX, and purge deletes only those.
    • Old temp names are kept: the ambiguous pr.json.<digits> and loop-check.md.XXXXXX stay, named in the line.
    • Run-folder suffixes follow run_dir_new: none, or -2 and up.
    • Tests: loop-check.md.backup and run-20260101T000000-1 both survive.
  • F3, lib/gc.sh:126, and the nested-worktree critical, lib/gc.sh:222 (state or another checkout inside the review worktree): b3b3a71. gc removes a review worktree only when it is clean: git status --porcelain --untracked-files=all --ignored --ignore-submodules=none prints nothing.
    • Removal: it then runs git worktree remove without --force. Without --force, git still deletes ignored files silently, so our --ignored check is what protects them.
    • What this covers: nested state, a loop-check-only legacy folder, a nested linked worktree or clone, a stray pid file. Each shows as untracked or ignored, so the scan for nested state (gc_state_in) is gone.
    • When the worktree is left: the line names the first entries and gives git -C <clone> worktree remove --force <path>. The PR's refs and pr.json stay, so a later gc finishes the job.
    • Tests (preview and run, then what survives): another review's state folder with a live lock; a linked worktree of another repo with a dirty file (its change and registration survive); an ignored file; a changed tracked file. Control: a tracked fixtures/pid holding a live PID doesn't block. After a manual removal, a second gc deletes the refs.
    • Trade-off: a closed PR's worktree with build output in it is now left for you, not deleted.
  • lib/gc.sh:474 (--fresh run folders): 104d060. Before deleting anything in a PR folder, gc checks every run, round and preview folder it would delete.
    • --fresh checkout: a folder's only allowed .git is the checkout at <run>/repo. That checkout must be clean by the same status check, and have no other .git or linked worktrees.
    • Other names refused: any marker, pr.json, loop-check.md or lock outside repo/. I checked these against every file gh-pr-review writes into a run folder.
    • On a hit: nothing in that PR folder is deleted, pr.json stays, and the line names the path.
    • Tests: the second PR's state root under preview-…/repo keeps its history and live lock; a dirty linked worktree inside repo/ survives; a pre-marker state folder in a run folder is kept. Control: a clean checkout is purged.

Important

  • F4, lib/gc.sh:385 (marked-root siblings): 72fcdd5, above. The test at tests/gc.sh:500 is reversed: an unrelated h/x/y/7 and a loop-check.md-only folder beside a real PR are left, and gh isn't asked about them. A marker-only folder and the real PR are purged.
  • F8, lib/gc.sh:55 (preview approves locks execution can't take): 3457236, above.
    • Locks that can't be created: lock_state reports cannot for an empty lock folder without write permission, so no pid file can be made in it. A missing clone lock is checked against its nearest existing parent.
    • Paired tests: an empty mode-0500 PR lock, and a missing clone lock under a read-only .reviews. On the old code both previews said "would remove".
  • lib/gc.sh:634 (unreadable directories): 33d75dd. A state folder, <host>, <owner>, <repo> or PR folder that can't be read and searched is named. Its siblings are still handled, and gc exits 1, including with "No PRs found in X, but N folders could not be listed." A missing state root is still "No PRs", exit 0.

Minor

  • lib/gc.sh:274 (gc_tidy): 194439d. A non-empty ancestor ends only that walk, and the emptied .locks folders are still removed. Test: an open PR in the same repo.
  • lib/gc.sh:139 (a pid file read as a lock): gone with b3b3a71, since gc no longer reads pid files inside worktrees.

Recommendation: in. The paired tests now also check what survives. They cover an unrelated folder beside a real PR under a marked root, and an independently owned checkout and state root inside each kind of recursive deletion target (the review worktree, and a --fresh checkout).

Checks on 194439d:

  • Local runs: every test file passes on macOS bash 5 and on Ubuntu 26.04, which also ran the lock stress test with 900 entered and 0 overlaps.
  • Older shell and git: gc, state, worktree and flow pass on /bin/bash 3.2, and gc passes on Ubuntu 24.04 (git 2.43).
  • Lint: shellcheck and shfmt are clean.
  • CI: green on Ubuntu 26.04 (1875 ok, 2 skip, 0 FAIL): https://github.com/catalan-adobe/gh-pr-review/actions/runs/46404822644/job/141800316287

@catalan-adobe catalan-adobe left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 3 · since round 2

6 fixed · 3 still open · 4 new (4 in the new commits) · open blocking: 6 (was 7) · loop: churning
Next: Split the PR: each part converges on its own

Approach

What it does: Adds gh pr-review gc to remove merged or closed PRs’ review worktrees and private refs. Local history stays unless --purge is passed.

Fit with the repo: lib/gc.sh is where docs/superpowers/plans/2026-11-26-review-tracking-pr3-local-worktrees.md puts this command. Both round-2 concerns are resolved: preview and acquisition share lock_state in lib/state.sh and clone_lock_path in lib/worktree.sh. Purge now requires evidence inside the PR directory; a marked state root no longer authorizes deleting a sibling.

Strongest case for the approach as built: As the author says, “a closed PR’s worktree with build output in it is now left for you, not deleted.” Checking ignored files and removing without --force makes that trade-off explicit. The refs and pr.json stay so cleanup can be retried.

Alternatives: Requiring .gh-pr-review-pr for every purge would leave older runs for manual cleanup. I’d choose that stricter rule if existing run names proved ambiguous in practice.

Questions for the author: None.
Missing context: None for this decision.

Approach: Sound

Strengths

  • [lib/gc.sh:265] — When GC leaves a worktree, it now keeps the PR’s refs as well as pr.json. That makes the failure retryable without losing the round pins.
  • [tests/gc.sh:555] — The marked-root test checks three outcomes for an unrelated sibling: no GitHub lookup, no cleanup report, and the directory still exists. That directly verifies the ownership boundary from round 2.
  • [tests/gc.sh:802] — The unreadable-directory test verifies that GC names the failure, continues with a readable sibling, and returns a nonzero batch result.

Issues

🚨 Critical (Must Fix Before Merge)

  • F10 · [lib/gc.sh:313] — Purge still misses another PR’s state inside a --fresh checkout’s .git directory. For example, a second review can use GH_PR_REVIEW_STATE=.git/review-state to keep its history out of the working tree. git status cannot see that history, and the new find explicitly prunes ./repo/.git. Purging the outer PR can therefore delete the second review’s history and live lock.

    • Check for state markers and legacy state below the Git directory too, before removing any artifact. The Git directory itself is expected; an independent review state root inside it is not.
  • F11 · [lib/gc.sh:138] — A nested checkout is not always visible in the outer worktree’s status. If a developer checks out a vendored dependency over the same files the PR already tracks, the only additional entry can be vendor/.git. I checked the status command against an unchanged tracked directory containing an extra .git entry: it produced zero bytes. Removing the outer worktree can then erase a nested clone’s unpublished history or leave a linked checkout registered at a path that no longer exists.

    • Check for descendant .git entries independently of status, excluding only the review worktree’s own .git. The --fresh path already makes this distinction.
  • [lib/gc.sh:302] — The repo/ exception accepts an unrelated clone as the run’s disposable checkout. A local-worktree review never creates <run>/repo, but if a developer later puts a clean clone there, GC accepts it without checking even the PR’s private refs. Purge then deletes the entire clone, including any local-only branches and stash. The success fixture at tests/gc.sh:578 actually uses an ordinary git clone, not fresh_checkout. Conversely, a nonempty repo/ whose .git is missing falls through without a cleanliness check at all.

    • Establish that a nonempty repo/ belongs to this run before deleting it. Record ownership for new fresh checkouts, use the expected PR refs where they provide evidence for older ones, and leave ambiguous directories for manual cleanup. Use fresh_checkout for the positive test.
  • [lib/gc.sh:78] — gc_status can miss a changed tracked file marked assume-unchanged in the index. Git deliberately omits the content check for that file; --ignored and --untracked-files=all do not override the bit. A local edit can therefore pass the new cleanliness test and be deleted. The same helper guards both review worktrees and archived checkouts.

    • Refuse automatic removal when index flags hide changes, or verify those entries independently without modifying the real index. Add a preservation test for an edited, assume-unchanged file.

⚠️ Important (Should Fix)

  • F8 · [lib/state.sh:198] — Preview now handles an empty read-only lock, but still approves takeover of a stale read-only lock. With a writable parent and a mode-0500 lock directory containing only a dead PID, I observed lock_check return 0 and lock_take return 1: the parent permits removing the directory, but the lock directory does not permit unlinking pid.

    • Check permission to remove the PID file as well as the lock directory, and add this case to the paired probe/acquisition tests.
  • [lib/gc.sh:349] — GC writes the PR key into .gh-pr-review-pr but never checks it. If a --fresh state directory for open PR 8 is moved or restored under closed PR 7, its marker still says …/8. GC asks about PR 7 and purges PR 8’s history despite that explicit contradiction.

    • When a marker exists, compare its contents with the candidate key before cleanup. Refuse a mismatch and name both keys; the existing fallback can still serve legacy directories without markers.

💡 Minor (Nice to Have)

  • [lib/worktree.sh:300] — ${lock%/.locks/*} strips the shortest matching suffix. For the valid repo name .locks, a lock at r.reviews/.locks/h/o/.locks/1 yields r.reviews/.locks/h/o as the directory to chmod, not r.reviews. An existing .reviews can retain its old permissions. Strip the known /.locks/<pr-key> suffix literally instead.
Fixed since the last round (6)
  • F1 — Purge preserves the ambiguous legacy temp names and rejects collision suffixes the writer does not use, including -1 and -02.
  • F3 — In the reported worktree layouts, nested review files are now detected as untracked or ignored regardless of directory depth or the location of the state-root marker.
  • F4 — A marked state root no longer qualifies an unrelated sibling for purge; evidence must be in the candidate PR directory.
  • F12 — Discovery reports non-listable state directories, processes readable siblings, and retains exit 1 even when no PR was found.
  • F13 — A nonempty worktree ancestor now ends only that walk; cleanup still visits the independent .locks hierarchy.
  • F14 — GC no longer interprets arbitrary worktree files named pid as live locks.

Recommendations

Keep the paired preview/execution tests, but distinguish ownership from cleanliness in their fixtures. Use a real run-created checkout as the positive control, then test an unrelated clean clone, a damaged checkout, and Git metadata that porcelain does not report. For each refusal, assert that the underlying history or edited file survives, not just that the output lines agree.

Assessment

Ready to merge? No

Reasoning: The retry behavior and batch reporting are substantially better. The remaining blockers are deletion decisions: an empty Git status does not establish ownership or prove that all local data is disposable, and the fresh-checkout scan skips a location that can hold another active review.


Review generated by gh pr-review · model: azure-openai-direct/gpt-6.2-astra

…PR), with the code, tests and docs only it used: gc_purge and its checks, the handling of PR folders without pr.json, and the state folder and PR markers
… own, which git status never lists (a clone or worktree of yours checked out over files the PR tracks), or that find can't search for one; the status and .git checks are one helper, gc_disposable
…lagged assume-unchanged (core.ignoreStat=true flags them all) or skip-worktree (gc_flagged, git ls-files -v), and reads its status with each file's stat data checked in full (core.checkStat, core.trustctime) and the untracked cache off
… lock_take finds it: one it can't remove (its pid file can't be deleted), so gc --dry-run says the run fails, with its error; the probe/acquisition table covers it and its siblings
…<pr-key> from the lock's path, not the shortest /.locks/*, which a repo named .locks matches too
@catalan-adobe

Copy link
Copy Markdown
Owner Author

Thanks for round 3. Following its loop check ("churning", too big; split the PR), this PR is now split. --purge and everything only it used are out of #18 (1bcf4a1). gc now removes only review worktrees and refs; it keeps the review history. Deleting history moves to its own PR, designed so a run records what it creates. Three findings move with it, unfixed here: F10 (state inside a --fresh checkout's .git), the <run>/repo ownership finding, and the marker mismatch. The PR description is updated.

Removed in 1bcf4a1:

  • Purge code and the folders it alone handled: gc_purge, gc_purge_plan, gc_rm, gc_owned, gc_run_foreign, gc_artifact, gc_path_bad, gc_takeover_ends, and the handling of PR folders without pr.json, which are now passed over without asking GitHub.
  • Markers: .gh-pr-review-state and .gh-pr-review-pr, which nothing in Add gh pr-review gc, the --doctor paths and one section on where reviews run #18 reads any more.
  • Size: lib/gc.sh goes from 717 to 494 lines. The writers keep the .pr.json.tmp.<pid> and .loop-check.md.tmp.XXXXXX temp names.

The four findings that remain in #18 are fixed, one commit each, with tests that failed on the commit before. A worktree is now removed only when the new gc_disposable passes: the status, plus checks for files the status doesn't look at and for a nested .git. Per your recommendation, every worktree in these tests is made by the run's own code, and each refusal checks that the file or history survives.

Critical

  • F11, lib/gc.sh:138 (a nested .git the status can't see): fec461c. After the status, gc_disposable runs find . -path ./.git -prune -o -name .git -print. That catches a .git at any depth other than the worktree's own, without following symlinks. Any find error also leaves the worktree. When the worktree is left, so are its refs and pr.json, and the line gives the --force command.
    • Tests: over a tracked vendor/ where git status prints nothing, a clone of mine with an unpublished commit (the commit survives), and a linked worktree of another repo (it stays registered). Also a find that fails, compared preview vs run. Control: a tracked vendor/linked symlink to a folder holding .git doesn't block removal.
  • lib/gc.sh:78 (edits hidden by index flags): efe0e3f. New gc_flagged (git ls-files -v) leaves a worktree with any assume-unchanged or skip-worktree entry and names them. I also checked config that can make status miss an edit:
    • core.ignoreStat=true flags every file assume-unchanged at checkout, so it is caught by the same check.
    • core.trustctime=false and core.checkStat=minimal hide an edit that keeps size and mtime, so gc_status now forces core.checkStat=default and core.trustctime=true.
    • The untracked cache is now off; I couldn't make it hide anything.
    • The fsmonitor was already off in rgit.
    • Not covered: clean/smudge filters and EOL conversion can make a byte change compare equal, and I found no general override.
    • Tests: an edited assume-unchanged file, an edited skip-worktree file, a core.ignoreStat=true checkout, and a same-size edit with mtime set back under trustctime=false and checkStat=minimal. Each edit survives, and preview and run agree. Control: fsmonitor.

Important

  • F8, lib/state.sh:198 (a dead run's read-only lock): c91eb12. lock_probe reports cannot-remove when the lock folder itself isn't writable, so its pid can't be unlinked. That is what lock_take hits, with its message.
    • New rows in the tests/state.sh table (verdict, nothing changed, lock_check vs a real lock_take): dead-ro, dead-notlock-ro and dead-empty-takeover-ro failed before the fix.
    • Similar cases, already right: live-ro, takeover-ro, takeover-dead-ro and pid-ro (a read-only pid in a writable folder, which can be taken over).
    • Paired preview/run cases in tests/gc.sh: a read-only dead PR lock and a read-only dead clone lock. Both locks stay as they were, with no .takeover left.

Minor

  • lib/worktree.sh:300 (${lock%/.locks/*}): 1ba885a. clone_lock strips /.locks/<pr-key> literally. Test: a repo named .locks with a 0755 .reviews, which is now made 0700.

Checks on 1ba885a:

@catalan-adobe catalan-adobe left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 4 · since round 3

3 fixed · 1 still open · 4 new (2 in the new commits) · 3 declined · open blocking: 3 (was 6) · loop: converging

Approach

Unchanged since round 3: Splitting out --purge keeps lib/gc.sh focused on removing a closed PR’s review worktree and private refs under the existing locks, without having to infer which history files it owns.

Approach: Sound

Strengths

  • [lib/gc.sh:322] — A refused worktree keeps its private refs as well as pr.json. That makes cleanup retryable without losing the round pins.
  • [tests/gc.sh:586] — The nested-clone test checks that the unpublished commit is still readable, not just that GC printed a refusal. That is the right assertion for a deletion command.
  • [lib/state.sh:184] — The stale-lock probe now checks whether the PID file can be unlinked. The paired test covers both PR and clone locks; I also ran tests/state.sh: 207 checks passed.

Issues

🚨 Critical (Must Fix Before Merge)

  • F11 · [lib/gc.sh:121] — The new nested-checkout scan still misses a .git directory stored as .GIT on a case-insensitive volume. With the usual core.ignoreCase=true, Git excludes that spelling from status, but find -name .git compares the directory entry’s spelling. I confirmed on the review machine that .git resolved to a directory named .GIT while this find predicate returned nothing. A nested clone over tracked vendor/ files can therefore still lose its unpublished history.

    • Match descendant .git names case-insensitively, excluding only the review worktree’s own entry. Extend the existing unpublished-commit fixture with the case variant.
  • [lib/gc.sh:105] — A nonempty uninitialized submodule can pass all three disposal checks. For example, a review checkout contains the gitlink deps/sdk, and a developer copies notes.txt into that directory without initializing the submodule. Git does not list its contents as untracked, the gitlink need not have either index flag, and there is no descendant .git to find. Git’s own non-forced removal check skips unpopulated submodules, so the note is deleted. Earlier rounds tested nested checkouts, not files under a gitlink with no checkout.

    • Inspect mode-160000 index entries and refuse removal when the corresponding directory contains anything. Test both a nonempty directory that survives and an empty one that can be collected.
  • [lib/gc.sh:208] — Removing a clean review worktree can discard the only reference to a local commit. The run itself has a concrete path to this state: tests/flow.sh:1807 checks that a commit made on the review worktree’s detached HEAD stops the run with exit 4. If the PR then closes, status is clean against that new commit. GC removes the worktree’s HEAD and reflog, leaving the commit unreachable and eligible for pruning. Earlier GC tests checked dirty files and commits in a nested clone, not a commit on the review worktree’s own HEAD.

    • Before removal, verify that the detached HEAD is a commit the tool recorded for this PR. On a mismatch, retain the worktree and refs and print the unexpected commit ID so the user can save it.

⚠️ Important (Should Fix)

(none found)

💡 Minor (Nice to Have)

  • [tests/gc.sh:259] — line 'h/x/y#' searches for the literal h/x/y#: because line appends : . It cannot detect an unexpected report for h/x/y#7 or h/x/y#8. Check both complete labels; keep the separate assertion that GitHub was not queried.
  • [README.md:290] — The manual history-deletion instructions say to check the lock, but not to finish GC first. Removing pr.json after a dirty-worktree refusal or an offline-clone skip loses the inventory a retry needs. Tell users to confirm cleanup for that PR before deleting its state folder.
Fixed since the last round (6)
  • F8 — lock_probe now refuses a stale read-only lock whose pid cannot be unlinked.
  • F10 — declined for this PR: “Deleting history moves to its own PR, designed so a run records what it creates.” GC no longer deletes a fresh checkout’s .git.
  • F15 — declined for this PR: “Deleting history moves to its own PR, designed so a run records what it creates.” GC no longer decides whether <run>/repo is disposable.
  • F16 — gc_flagged checks the index independently of status and retains worktrees with assume-unchanged or skip-worktree entries.
  • F17 — declined for this PR: “Deleting history moves to its own PR, designed so a run records what it creates.” No marker authorizes history deletion in this version.
  • F18 — clone_lock strips the literal /.locks/<pr-key> suffix, including when the repo is named .locks.

Recommendations

Keep the preview/execution pairs. For each remaining deletion case, assert that the local file or commit is still accessible at its original path or ref after execution. Preview and execution can agree and still both make the wrong disposal decision.

Assessment

Ready to merge? No

Reasoning: Removing --purge resolves the history-deletion concerns for this PR, and the lock and index-flag fixes address their reported cases. Worktree removal can still erase user files or leave an unpublished commit without a reference, so the remaining fixes belong in GC before merge.


Review generated by gh pr-review · model: azure-openai-direct/gpt-6.2-astra

…ow the review worktree, whether <folder>/.git is there, asked of the file system (gc_nested, one sh per batch of folders), not find -name .git, so a .GIT on a case-insensitive volume is found too
…hat is not checked out, or something other than a folder there, which neither git status nor git worktree remove looks at (gc_gitlinks: each gitlink in the index must be an empty folder, or not there)
…s has (its HEAD, its HEAD's reflog, refs/worktree, refs/bisect, refs/rewritten and their reflogs: gc_commits), naming their IDs, or with a rebase, merge, cherry-pick, revert or bisect in progress (gc_operations); the run marks the PR heads it checks out in the worktree's reflog (REVIEW_REFLOG), so a head force-pushed away is not taken for a commit of yours
…l labels: line 'h/x/y#' looked for 'h/x/y#: ', which no line has
…rktree and refs (its line said removed, or gc --dry-run says nothing to remove), since pr.json is what a later gc needs, and while no review of it runs
@catalan-adobe

Copy link
Copy Markdown
Owner Author

Thanks for round 4. The three critical findings and both minors are fixed, one commit each, with tests that failed on the commit before (controls that pass on both are labelled). Each fix covers the whole class the example belongs to. As you recommended, every refusal test checks that the file or commit is still at its original path or ref after the real run, and that the PR's refs and pr.json stayed. The new checks are in gc_disposable, so preview and run share them.

Critical

  • F11, lib/gc.sh:121 (.GIT on a case-insensitive volume): afd768f. The new gc_nested doesn't match names any more. For every folder below the worktree, it asks the file system whether <folder>/.git exists, as git does. That covers case, Unicode normalization and HFS+ ignorable code points at once.

    • How: its own .git is pruned, symlinks aren't followed, and the folders go to sh in batches. On 21,041 folders this takes about 1.96 s, against 1.5 s for the old find -name .git.
    • Test: a nested clone whose .git is a folder named .GIT. It is left, and its commit is still readable at vendor/ by its ID. On case-sensitive file systems the test is skipped.
  • lib/gc.sh:105 (files in a submodule that isn't checked out): b911f01. In the new gc_gitlinks, each gitlink in the index (ls-files -s -z) must be absent or an empty folder. A file, a symlink or a non-empty folder there leaves the worktree, named. I also checked that a symlink at a gitlink path makes git status print nothing.

    • Tests: notes.txt in deps/sdk survives. Control: the empty folder the run makes is removed.
  • lib/gc.sh:208 (a commit only the review worktree references): 69b54f1. The new gc_commits collects every commit the worktree alone names:

    • its HEAD;
    • the old and new values in its reflogs (logs/HEAD and its per-worktree logs/refs/**);
    • its refs/worktree, refs/bisect and refs/rewritten.

    Each must be reachable from a ref that stays: every ref in the common git dir (the PR's own included, since their commits came from GitHub), the main worktree's HEAD, and the other worktrees' HEADs. One rev-list --ignore-missing --stdin call checks them, and --all is never used because it would include this worktree's own HEAD. Otherwise the worktree, its refs and pr.json stay, and the line prints the commit IDs.

    • Labelled checkouts: a --no-post or failed run leaves a PR head in the reflog with no pin, and a later force-push removes it from every ref. So the run now labels its checkout of the PR head (GIT_REFLOG_ACTION="gh-pr-review: checkout of the PR head", in lib/worktree.sh). gc exempts the new value of those entries and of the first entry from git worktree add. Old values are never exempt, so a commit you made there is still caught after a later run moves away from it. A worktree from before this change, with such a head in its reflog, is left; that errs on the safe side.
    • Also in this commit, the same kind of loss: a worktree with a rebase, merge, cherry-pick, revert, sequencer or bisect in progress is left.
    • Unusual setups: a repository whose refs aren't kept as files (reftable) is left as "can't tell". A reflog entry whose object is already gone is skipped. A non-commit object found there is reported.
    • Tests, each left and checked by ID afterwards: a commit on the detached HEAD (the tests/flow.sh:1807 case); a commit reset away, so it is only in the reflog; a commit only on refs/worktree/x; a rebase stopped at edit.
    • Controls, each removed: a commit that is on a branch of yours (the branch keeps it); three rounds made by the run's own code (fast-forward, then force-push); two --no-post runs whose heads were force-pushed away, then a posted round. The last control fails if either exemption is removed.

Minor

  • tests/gc.sh:259: c863449. The check now covers both complete labels, h/x/y#7 and h/x/y#8, and still asserts that gh wasn't asked. To confirm it catches the problem, I briefly made gc print a line for folders without pr.json: the new check failed and the old one passed.
  • README.md:290: 5d439f3. Delete a PR's history by hand only once gc has removed its worktree and refs (its line said removed, or gc --dry-run has nothing to remove), since a retry needs pr.json, and only while no review of it is running.

The PR description is updated.

Checks on 5d439f3:

@catalan-adobe catalan-adobe left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 5 · since round 4

3 fixed · 2 still open · 5 new (4 in the new commits) · open blocking: 5 (was 3) · loop: churning
Next: Split the PR: each part converges on its own

Approach

Unchanged since round 4: Preview and cleanup share the stricter gc_disposable checks in lib/gc.sh, which now protect worktree-only commits and files in uninitialized submodules while leaving review history untouched.

Approach: Sound

Strengths

  • [lib/gc.sh:105] — Asking the filesystem whether each directory contains .git fixes the case-alias problem without following symlinks or guessing which spellings a volume treats as equivalent.
  • [tests/gc.sh:758] — The commit-preservation tests check that the commit is still accessible through its original HEAD, reflog, or worktree ref after cleanup. That verifies more than a refusal message or an object that happens not to have been pruned yet.

Issues

🚨 Critical (Must Fix Before Merge)

  • F19 · [lib/gc.sh:124] — A nonempty submodule directory can still be mistaken for an empty one. Bash strips trailing newlines from names=$(ls -A ...). I checked gc_gitlinks with a gitlink index record and a directory containing a six-byte file whose name was a single newline: the helper returned success with no output. Git's status and non-forced removal do not protect that file.

    • Test for the presence of an entry, not for nonempty filename text. Carry the refusal separately from the pathname used for display, and add this case to the preservation test.
  • F20 · [lib/gc.sh:193] — The reachability check counts refs that the same GC is about to delete. If a local commit is on the detached HEAD and the PR's private base ref was moved to it, for-each-ref supplies the commit as an exclusion. GC can then remove the worktree and the private ref, leaving no reference to the commit. This is not just a hypothetical ref namespace: tests/flow.sh:1846 explicitly exercises a reviewer moving the private base ref.

    • Exclude the refs scheduled for deletion from the surviving roots. Recognize genuine run-owned commits separately; the current value of a mutable private ref is not proof that it came from GitHub.
  • [lib/gc.sh:322] — A missing worktree folder bypasses the new commit check. Deleting the checkout outside Git does not delete its administrative HEAD, reflogs, or private refs. If the developer made a detached commit before deleting the folder, GC removes the registration at line 352 and with it the last reference to that commit. Earlier rounds checked the path of a missing registration and the commits of a present checkout, not the combination.

    • Resolve the recorded registration to its administrative directory and check its commits and operation state before unregistering it. Retain the registration and name the commit if it is the only reference.
  • [lib/gc.sh:160] — An empty-message first reflog entry proves that Git created a worktree, not that the review run checked out a PR head. For example, a developer can recreate a worktree at the saved path from a temporary local branch, detached, then delete the branch. The replacement passes the path and registration checks; its initial local commit is classified as exempt, even though the run never checked it out.

    • Record the initial checkout SHA when the run creates the worktree, as well as identifying subsequent checkouts. Treat an unlabelled legacy entry as unknown unless its commit is otherwise accounted for.
  • [lib/gc.sh:191] — Two collectible worktrees can each count the other's HEAD as the surviving reference to the same unpublished commit. On an unchanged filesystem, preview approves both, while sequential execution removes the first and refuses the second. More seriously, two GC processes handling different PRs can both finish the check before either removes its worktree; their per-PR locks do not conflict, and neither reference survives.

    • Do not count another collectible review worktree as a durable root. Add a two-PR fixture with the same detached local commit and no branch, and check that preview agrees with execution and that a reference survives.

⚠️ Important (Should Fix)

(none found)

💡 Minor (Nice to Have)

  • [lib/gc.sh:270] — Lost commit IDs go through gc_entries, which prints only three values and “N more.” If several independent commits need saving, the user cannot identify all of them from the refusal before using the suggested force command. Print all at-risk IDs, or provide a read-only command that lists them.
  • [README.md:299] — The new history-deletion prerequisite is impossible to satisfy for a --fresh-only PR: the preceding sentence correctly says GC prints no line for it. Distinguish that case from a PR with pr.json; the latter must finish GC first.
Fixed since the last round (3)
  • F11 — The descendant check now uses filesystem lookup, and the case-insensitive fixture verifies that the nested clone's unpublished commit survives.
  • F21 — The test checks both complete PR labels and independently verifies that GitHub was not queried.
  • F22 — The README now tells users to retain pr.json after a refusal or offline-clone skip until cleanup finishes.

Recommendations

Build the reachability check around what will still name a commit after cleanup, and use that check for both present and missing worktrees. Keep the paired preview/execution tests, but include a pair of PRs whose cleanup decisions depend on each other.

I checked the filename edge case independently. The full tests/gc.sh suite could not start in this review environment because the read-only Git wrapper refused the fixture's git init.

Assessment

Ready to merge? No

Reasoning: The common dirty-file and detached-commit cases are now covered, but GC can still delete a file or remove the last reference to an unpublished commit while reporting successful cleanup. Those failures belong in the automatic disposal checks, not in manual recovery instructions.


Review generated by gh pr-review · model: azure-openai-direct/gpt-6.2-astra

…file alone, by find (dir_holds), never from ls's names as text, which drop a name's trailing newlines: a submodule folder holding only a file named a newline is no longer taken for empty; gc_gitlinks's verdict is whether it printed anything, its paths shell-quoted
…(worktree_sha, empty when it reuses one pr.json does not name), and gc takes that commit, and the new values of entries with the run's label, for the run's PR heads: no longer the first reflog entry git worktree add writes, which a worktree of yours made again at that path from a deleted branch also has; a worktree an earlier version made is removed only when its commits are in a ref that stays
…private refs of any PR (this gc deletes this PR's, a gc of another PR may be deleting theirs) and symbolic refs, the main worktree's HEAD, and the HEADs of worktrees outside .reviews (gc_kept_worktree: a review worktree's may be going too): a commit that this PR's base ref was moved to, another PR's ref alone has, or two review worktrees' HEADs share, leaves the worktree
…de git before it removes its registration (gc_gone): found in worktrees/<id> by its gitdir file, it holds the worktree's HEAD, reflogs and own refs, so a commit only it names, or an operation in progress there, leaves the registration, its refs and pr.json, named; gc_commits reads through --git-dir
…y more (gc_all); README: a PR folder without pr.json (--fresh only, no gc line) can be deleted while no review of it runs, one with pr.json only once gc has removed its worktree and refs
@catalan-adobe

Copy link
Copy Markdown
Owner Author

Thanks for round 5. All five critical findings were in round 4's new code, and each fix tightens the same rules rather than changing the design. As agreed before this round, this is the last one: after these fixes and a green CI, the PR is merged. The fixes are one commit each, with tests that failed on the commit before (controls that pass on both are labelled). Every refusal test checks that the file or commit is still at its path or ref after the real run, and that preview and run agree.

Critical

  • F19, lib/gc.sh:124 (emptiness read from text): cfee709. A new dir_holds <dir> [<name>] (lib/state.sh) asks find … -exec printf x \; -quit whether an entry exists. A folder that can't be listed counts as holding something. I audited every site that judged emptiness from names as text:
    • lib/gc.sh: gc_gitlinks and gc_rmdir. gc_gitlinks's verdict is now whether it printed anything, with paths shell-quoted, so a submodule whose path is a newline is caught too.
    • lib/state.sh locks: lock_claim, lock_remove (twice), lock_state and lock_probe. A file named pid plus a newline did fool lock_remove.
    • Tests: a gitlink folder holding only a file named newline, and a submodule whose path is a newline, both survive. New lock-table rows cover such names (notlock-nl, dead-notlock-nl, dead-notlock-pidnl), plus a lock_release case.
  • F20, lib/gc.sh:193, and the two-worktree critical, lib/gc.sh:191 (roots gc may delete): 67fb6fe. Nothing gc may delete counts as keeping a commit. What counts is every ref except all of refs/pr-review/* (any PR's, since another gc may be deleting them) and symbolic refs, the main worktree's HEAD, and the HEADs of worktrees outside .reviews.
    • Telling review worktrees apart: gc_kept_worktree resolves each registration's gitdir file. A worktree counts only when its path can be placed and is outside <clone>.reviews (compared by file-system identity where the folders exist).
    • Tests: your F20 case (base moved to the local commit): left, the commit still HEAD and reachable per git fsck --unreachable --no-reflogs, base still at it. Two closed PRs sharing a detached commit: preview equals run, and a reference survives. A commit kept only by another open PR's round-2 ref: left. Control: a commit held by a worktree of mine outside .reviews doesn't block.
    • Checked by hand: rev-list --ignore-missing --stdin with ^<annotated tag>, ^<blob> and ^<tree> lines, on git 2.55 and 2.43.
  • lib/gc.sh:322 (a deleted folder skips the commit check): 08ccb24. gc_gone finds the one <common>/worktrees/<id> whose gitdir leads to the recorded path; zero or several matches leave everything. It then runs the same operation and commit checks (gc_history, now read through --git-dir) before unregistering.
    • Tests: a detached commit made before the folder was deleted, and a stopped rebase. In both, the registration, refs and pr.json are kept, and the commit is still HEAD in the leftover git folder. Control: a worktree the run made, whose folder was deleted, is unregistered.
  • lib/gc.sh:160 (the unlabelled first entry): 8d9fb02. When the run creates the worktree, it records the commit in pr.json as worktree_sha. On reuse of the worktree pr.json names, the value is kept; on reuse of another worktree, it is cleared. gc takes only that value (if it is a full object ID) and the new values of labelled entries as the run's PR heads, and the "first entry with no message" rule is gone. This also works for a bare cache clone, whose reflogs are off.
    • Worktrees made before this change have neither record, so they are removed only when all their commits are reachable from a ref that stays. Otherwise they're left with the IDs and the --force command, which the README says.
    • Tests: your case, a worktree remade at the saved path from a deleted local branch: left, with the commit readable. Controls: worktrees reused across rounds (fast-forward, force-push, --no-post); an earlier version's worktree whose heads were merged into main with a merge commit is removed; one whose heads are only on its PR refs is left.

Minor

  • lib/gc.sh:270: c6e1cd6. The line names every lost commit ID.
  • README.md:299: c6e1cd6. The README now separates the two cases. A PR folder without pr.json (reviewed only with --fresh, so gc prints no line) can be deleted once no review of it runs. One with pr.json can be deleted only after gc has removed its worktree and refs.

Not in this PR: a review run that remakes a deleted review worktree with git worktree add --force can drop a commit that only the old registration held. That code is from #16, so it's filed as #19, with this PR's gc_history to reuse.

The PR description is updated.

Checks on c6e1cd6:

@catalan-adobe
catalan-adobe merged commit 9ca793c into main Nov 30, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant