Skip to content

[SCR-273] Add prune-merged-worktrees script - #274

Merged
itsryanarmani merged 4 commits into
mainfrom
scr-273-prune-merged-worktrees
Sep 4, 2026
Merged

itsryanarmani merged 4 commits into
mainfrom
scr-273-prune-merged-worktrees

Conversation

@itsryanarmani

@itsryanarmani itsryanarmani commented Sep 4, 2026 •

Copy link
Copy Markdown
Owner

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; --apply to remove.

Why

Manual worktree cleanup deleted a real repo when an rm -rf fallback 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 to rm -rf.

How I verified

$ bash -n prune-merged-worktrees.sh; echo "exit $?"
exit 0

$ bash prune-merged-worktrees.sh ~/Documents/Personal/skills
== worktree hygiene ==
mode: dry-run (pass --apply to remove)
removed: 3
  - .../skills/fleet (parab/self-hosted-runner-fleet) [dry-run]
  - .../skills/fleet2 (parab/fleet-host-toolchains) [dry-run]
  - .../skills/retire (parab/fleet-skill-retirement) [dry-run]
skipped: 6
  - .../_wt/fix344 (ski-343-... not merged)
  - .../_wt/gd-priv (detached HEAD)
needs-review: 0

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

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.
@coderabbitai

coderabbitai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 11 minutes.

Check out review usage here.

View limit details

Limit 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.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Team

Run ID: f9b351e6-8e5a-422d-87e5-4150afb16d89

📥 Commits

Reviewing files that changed from the base of the PR and between ef10b42 and d044f6e.

📒 Files selected for processing (1)
  • prune-merged-worktrees.sh

Comment @coderabbitai help to get the list of available commands.

- 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.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

  1. 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 named BRIEF.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.
  2. --apply could never actually remove a scratch-only worktree (correctness, Major — the PR's headline feature didn't work). git worktree remove refuses any dirty worktree without --force; an untracked WORKER_BRIEF.md etc. 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 calling git worktree remove (still without --force, since --force also bypasses git worktree lock, which must keep blocking removal).
  3. MAIN_TOP misidentified the main worktree when run from inside a linked worktree (correctness, Minor-to-Major depending on usage). git rev-parse --show-toplevel reports 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 of git worktree list --porcelain, which is always the main worktree.
  4. Exit status of git worktree list --porcelain was 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 mechanical pr-standards check.
  • Assisted-by: Claude Opus 4.8 doesn'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 --apply against 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)

vibecodereview[bot] added 2 commits September 4, 2026 00:29
- 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.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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). Needs grep -Fqx for 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 verified transcript cannot be from this revision: every current invocation unconditionally prints repo: $MAIN_TOP in the summary (line 239), but the pasted dry-run output has no repo: line at all. The evidence predates the final commit(s).
  • Proof gap — the transcript only exercises the dry-run path. --apply is this PR's primary and most dangerous behavior (it's the codepath that clears scratch files and calls git 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 --quiet only reliably refreshes refs/remotes/origin/main under the standard clone fetch refspec. A repo with a nonstandard refspec that excludes main could leave a stale origin/main in place while FETCH_OK is 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.sh accompanies 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)

Comment thread prune-merged-worktrees.sh
intobranch="master"
fi
fi
if git branch --merged "$intobranch" --format='%(refname)' 2>/dev/null | grep -qx "refs/heads/$short"; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread prune-merged-worktrees.sh

# --- Summary ---
echo "== worktree hygiene =="
echo "repo: $MAIN_TOP"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread prune-merged-worktrees.sh
fi

# --- Safe to remove (or dry-run report) ---
if [ "$APPLY" -eq 1 ]; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

@itsryanarmani
itsryanarmani merged commit b4762d0 into main Sep 4, 2026
4 checks passed
@itsryanarmani
itsryanarmani deleted the scr-273-prune-merged-worktrees branch September 4, 2026 06:00
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.

Add prune-merged-worktrees script

1 participant