Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ”§ chore(skills): classify squash-merged and scratch-only worktrees in cleanup (#22777)

Arvin Xufaed5249f3b9
diff --git a/.agents/skills/cleanup-git-worktrees/SKILL.md b/.agents/skills/cleanup-git-worktrees/SKILL.md
index ae7067122f0..908573a1028 100644
--- a/.agents/skills/cleanup-git-worktrees/SKILL.md
+++ b/.agents/skills/cleanup-git-worktrees/SKILL.md
@@ -16,30 +16,35 @@ Use the bundled script to make classification deterministic. Treat cleanup as a
```
- `--fetch`: prune the remote first. Omit only when offline and say so.
- - `--gh`: look up each branch's PR (number, state, head SHA) with the `gh` CLI. This is what turns `[gone]` into a verified merge; use it whenever `gh` is authenticated. It costs roughly one second per branch, so run it in the background on large repos.
+ - `--gh`: look up each branch's PR (number, state, head SHA, `mergedAt`) with the `gh` CLI. This is what turns `[gone]` into a verified merge; use it whenever `gh` is authenticated. The script prefetches the latest 3000 PRs in one call and only queries older branches one by one; a full audit of ~300 entries still takes minutes, so run it in the background.
- `--stale-days N`: mark clean branches idle longer than N days with nothing unpushed as `candidate-stale`. The repository default the user has approved is 15 days.
- `--noise REGEX`: untracked paths that never count as dirt (default `node_modules|\.goal-tracing/`).
+ - `--scratch REGEX`: untracked local scratch that never counts as dirt (default: `*.probe.test.ts(x)`, `*.png`, `pr-body*.md`, `.records*`). Tracked files whose content equals the base are also not dirt. All three count in the `noise` column and are removed with `--force`.
2. Interpret classifications:
- | Classification | Meaning | Action |
- | -------------------------- | ----------------------------------------------------------------- | ------------------------------------------ |
- | `protected-branch` | `main`, `canary`, or the base ref | never |
- | `protect-current` | the worktree running the command | never |
- | `protect-dirty` | tracked modifications, or untracked files outside the noise regex | keep; list the files |
- | `candidate-merged` | tip is an ancestor of the base | delete |
- | `candidate-pr-merged` | PR state MERGED and local tip == PR head SHA | delete |
- | `candidate-pr-closed` | PR CLOSED and tip == PR head or nothing unpushed | delete |
- | `candidate-gone` | upstream pruned and nothing unpushed | delete after confirming PR state |
- | `candidate-stale` | older than `--stale-days`, clean, nothing unpushed | delete |
- | `review-pr-merged-ahead` | PR merged but local tip has extra commits | check the extra commits by subject (below) |
- | `review-gone-unpushed` | upstream pruned but local-only commits exist | keep; deleting loses work |
- | `review-no-upstream` | no upstream, not merged | keep unless the user names it |
- | `review-detached` | detached HEAD worktree | keep; show its dirty files |
- | `broken-registration(...)` | registration whose gitdir is gone | see below |
- | `active` | everything else | keep |
-
- Columns worth reading: `dirty` (real dirt), `noise` (ignorable untracked), `age_days`, `unpushed` (commits no remote ref reaches), `pr` / `pr_state` / `tip_eq_pr`.
+ | Classification | Meaning | Action |
+ | ----------------------------- | ------------------------------------------------------------------------------ | -------------------------------------- |
+ | `protected-branch` | `main`, `canary`, or the base ref | never |
+ | `protect-current` | the worktree running the command | never |
+ | `protect-main` | the repository's main worktree | never |
+ | `review-pr-done-dirty` | PR MERGED/CLOSED but the tree has real (non-scratch) edits | list the files; delete only when named |
+ | `protect-dirty` | real dirt and no merged/closed PR | keep; list the files |
+ | `candidate-merged` | tip is an ancestor of the base | delete |
+ | `candidate-pr-merged` | PR state MERGED and local tip == PR head SHA | delete |
+ | `candidate-pr-merged-history` | PR MERGED; tip != PR head, but no commit off the base is newer than `mergedAt` | delete |
+ | `candidate-pr-merged-pushed` | PR MERGED; post-merge commits exist but all are on a remote ref | delete; mention unlanded commits |
+ | `candidate-pr-closed` | PR CLOSED and tip == PR head or nothing unpushed | delete |
+ | `candidate-gone` | upstream pruned and nothing unpushed | delete after confirming PR state |
+ | `candidate-stale` | older than `--stale-days`, clean, nothing unpushed | delete |
+ | `review-pr-merged-ahead` | PR merged; local-only commits newer than `mergedAt` | inspect those commits (below) |
+ | `review-gone-unpushed` | upstream pruned but local-only commits exist | keep; deleting loses work |
+ | `review-no-upstream` | no upstream, not merged | keep unless the user names it |
+ | `review-detached` | detached HEAD worktree | keep; show its dirty files |
+ | `broken-registration(...)` | registration whose gitdir is gone | see below |
+ | `active` | everything else | keep |
+
+ Columns worth reading: `dirty` (real dirt), `noise` (disposable: noise, scratch, base-equal files), `age_days`, `unpushed` (commits no remote ref reaches), `pr` / `pr_state` / `tip_eq_pr`, `after_merge` (commits on the branch but not the base that are newer than `mergedAt`).
3. Present one compact table split into three groups: deletable now (all `candidate-*`), needs a manual check (`review-*`), and protected. Keep `candidate-merged` separate from `candidate-gone`, and never describe `[gone]` alone as proof of merge.
@@ -53,9 +58,17 @@ Use the bundled script to make classification deterministic. Treat cleanup as a
--apply
```
- Without `--apply`, cleanup is a dry run. The script re-classifies every target immediately before deletion and refuses anything that is not `candidate-*`. Worktrees whose only dirt is noise are removed with `git worktree remove --force`; everything else uses the plain, refusing form.
+ For a batch, write the branch names one per line and pass `--branches-file <path>`. Do not build `--branch` lists in a shell variable: the interactive shell is zsh, which passes an unquoted `$args` as one argument.
- Removing a worktree that still holds `node_modules` can take several minutes each. Run large batches in the background and report progress rather than waiting on a single foreground call.
+ Without `--apply`, cleanup is a dry run. The script re-classifies every target immediately before deletion. It skips, with a `REFUSED` line on stderr, anything that is not `candidate-*` and any worktree a live process uses as its cwd (another session may be working there); the rest of the batch continues. Worktrees whose only dirt is disposable are removed with `git worktree remove --force`; everything else uses the plain, refusing form.
+
+ Removing a worktree that still holds `node_modules` takes one to two minutes each, so a batch of 100 runs for hours, longer than a background task's time limit. A time limit kills the run mid-removal and leaves a half-deleted directory. Launch large batches detached and poll the log:
+
+ ```bash
+ nohup bash .agents/skills/cleanup-git-worktrees/scripts/cleanup.sh clean \
+ --gh --stale-days 15 --base origin/canary --branches-file /tmp/<unique>-targets.txt --apply \
+ > /tmp/<unique>-clean.log 2>&1 < /dev/null & disown
+ ```
5. Run the audit again and report:
@@ -81,12 +94,18 @@ The repository owner has approved the following for this repo, so a cleanup run
- **Dirt equal to the base is not dirt.** A tracked file listed as modified whose content is byte-identical to the base (`git diff --quiet <base> -- <file>`) is stale residue of a branch that is simply behind. When presenting, do not count it as a real change: list such files in their own group so the genuine modifications stay visible.
- **Merged / closed PR branches are disposable together with their local commits.** When a branch's PR is `MERGED` or `CLOSED`, its worktree and local branch may be removed even when `unpushed > 0` or the tree is dirty. Record every branch SHA before deleting (reflog keeps them \~90 days) and state in the report that uncommitted edits are not recoverable.
-- **Local scratch does not block removal.** Untracked `*.probe.test.ts`, spike scripts under `scripts/`, and untracked screenshots (`*.png`) are disposable; do not raise them as blockers.
+- **Local scratch does not block removal.** Untracked `*.probe.test.ts`, screenshots (`*.png`), PR body drafts (`pr-body*.md`) and `.records*` evidence are disposable (the `--scratch` default). Untracked spike scripts under `scripts/` are too, but they stay out of the default regex because `scripts/` also holds real new files; judge them by hand.
- Still never delete: `main`, `canary`, the base ref, and the worktree running the command. A branch whose PR is **OPEN** is kept while it still holds local-only work (dirty files or `unpushed > 0`); a clean, fully-pushed branch with an open PR is the redundant local copy the stale rule already covers.
-**Proving a merge when the repo squash-merges.** This repo squash-merges, so a landed PR leaves the squash commit on the base but none of the branch's own commits. Searching the base for an individual commit subject therefore fails for every squashed branch β€” do not read that as "unmerged". Decide `review-pr-merged-ahead` by the PR's state plus commit dates instead: if the branch tip is not newer than `mergedAt`, the branch is pure pre-merge history whose content is already on the base (verify the PR's `mergeCommit` with `git merge-base --is-ancestor <mergeCommit> origin/canary`). Only commits dated after `mergedAt` are candidate unmerged work β€” keep the branch and list them.
+**Proving a merge when the repo squash-merges.** This repo squash-merges, so a landed PR leaves the squash commit on the base but none of the branch's own commits. Searching the base for an individual commit subject therefore fails for every squashed branch; do not read that as "unmerged". The script decides by commit dates instead: commits off the base that are not newer than `mergedAt` are pre-merge history the squash already carries (`candidate-pr-merged-history`). Post-merge commits that a remote ref still holds lose nothing locally (`candidate-pr-merged-pushed`), but say in the report that they never reached the base.
+
+`review-pr-merged-ahead` is left for local-only commits newer than the merge. List them with `git log --format='%h %cI %s' <branch> --not origin/canary --remotes=origin` and judge each:
+
+- a follow-up that landed through a later PR shows up on the base under the same subject plus `(#N)`: `git log origin/canary --oneline -F --grep="<subject>"`. Disposable.
+- a follow-up nobody opened a PR for, made obsolete by later work on the base, is disposable under the policy above.
+- anything still relevant is kept and reported.
-The bundled script still refuses anything outside `candidate-*`, so these removals are done manually: `wt_path=$(git worktree list --porcelain …)` β†’ record `git rev-parse <branch>` β†’ `git worktree remove --force` β†’ `git branch -D`. Keep the run in the background; removals that hold `node_modules` take minutes each.
+The bundled script refuses `review-*`, so removals the user approves for those are done manually: `wt_path=$(git worktree list --porcelain …)` β†’ check no process has its cwd there (`lsof -d cwd`) β†’ record `git rev-parse <branch>` β†’ `git worktree remove --force` β†’ `git branch -D`. Run them detached the same way.
## Broken registrations
@@ -102,6 +121,7 @@ The bundled script still refuses anything outside `candidate-*`, so these remova
- Never use recursive deletion on a registered worktree. If Git partially removes a directory, stop and inspect the exact path before deciding how to recover.
- Never delete `main`, `canary`, or the base branch.
- Preserve unrelated user changes and concurrent worktrees. The user's other sessions may be working in them.
+- The repo is a partial clone. Probing an object that is not local (an old PR head via `git cat-file`, `git log <pr-head>..`) silently fetches it from the remote, which turns a loop over 30 branches into tens of minutes. Export `GIT_NO_LAZY_FETCH=1` in ad-hoc loops, as the script does.
- When writing ad-hoc verification loops, run them under `bash`, not the interactive `zsh`: zsh does not word-split `$var` in `for`/argument positions, so file lists collapse into one argument and checks silently pass.
## Script
diff --git a/.agents/skills/cleanup-git-worktrees/scripts/cleanup.sh b/.agents/skills/cleanup-git-worktrees/scripts/cleanup.sh
index 6708d7ac2a9..a0300cef5c5 100755
--- a/.agents/skills/cleanup-git-worktrees/scripts/cleanup.sh
+++ b/.agents/skills/cleanup-git-worktrees/scripts/cleanup.sh
@@ -2,23 +2,34 @@
set -euo pipefail
+# The repo may be a partial clone: never let a probe for a missing object (an
+# old PR head) trigger a network fetch per branch.
+export GIT_NO_LAZY_FETCH=1
+
usage() {
cat <<'EOF'
Usage:
cleanup.sh audit [--fetch] [--gh] [--stale-days <n>] [--base <ref>] [--noise <regex>]
+ [--scratch <regex>]
cleanup.sh clean [--gh] [--stale-days <n>] [--base <ref>] [--noise <regex>] \
- --branch <name> [--branch <name> ...] [--apply]
+ [--scratch <regex>] [--apply] \
+ (--branch <name> [--branch <name> ...] | --branches-file <path>)
Audit is read-only except for optional fetch/prune. Clean defaults to a dry run.
--fetch git fetch --prune the base remote first.
- --gh Query GitHub PR state per branch (needs `gh`). Enables the
- candidate-pr-merged / candidate-pr-closed classifications.
+ --gh Query GitHub PR state (needs `gh`). Enables the
+ candidate-pr-* classifications. Recent PRs are prefetched in
+ one call; only branches missing from it are looked up singly.
--stale-days n Treat a clean branch whose last commit is older than n days
and which has no unpushed commits as candidate-stale.
--noise regex Untracked paths matching this regex do not count as dirty
(default: node_modules|\.goal-tracing/). They are removed
together with the worktree.
+ --scratch regex Untracked paths that are disposable local scratch (default:
+ probe tests, screenshots, PR body drafts, .records*). Like
+ noise they do not count as dirty and are removed with --force.
+ --branches-file Read target branches from a file, one per line.
Pass the same --gh / --stale-days / --noise flags to clean that you used for
audit, otherwise the pre-deletion re-classification will refuse the target.
@@ -46,6 +57,7 @@ fetch_remote=false
use_gh=false
stale_days=0
noise_regex='node_modules|\.goal-tracing/'
+scratch_regex='\.probe\.test\.tsx?$|\.png$|(^|/)pr-body[^/]*\.md$|(^|/)\.records[^/]*'
apply=false
branches=()
@@ -65,6 +77,14 @@ while (($#)); do
branches+=("$2")
shift 2
;;
+ --branches-file)
+ (($# >= 2)) || die '--branches-file requires a path'
+ [[ -r "$2" ]] || die "cannot read branches file: $2"
+ while IFS= read -r line || [[ -n "$line" ]]; do
+ [[ -n "$line" ]] && branches+=("$line")
+ done < "$2"
+ shift 2
+ ;;
--fetch)
fetch_remote=true
shift
@@ -78,6 +98,11 @@ while (($#)); do
noise_regex=$2
shift 2
;;
+ --scratch)
+ (($# >= 2)) || die '--scratch requires a regex'
+ scratch_regex=$2
+ shift 2
+ ;;
--stale-days)
(($# >= 2)) || die '--stale-days requires a number'
[[ "$2" =~ ^[0-9]+$ ]] || die '--stale-days must be an integer'
@@ -105,11 +130,22 @@ if $fetch_remote; then
git fetch --prune "$remote"
fi
+pr_cache=''
if $use_gh; then
command -v gh >/dev/null 2>&1 || die '--gh requires the gh CLI'
+ # One bulk call instead of one per branch. Newest PR first, so the first
+ # match for a head branch is its latest PR.
+ pr_cache=$(mktemp)
+ trap 'rm -f "$pr_cache"' EXIT
+ gh pr list --state all --limit 3000 \
+ --json number,state,headRefName,headRefOid,mergedAt \
+ --jq '.[] | "\(.headRefName)\t\(.number)\t\(.state)\t\(.headRefOid)\t\(.mergedAt // "-")"' \
+ > "$pr_cache" 2>/dev/null || : > "$pr_cache"
fi
now_epoch=$(date +%s)
+# The main worktree holds the repository itself and cannot be removed.
+main_worktree=$(cd "$common_dir/.." && pwd -P)
# ---------------------------------------------------------------------------
# Worktree enumeration. Emits: path <TAB> branch <TAB> prunable-reason
@@ -135,20 +171,45 @@ branch_worktree() {
list_worktrees | awk -F'\t' -v b="$1" '$2 == b { print $1; exit }'
}
+# A process whose cwd is inside the worktree means another session may be
+# working there, whatever its Git state says.
+worktree_in_use() {
+ command -v lsof >/dev/null 2>&1 || return 1
+ local path
+ path=$(cd "$1" && pwd -P)
+ lsof -d cwd -Fn 2>/dev/null | awk -v p="$path" '
+ substr($0, 1, 1) == "n" { d = substr($0, 2); if (d == p || index(d, p "/") == 1) { found = 1; exit } }
+ END { exit !found }
+ '
+}
+
worktree_is_usable() {
local path=$1
[[ -d "$path" ]] && git -C "$path" rev-parse --is-inside-work-tree >/dev/null 2>&1
}
-# Real dirt: any tracked change, plus untracked paths that do not match the
-# noise regex. Noise: untracked paths that match it (safe to drop with --force).
-dirty_count() {
- # grep exits 1 when nothing survives the filter; that is "clean", not an error.
- { git -C "$1" status --porcelain | grep -Ev "^\?\? .*(${noise_regex})" || true; } | wc -l | tr -d ' '
-}
-
-noise_count() {
- { git -C "$1" status --porcelain | grep -E "^\?\? .*(${noise_regex})" || true; } | wc -l | tr -d ' '
+# Splits `git status` into real dirt and disposable entries (safe to drop with
+# --force): untracked noise or scratch, and tracked files whose content equals
+# the base (stale residue of a branch that is merely behind). Prints
+# "<dirty> <disposable>".
+dirt_counts() {
+ local path=$1 dirty=0 disposable=0 line file
+ while IFS= read -r line; do
+ [[ -n "$line" ]] || continue
+ file=${line:3}
+ if [[ "$line" == '?? '* ]]; then
+ if [[ "$file" =~ $noise_regex || "$file" =~ $scratch_regex ]]; then
+ disposable=$((disposable + 1))
+ else
+ dirty=$((dirty + 1))
+ fi
+ elif [[ "$file" != *' -> '* ]] && git -C "$path" diff --quiet "$base_ref" -- "$file" 2>/dev/null; then
+ disposable=$((disposable + 1))
+ else
+ dirty=$((dirty + 1))
+ fi
+ done < <(git -C "$path" status --porcelain --untracked-files=normal)
+ printf '%s %s\n' "$dirty" "$disposable"
}
upstream_track() {
@@ -175,27 +236,41 @@ unpushed_count() {
git rev-list --count "$1" --not --remotes="$remote"
}
-# Emits: number <TAB> state <TAB> tip_eq_head (eq|ne) β€” or "-\t-\t-" without --gh.
+# Emits: number <TAB> state <TAB> tip_eq_head <TAB> after_merge β€” or dashes
+# without --gh. tip_eq_head is eq|ne. after_merge counts commits on the branch
+# but not the base that are newer than mergedAt: a squash merge leaves the
+# branch's own pre-merge commits off the base, so only these can be unmerged
+# work. Computed from local objects only (the PR head may not be fetched).
pr_info() {
local branch=$1
if ! $use_gh; then
- printf -- '-\t-\t-\n'
+ printf -- '-\t-\t-\t-\n'
return
fi
- local raw number state head
- raw=$(gh pr list --state all --head "$branch" --limit 1 \
- --json number,state,headRefOid \
- --jq '.[0] | "\(.number)\t\(.state)\t\(.headRefOid)"' 2>/dev/null || true)
- if [[ -z "$raw" || "$raw" == $'null\tnull\tnull' ]]; then
- printf -- '-\t-\t-\n'
+ local raw number state head merged_at
+ raw=$(awk -F'\t' -v b="$branch" '$1 == b { print $2 "\t" $3 "\t" $4 "\t" $5; exit }' "$pr_cache")
+ if [[ -z "$raw" ]]; then
+ raw=$(gh pr list --state all --head "$branch" --limit 1 \
+ --json number,state,headRefOid,mergedAt \
+ --jq '.[0] | "\(.number)\t\(.state)\t\(.headRefOid)\t\(.mergedAt // "-")"' 2>/dev/null || true)
+ fi
+ if [[ -z "$raw" || "$raw" == null* ]]; then
+ printf -- '-\t-\t-\t-\n'
return
fi
- IFS=$'\t' read -r number state head <<<"$raw"
+ IFS=$'\t' read -r number state head merged_at <<<"$raw"
if [[ "$(git rev-parse "$branch")" == "$head" ]]; then
- printf '%s\t%s\teq\n' "$number" "$state"
- else
- printf '%s\t%s\tne\n' "$number" "$state"
+ printf '%s\t%s\teq\t0\n' "$number" "$state"
+ return
+ fi
+ local after=-
+ if [[ "$state" == MERGED && "$merged_at" != - ]]; then
+ local merged_epoch
+ merged_epoch=$(date -j -u -f '%Y-%m-%dT%H:%M:%SZ' "$merged_at" +%s 2>/dev/null \
+ || date -u -d "$merged_at" +%s)
+ after=$(git log --format=%ct "$branch" --not "$base_ref" | awk -v m="$merged_epoch" '$1 > m' | wc -l | tr -d ' ')
fi
+ printf '%s\t%s\tne\t%s\n' "$number" "$state" "$after"
}
is_protected_branch() {
@@ -204,10 +279,10 @@ is_protected_branch() {
[[ "$branch" == main || "$branch" == canary || "$branch" == "$base_ref" || "$branch" == "$base_short" ]]
}
-# classify <branch> <worktree> <dirty> <age> <unpushed> <pr_state> <tip_eq>
+# classify <branch> <worktree> <dirty> <age> <unpushed> <pr_state> <tip_eq> <after_merge>
classify() {
local branch=$1 worktree=${2:-} dirty=${3:-0} age=${4:-0} unpushed=${5:-0}
- local pr_state=${6:--} tip_eq=${7:--}
+ local pr_state=${6:--} tip_eq=${7:--} after=${8:--}
local track
track=$(upstream_track "$branch")
@@ -215,15 +290,27 @@ classify() {
printf 'protected-branch'
elif [[ -n "$worktree" && "$(cd "$worktree" && pwd -P)" == "$(pwd -P)" ]]; then
printf 'protect-current'
+ elif [[ -n "$worktree" && "$(cd "$worktree" && pwd -P)" == "$main_worktree" ]]; then
+ printf 'protect-main'
+ elif ((dirty > 0)) && [[ "$pr_state" == MERGED || "$pr_state" == CLOSED ]]; then
+ # Owner policy allows discarding these, but the edits are unrecoverable:
+ # list the files and get the user to name the branch.
+ printf 'review-pr-done-dirty'
elif ((dirty > 0)); then
printf 'protect-dirty'
elif is_merged "$branch"; then
printf 'candidate-merged'
elif [[ "$pr_state" == MERGED && "$tip_eq" == eq ]]; then
printf 'candidate-pr-merged'
+ elif [[ "$pr_state" == MERGED && "$after" == 0 ]]; then
+ # Tip differs from the PR head but has nothing newer than the merge: pure
+ # pre-merge history that the squash commit already carries.
+ printf 'candidate-pr-merged-history'
+ elif [[ "$pr_state" == MERGED && "$unpushed" == 0 ]]; then
+ # Post-merge commits exist but a remote ref keeps them all.
+ printf 'candidate-pr-merged-pushed'
elif [[ "$pr_state" == MERGED ]]; then
- # Local tip moved past the PR head: check the extra commits by subject
- # against the base log before deleting.
+ # Local-only commits newer than the merge: possibly unmerged work.
printf 'review-pr-merged-ahead'
elif [[ "$pr_state" == CLOSED && ( "$tip_eq" == eq || "$unpushed" == 0 ) ]]; then
printf 'candidate-pr-closed'
@@ -242,29 +329,30 @@ classify() {
}
print_header() {
- printf 'scope\tpath\tbranch\tdirty\tnoise\tage_days\tunpushed\tupstream\ttrack\tmerged_into_base\tpr\tpr_state\ttip_eq_pr\tclassification\n'
+ printf 'scope\tpath\tbranch\tdirty\tnoise\tage_days\tunpushed\tupstream\ttrack\tmerged_into_base\tpr\tpr_state\ttip_eq_pr\tafter_merge\tclassification\n'
}
print_row() {
local scope=$1 path=$2 branch=$3
- local dirty noise age unpushed upstream track merged pr_number pr_state tip_eq classification
+ local dirty noise age unpushed upstream track merged pr_number pr_state tip_eq after classification
local worktree=''
+ # A concurrent cleanup may delete the branch after it was enumerated.
+ git show-ref --verify --quiet "refs/heads/$branch" || return 0
[[ "$scope" == worktree ]] && worktree=$path
dirty=0; noise=0
if [[ -n "$worktree" ]]; then
- dirty=$(dirty_count "$worktree")
- noise=$(noise_count "$worktree")
+ read -r dirty noise < <(dirt_counts "$worktree")
fi
age=$(age_days "$branch")
unpushed=$(unpushed_count "$branch")
upstream=$(upstream_name "$branch")
track=$(upstream_track "$branch")
if is_merged "$branch"; then merged=yes; else merged=no; fi
- IFS=$'\t' read -r pr_number pr_state tip_eq < <(pr_info "$branch") || true
- classification=$(classify "$branch" "$worktree" "$dirty" "$age" "$unpushed" "$pr_state" "$tip_eq")
- printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
+ IFS=$'\t' read -r pr_number pr_state tip_eq after < <(pr_info "$branch") || true
+ classification=$(classify "$branch" "$worktree" "$dirty" "$age" "$unpushed" "$pr_state" "$tip_eq" "$after")
+ printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
"$scope" "$path" "$branch" "$dirty" "$noise" "$age" "$unpushed" \
- "${upstream:-none}" "${track:-none}" "$merged" "$pr_number" "$pr_state" "$tip_eq" "$classification"
+ "${upstream:-none}" "${track:-none}" "$merged" "$pr_number" "$pr_state" "$tip_eq" "$after" "$classification"
}
audit() {
@@ -285,17 +373,17 @@ audit() {
local reason=${prunable:-directory is not a git worktree}
local present=missing
[[ -d "$worktree" ]] && present=directory-present
- printf 'worktree\t%s\t%s\t?\t?\t-\t-\t-\t-\t-\t-\t-\t-\tbroken-registration(%s; %s)\n' \
+ printf 'worktree\t%s\t%s\t?\t?\t-\t-\t-\t-\t-\t-\t-\t-\t-\tbroken-registration(%s; %s)\n' \
"$worktree" "${branch:--}" "$present" "$reason"
[[ -n "$branch" ]] && printf '%s\n' "$branch" >> "$bound_file"
continue
fi
if [[ -z "$branch" ]]; then
- local head dirty
+ local head dirty noise
head=$(git -C "$worktree" rev-parse --short HEAD)
- dirty=$(dirty_count "$worktree")
- printf 'worktree\t%s\t(detached %s)\t%s\t%s\t-\t-\t-\t-\t-\t-\t-\t-\treview-detached\n' \
- "$worktree" "$head" "$dirty" "$(noise_count "$worktree")"
+ read -r dirty noise < <(dirt_counts "$worktree")
+ printf 'worktree\t%s\t(detached %s)\t%s\t%s\t-\t-\t-\t-\t-\t-\t-\t-\t-\treview-detached\n' \
+ "$worktree" "$head" "$dirty" "$noise"
continue
fi
printf '%s\n' "$branch" >> "$bound_file"
@@ -311,26 +399,41 @@ audit() {
clean() {
((${#branches[@]} > 0)) || die 'clean requires at least one --branch'
- local branch worktree dirty noise age unpushed pr_number pr_state tip_eq classification
+ local branch worktree dirty noise age unpushed pr_number pr_state tip_eq after classification
for branch in "${branches[@]}"; do
- git show-ref --verify --quiet "refs/heads/$branch" || die "local branch not found: $branch"
+ if ! git show-ref --verify --quiet "refs/heads/$branch"; then
+ printf 'MISSING\t%s\n' "$branch" >&2
+ continue
+ fi
worktree=$(branch_worktree "$branch")
dirty=0; noise=0
if [[ -n "$worktree" ]]; then
- worktree_is_usable "$worktree" || die "$branch: worktree $worktree is a broken registration; run 'git worktree prune' and inspect the directory first"
- dirty=$(dirty_count "$worktree")
- noise=$(noise_count "$worktree")
+ if ! worktree_is_usable "$worktree"; then
+ printf 'REFUSED\t%s\tbroken-registration %s (git worktree prune, then inspect the directory)\n' "$branch" "$worktree" >&2
+ continue
+ fi
+ read -r dirty noise < <(dirt_counts "$worktree")
fi
age=$(age_days "$branch")
unpushed=$(unpushed_count "$branch")
- IFS=$'\t' read -r pr_number pr_state tip_eq < <(pr_info "$branch") || true
- classification=$(classify "$branch" "$worktree" "$dirty" "$age" "$unpushed" "$pr_state" "$tip_eq")
+ IFS=$'\t' read -r pr_number pr_state tip_eq after < <(pr_info "$branch") || true
+ classification=$(classify "$branch" "$worktree" "$dirty" "$age" "$unpushed" "$pr_state" "$tip_eq" "$after")
case "$classification" in
candidate-*) ;;
- *) die "$branch is $classification; refusing cleanup" ;;
+ *)
+ # Skip rather than abort, so one refused target does not strand the
+ # rest of a long batch.
+ printf 'REFUSED\t%s\t%s\n' "$branch" "$classification" >&2
+ continue
+ ;;
esac
+ if [[ -n "$worktree" ]] && worktree_in_use "$worktree"; then
+ printf 'REFUSED\t%s\tin-use (a process has its cwd in %s)\n' "$branch" "$worktree" >&2
+ continue
+ fi
+
if ! $apply; then
printf 'DRY-RUN\t%s\t%s\t%s\tnoise=%s\n' "$branch" "${worktree:--}" "$classification" "$noise"
continue