diff --git a/plugins/repo-hygiene/.claude-plugin/plugin.json b/plugins/repo-hygiene/.claude-plugin/plugin.json index a45c61c0ed8..2fb2b2c5595 100644 --- a/plugins/repo-hygiene/.claude-plugin/plugin.json +++ b/plugins/repo-hygiene/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json", "name": "repo-hygiene", - "version": "0.6.0", + "version": "0.7.0", "description": "Repo hygiene action-router: /repo-hygiene:clean sweeps reclaimable caches, build artifacts, and stale git metadata, and can realign the working tree to a fresh-pull state — dry-run-first, with destructive tiers gated behind explicit confirmation and a session-scoped destructive-command guard. Ecosystem targets are detected at runtime; secrets, runtime dependencies, and skill data are preserved by default.", "author": { "name": "Melodic Software", diff --git a/plugins/repo-hygiene/CHANGELOG.md b/plugins/repo-hygiene/CHANGELOG.md index 409cd488cde..724fa7b361c 100644 --- a/plugins/repo-hygiene/CHANGELOG.md +++ b/plugins/repo-hygiene/CHANGELOG.md @@ -3,6 +3,55 @@ All notable changes to the `repo-hygiene` plugin are documented here. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this plugin uses semantic versioning. +## [0.7.0] + +### Added + +- **`stash` action — stash audit and triage across every tier that previously + ignored stashes.** `git-stash-audit.sh` reports each stash's age, source + branch, diffstat, and a PR/merge signal, with a per-stash keep/drop advisory — + and **never drops a stash**; the agent confirms keep-or-drop per entry. A + `possibly superseded` / `likely superseded` advisory (source branch merged into + `origin/` or via a merged PR) is a hint to raise first, never an + autonomous drop. Deduped across linked worktrees by the `--git-common-dir` + `StashStore:` key (worktrees share one stash ref). Each stash also carries its + stable commit id (`Commit:`) — the safe handle when dropping several, since the + `stash@{n}` selector renumbers after every drop — and a confirmed `git stash + drop`/`clear` is now covered by the session destructive guard (blocked until the + `CLEAN_GUARD_ACK=1` acknowledgement). Runs standalone (`stash`) and as part of + the `git` tier. (#996) +- **Branch audit now surfaces unpushed commits per branch, including no-upstream + branches.** A new `Unpushed:` line reports `N ahead of ` or, for a + never-pushed branch, `no upstream, M commits not on origin/` — the + latter is invisible to `@{upstream}`-based ahead reporting, so unmerged local + work no longer goes unseen. Such branches form their own REVIEW class ranked + above generic stale/orphaned, so the unpushed-commit count is the headline. A + branch whose upstream is `gone` but that still carries commits not on + origin/ is held in REVIEW too, rather than offered as a LIKELY-SAFE + deletion candidate that would lose those commits. (#998) +- **The resolver echoes trailing free text as a `Note:` line.** When a leading + action token is followed by a question or a live-session constraint (e.g. + `all mind the 6 live sessions`), the remainder is emitted as advisory context + the agent must address, instead of being silently dropped during action + resolution. (#1000) + +### Changed + +- **Branches checked out in a linked worktree are their own `WORKTREE` bucket, no + longer folded into `PROTECTED`.** Such a branch is a real cleanup candidate but + `git branch -d` on it fails or, forced, breaks the worktree — so it is + subtracted from the deletion set and routed to the worktree-management tool + ("clean up the worktree first") rather than mislabeled untouchable. The + protected-name checks now rank above the worktree check so a `release/*` or + default branch checked out in a worktree stays PROTECTED. `Summary:` gains a + `worktree=` count. (#997) +- **`scan.sh` enumerates through the shared single pruned-walk engine.** The + read-only inventory dropped its per-pattern unpruned `find` walks (which still + descended `.git/`, `node_modules/`, `.venv/` despite `! -path` filters) for + `clean_caches_candidates` / `clean_build_candidates`, so the scan and the + mutating caches/build tiers now share one enumeration way and one prune set. + (#1011) + ## [0.6.0] ### Added diff --git a/plugins/repo-hygiene/skills/clean/SKILL.md b/plugins/repo-hygiene/skills/clean/SKILL.md index 9886937041c..27bbb3c0f3c 100644 --- a/plugins/repo-hygiene/skills/clean/SKILL.md +++ b/plugins/repo-hygiene/skills/clean/SKILL.md @@ -1,8 +1,8 @@ --- name: clean -description: "Repo hygiene action-router: scan (inventory), caches, build, git (prune/branch audit), tree (destructive fresh-pull reset), tree-batch (multi-repo tree reset with skip-list + dirty guard), all, and fleet batch forms of the selective tiers (caches-batch / build-batch / git-batch / all-batch over many repos behind one gate). Bare invocation detects intent from conversation or shows a menu. Dry-run-first; destructive actions require explicit confirmation. Use when: clean, disk space, remove caches, build artifacts, fresh pull, fresh clone state, reset to origin, reset all my repos, clean caches across all repos, clear build artifacts across all my repos, prune git across the fleet, stale branches, repo hygiene. Skip: removing git worktree directories (a worktree-management tool handles those)." +description: "Repo hygiene action-router: scan (inventory), caches, build, git (prune/branch audit), stash (stash audit/triage), tree (destructive fresh-pull reset), tree-batch (multi-repo tree reset with skip-list + dirty guard), all, and fleet batch forms of the selective tiers (caches-batch / build-batch / git-batch / all-batch over many repos behind one gate). Bare invocation detects intent from conversation or shows a menu. Dry-run-first; destructive actions require explicit confirmation. Use when: clean, disk space, remove caches, build artifacts, fresh pull, fresh clone state, reset to origin, reset all my repos, clean caches across all repos, clear build artifacts across all my repos, prune git across the fleet, stale branches, stashes, repo hygiene. Skip: removing git worktree directories (a worktree-management tool handles those)." user-invocable: true -argument-hint: "[scan|caches|build|git|tree|tree-batch|all|caches-batch|build-batch|git-batch|all-batch|aliases…] (bare → menu or auto-detect)" +argument-hint: "[scan|caches|build|git|stash|tree|tree-batch|all|caches-batch|build-batch|git-batch|all-batch|aliases…] (bare → menu or auto-detect)" allowed-tools: - Bash(bash ${CLAUDE_PLUGIN_ROOT}/skills/clean/scripts/*) hooks: @@ -38,6 +38,8 @@ Bare invocation never mutates silently: resolve intent → dry-run → user conf bash ${CLAUDE_PLUGIN_ROOT}/skills/clean/scripts/resolve-clean-action.sh $ARGUMENTS ``` +When a leading action token is followed by free text, the resolver also emits a `Note: ` line. That note is **advisory context you must address** — a question to answer (e.g. "does this include stashes?") or a live-session constraint to honor (e.g. "6-7 live sessions, mind WIP") — not part of action selection. Surface it and act on it alongside the resolved action; never silently drop it. + ### Bare invocation (empty args) 1. Infer from conversation (fresh pull → `tree`, disk space → `scan`, … — see action-router). @@ -51,7 +53,8 @@ bash ${CLAUDE_PLUGIN_ROOT}/skills/clean/scripts/resolve-clean-action.sh $ARGUMEN | `scan` | Show what's reclaimable | Safe | No | — | | `caches` | Clear tool and linter caches | Low | Yes | — | | `build` | Clear build output and logs | Low | Yes (includes caches) | — | -| `git` | Prune stale git metadata; audit branches | Low | No | Yes | +| `git` | Prune stale git metadata; audit branches + stashes | Low | No | Yes | +| `stash` | Audit and triage stashes (age, source, diffstat) | Safe | No | — | | `tree` | Reset working tree like a fresh pull | **Destructive** | No (always dry-run first) | **Never** | | `tree-batch` | Reset many repos like a fresh pull (skip-list + dirty guard) | **Destructive** | No (always dry-run first) | **Never** | | `all` | Sweep caches + build + git hygiene | Medium | Yes | — | @@ -72,7 +75,7 @@ Protected-path enforcement gates `scan`, `caches`, `build`, `git`, AND `tree` (` `tree` requires explicit confirmation and is never auto-invoked. Any file tracked by git is reset via `git reset --hard`, not selective deletion — and any tracked file deleted by reparse-point traversal (junction/symlink into a tracked dir) is auto-restored. -**Session-scoped destructive guard (frontmatter hook).** While this skill is active, a PreToolUse hook (`scripts/destructive-guard.sh`) blocks destructive Bash commands (`rm -rf`, `git clean -f*`, `git reset --hard`, `git checkout --`, recursive `Remove-Item`). After the dry-run → user-confirmation gate passes, re-issue the confirmed command with the acknowledgement prefix `CLEAN_GUARD_ACK=1 ` — never add the prefix without the user's explicit confirmation in this session. Kill switch: the `clean_destructive_guard_enabled` userConfig option set to `false` (`/plugin configure repo-hygiene`). +**Session-scoped destructive guard (frontmatter hook).** While this skill is active, a PreToolUse hook (`scripts/destructive-guard.sh`) blocks destructive Bash commands (`rm -rf`, `git clean -f*`, `git reset --hard`, `git checkout --`, `git stash drop`/`clear`, recursive `Remove-Item`). After the dry-run → user-confirmation gate passes, re-issue the confirmed command with the acknowledgement prefix `CLEAN_GUARD_ACK=1 ` — never add the prefix without the user's explicit confirmation in this session. Kill switch: the `clean_destructive_guard_enabled` userConfig option set to `false` (`/plugin configure repo-hygiene`). ## Cleanup configuration @@ -120,7 +123,13 @@ Both selective mutating tiers pay the filesystem walk **once**. `--dry-run` writ #### 4.2 Branch audit -`bash ${CLAUDE_PLUGIN_ROOT}/skills/clean/scripts/git-branch-audit.sh` — deletion via `AskUserQuestion` per [context/git-branch-cleanup.md](context/git-branch-cleanup.md). +`bash ${CLAUDE_PLUGIN_ROOT}/skills/clean/scripts/git-branch-audit.sh` — deletion via `AskUserQuestion` per [context/git-branch-cleanup.md](context/git-branch-cleanup.md). Branches in the `WORKTREE` tier are checked out in a linked worktree: never offer them for `git branch -d` — route the user to the worktree-management tool to clean up the worktree first. Branches carrying `no upstream, M commits not on origin/` are never-pushed local work — surface the count and confirm before any deletion. + +#### 4.3 Stash audit + +`bash ${CLAUDE_PLUGIN_ROOT}/skills/clean/scripts/git-stash-audit.sh` — read-only per-stash facts (age, source branch, diffstat, PR/merge signal, advisory). **Never drops a stash.** Present the list and, for each stash, ask the user keep-or-drop via `AskUserQuestion`; a `possibly superseded` / `likely superseded` advisory is a hint to raise first, never an autonomous drop. Dedup a fleet sweep by the `StashStore:` key (linked worktrees share one stash ref). When the resolved action is `stash`, run only this step. + +**Dropping stashes safely.** A confirmed drop is destructive and gated by the session guard — after the user confirms, re-issue as `CLEAN_GUARD_ACK=1 git stash drop `. The `Stash:` selector (`stash@{n}`) is **volatile**: the list renumbers after every drop, so dropping more than one by selector top-down retargets the wrong entry. Drop by the stable `Commit:` id (resolve it to its current selector immediately before each drop), or drop the highest-numbered selector first so lower indices stay valid. ### 5. All diff --git a/plugins/repo-hygiene/skills/clean/context/action-router.md b/plugins/repo-hygiene/skills/clean/context/action-router.md index aaa3a19f0d7..0f7b71bcff0 100644 --- a/plugins/repo-hygiene/skills/clean/context/action-router.md +++ b/plugins/repo-hygiene/skills/clean/context/action-router.md @@ -9,7 +9,8 @@ SKILL.md carries the action table headline; this file carries alias resolution, | `scan` | "Show what's reclaimable" | Read-only inventory | Safe | N/A (no mutation) | | `caches` | "Clear tool and linter caches" | `.pytest_cache/`, `.ruff_cache/`, `__pycache__/`, … | Low | **Never** | | `build` | "Clear build output and logs" | `bin/`, `obj/`, `dist/`, `*.binlog`, … | Low | **Never** | -| `git` | "Prune stale git metadata" | `worktree prune`, `remote prune`, `gc`, branch audit | Low | Prune/gc only after user OK; branch delete always opt-in | +| `git` | "Prune stale git metadata" | `worktree prune`, `remote prune`, `gc`, branch audit, stash audit | Low | Prune/gc only after user OK; branch delete always opt-in | +| `stash` | "Audit and triage my stashes" | Read-only per-stash facts (age, source branch, diffstat, PR/merge signal) | Safe | **Never** drops — keep/drop confirmed per stash | | `tree` | "Reset working tree like a fresh pull" | `fetch` + `reset --hard` upstream + `clean -fdx` (default-preserve secrets/deps/skill-data; `--include-deps` / `--include-secrets` to widen) | **Destructive** | **Never** | | `tree-batch` | "Reset all my repos like a fresh pull" | `tree` across a repo set behind one gate; separator-agnostic skip list; dirty/unpushed skipped unless `--include-dirty` | **Destructive** | **Never** | | `all` | "Sweep caches, build artifacts, and git hygiene" | `build` + `git` (not `tree`) | Medium | **Never** | @@ -23,7 +24,7 @@ SKILL.md carries the action table headline; this file carries alias resolution, bash ${CLAUDE_PLUGIN_ROOT}/skills/clean/scripts/resolve-clean-action.sh ``` -Emits `Action: `. Single-token aliases: +Emits `Action: `, plus an optional `Note: ` line when a leading action token is trailed by free text (a question or a live-session constraint) — advisory context the agent must address, never part of resolution. Single-token aliases: | Tokens → | Action | | --- | --- | @@ -31,6 +32,7 @@ Emits `Action: `. Single-token aliases: | `cache`, `caches`, `linter-caches`, `linter` | `caches` | | `build`, `artifacts`, `artifact`, `bin`, `obj`, `output` | `build` | | `git`, `branches`, `branch`, `prune`, `gc` | `git` | +| `stash`, `stashes`, `stash-audit` | `stash` | | `tree`, `fresh`, `fresh-pull`, `fresh-pull-state`, `pristine`, `reset-tree`, `working-tree` | `tree` | | `tree-batch`, `batch`, `fleet`, `multi-repo`, `reset-all` | `tree-batch` | | `all`, `sweep`, `everything` | `all` | @@ -59,7 +61,8 @@ Default when still unsure after one question: **`scan`** (safest). | --- | --- | --- | | `scan` | Run `scan.sh` | None | | `caches`, `build`, `all` | `preflight.sh` + tier scripts `--dry-run` (writes a manifest; emits `Manifest:` + `Summary: planned=N bytes=K`) | `AskUserQuestion` when preflight non-empty OR before `--apply` — surface the `bytes` reclaimable total; apply the same manifest (`--apply --manifest `), which emits `Summary: removed=N failed=M bytes=K` and exits non-zero on failure | -| `git` | `git-prune.sh --dry-run`, `git-branch-audit.sh` | Before `--apply` prune; before any branch deletion | +| `git` | `git-prune.sh --dry-run`, `git-branch-audit.sh`, `git-stash-audit.sh` | Before `--apply` prune; before any branch deletion; per-stash keep/drop | +| `stash` | `git-stash-audit.sh` (read-only) | Per-stash keep/drop — **never** auto-dropped, even a `superseded` advisory | | `tree` | `git-tree-reset.sh --dry-run` (always) | **Mandatory** `AskUserQuestion` before `--apply` (surface `PreserveDeps`/`PreserveSecrets`/`AheadCount`); a non-zero `AheadCount` or exit 4 needs explicit unpushed-loss confirmation before `--allow-unpushed`; `--include-secrets` is UNRECOVERABLE — confirm separately; never autonomous | | `tree-batch` | `git-tree-reset-batch.sh --dry-run` (always) | **Mandatory** single batch-wide `AskUserQuestion` before `--apply` (surface the per-repo `Outcome`/`Reason`, `Summary`, and `UnmatchedSkip:`); one gate for the whole batch, never per repo; `--include-dirty` re-enables the data-loss vector — confirm separately naming the dirty repos, like `--include-secrets`; never autonomous. Detail: [git-tree-reset-batch.md](git-tree-reset-batch.md) | | `caches-batch` / `build-batch` / `git-batch` / `all-batch` | `clean-batch.sh --tier <…> --dry-run` (writes a batch plan; emits `BatchPlan:` + aggregate `Summary: repos=N planned=P bytes=K`) | **Mandatory** single batch-wide `AskUserQuestion` before `--apply` (surface per-repo `Outcome`/`Reason`, `Summary` reclaimable `bytes`, `UnmatchedSkip:`); apply the **same** plan (`CLEAN_GUARD_ACK=1 … --apply --batch-plan `, which errors without the plan) — one gate for the whole batch, never per repo; never autonomous. Detail: [clean-batch.md](clean-batch.md) | diff --git a/plugins/repo-hygiene/skills/clean/context/git-branch-cleanup.md b/plugins/repo-hygiene/skills/clean/context/git-branch-cleanup.md index 606f9fc9289..485240d07ed 100644 --- a/plugins/repo-hygiene/skills/clean/context/git-branch-cleanup.md +++ b/plugins/repo-hygiene/skills/clean/context/git-branch-cleanup.md @@ -10,7 +10,9 @@ Run the branch-audit script — do not reimplement collection inline: bash ${CLAUDE_PLUGIN_ROOT}/skills/clean/scripts/git-branch-audit.sh ``` -**Output contract** (per branch): `Branch:`, `Tier:`, `Age days:`, `PR:`, `Reason:`; trailing `Summary: protected=… safe=… likely-safe=… review=…`. +**Output contract** (per branch): `Branch:`, `Tier:`, `Age days:`, `PR:`, `Unpushed:`, `Reason:`; trailing `Summary: protected=… worktree=… safe=… likely-safe=… review=…`. + +**`Unpushed:` line** — commits at risk of loss. With an upstream: `N ahead of `. With no upstream: `no upstream, M commits not on origin/` (or `no upstream (no origin/ to compare)` when the default branch is unfetched). Never-pushed local work is invisible to `@{upstream}`-based ahead reporting, so this line is the only signal that a no-upstream branch carries unmerged commits — surface it before offering any deletion. **Default branch resolution** (inside script): `origin/HEAD` symbolic ref → `gh repo view --json defaultBranchRef` → `main`. @@ -24,19 +26,24 @@ The script applies rules in priority order (first match wins). Agent interprets |----------|-----------|------|--------| | 1 | Branch = current | PROTECTED | current branch | | 2 | Branch = default | PROTECTED | default branch | -| 3 | Branch in worktree list | PROTECTED | worktree-attached | -| 4 | Branch glob-matches protected pattern (see list below) | PROTECTED | protected pattern | +| 3 | Branch glob-matches protected pattern (see list below) | PROTECTED | protected pattern | +| 4 | Branch checked out in a linked worktree | WORKTREE | checked out in worktree — clean up the worktree first | | 5 | `PR` = MERGED and local tip matches PR headRefOid | SAFE | PR merged | | 5b | `PR` = MERGED and local tip differs from headRefOid | REVIEW | PR merged but branch has commits since merge | | 6 | Branch in git `--merged` ancestry | SAFE | merged (non-squash) | | 7 | `PR` = CLOSED | REVIEW | PR closed without merge | | 8 | Upstream gone (`: gone]` in `branch -vv`) | LIKELY-SAFE | upstream deleted | -| 9 | Age > 90 days | REVIEW | stale | -| 10 | No PR, no tracking, not merged | REVIEW | orphaned | +| 9 | No upstream, M commits not on origin/default | REVIEW | no upstream, M commits not on origin/ | +| 10 | Age > 90 days | REVIEW | stale | +| 11 | No PR, no tracking, not merged | REVIEW | orphaned | Stale threshold: 90 days (`CLEAN_STALE_BRANCH_DAYS` in `cleanup-paths.sh`). Branch can match multiple REVIEW reasons — list all in report. -**Protected branch patterns (priority 4):** exact names and globs that MUST NEVER be offered for deletion — `main`, `master`, `develop`, `release/*`, `hotfix/*`. Matched via bash `case` in `clean_branch_matches_protected_pattern`. Extend with repo-specific long-lived branches if needed (e.g. `staging`, `production`, `deploy/*`). +**WORKTREE tier (priority 4)** — a branch checked out in a linked worktree is a real cleanup candidate (it may be merged or gone), but `git branch -d` on it fails or, forced, breaks the worktree. It is therefore its own bucket, distinct from PROTECTED: never offer it for deletion here — route the user to the worktree-management tool to remove the worktree first (after which a later audit reclassifies the branch on its merge/PR state). Priority 4 sits below the protected checks so a `release/*` or default branch that also happens to be checked out stays PROTECTED. + +**No-upstream class (priority 9)** — a never-pushed branch with commits not on `origin/` is unmerged local work; it ranks above the generic stale/orphaned REVIEW reasons so the unpushed-commit count is the headline. Stays REVIEW (never a deletion candidate) — confirm the commit loss explicitly before any deletion. + +**Protected branch patterns (priority 3):** exact names and globs that MUST NEVER be offered for deletion — `main`, `master`, `develop`, `release/*`, `hotfix/*`. Matched via bash `case` in `clean_branch_matches_protected_pattern`. Extend with repo-specific long-lived branches if needed (e.g. `staging`, `production`, `deploy/*`). **Squash-merge handling:** `git branch --merged` (priority 6) misses squash-merged branches because squash creates a new combined commit. `gh pr list` (priority 5) correctly detects these via PR state. When `gh` is unavailable, squash-merged branches land in REVIEW tier — safe-conservative handling. @@ -47,16 +54,18 @@ Map script output to a table: ```markdown ## Branch Audit -| Branch | Tier | Age | PR | Reason | -|--------|------|-----|----|--------| -| main | PROTECTED | 0d | — | default branch | -| worktree-worktree-2 | PROTECTED | 0d | — | current branch, worktree-attached | -| feat/old-thing | SAFE | 45d | #123 MERGED | PR merged | -| refactor/x | LIKELY-SAFE | 12d | — | upstream gone | -| experiment | REVIEW | 120d | — | stale (120d), orphaned | - -**Summary:** N protected, M safe, P likely-safe, Q review -**Deletion candidates (M+P):** +| Branch | Tier | Age | PR | Unpushed | Reason | +|--------|------|-----|----|----------|--------| +| main | PROTECTED | 0d | — | 0 ahead of origin/ | default branch | +| feat/parked | WORKTREE | 3d | — | 0 ahead of origin/feat/parked | checked out in worktree — clean up the worktree first | +| feat/old-thing | SAFE | 45d | #123 MERGED | 0 ahead of origin/feat/old-thing | PR merged | +| refactor/x | LIKELY-SAFE | 12d | — | no upstream (no origin/ to compare) | upstream gone | +| draft/local | REVIEW | 4d | — | no upstream, 5 commits not on origin/ | no upstream, 5 commits not on origin/ | +| experiment | REVIEW | 120d | — | 0 ahead of origin/experiment | stale (120d), orphaned | + +**Summary:** N protected, W worktree, M safe, P likely-safe, Q review +**Deletion candidates (M+P):** +**Worktree cleanup first:** ``` ## 4.7 Interactive deletion diff --git a/plugins/repo-hygiene/skills/clean/scripts/destructive-guard.sh b/plugins/repo-hygiene/skills/clean/scripts/destructive-guard.sh index f10e88c0620..7632e9c9aae 100755 --- a/plugins/repo-hygiene/skills/clean/scripts/destructive-guard.sh +++ b/plugins/repo-hygiene/skills/clean/scripts/destructive-guard.sh @@ -50,7 +50,7 @@ is_destructive() { grep -qE '[[:space:]]-[a-zA-Z]*f|[[:space:]]--force([[:space:]]|=|$)' <<<"$cmd"; then return 0 fi - grep -qE "git[[:space:]]+${gopt}reset[[:space:]]+--hard|git[[:space:]]+${gopt}checkout[[:space:]]+--[[:space:]]|Remove-Item[[:space:]].*-Recurse" <<<"$cmd" + grep -qE "git[[:space:]]+${gopt}reset[[:space:]]+--hard|git[[:space:]]+${gopt}checkout[[:space:]]+--[[:space:]]|git[[:space:]]+${gopt}stash[[:space:]]+(drop|clear)([[:space:]]|$)|Remove-Item[[:space:]].*-Recurse" <<<"$cmd" } # jq parses the hook payload. Without it the ack prefix cannot be verified, so diff --git a/plugins/repo-hygiene/skills/clean/scripts/destructive-guard.test.sh b/plugins/repo-hygiene/skills/clean/scripts/destructive-guard.test.sh index e7485d60ac5..276f2ae21e4 100755 --- a/plugins/repo-hygiene/skills/clean/scripts/destructive-guard.test.sh +++ b/plugins/repo-hygiene/skills/clean/scripts/destructive-guard.test.sh @@ -39,6 +39,10 @@ for cmd in \ "git reset --hard origin/main" \ "git checkout -- ." \ "git -C /tmp/x checkout -- ." \ + "git stash drop" \ + "git stash drop stash@{0}" \ + "git stash clear" \ + "git -C /tmp/x stash drop" \ "Remove-Item -Recurse -Force obj"; do assert_exit "blocks: $cmd" 2 "$(guard_exit "$cmd")" done @@ -53,10 +57,11 @@ assert_contains "block reason names the ack path" "$reason" "CLEAN_GUARD_ACK=1" assert_exit "ack prefix allows git clean" 0 "$(guard_exit "CLEAN_GUARD_ACK=1 git clean -fdx -e node_modules/")" assert_exit "ack prefix allows reset --hard" 0 "$(guard_exit "CLEAN_GUARD_ACK=1 git reset --hard origin/main")" +assert_exit "ack prefix allows stash drop" 0 "$(guard_exit "CLEAN_GUARD_ACK=1 git stash drop stash@{1}")" # --- 5. Benign commands pass ----------------------------------------------------- -for cmd in "git status" "rm file.txt" "git clean -n" "git clean -nx" "git clean -x" "ls -rf" "dotnet build"; do +for cmd in "git status" "rm file.txt" "git clean -n" "git clean -nx" "git clean -x" "ls -rf" "dotnet build" "git stash list" "git stash show stash@{0}"; do assert_exit "allows: $cmd" 0 "$(guard_exit "$cmd")" done diff --git a/plugins/repo-hygiene/skills/clean/scripts/git-branch-audit.sh b/plugins/repo-hygiene/skills/clean/scripts/git-branch-audit.sh index bc6fdb7dd73..8da408dfc1f 100755 --- a/plugins/repo-hygiene/skills/clean/scripts/git-branch-audit.sh +++ b/plugins/repo-hygiene/skills/clean/scripts/git-branch-audit.sh @@ -2,7 +2,7 @@ # shellcheck disable=SC2154 # Branch audit facts for the clean git branch cleanup. No deletion. # -# Output: Branch, Tier, Age days, PR, Reason; Summary line. +# Output: Branch, Tier, Age days, PR, Unpushed, Reason; Summary line. # Exit: 0. # Omit -e/-o pipefail: script always exits 0; sub-commands are best-effort (gh may be absent). set -u @@ -62,11 +62,35 @@ WORKTREE_BRANCHES="$(git -C "$REPO_ROOT" worktree list --porcelain 2>/dev/null | GONE_BRANCHES="$(git -C "$REPO_ROOT" branch -vv 2>/dev/null | grep ': gone]' | awk '{print $1}' | tr -d '\r')" MERGED_BRANCHES="$(git -C "$REPO_ROOT" branch --merged "origin/${DEFAULT_BRANCH}" 2>/dev/null | sed 's/^[ *]*//' | grep -v "^${DEFAULT_BRANCH}$" | tr -d '\r' || true)" -prot=0 safe=0 likely=0 review=0 +prot=0 wt=0 safe=0 likely=0 review=0 NOW=$(date +%s) classify_branch() { local branch="$1" age_days="$2" tier reason pr_line="none" local_tip + local upstream no_upstream=0 ahead_default="" unpushed_line ahead_up + + # No-upstream branches are invisible to `@{upstream}`-based ahead/behind + # reporting (it yields nothing), so never-pushed local work goes unseen. Detect + # the missing upstream and, when origin/ exists, count the branch's + # commits absent from it — surfaced below as its own class and Unpushed line. + # `rev-parse --abbrev-ref` echoes its input to stdout on failure (no upstream + # configured, or a configured upstream whose tracking ref is unfetched), so gate + # on its exit status rather than on empty output — otherwise that echo reads as a + # real upstream. + if upstream="$(git -C "$REPO_ROOT" rev-parse --abbrev-ref "${branch}@{upstream}" 2>/dev/null)"; then + upstream="${upstream%$'\r'}" + else + upstream="" + fi + [[ -z "$upstream" ]] && no_upstream=1 + # Commits on this branch absent from origin/ — the work lost if the + # branch were deleted. Computed for every branch (when origin/ exists) + # so both the upstream-gone and no-upstream classes can guard deletion on it: a + # `gone` upstream normally means merged-and-deleted, but a gone branch still + # carrying such commits is unmerged local work, not a safe-delete candidate. + if git -C "$REPO_ROOT" rev-parse --verify --quiet "refs/remotes/origin/${DEFAULT_BRANCH}" >/dev/null 2>&1; then + ahead_default="$(git -C "$REPO_ROOT" rev-list --count "origin/${DEFAULT_BRANCH}..refs/heads/${branch}" 2>/dev/null | tr -d '\r')" + fi if [[ "$branch" == "$CURRENT_BRANCH" ]]; then tier="PROTECTED" @@ -74,12 +98,12 @@ classify_branch() { elif [[ "$branch" == "$DEFAULT_BRANCH" ]]; then tier="PROTECTED" reason="default branch" - elif grep -qxF "$branch" <<<"$WORKTREE_BRANCHES"; then - tier="PROTECTED" - reason="worktree-attached" elif clean_branch_matches_protected_pattern "$branch"; then tier="PROTECTED" reason="protected pattern" + elif grep -qxF "$branch" <<<"$WORKTREE_BRANCHES"; then + tier="WORKTREE" + reason="checked out in worktree — clean up the worktree first" elif [[ -n "${PR_STATE[$branch]:-}" && "${PR_STATE[$branch]}" == "MERGED" ]]; then local_tip="$(git -C "$REPO_ROOT" rev-parse "refs/heads/$branch" 2>/dev/null | tr -d '\r')" if [[ -n "${PR_REFOID[$branch]:-}" && -n "$local_tip" && "$local_tip" != "${PR_REFOID[$branch]}" ]]; then @@ -99,8 +123,23 @@ classify_branch() { reason="PR closed without merge" pr_line="#${PR_NUM[$branch]} CLOSED" elif grep -qxF "$branch" <<<"$GONE_BRANCHES"; then - tier="LIKELY-SAFE" - reason="upstream gone" + if [[ -z "$ahead_default" ]]; then + # Upstream gone AND no origin/ to compare against (feature-only + # clone, unfetched/missing remote HEAD): the script cannot prove the branch + # is merged, so fail closed to REVIEW rather than offer it as a deletable + # LIKELY-SAFE candidate that might carry local-only commits. + tier="REVIEW" + reason="upstream gone, cannot compare against origin/${DEFAULT_BRANCH}" + elif [[ "$ahead_default" -gt 0 ]]; then + tier="REVIEW" + reason="upstream gone, ${ahead_default} commits not on origin/${DEFAULT_BRANCH}" + else + tier="LIKELY-SAFE" + reason="upstream gone" + fi + elif [[ "$no_upstream" == 1 && -n "$ahead_default" && "$ahead_default" -gt 0 ]]; then + tier="REVIEW" + reason="no upstream, ${ahead_default} commits not on origin/${DEFAULT_BRANCH}" elif [[ "$age_days" -gt "$CLEAN_STALE_BRANCH_DAYS" ]]; then tier="REVIEW" reason="stale (${age_days}d)" @@ -111,6 +150,7 @@ classify_branch() { case "$tier" in PROTECTED) prot=$((prot + 1)) ;; + WORKTREE) wt=$((wt + 1)) ;; SAFE) safe=$((safe + 1)) ;; LIKELY-SAFE) likely=$((likely + 1)) ;; *) review=$((review + 1)) ;; @@ -120,10 +160,22 @@ classify_branch() { pr_line="#${PR_NUM[$branch]} ${PR_STATE[$branch]}" fi + if [[ "$no_upstream" == 1 ]]; then + if [[ -n "$ahead_default" ]]; then + unpushed_line="no upstream, ${ahead_default} commits not on origin/${DEFAULT_BRANCH}" + else + unpushed_line="no upstream (no origin/${DEFAULT_BRANCH} to compare)" + fi + else + ahead_up="$(git -C "$REPO_ROOT" rev-list --count "${branch}@{upstream}..refs/heads/${branch}" 2>/dev/null | tr -d '\r')" + unpushed_line="${ahead_up:-0} ahead of ${upstream}" + fi + printf 'Branch: %s\n' "$branch" printf 'Tier: %s\n' "$tier" printf 'Age days: %s\n' "$age_days" printf 'PR: %s\n' "$pr_line" + printf 'Unpushed: %s\n' "$unpushed_line" printf 'Reason: %s\n' "$reason" } @@ -135,5 +187,5 @@ while IFS= read -r line; do classify_branch "$branch" "$age_days" done < <(git -C "$REPO_ROOT" for-each-ref refs/heads/ --format='%(refname:short) %(committerdate:unix)' 2>/dev/null | tr -d '\r') -printf 'Summary: protected=%s safe=%s likely-safe=%s review=%s\n' "$prot" "$safe" "$likely" "$review" +printf 'Summary: protected=%s worktree=%s safe=%s likely-safe=%s review=%s\n' "$prot" "$wt" "$safe" "$likely" "$review" exit 0 diff --git a/plugins/repo-hygiene/skills/clean/scripts/git-branch-audit.test.sh b/plugins/repo-hygiene/skills/clean/scripts/git-branch-audit.test.sh index 15933dc5172..456fa501dbc 100755 --- a/plugins/repo-hygiene/skills/clean/scripts/git-branch-audit.test.sh +++ b/plugins/repo-hygiene/skills/clean/scripts/git-branch-audit.test.sh @@ -15,7 +15,7 @@ rc=0 bash "$AUDIT" --help >/dev/null 2>&1 || rc=$? assert_exit "--help exits 0" 0 "$rc" -git init "$TEST_TMPDIR/repo" >/dev/null 2>&1 +git init -b main "$TEST_TMPDIR/repo" >/dev/null 2>&1 git -C "$TEST_TMPDIR/repo" config user.email "t@example.com" git -C "$TEST_TMPDIR/repo" config user.name "Test" echo x >"$TEST_TMPDIR/repo/x" @@ -52,6 +52,110 @@ FAKEGH assert_contains "closed pr reason" "$closed_out" "PR closed without merge" fi +# A no-op gh stub keeps the worktree / no-upstream cases below deterministic and +# offline (the real gh would hit the network for its PR map). +STUB_BIN="$TEST_TMPDIR/stub-bin" +mkdir -p "$STUB_BIN" +printf '#!/usr/bin/env bash\nexit 1\n' >"$STUB_BIN/gh" +chmod +x "$STUB_BIN/gh" + +# Worktree exclusion: a branch checked out in a linked worktree is its own +# WORKTREE bucket — never a deletion candidate lumped under PROTECTED, and never +# offered for `git branch -d` (which would break the worktree). +WT_REPO="$TEST_TMPDIR/wt-repo" +git init -q -b main "$WT_REPO" +git -C "$WT_REPO" config user.email "t@example.com" +git -C "$WT_REPO" config user.name "Test" +echo x >"$WT_REPO/x" +git -C "$WT_REPO" add x +git -C "$WT_REPO" commit -qm init +git -C "$WT_REPO" branch feat/parked +git -C "$WT_REPO" worktree add -q "$TEST_TMPDIR/wt-linked" feat/parked +wt_out="$(PATH="$STUB_BIN:$PATH" bash -c "cd '$WT_REPO' && bash '$AUDIT'")" +assert_contains "worktree branch own tier" "$wt_out" "Tier: WORKTREE" +assert_contains "worktree branch reason" "$wt_out" "clean up the worktree first" +assert_contains "summary counts worktree bucket" "$wt_out" "worktree=1" + +# No-upstream classification: a never-pushed branch with commits not on +# origin/ is surfaced as its own class and Unpushed line, not left +# invisible behind @{upstream}-only ahead reporting. +NU_REPO="$TEST_TMPDIR/nu-repo" +git init -q --bare "$TEST_TMPDIR/nu-origin.git" +git init -q -b main "$NU_REPO" +git -C "$NU_REPO" config user.email "t@example.com" +git -C "$NU_REPO" config user.name "Test" +echo a >"$NU_REPO/a" +git -C "$NU_REPO" add a +git -C "$NU_REPO" commit -qm init +git -C "$NU_REPO" remote add origin "$TEST_TMPDIR/nu-origin.git" +git -C "$NU_REPO" push -q origin HEAD:main +git -C "$NU_REPO" symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main +git -C "$NU_REPO" checkout -q -b feat/never-pushed +echo b >"$NU_REPO/b" +git -C "$NU_REPO" add b +git -C "$NU_REPO" commit -qm b +git -C "$NU_REPO" checkout -q main +nu_out="$(PATH="$STUB_BIN:$PATH" bash -c "cd '$NU_REPO' && bash '$AUDIT'")" +assert_contains "no-upstream unpushed line" "$nu_out" "no upstream, 1 commits not on origin/main" +assert_contains "no-upstream own review class" "$nu_out" "Reason: no upstream, 1 commits not on origin/main" + +# A configured upstream whose tracking ref is unfetched still counts as no-upstream: +# `rev-parse --abbrev-ref` echoes the literal input on failure, which must not be +# mistaken for a real upstream (it would print `@{upstream}` as the ahead +# base). Configure tracking, then delete the remote-tracking ref to simulate it. +git -C "$NU_REPO" checkout -q -b feat/tracked-unfetched +echo c >"$NU_REPO/c" +git -C "$NU_REPO" add c +git -C "$NU_REPO" commit -qm c +git -C "$NU_REPO" config branch.feat/tracked-unfetched.remote origin +git -C "$NU_REPO" config branch.feat/tracked-unfetched.merge refs/heads/feat/tracked-unfetched +git -C "$NU_REPO" checkout -q main +uf_out="$(PATH="$STUB_BIN:$PATH" bash -c "cd '$NU_REPO' && bash '$AUDIT'")" +assert_not_contains "unfetched upstream not echoed literally" "$uf_out" "@{upstream}" +assert_contains "unfetched upstream falls to no-upstream count" "$uf_out" "no upstream, 1 commits not on origin/main" + +# A branch whose upstream is GONE but that still carries commits not on +# origin/ is unmerged local work — it must be REVIEW, not the LIKELY-SAFE +# deletion candidate the bare `gone` check would assign (deleting it loses those +# commits). +git -C "$NU_REPO" checkout -q -b feat/gone +echo g >"$NU_REPO/g" +git -C "$NU_REPO" add g +git -C "$NU_REPO" commit -qm g +git -C "$NU_REPO" push -q -u origin feat/gone +echo g2 >>"$NU_REPO/g" +git -C "$NU_REPO" add g +git -C "$NU_REPO" commit -qm g2 +git -C "$NU_REPO" push -q origin --delete feat/gone +git -C "$NU_REPO" fetch -q --prune origin +git -C "$NU_REPO" checkout -q main +gone_out="$(PATH="$STUB_BIN:$PATH" bash -c "cd '$NU_REPO' && bash '$AUDIT'")" +assert_contains "gone+unpushed is review not likely-safe" "$gone_out" "Reason: upstream gone, 2 commits not on origin/main" + +# Gone upstream with NO origin/ to compare against (feature-only clone / +# unfetched remote HEAD): the script cannot prove the branch is merged, so it must +# fail closed to REVIEW, not offer it as a deletable LIKELY-SAFE candidate. +GC_REPO="$TEST_TMPDIR/gc-repo" +git init -q --bare "$TEST_TMPDIR/gc-origin.git" +git init -q -b main "$GC_REPO" +git -C "$GC_REPO" config user.email "t@example.com" +git -C "$GC_REPO" config user.name "Test" +echo a >"$GC_REPO/a" +git -C "$GC_REPO" add a +git -C "$GC_REPO" commit -qm init +git -C "$GC_REPO" remote add origin "$TEST_TMPDIR/gc-origin.git" +git -C "$GC_REPO" checkout -q -b feat/gone-nocmp +echo g >"$GC_REPO/g" +git -C "$GC_REPO" add g +git -C "$GC_REPO" commit -qm g +git -C "$GC_REPO" push -q -u origin feat/gone-nocmp +git -C "$GC_REPO" push -q origin --delete feat/gone-nocmp +git -C "$GC_REPO" fetch -q --prune origin +git -C "$GC_REPO" checkout -q main +gc_out="$(PATH="$STUB_BIN:$PATH" bash -c "cd '$GC_REPO' && bash '$AUDIT'")" +assert_contains "gone + no default to compare fails closed to review" "$gc_out" "Reason: upstream gone, cannot compare against origin/main" +assert_not_contains "gone + no default is never likely-safe" "$gc_out" "Tier: LIKELY-SAFE" + if [[ $FAILED -ne 0 ]]; then echo "FAILED: $FAILED test(s)" exit 1 diff --git a/plugins/repo-hygiene/skills/clean/scripts/git-stash-audit.sh b/plugins/repo-hygiene/skills/clean/scripts/git-stash-audit.sh new file mode 100755 index 00000000000..8d52414229f --- /dev/null +++ b/plugins/repo-hygiene/skills/clean/scripts/git-stash-audit.sh @@ -0,0 +1,121 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2154 +# Stash audit facts for the clean git tier. No stash is ever dropped. +# +# Output contract (stable labels): +# StashStore: (dedup key across worktrees) +# per stash — Stash, Commit, Age days, Source branch, Diffstat, PR, Advisory +# Stash count: +# Summary: stashes= likely-superseded= (never auto-dropped) +# `Stash` is the volatile `stash@{n}` selector (renumbers after every drop); +# `Commit` is the stash's stable object id — the safe handle when dropping more +# than one stash from a single audit. +# Exit: 0. +# Omit -e/-o pipefail: always exits 0; sub-commands are best-effort (gh may be absent). +set -u + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=lib/clean-common.sh source=lib/cleanup-paths.sh +source "$SCRIPT_DIR/lib/clean-common.sh" + +usage() { + cat <<'EOF' +git-stash-audit.sh — emit stash audit facts for the clean git tier. + +Usage: + git-stash-audit.sh + git-stash-audit.sh --help + +Never drops a stash (read-only). Exit: 0. +EOF +} + +case "${1:-}" in +-h | --help) + usage + exit 0 + ;; +*) ;; +esac + +REPO_ROOT="$(clean_repo_root)" +if [[ -z "$REPO_ROOT" ]]; then + echo "Error: not a git repository" + exit 0 +fi + +# Linked worktrees share one stash ref (stored against the common git dir), so a +# fleet sweep visiting several worktrees of the same repo must dedup on this key +# rather than counting each worktree's identical stash list. +COMMON_DIR="$(git -C "$REPO_ROOT" rev-parse --path-format=absolute --git-common-dir 2>/dev/null | tr -d '\r')" +[[ -z "$COMMON_DIR" ]] && COMMON_DIR="$(git -C "$REPO_ROOT" rev-parse --git-common-dir 2>/dev/null | tr -d '\r')" +printf 'StashStore: %s\n' "${COMMON_DIR:-unknown}" + +DEFAULT_BRANCH="$(git -C "$REPO_ROOT" symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's|^refs/remotes/origin/||' | tr -d '\r')" +if [[ -z "$DEFAULT_BRANCH" ]] && command -v gh >/dev/null 2>&1; then + DEFAULT_BRANCH="$(gh repo view --json defaultBranchRef -q .defaultBranchRef.name 2>/dev/null | tr -d '\r')" +fi +DEFAULT_BRANCH="${DEFAULT_BRANCH:-main}" + +# PR map (best-effort): source-branch → state, so a stash whose source branch was +# merged can be flagged likely-superseded. Same batched gh call as the branch audit. +declare -A PR_STATE=() +declare -A PR_NUM=() +if command -v gh >/dev/null 2>&1; then + while IFS=$'\t' read -r head state num; do + [[ -z "$head" ]] && continue + PR_STATE["$head"]="$state" + PR_NUM["$head"]="$num" + done < <(gh pr list --state all --json headRefName,state,number --limit 200 2>/dev/null | + jq -r '.[] | [.headRefName, .state, .number] | @tsv' 2>/dev/null | tr -d '\r') +fi + +NOW=$(date +%s) +count=0 superseded=0 + +while IFS=$'\t' read -r sel sha ts subject; do + [[ -z "$sel" ]] && continue + count=$((count + 1)) + age_days=$(((NOW - ts) / 86400)) + # Source branch from the stash subject ("WIP on X: …" / "On X: …"). + src="$(printf '%s' "$subject" | sed -n 's/^\(WIP on\|On\) \([^:]*\):.*/\2/p')" + src="${src:-unknown}" + # Prefer the untracked-inclusive stat (a `stash -u` pre-rebase backup is often + # all untracked, invisible to the default stat); fall back to the tracked-only + # stat on git too old for --include-untracked, then to a plain marker. + diffstat="$(git -C "$REPO_ROOT" stash show --include-untracked --stat "$sel" 2>/dev/null | tail -1 | sed 's/^[[:space:]]*//')" + [[ -z "$diffstat" ]] && diffstat="$(git -C "$REPO_ROOT" stash show --stat "$sel" 2>/dev/null | tail -1 | sed 's/^[[:space:]]*//')" + [[ -z "$diffstat" ]] && diffstat="(no tracked changes)" + + pr_line="none" + advisory="review — confirm with the user before dropping (never auto-dropped)" + if [[ "$src" != "unknown" && -n "${PR_STATE[$src]:-}" ]]; then + pr_line="#${PR_NUM[$src]} ${PR_STATE[$src]}" + if [[ "${PR_STATE[$src]}" == "MERGED" ]]; then + advisory="likely superseded — source branch PR merged; still confirm before dropping" + superseded=$((superseded + 1)) + fi + elif [[ "$src" != "unknown" && "$src" != "$DEFAULT_BRANCH" ]] && + git -C "$REPO_ROOT" rev-parse --verify --quiet "refs/remotes/origin/${DEFAULT_BRANCH}" >/dev/null 2>&1 && + git -C "$REPO_ROOT" show-ref --verify --quiet "refs/heads/${src}" && + [[ -z "$(git -C "$REPO_ROOT" rev-list "origin/${DEFAULT_BRANCH}..refs/heads/${src}" 2>/dev/null | head -1)" ]]; then + # No PR record but the source branch is fully merged into origin/: + # its committed work is on the default branch, so the stash is more likely a + # superseded pre-merge backup. The stash's own diff may still be unique — hence + # advisory only, never auto-drop. + advisory="possibly superseded — source branch merged into origin/${DEFAULT_BRANCH}; confirm before dropping" + superseded=$((superseded + 1)) + fi + + printf 'Stash: %s\n' "$sel" + printf 'Commit: %s\n' "$sha" + printf 'Age days: %s\n' "$age_days" + printf 'Source branch: %s\n' "$src" + printf 'Diffstat: %s\n' "$diffstat" + printf 'PR: %s\n' "$pr_line" + printf 'Advisory: %s\n' "$advisory" +done < <(git -C "$REPO_ROOT" stash list --format='%gd%x09%H%x09%ct%x09%gs' 2>/dev/null | tr -d '\r') + +printf 'Stash count: %s\n' "$count" +printf 'Summary: stashes=%s likely-superseded=%s (never auto-dropped)\n' "$count" "$superseded" +exit 0 diff --git a/plugins/repo-hygiene/skills/clean/scripts/git-stash-audit.test.sh b/plugins/repo-hygiene/skills/clean/scripts/git-stash-audit.test.sh new file mode 100755 index 00000000000..bb7f8b19a8d --- /dev/null +++ b/plugins/repo-hygiene/skills/clean/scripts/git-stash-audit.test.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# Tests for git-stash-audit.sh +set -uo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=lib/test-helpers.sh +source "$SCRIPT_DIR/lib/test-helpers.sh" + +AUDIT="$SCRIPT_DIR/git-stash-audit.sh" +TEST_TMPDIR="$(mktemp -d)" +trap 'rm -rf "$TEST_TMPDIR"' EXIT +FAILED=0 + +rc=0 +bash "$AUDIT" --help >/dev/null 2>&1 || rc=$? +assert_exit "--help exits 0" 0 "$rc" + +# A no-op gh stub keeps the audit deterministic and offline. +STUB_BIN="$TEST_TMPDIR/stub-bin" +mkdir -p "$STUB_BIN" +printf '#!/usr/bin/env bash\nexit 1\n' >"$STUB_BIN/gh" +chmod +x "$STUB_BIN/gh" + +# Empty repo: no stashes → count 0, never an error, exit 0. +# `-b main` pins the initial branch so the assertions below hold on machines where +# `git init` still defaults to `master`. +git init -q -b main "$TEST_TMPDIR/empty" +git -C "$TEST_TMPDIR/empty" config user.email "t@example.com" +git -C "$TEST_TMPDIR/empty" config user.name "Test" +echo x >"$TEST_TMPDIR/empty/x" +git -C "$TEST_TMPDIR/empty" add x +git -C "$TEST_TMPDIR/empty" commit -qm init +empty_out="$(PATH="$STUB_BIN:$PATH" bash -c "cd '$TEST_TMPDIR/empty' && bash '$AUDIT'")" +assert_contains "emits stash store key" "$empty_out" "StashStore:" +assert_contains "zero stash count" "$empty_out" "Stash count: 0" +assert_contains "summary line" "$empty_out" "Summary: stashes=0" + +# Populated repo: a stash on the default branch is live WIP (never superseded), +# a stash whose source branch merged into origin/ is flagged possibly +# superseded — but only ever as advisory, never dropped. +REPO="$TEST_TMPDIR/repo" +git init -q --bare "$TEST_TMPDIR/origin.git" +git init -q -b main "$REPO" +git -C "$REPO" config user.email "t@example.com" +git -C "$REPO" config user.name "Test" +echo a >"$REPO/a" +git -C "$REPO" add a +git -C "$REPO" commit -qm init +git -C "$REPO" remote add origin "$TEST_TMPDIR/origin.git" +git -C "$REPO" push -q origin HEAD:main +git -C "$REPO" symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main +echo change >"$REPO/a" +git -C "$REPO" stash push -q -m "live wip on main" +git -C "$REPO" checkout -q -b feat/done +echo b >"$REPO/b" +git -C "$REPO" add b +git -C "$REPO" commit -qm b +git -C "$REPO" checkout -q main +git -C "$REPO" merge -q feat/done +git -C "$REPO" push -q origin main +git -C "$REPO" checkout -q feat/done +echo edit >>"$REPO/b" +git -C "$REPO" stash push -q -m "pre-merge backup" +git -C "$REPO" checkout -q main +out="$(PATH="$STUB_BIN:$PATH" bash -c "cd '$REPO' && bash '$AUDIT'")" +assert_contains "counts both stashes" "$out" "Stash count: 2" +assert_contains "emits diffstat" "$out" "Diffstat:" +assert_contains "attributes source branch" "$out" "Source branch: feat/done" +assert_contains "merged source flagged superseded" "$out" "possibly superseded" +# A stash on the default branch is live WIP, never flagged superseded. +assert_contains "main stash stays review" "$out" "review — confirm with the user" +assert_contains "never auto-dropped disclaimer" "$out" "never auto-dropped" +# Each stash carries its stable commit id — the safe handle for multi-drop, since +# the stash@{n} selector renumbers after every drop. +sha0="$(git -C "$REPO" rev-parse "stash@{0}" 2>/dev/null)" +assert_contains "emits stable stash commit id" "$out" "Commit: $sha0" + +if [[ $FAILED -ne 0 ]]; then + echo "FAILED: $FAILED test(s)" + exit 1 +fi +echo "OK: git-stash-audit.sh tests passed" diff --git a/plugins/repo-hygiene/skills/clean/scripts/lib/cleanup-paths.sh b/plugins/repo-hygiene/skills/clean/scripts/lib/cleanup-paths.sh index d6fd3abcbe5..7e149a6885a 100644 --- a/plugins/repo-hygiene/skills/clean/scripts/lib/cleanup-paths.sh +++ b/plugins/repo-hygiene/skills/clean/scripts/lib/cleanup-paths.sh @@ -5,15 +5,13 @@ # Heavy trees that hold no cleanup targets we own — never descended by the # single-walk enumeration (`-prune`) and, symmetrically, never accepted from a -# manifest at `--apply`, so both sides share one prune set. SSOT: the scan tier -# still uses the per-glob CLEAN_FIND_EXCLUDE_* below (its migration to this walk -# is deferred). +# manifest at `--apply`, so both sides share one prune set. The caches/build/scan +# tiers all enumerate through this engine; only preflight's narrow recent-build +# probe still runs a standalone find (CLEAN_FIND_EXCLUDE_GIT below). CLEAN_PRUNE_DIRS=(.git node_modules .venv) -# Universal find exclusions (cleanup-config.md intro) +# Standalone-find exclusion for preflight's recent-build probe (cleanup-config.md intro). CLEAN_FIND_EXCLUDE_GIT='*/.git/*' -CLEAN_FIND_EXCLUDE_VENV='*/.venv/*' -CLEAN_FIND_EXCLUDE_NODE_MODULES='*/node_modules/*' # caches — explicit repo-root paths (trailing slash = directory; no slash on files). # Generic across ecosystems; regenerated on the next tool run. diff --git a/plugins/repo-hygiene/skills/clean/scripts/resolve-clean-action.sh b/plugins/repo-hygiene/skills/clean/scripts/resolve-clean-action.sh index 29dbcb2f59c..585c12c230b 100755 --- a/plugins/repo-hygiene/skills/clean/scripts/resolve-clean-action.sh +++ b/plugins/repo-hygiene/skills/clean/scripts/resolve-clean-action.sh @@ -1,7 +1,9 @@ #!/usr/bin/env bash # Map clean-skill user tokens to canonical action names (Tier-0 fact emission). # -# Output: Action: +# Output: Action: +# plus an optional `Note: ` when a leading action token is +# followed by advisory context (a question or a live-session constraint). # Exit: 0 always. set -u @@ -47,6 +49,9 @@ resolve_one() { git | branches | branch | prune | gc) printf 'git' ;; + stash | stashes | stash-audit) + printf 'stash' + ;; tree | fresh | fresh-pull | fresh-pull-state | pristine | reset-tree | working-tree) printf 'tree' ;; @@ -133,27 +138,56 @@ if [[ -n "$sel" && "$sel" != "__conflict__" ]] && has_fleet_indicator "$joined"; fi canonical="" -for token in "$@"; do - lower="$(printf '%s' "$token" | tr '[:upper:]' '[:lower:]')" - hit="$(resolve_one "$lower")" - # A bare "all" token is the single-repo `all` tier, but inside a fleet phrase it - # names a multi-repo sweep. Reset/fresh-pull phrasing ("reset all my repos") is - # the DESTRUCTIVE tree-batch; a plain fleet cleanup ("clean all repos", "sweep - # across all repos") is the SELECTIVE all-batch — never preview a reset-hard for - # an innocuous all-tier request. A genuine conflict with another explicit token - # (e.g. "scan all repos") still falls to the menu via the mismatch check below. - if [[ "$hit" == "all" ]] && is_fleet_phrase "$joined"; then - if has_reset_intent "$joined"; then hit=tree-batch; else hit=all-batch; fi - fi - if [[ -n "$hit" ]]; then - if [[ -z "$canonical" ]]; then - canonical="$hit" - elif [[ "$canonical" != "$hit" ]]; then - printf 'Action: menu\n' - exit 0 +note="" + +# "Action token + advisory note" shape: a leading action token followed by free +# text (a question or a live-session constraint), where that trailing text is NOT +# itself a second action token and the whole input carries no fleet indicator. The +# note must not be re-interpreted as an action — so trailing text that merely +# mentions an action word (e.g. "…include stashes?") does not read as a conflict. +# A genuine second action token (e.g. "scan tree", "scan all repos") is left to the +# full-token resolution below, which reports the ambiguity as `menu`. Gate on +# has_fleet_indicator (not just is_fleet_phrase) so a fleet request the phrase list +# misses ("all across the fleet") routes to the batch tier below instead of being +# preempted into a single-repo action with the fleet words demoted to a note. +first_lower="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" +first_action="$(resolve_one "$first_lower")" +second_action="" +if [[ $# -ge 2 ]]; then + second_lower="$(printf '%s' "$2" | tr '[:upper:]' '[:lower:]')" + second_action="$(resolve_one "$second_lower")" +fi +if [[ -n "$first_action" && $# -ge 2 && -z "$second_action" ]] && ! has_fleet_indicator "$joined"; then + canonical="$first_action" + shift + note="$*" + note="${note#"${note%%[![:space:]]*}"}" + note="${note%"${note##*[![:space:]]}"}" +fi + +if [[ -z "$canonical" ]]; then + for token in "$@"; do + lower="$(printf '%s' "$token" | tr '[:upper:]' '[:lower:]')" + hit="$(resolve_one "$lower")" + # A bare "all" token is the single-repo `all` tier, but inside a fleet phrase it + # names a multi-repo sweep. Reset/fresh-pull phrasing ("reset all my repos") is + # the DESTRUCTIVE tree-batch; a plain fleet cleanup ("clean all repos", "sweep + # across all repos") is the SELECTIVE all-batch — never preview a reset-hard for + # an innocuous all-tier request. A genuine conflict with another explicit token + # (e.g. "scan all repos") still falls to the menu via the mismatch check below. + if [[ "$hit" == "all" ]] && is_fleet_phrase "$joined"; then + if has_reset_intent "$joined"; then hit=tree-batch; else hit=all-batch; fi fi - fi -done + if [[ -n "$hit" ]]; then + if [[ -z "$canonical" ]]; then + canonical="$hit" + elif [[ "$canonical" != "$hit" ]]; then + printf 'Action: menu\n' + exit 0 + fi + fi + done +fi if [[ -z "$canonical" ]]; then if is_fleet_phrase "$joined"; then @@ -181,5 +215,6 @@ if [[ -z "$canonical" ]]; then printf 'Action: menu\n' else printf 'Action: %s\n' "$canonical" + [[ -n "$note" ]] && printf 'Note: %s\n' "$note" fi exit 0 diff --git a/plugins/repo-hygiene/skills/clean/scripts/resolve-clean-action.test.sh b/plugins/repo-hygiene/skills/clean/scripts/resolve-clean-action.test.sh index b7992870e45..36693a5b7a1 100755 --- a/plugins/repo-hygiene/skills/clean/scripts/resolve-clean-action.test.sh +++ b/plugins/repo-hygiene/skills/clean/scripts/resolve-clean-action.test.sh @@ -17,6 +17,24 @@ assert_action() { assert_contains "$label" "$out" "Action: $want" } +# assert_note LABEL WANT ARG... — args passed verbatim (each a distinct token) so +# a multi-word note stays one logical note. +assert_note() { + local label="$1" want="$2" + shift 2 + local out + out="$(bash "$RESOLVE" "$@")" + assert_contains "$label" "$out" "Note: $want" +} + +assert_no_note() { + local label="$1" + shift + local out + out="$(bash "$RESOLVE" "$@")" + assert_not_contains "$label" "$out" "Note:" +} + assert_action "empty -> menu" "" "menu" assert_action "scan" "scan" "scan" assert_action "inventory alias" "inventory" "scan" @@ -24,6 +42,9 @@ assert_action "fresh alias" "fresh" "tree" assert_action "fresh-pull alias" "fresh-pull" "tree" assert_action "build alias" "artifacts" "build" assert_action "git alias" "branches" "git" +assert_action "stash token" "stash" "stash" +assert_action "stashes alias" "stashes" "stash" +assert_action "stash-audit alias" "stash-audit" "stash" assert_action "tree-batch token" "tree-batch" "tree-batch" assert_action "batch alias" "batch" "tree-batch" assert_action "fleet alias" "fleet" "tree-batch" @@ -67,6 +88,23 @@ assert_action "everything alias -> single-repo all" "everything" "all" # A genuine conflict (explicit non-all token + fleet phrase) still routes to menu. assert_action "scan + fleet phrase -> menu" "scan all repos" "menu" +# Multi-arg intent: a leading action token still resolves, and the trailing free +# text (a question, live-session constraints) surfaces as an advisory Note. +assert_action "action token before note still resolves" "all mind the live sessions" "all" +assert_note "trailing text becomes note" "mind the live sessions" all mind the live sessions +assert_note "question after action becomes note" "does this include stashes" scan does this include stashes +# A single quoted multi-line note stays one note verbatim. +assert_note "multiline note preserved" $'6-7 live sessions\nmind WIP' all $'6-7 live sessions\nmind WIP' +# No spurious note when the action stands alone or the whole input is one phrase. +assert_no_note "bare action emits no note" all +assert_no_note "fleet phrase emits no note" reset all my repos +# A fleet indicator the phrase list misses ("across the fleet") must not be +# preempted by the note path into a single-repo `all` with the fleet words demoted +# to a note — it goes to the fleet/batch resolution (here menu, since bare `fleet` +# is itself the destructive tree-batch token, conflicting with the `all` tier). +assert_no_note "fleet indicator not demoted to a note" all across the fleet +assert_action "fleet all-indicator is not single-repo all" "all across the fleet" "menu" + if [[ $FAILED -ne 0 ]]; then echo "FAILED: $FAILED test(s)" exit 1 diff --git a/plugins/repo-hygiene/skills/clean/scripts/scan.sh b/plugins/repo-hygiene/skills/clean/scripts/scan.sh index f497dfded0e..88552e3e61f 100755 --- a/plugins/repo-hygiene/skills/clean/scripts/scan.sh +++ b/plugins/repo-hygiene/skills/clean/scripts/scan.sh @@ -48,17 +48,18 @@ format_size() { } emit_path_line() { - local category="$1" tier="$2" rel="$3" abs - abs="$REPO_ROOT/$rel" + local category="$1" tier="$2" abs="$3" rel kb [[ -e "$abs" ]] || return 0 if clean_path_is_protected "$REPO_ROOT" "$abs"; then return 0 fi + rel="${abs#"$REPO_ROOT"/}" printf 'Category: %s\n' "$category" printf 'Path: %s\n' "$rel" printf 'Size: %s\n' "$(format_size "$abs")" printf 'Tier: %s\n' "$tier" - TOTAL_BYTES=$((TOTAL_BYTES + $(du -sk "$abs" 2>/dev/null | awk '{print $1}') * 1024)) + kb="$(du -sk "$abs" 2>/dev/null | awk '{print $1}')" + TOTAL_BYTES=$((TOTAL_BYTES + ${kb:-0} * 1024)) } REPO_ROOT="$(clean_repo_root)" @@ -71,57 +72,18 @@ fi cd "$REPO_ROOT" || exit 0 -for rel in "${CLEAN_CACHE_EXPLICIT[@]}"; do - emit_path_line "Caches" "caches" "$rel" -done - -for rel in "${CLEAN_CACHE_EXPLICIT_FILES[@]}"; do - emit_path_line "Caches" "caches" "$rel" -done - -for name in "${CLEAN_CACHE_FIND_DIR_NAMES[@]}"; do - while IFS= read -r abs; do - [[ -z "$abs" ]] && continue - rel="${abs#"$REPO_ROOT"/}" - emit_path_line "Caches" "caches" "$rel" - done < <(find "$REPO_ROOT" -type d -name "$name" \ - ! -path "$CLEAN_FIND_EXCLUDE_GIT" \ - ! -path "$CLEAN_FIND_EXCLUDE_VENV" \ - ! -path "$CLEAN_FIND_EXCLUDE_NODE_MODULES" 2>/dev/null) -done - -for glob in "${CLEAN_CACHE_FIND_FILE_GLOBS[@]}"; do - while IFS= read -r abs; do - [[ -z "$abs" ]] && continue - rel="${abs#"$REPO_ROOT"/}" - emit_path_line "Caches" "caches" "$rel" - done < <(find "$REPO_ROOT" -type f -name "$glob" \ - ! -path "$CLEAN_FIND_EXCLUDE_GIT" \ - ! -path "$CLEAN_FIND_EXCLUDE_VENV" \ - ! -path "$CLEAN_FIND_EXCLUDE_NODE_MODULES" 2>/dev/null | head -50) -done - -for name in "${CLEAN_BUILD_DIR_NAMES[@]}"; do - while IFS= read -r abs; do - [[ -z "$abs" ]] && continue - rel="${abs#"$REPO_ROOT"/}" - emit_path_line "Build artifacts" "build" "$rel" - done < <(find "$REPO_ROOT" -type d -name "$name" \ - ! -path "$CLEAN_FIND_EXCLUDE_GIT" \ - ! -path "$CLEAN_FIND_EXCLUDE_VENV" \ - ! -path "$CLEAN_FIND_EXCLUDE_NODE_MODULES" 2>/dev/null | head -100) -done - -for glob in "${CLEAN_BUILD_FILE_GLOBS[@]}"; do - while IFS= read -r abs; do - [[ -z "$abs" ]] && continue - rel="${abs#"$REPO_ROOT"/}" - emit_path_line "Build artifacts" "build" "$rel" - done < <(find "$REPO_ROOT" -type f -name "$glob" \ - ! -path "$CLEAN_FIND_EXCLUDE_GIT" \ - ! -path "$CLEAN_FIND_EXCLUDE_VENV" \ - ! -path "$CLEAN_FIND_EXCLUDE_NODE_MODULES" 2>/dev/null | head -50) -done +# Enumeration shares the single pruned-walk engine with the mutating caches/build +# tiers (clean-common.sh) so the read-only inventory and the tiers that act on it +# report the same targets from one walk that never descends .git/node_modules/.venv. +while IFS= read -r abs; do + [[ -z "$abs" ]] && continue + emit_path_line "Caches" "caches" "$abs" +done < <(clean_caches_candidates "$REPO_ROOT") + +while IFS= read -r abs; do + [[ -z "$abs" ]] && continue + emit_path_line "Build artifacts" "build" "$abs" +done < <(clean_build_candidates "$REPO_ROOT") WT_COUNT="$(git worktree list 2>/dev/null | wc -l | tr -d ' ')" echo "Git worktrees: ${WT_COUNT:-0}" diff --git a/plugins/repo-hygiene/skills/clean/scripts/scan.test.sh b/plugins/repo-hygiene/skills/clean/scripts/scan.test.sh index b2be7c287bc..b058156f371 100755 --- a/plugins/repo-hygiene/skills/clean/scripts/scan.test.sh +++ b/plugins/repo-hygiene/skills/clean/scripts/scan.test.sh @@ -37,6 +37,17 @@ assert_contains "finds untracked cache" "$out" ".ruff_cache" assert_contains "emits category" "$out" "Category:" assert_contains "emits total" "$out" "Total reclaimable:" +# Single pruned-walk engine: a build dir NESTED inside a pruned tree +# (node_modules) is never descended into, while a top-level build dir still +# enumerates. This proves the walk prunes rather than merely filters output. +mkdir -p "$TEST_TMPDIR/repo/node_modules/pkg/bin" +echo z >"$TEST_TMPDIR/repo/node_modules/pkg/bin/z" +mkdir -p "$TEST_TMPDIR/repo/src/bin" +echo z >"$TEST_TMPDIR/repo/src/bin/z" +out="$(GIT_DIR="$TEST_TMPDIR/repo/.git" GIT_WORK_TREE="$TEST_TMPDIR/repo" bash -c "cd '$TEST_TMPDIR/repo' && bash '$SCAN'")" +assert_contains "top-level build dir inventoried" "$out" "src/bin" +assert_not_contains "build dir under pruned node_modules skipped" "$out" "node_modules/pkg/bin" + if [[ $FAILED -ne 0 ]]; then echo "FAILED: $FAILED test(s)" exit 1