Repository navigation
[SCR-273] Add prune-merged-worktrees script - #274
Conversation
Remove linked worktrees whose branch merged into main (or whose PR is merged/closed). Skip any with real uncommitted changes. Refuse to touch a misplaced main clone and never fall back to rm -rf. Dry-run by default.
|
Warning Review limit reachedNext included review available in 11 minutes. View limit detailsLimit details: You’ve used the included review currently available. Your 90 included PR review attempts over the past 7 days set your current allowance at 1 review per hour. Your organization has reached its usage spending cap. Adjust your spending cap in the billing tab. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (1)
Comment |
- Match scratch filenames against the full repo-relative path instead of basename, so a real file like docs/BRIEF.md is no longer mistaken for the harmless root-level scratch note. - Clear verified scratch-only files before calling 'git worktree remove' so --apply can actually remove them (git refuses any dirty worktree without --force, which we avoid since it would also bypass worktree locks). - Derive the main worktree path from 'git worktree list --porcelain' instead of 'git rev-parse --show-toplevel', so the script no longer misidentifies and skips the worktree it happens to be invoked from. - Fetch origin/main once up front instead of once per worktree, and fail loudly if 'git worktree list --porcelain' itself fails instead of silently reporting zero worktrees.
There was a problem hiding this comment.
Reviewed head: 75c56f857eaa91f7be272979fe30c1b9f8242710 (fixes pushed on top at a370803).
I verified the council's claims against the actual code (and git worktree remove -h, which confirms -f/--force is required to remove a dirty or locked worktree) and pushed fixes for four confirmed bugs.
Fixed
- Scratch-file matching used
basename, not the full path (correctness, Major — real risk of the exact "safe classification that isn't" failure mode this script exists to prevent). A real, dirty file nested anywhere in the tree that happened to be namedBRIEF.md/CONTINUE.md/WORKER_BRIEF.md(e.g.docs/BRIEF.md) was treated as harmless scratch and the worktree reported/removed as clean. Now matched against the full repo-relative path. --applycould never actually remove a scratch-only worktree (correctness, Major — the PR's headline feature didn't work).git worktree removerefuses any dirty worktree without--force; an untrackedWORKER_BRIEF.mdetc. is "dirty" to git regardless of the script's own scratch allowlist, so every scratch-only case fell through to "remove failed" → needs-review instead of being removed. Fixed by clearing the verified scratch paths before callinggit worktree remove(still without--force, since--forcealso bypassesgit worktree lock, which must keep blocking removal).MAIN_TOPmisidentified the main worktree when run from inside a linked worktree (correctness, Minor-to-Major depending on usage).git rev-parse --show-toplevelreports whichever worktree you're standing in, not the actual main worktree, so invoking the script from inside a merged/clean linked worktree silently skipped that worktree entirely (and, separately, the real main worktree was only correctly excluded via the later gitdir check, not this one). Now derived from the first entry ofgit worktree list --porcelain, which is always the main worktree.- Exit status of
git worktree list --porcelainwas discarded via< <(...)process substitution — a failure would silently print "removed: 0 / skipped: 0" instead of an error. Now captured up front and checked.
Folded into the same commit: moved git fetch origin main out of the per-worktree loop (was one blocking network call per worktree for identical data — confirmed real, Minor).
Discarded from council findings
- "grep forked per dirty file" (perf lens): real but negligible — worktrees don't realistically have enough dirty files for process-spawn overhead to matter. Style-level, not fixed.
- Kimi K3 (security) and Grok 4.5 (maintainability): both errored/timed out, no findings produced.
Not fixed — flagged for the author (PR-standards / proof, not code)
- Body heading is
## How verified, not the required## How I verified— likely fails the mechanicalpr-standardscheck. Assisted-by: Claude Opus 4.8doesn't match the required<agent>:<model>colon-separated form (e.g.claude-personal:claude-opus-5).- Proof gap: the body's manual-verification narrative claims "scratch-only treated clean" was exercised, but that's exactly the path that was broken (finding #2) — worth re-running
--applyagainst a scratch-only worktree and pasting the actual output now that it's fixed, rather than relying on the prior prose description.
I did not edit the PR body — that's the author's evidence to produce, not mine to invent.
🧑⚖️ Council
| Model | Lens | Result |
|---|---|---|
| GPT-5.6 (Codex) | correctness | confirmed (3 of 4 findings fixed; MAIN_TOP finding fixed too) |
| Gemini 3 Pro | performance | confirmed (fetch N+1 fixed); grep-per-file rejected as negligible |
| Kimi K3 | security | error (429 / timeout, no findings) |
| Grok 4.5 | maintainability | error (timeout, no findings) |
| GPT-5.6 (scope) | scope | confirmed (duplicate of correctness finding #2, fixed) |
- Anchor the linked-worktree check on the repo's actual common gitdir instead of a bare "*/worktrees/*" substring test, so a stale worktree slot replaced by an unrelated clone whose own path happens to contain a "worktrees" component can't be mistaken for a real linked worktree. - Treat a merged-via-origin/main verdict as needs-review (not removed) when the preceding fetch failed, since a stale cached origin/main can misreport a branch as merged after a remote history rewrite. - Unstage scratch files (git reset) before restoring them, since `checkout -- <path>` alone leaves a staged scratch-file change staged and `git worktree remove` still refuses the worktree.
…s.sh - Treat any renamed path (old -> new) as a real change instead of checking only the destination name, since a rename into a scratch-looking name (e.g. important.txt -> BRIEF.md) was classified as harmless and --apply's cleanup could delete the only copy of the content. - Re-anchor the shell's cwd to the main worktree before the loop, so invoking the script with a repo-path that points at a linked worktree eligible for removal can't delete the directory the shell is currently sitting in and break every later ambient git call. - Only fall back to a local main/master ref when origin/main can't be resolved AND that isn't due to a failed fetch against a configured origin, since trusting local main in that case is the same stale-history trap FETCH_OK already guards against elsewhere.
There was a problem hiding this comment.
Reviewed head: d044f6ed67e068be3cc625b17c10977702b57b6d
Verified every council claim against the code at that SHA (working tree matches HEAD exactly for this file). Two are real bugs; two are proof gaps; one is a narrow edge case I'm not blocking on. No test file ships with the script, which breaks this repo's usual pattern (every other script here has an adjacent *.test.sh), but nothing in AGENTS.md mandates it and CI doesn't require it, so it's a Minor note rather than a blocker.
Since I cannot push in this run (loop guard, cycle 4), I'm leaving findings as review comments only — no fixes applied.
Confirmed Major:
prune-merged-worktrees.sh:131—grep -qx "refs/heads/$short"treats the branch name as a regex, not a literal. A branch containing regex metacharacters (e.g.topic/a.b) can be falsely matched as merged by an unrelated ref (e.g.topic/aXb) whose name differs only where the metacharacter sits, since.matches any character. That breaks this script's core promise — only removing genuinely-merged worktrees — for a realistic class of branch names (dots are common in version/date-style branch names). Needsgrep -Fqxfor an exact literal match. (Line differs slightly from the council's cited:139— file content is identical, just a different line-counting; verified directly against the current file.)- Proof gap — the
## How I verifiedtranscript cannot be from this revision: every current invocation unconditionally printsrepo: $MAIN_TOPin the summary (line 239), but the pasted dry-run output has norepo:line at all. The evidence predates the final commit(s). - Proof gap — the transcript only exercises the dry-run path.
--applyis this PR's primary and most dangerous behavior (it's the codepath that clears scratch files and callsgit worktree remove), and it has zero recorded evidence of ever running.
Noted, not blocking (Minor, rolled up):
prune-merged-worktrees.sh:65—git fetch origin main --quietonly reliably refreshesrefs/remotes/origin/mainunder the standard clone fetch refspec. A repo with a nonstandard refspec that excludesmaincould leave a staleorigin/mainin place whileFETCH_OKis still reported as 1. This requires an atypical remote configuration to trigger, so I'm flagging it for awareness rather than treating it as confirmed-in-the-wild.- No
prune-merged-worktrees.test.shaccompanies the script, unlike every other script in this repo.
PR-standard check: branch/title/body format, Closes #273 (single), ## What/## Why/## How I verified, single Assisted-by: line, and size (246 lines, 1 file) all comply with .github/pr-standards.json / AGENTS.md. Only the evidence content under ## How I verified is stale/incomplete (see above) — the structure itself is fine.
What would settle the proof gaps: rerun bash prune-merged-worktrees.sh <repo> dry-run against the final commit and paste the full output (including the repo: line), then run --apply against a disposable fixture with at least one eligible-clean, one dirty, and one main-clone worktree, and paste that output too.
🧑⚖️ Council
| Model | Lens | Result |
|---|---|---|
| GPT-5.6 (Codex) | correctness | confirmed (grep -qx regex issue); confirmed but downgraded to minor/edge-case (fetch refspec issue) |
| Gemini 3 Pro | performance | no findings (429/timeout, did not run) |
| Kimi K3 | security | no findings |
| Grok 4.5 | maintainability | no findings (timed out, did not run) |
| GPT-5.6 (scope) | proof/scope | confirmed (both: stale transcript, untested --apply path) |
| intobranch="master" | ||
| fi | ||
| fi | ||
| if git branch --merged "$intobranch" --format='%(refname)' 2>/dev/null | grep -qx "refs/heads/$short"; then |
There was a problem hiding this comment.
Major (correctness): grep -qx matches "refs/heads/$short" as a regex, not a literal string. A branch name containing a regex metacharacter (e.g. topic/a.b) can be falsely reported as merged whenever a different, actually-merged ref differs only at that character (e.g. topic/aXb), because . matches any character. That defeats the "only remove merged branches" safety guarantee this script exists to provide. Fix: grep -Fqx "refs/heads/$short" for an exact literal match.
|
|
||
| # --- Summary --- | ||
| echo "== worktree hygiene ==" | ||
| echo "repo: $MAIN_TOP" |
There was a problem hiding this comment.
Major (proof): every current run unconditionally prints repo: $MAIN_TOP here, but the PR body's ## How I verified dry-run transcript has no repo: line at all. That means the pasted evidence predates this revision and doesn't demonstrate the code as it stands now. Please rerun against the final commit and paste the complete output.
| fi | ||
|
|
||
| # --- Safe to remove (or dry-run report) --- | ||
| if [ "$APPLY" -eq 1 ]; then |
There was a problem hiding this comment.
Major (proof): this --apply branch — which clears scratch files and calls git worktree remove — is the PR's primary and riskiest behavior, and the verification transcript only ever exercises the dry-run path. Please run --apply against a disposable fixture (an eligible-clean worktree, a dirty one, and a main-clone) and include that output as evidence.
Closes #273
What
Adds
prune-merged-worktrees.sh: removes linked git worktrees whose branch merged into main (or whose PR is merged/closed), skipping any with real uncommitted changes. Dry-run by default;--applyto remove.Why
Manual worktree cleanup deleted a real repo when an
rm -rffallback ran on a misplaced main clone. This script encodes the fix: it verifies each dir is a genuine linked worktree (gitdir must contain/worktrees/) and never falls back torm -rf.How I verified
Real merged worktrees were detected for removal; unmerged and detached-HEAD ones were correctly skipped; no main clone was touched.
Assisted-by: claude-code:claude-opus-4-8