[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79QABW7RRFBYRAP0TDZ2QKP":3,"skill-same:01M79QABW7RRFBYRAP0TDZ2QKP":86},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":13,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":43},"01M79QABW7RRFBYRAP0TDZ2QKP","git-cleanup",null,"Safely analyzes and cleans up local git branches and worktrees by categorizing them as merged, squash-merged, superseded, or active work.","AndreHahm\u002Fandres-cc-marketplace","AndreHahm","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F80748019?v=4","01M79N2VZJT9MAJ7K695C9VXQ4","01M79N2W06PFX8BSCQ592M8K8K",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: git-cleanup\ndescription: >-\n  Safely analyzes and cleans up local git branches and worktrees by categorizing them as merged, squash-merged, superseded, or active work.\ndisable-model-invocation: true\nallowed-tools: Bash(git branch:*), Bash(git worktree:*), Bash(git fetch:*), Bash(git log:*), Bash(git status:*), Bash(git symbolic-ref:*), Bash(git -C:*), Bash(gh pr view:*), Bash(gh repo view:*), Bash(gh api -X DELETE repos\u002F*\u002Fgit\u002Frefs\u002Fheads\u002F*:*), Bash(bash ${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh:*), Bash(*\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fphase1-analysis.sh:*), Bash(*\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh:*), Read, Grep\n---\n\n# Git Cleanup\n\nSafely clean up accumulated git worktrees and local branches by categorizing them into: safely deletable (merged), potentially related (similar themes), and active work (keep).\n\n**On the `Bash(git -C:*)` grant:** this is broad by necessity, not oversight — Phase 4's dirty-state and\ngitignored-content checks run `git -C \u003Cworktree-path> status --porcelain[--ignored]` against a worktree\npath that's only known at runtime, and `Bash(prefix:*)` permission syntax can't express \"any `-C \u003Cpath>`\nbut only followed by `status`\" without a wrapper script. Reviewed 2026-08-11 (git-kit retro follow-up);\nno narrower grant is expressible with the current permission syntax.\n\n## Quick Start\n\n1. Run from a session in the primary checkout, only on the user's explicit `\u002Fgit-cleanup`.\n2. Analyze and group branches, remote leftovers and rebase-backup tags (Phases 1-3.6), then check every\n   worktree for dirty and gitignored content with `git -C`, never `cd` (Phase 4).\n3. Gate 1: present the analysis. Gate 2: confirm the exact deletions, then execute (Phase 5).\n4. Report what was deleted and what remains (Phase 6); optionally offer Phase 7's guided tag review.\n\n## When to Use\n\n- When the user has accumulated many local branches and worktrees\n- When branches have been merged but not cleaned up locally\n- When remote branches have been deleted but local tracking branches remain\n\n## When NOT to Use\n\n- Do not use for general remote branch management (this is local cleanup only) — **narrow exception:**\n  Phase 3.5's remote-branch fallback deletes a remote branch only when its own PR is live-confirmed\n  `MERGED` via `gh pr view`, as a repair for a known `gh pr merge --delete-branch` failure mode (see\n  Phase 3.5 for the mechanism). It never deletes a remote branch for any other reason — an open PR, no\n  PR at all, or \"no local counterpart\" alone are never sufficient by themselves.\n- Do not use for repository maintenance tasks like gc or prune\n- Not designed for headless or non-interactive automation (requires user confirmations at two gates)\n- Cannot run from a session sandboxed to a worktree checkout — this command needs to operate on the\n  primary checkout's branch\u002Fworktree list, and a worktree-sandboxed session cannot `cd` there. Run it from\n  a session started in the primary checkout instead. See `finishing-work`'s hand-off note for the same\n  constraint on the more common path into this skill.\n\n## Core Principle: SAFETY FIRST\n\n**Never delete anything without explicit user confirmation.** This skill uses a gated workflow where users must approve each step before any destructive action.\n\n## Critical Implementation Notes\n\nSee [references\u002Fcritical-implementation-notes.md](references\u002Fcritical-implementation-notes.md) for the\nsquash-merge `-D` requirement, the PR-history investigation commands and why Safety Rule 10's\nrebase-backup tag reachability check is built the way it is — the branch-grouping procedure\nitself is already fully covered by Phase 2 below, so the reference file doesn't restate it. Read the\nreference before Phase 3 (Categorize) for the squash-merge nuance; the PR-history commands apply\nspecifically to `[gone]` branches within Phase 2\u002F3.\n\n## Workflow\n\n### Phase 1: Comprehensive Analysis\n\nGather ALL information upfront before any categorization. Run `\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fphase1-analysis.sh\"` directly via `Bash` — it resolves the default branch, lists local branches and worktrees, fetches\u002Fprunes, gets merged-branch and recent PR-merge history, and for each non-protected branch (protected names excluded via the script's own `grep -vE` filter) reports unmerged and unpushed commits plus whether its `origin\u002F\u003Cbranch>` counterpart still exists. It also lists remote-only branches with no local counterpart at all (candidates for Phase 3.5's fallback), and every local `*-rebase-backup-*` tag left over from `git-rebase-sync`'s pre-rebase safety backup, alongside its derived branch name and that branch's current status (candidates for Phase 3.6's cleanup). Read its output rather than re-deriving these git calls by hand.\n\n**Note on branch names:** Git branch names can contain characters that break shell expansion. Always quote `\"$branch\"` in commands.\n\n### Phase 2: Group Related Branches\n\n**Do this BEFORE individual categorization.**\n\nIdentify branch groups by shared prefixes:\n\n```bash\n# List branches and extract prefixes\ngit branch --format='%(refname:short)' | sed 's\u002F-[^-]*$\u002F\u002F' | sort | uniq -c | sort -rn\n```\n\nFor each group with 2+ branches:\n\n1. **Compare commit histories** - Which branches contain commits from others?\n2. **Find merge evidence** - Which PRs incorporated work from this group?\n3. **Identify the \"final\" branch** - Usually the most recent or most complete\n4. **Mark superseded branches** - Older iterations whose work is in main or in a newer branch\n\n**SUPERSEDED requires evidence, not just shared prefix:**\n- A PR merged the work into main, OR\n- A newer branch contains all commits from the older branch\n- Name prefix alone is NOT sufficient — similarly named branches may contain independent work\n\nExample analysis for `feat\u002Fapi-*` branches:\n\n```markdown\n### Related Branch Group: feat\u002Fapi-*\n\n| Branch | Commits | PR Merged | Status |\n|--------|---------|-----------|--------|\n| feat\u002Fapi | 12 | #29 (initial API) | Superseded - work in main |\n| feat\u002Fapi-v2 | 8 | #45 (API improvements) | Superseded - work in main |\n| feat\u002Fapi-refactor | 5 | #67 (refactor) | Superseded - work in main |\n| feat\u002Fapi-final | 4 | None found | Superseded by above PRs |\n\n**Recommendation:** All 4 branches can be deleted - work incorporated via PRs #29, #45, #67\n```\n\n### Phase 3: Categorize Remaining Branches\n\nFor branches NOT in a related group, categorize individually:\n\n```\nIs branch merged into default branch?\n├─ YES → SAFE_TO_DELETE (use -d)\n└─ NO → Is tracking a remote?\n        ├─ YES → Remote deleted? ([gone])\n        │        ├─ YES → Was work squash-merged? (check main for PR)\n        │        │        ├─ YES → SQUASH_MERGED (use -D)\n        │        │        └─ NO → REMOTE_GONE (needs review)\n        │        └─ NO → Local ahead of remote? (check: git log origin\u002F\u003Cbranch>..\u003Cbranch>)\n        │                ├─ YES (has output) → UNPUSHED_WORK (keep)\n        │                └─ NO (empty output) → SYNCED_WITH_REMOTE (keep)\n        └─ NO → Has unique commits?\n                ├─ YES → LOCAL_WORK (keep)\n                └─ NO → SAFE_TO_DELETE (use -d)\n```\n\n**Category definitions:**\n\n| Category | Meaning | Delete Command |\n|----------|---------|----------------|\n| SAFE_TO_DELETE | Merged into default branch | `git branch -d` |\n| SQUASH_MERGED | Work incorporated via squash merge | `git branch -D` |\n| SUPERSEDED | Part of a group, work verified in main via PR or in newer branch | `git branch -D` |\n| REMOTE_GONE | Remote deleted, work NOT found in main | Review needed |\n| UNPUSHED_WORK | Has commits not pushed to remote | Keep |\n| LOCAL_WORK | Untracked branch with unique commits | Keep |\n| SYNCED_WITH_REMOTE | Up to date with remote | Keep |\n| STALE_REMOTE_ONLY | No local branch; remote branch's own PR is live-confirmed `MERGED` (Phase 3.5) | `gh api -X DELETE` |\n| STALE_REBASE_BACKUP_TAG | Leftover `git-rebase-sync` pre-rebase tag; originating branch is gone or merged AND the tag's own commit is verified reachable from the default branch (Phase 3.6) | `delete-rebase-backup-tags.sh \u003Cindex>` |\n\n### Phase 3.5: Remote Branch Fallback (stale `origin\u002F\u003Cbranch>` after merge)\n\n**Why this exists:** `gh pr merge --delete-branch` deletes the local and remote branch together, but its\nlocal half needs to check out the default branch first — which fails with\n`fatal: '\u003Cdefault>' is already used by worktree ...` whenever that default branch is already checked out\nelsewhere (near-guaranteed if the merged branch had its own worktree, since the primary checkout almost\nalways has the default branch checked out). When that local checkout fails, the remote branch deletion is\nsilently skipped too — `merge-pr`'s own step 7 already works around the resulting non-zero exit by\nchecking PR state instead of trusting the exit code, but that fix only avoids a false \"merge failed\"\nreport; it doesn't repair the branch-deletion gap. `finishing-work`'s own step 1.5 is the primary fix,\napplied right after the merge that caused it — this phase is the safety net for anything that slipped\npast that (an older merge, a merge run through some other path).\n\n**Two cases, both requiring live PR-state confirmation before any deletion — never inferred from branch\nexistence alone:**\n\n1. **Still-listed local branches** (from Phase 1's per-branch loop): if a branch already categorized\n   `SAFE_TO_DELETE`\u002F`SQUASH_MERGED`\u002F`SUPERSEDED` above also shows `origin\u002F\u003Cbranch>` as \"still exists on\n   origin\" in Phase 1's output, its remote counterpart gets deleted alongside the local one — no separate\n   PR check needed here, since that category assignment already required merge evidence.\n2. **Remote-only orphans** (Phase 1's \"Remote-only branches\" list — no local counterpart at all, e.g. a\n   branch a prior `git-cleanup` run already deleted locally before this fallback existed): for each one,\n   run `gh pr view \u003Cbranch> --json state,number` live. Only if `state` is exactly `MERGED`, categorize it\n   `STALE_REMOTE_ONLY`. **Any other result — `OPEN`, `CLOSED` (without merging), or no PR found at\n   all — leaves that branch untouched entirely, not even flagged for review.** This is what keeps this\n   phase a narrow repair for one specific known failure mode rather than general remote branch management:\n   a branch with no merged PR evidence is out of scope, full stop.\n\n### Phase 3.6: Rebase-Backup Tag Cleanup (leftover `git-rebase-sync` safety tags)\n\n**Why this exists:** `git-rebase-sync`'s Step 3 creates a local-only, never-pushed annotated tag\n(`{branch}-rebase-backup-{timestamp}`) immediately before every rebase, as a recovery point if the rebase\ngoes wrong. Nothing in that skill — or anywhere else in git-kit — ever deletes these tags afterward, so\nthey accumulate indefinitely once the branch they were protecting is long gone or merged.\n\nPhase 1's own tag enumeration (`=== Rebase-backup tags ===`) already lists every tag matching the exact\n`{branch}-rebase-backup-{8-digit-date}-{6-digit-time}` shape, alongside its derived branch name, that\nbranch's current status, and — whenever the branch is gone OR merged — whether the tag's own commit is\nreachable from the default branch. Categorize each one from that output — no extra git calls needed here:\n\n- **Branch exists, not merged** → leave the tag alone, no reachability check needed. The branch may still\n  need this recovery point, and the tag being merely old is not evidence otherwise (see Rationalizations\n  below).\n- **Branch gone OR merged, tag reachable from the default branch** → `STALE_REBASE_BACKUP_TAG`, safe to\n  delete — the tag's own commit already made it into the default branch, so the tag is redundant.\n- **Branch gone OR merged, tag NOT reachable from the default branch** → **never categorize as safe to\n  delete**, regardless of which of the two the branch status is. Two independent reasons this happens, not\n  just one: (1) the branch's own deletion was never verified by this run — it may have been force-deleted\n  outside this skill's own SAFE_TO_DELETE\u002FSQUASH_MERGED evidence trail; (2) **rebasing rewrites commit\n  SHAs** — a merged branch's current tip being an ancestor of the default branch says nothing about\n  whether the tag's own *pre-rebase* commit is, since the rebase created a new commit object with a\n  different parent chain (live-verified: a plain rebase-then-merge sequence leaves `git branch --merged`\n  reporting the branch merged while the pre-rebase tag's own SHA is still unreachable from the default\n  branch). Either way, this tag may be the *only* remaining reachable copy of its commits. Leave it alone\n  and report it under a distinct \"needs review — unique history\" note outside the deletable list, the same\n  treatment Phase 3's REMOTE_GONE category already gets for the analogous branch-level case; never fold it\n  into \"delete all recommended.\"\n\nFold the result into Gate 1 as its own list, the same way Phase 3.5's stale remote branches get their own\nlist — never silently merge it into the branch categories above, since a tag isn't a branch and\n`git update-ref -d` isn't `git branch -d`\u002F`-D`.\n\n**Get the deletable list from the script, not by hand-deriving it from Phase 1's raw per-tag facts.** Run\n`\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh\" --list` — it independently\nre-applies the exact rule above (branch gone or merged AND reachable) and prints only the genuinely\ndeletable tags as a numbered list, snapshotting the exact tag names to a file the delete step (Phase 5)\nreads back rather than trusting text typed into this response. **Never type a tag name into a\n`git update-ref -d` command yourself, however it was validated** — see Phase 5's Execute section for why a character-class\ncheck on a value the agent then composes into a command is never fully safe: a git-legal tag name can\ncontain almost any shell metacharacter (`git check-ref-format` accepts e.g. `$(cmd)-rebase-backup-...`,\nlive-verified), and there is no character class that is both shell-safe and complete against every\ngit-legal name (a real gap in an earlier version of this fix — a narrower validating regex rejected\nlegitimately safe-to-delete tags on branches like `feat\u002Fc++`, `git check-ref-format`-legal but outside\n`[A-Za-z0-9._\u002F-]`, permanently blocking their cleanup even once verified safe; found by `cross-model-review`\nround 2 on PR #262). Present the script's numbered list at Gate 1 for the deletable category, and Phase 1's\nraw per-tag output (still gathered in full) for the separate \"needs review — unique history\" note — the\nscript's `--list` output never includes those, so nothing further filters them out.\n\n### Phase 4: Dirty State Detection\n\nCheck ALL worktrees and current directory for uncommitted changes:\n\n```bash\n# For each worktree path: always git -C, never cd (a cd rebinds this session to that worktree); pass the\n# path as one single-quoted argument, each ' inside it written as '\\'' (here and below)\ngit -C \u003Cworktree-path> status --porcelain\n\n# For current directory\ngit status --porcelain\n```\n\n**Also check for gitignored content** — `git status --porcelain` never lists gitignored files, tracked\nor not, so a worktree can carry a `.env`, a local settings override, or other gitignored content that this\ncheck alone would silently miss:\n\n```bash\n# For each worktree path\ngit -C \u003Cworktree-path> status --porcelain --ignored\n\n# For current directory\ngit status --porcelain --ignored\n```\n\nDo not use `git clean` here — it's a destructive command with no place in an analysis-only phase of a\nskill whose Core Principle is \"never delete anything without explicit user confirmation.\" `--ignored` is\nread-only and sufficient. If the ignored-file list is long (e.g. `node_modules\u002F`, `.venv\u002F`), show only the\ntop-level entries plus a count rather than every path, so the warning stays readable.\n\n**Exclude `.claude\u002Fsettings.local.json` and any `**\u002FCLAUDE.local.md`** from this warning — `starting-work`\nnow copies both into every worktree it creates from the main worktree's own copy, so a worktree's version\nis a duplicate, not the only copy; deleting the worktree does not lose them the way an untracked `.env` or\nscratch file would. Do not list these two patterns under \"will also be deleted\" below.\n\n**Display warnings prominently:**\n\n```markdown\nWARNING: ..\u002Fproj-auth has uncommitted changes:\n  M  src\u002Fauth.js\n  ?? new-file.txt\n\nIgnored (not tracked by git, will also be deleted):\n  .env\n\nThese changes will be LOST if you remove this worktree.\n```\n\n**Check for session locks:** `git worktree list --verbose` shows `locked: \u003Creason>` for any locked\nworktree (`starting-work` locks every worktree it creates — see its own Instructions). A locked worktree\nrecommended for deletion needs an unlock step before `git worktree remove` — note this against that\nworktree in the analysis rather than only discovering it when the removal command itself fails.\n\n### GATE 1: Present Complete Analysis\n\nPresent everything in ONE comprehensive view. Group related branches together. See `assets\u002Fanalysis-report-template.md` for the full example layout (related branch groups, individual branch categories, worktrees, and summary).\n\nUse AskUserQuestion with clear options:\n- Delete all recommended (groups + merged + squash-merged + stale remote-only + stale rebase-backup tags)\n- Delete specific groups\u002Fcategories\n- Let me pick individual branches\n\n**Do not proceed until user responds.**\n\n### GATE 2: Final Confirmation with Exact Commands\n\nShow the EXACT commands that will run, with correct flags:\n\n```markdown\nI will execute:\n\n# Merged branches (safe delete)\ngit branch -d fix\u002Ftypo\n\n# Squash-merged branches (force delete - work is in main via PRs)\ngit branch -D feat\u002Flogin\ngit branch -D feat\u002Fapi\ngit branch -D feat\u002Fapi-v2\ngit branch -D feat\u002Fapi-refactor\ngit branch -D feat\u002Fapi-final\n\n# Worktrees (unlock first if session-locked, per Phase 4's lock check)\ngit worktree unlock ..\u002Fproj-auth\ngit worktree remove ..\u002Fproj-auth\n\n# Stale remote branches (Phase 3.5 — PR confirmed MERGED via gh pr view)\ngh api -X DELETE repos\u002F\u003Cowner>\u002F\u003Crepo>\u002Fgit\u002Frefs\u002Fheads\u002Ffeat\u002Fold-worktree-feature\n\n# Stale rebase-backup tags (Phase 3.6 — from delete-rebase-backup-tags.sh --list)\n# 1  feat\u002Fgone-branch-rebase-backup-20260701-093000\n\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh\" 1\n\nConfirm? (yes\u002Fno)\n```\n\n**IMPORTANT:** This is the ONLY confirmation needed for deletion. Do not add extra confirmations if `-D` is required.\n\n### Phase 5: Execute\n\nRun each deletion as a **separate command** so partial failures don't block remaining deletions. Report the result of each. Immediately before each `git branch -D` call — never earlier, since git-kit's guard hook only accepts a marker up to 60 seconds old — run `bash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup`. This writes the marker git-kit's destructive-cleanup guard requires before it will let a raw `git branch -D` targeting a protected branch name through — the same marker-handshake pattern every other git-kit skill uses before its own guarded command. Plain `git branch -d` (lowercase, already-merged-only) and plain `git worktree remove` (no `--force`) aren't guarded and need no marker; only `git worktree remove --force`\u002F`-f` does, since a plain removal already refuses on a dirty or locked worktree via git's own safeguard.\n\n```bash\ngit branch -d fix\u002Ftypo\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit branch -D feat\u002Flogin\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit branch -D feat\u002Fapi\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit branch -D feat\u002Fapi-v2\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit branch -D feat\u002Fapi-refactor\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit branch -D feat\u002Fapi-final\ngit worktree unlock ..\u002Fproj-auth\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit worktree remove ..\u002Fproj-auth\ngh api -X DELETE repos\u002F\u003Cowner>\u002F\u003Crepo>\u002Fgit\u002Frefs\u002Fheads\u002Ffeat\u002Fold-worktree-feature\n\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh\" 1\n```\n\nIf a deletion fails, report the error and continue with remaining deletions. If `git worktree remove`\nfails specifically because the worktree is still locked (the unlock step above was skipped, or a lock was\nadded after Phase 4's check), report this distinctly from a generic removal failure — say plainly that it's\nlocked and by which reason, rather than surfacing git's raw error text unexplained.\n\n**Stale remote branches (Phase 3.5):** no marker write needed — `gh api -X DELETE repos\u002F*\u002Fgit\u002Frefs\u002Fheads\u002F*`\nisn't guarded by any PreToolUse hook (unlike `git branch -D` against a protected name), the same reason\n`merge-pr`'s own manual-delete-branch path calls it directly. Before each call, validate the branch name\nagainst `^[A-Za-z0-9._\u002F@+=-]+$` — the same safety check `merge-pr` applies before this exact command, since\ngit ref names can otherwise contain shell metacharacters (`;&|$`, backticks, parens) that would reach a\nshell context unsafely; if a name fails this check, skip it and report why rather than attempting the call.\nResolve `\u003Cowner>\u002F\u003Crepo>` via `gh repo view --json nameWithOwner --jq .nameWithOwner` once per run, not once per branch.\n\n**Stale rebase-backup tags (Phase 3.6):** no marker write needed — `delete-rebase-backup-tags.sh`'s own\n`git update-ref -d` call isn't guarded by `git-guard-raw-destructive-cleanup.sh` (that hook only matches\n`git branch -D`\u002F`worktree remove --force`), and deleting a tag never touches a protected branch name in\nthe first place. **Never type a tag name into a `git update-ref -d` command directly, and never pass one\nas an argument to any script either** — a git tag name is legal with almost any shell metacharacter (e.g.\n`` `$(cmd)-rebase-backup-20260831-120000` `` is a git-accepted tag name, `git check-ref-format` confirms\nit), so any value the agent composes into a command — even quoted, even as a validated-looking script\nargument — is a command-injection surface; and no character-class validation can be both shell-safe and\ncomplete against every git-legal name (a real, found-in-review gap: an earlier `^[A-Za-z0-9._\u002F-]+$` check\nrejected legitimate branches like `feat\u002Fc++`, permanently blocking their tags from ever being cleaned up).\nInstead, run `\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh\" --list` —\nit independently re-derives the deletable set itself (never trusting Phase 3.6's earlier read) and\nsnapshots the exact tag names to a file; pass back only the plain digit indices shown against Gate 2's\nconfirmed selections — `\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh\"\n\u003Cindex> [index...]` — the same index-only interface `git-stage-selected-files.sh` already uses for staged\nfilenames, for the identical reason. The script resolves each tag's current object id via the always-safe\nfully-qualified `refs\u002Ftags\u002F\u003Cname>` form (never the bare name, which could start with a dash) and deletes\nit with `git update-ref -d refs\u002Ftags\u002F\u003Cname> \u003Cresolved-oid>` — an atomic compare-and-delete that only\nsucceeds if the ref still points at the exact object just verified safe, closing the race between that\nverification and the actual delete (PR #275) — one call per tag internally, so a partial failure part-way\nthrough still lets the rest proceed, and reports which index (if any) failed.\n\n### Phase 6: Report\n\nReport what was deleted (branches, worktrees, Phase 3.5 remote branches, Phase 3.6 tags) and what remains,\nwith each remaining branch's status. Example: [references\u002Fcleanup-report-example.md](references\u002Fcleanup-report-example.md).\n\n### Phase 7: Guided Manual Review (optional, offered after Phase 6 — rebase-backup tags only)\n\nFollow `references\u002Fguided-manual-review.md` in full. In outline: `delete-rebase-backup-tags.sh\n--list-review` already drops any candidate with a still-valid \"keep\" decision recorded and prints a\ngeneration token every later call must pass back — only if anything remains, offer via `AskUserQuestion`\nto walk through them. Per item: show raw evidence (`--diff --generation \u003Ctoken> \u003Cindex>`), ask **Delete\nnow \u002F Keep \u002F Skip**, require a second confirmation before `--force --generation \u003Ctoken> \u003Cindex>`, and use\n`--keep --generation \u003Ctoken> \u003Cindex>` to record a decision — never a hand-composed `jq`\u002F`git` command with a\ntag name in it. `REMOTE_GONE` branches are explicitly NOT covered by this phase yet (an equivalent\nname-handling mechanism doesn't exist for branches — see the reference's own \"open design problem\"\nsection); continue reporting them exactly as Phase 3 already does. Do not improvise any of this from\nmemory — the reference has the full procedure and is the only place the decision-file schema lives.\n\n## Safety Rules\n\n1. **Never invoke automatically** - Only run when user explicitly uses `\u002Fgit-cleanup`\n2. **Two confirmation gates only for the main cleanup flow** - Analysis review, then deletion\n   confirmation. Phase 7's guided review is a separate, optional, opt-in extension for residual\n   \"needs review\" items only, gated by its own offer-then-decide-then-confirm flow — it doesn't add a\n   third gate to the main flow above, since a user who declines Phase 7's offer sees no extra gate at all\n3. **Use correct delete command** - `-d` for merged, `-D` for squash-merged\u002Fsuperseded\n4. **Never touch protected branches** - main, master, develop, release\u002F* are excluded from Phase 1's\n   per-branch commit-analysis loop by `scripts\u002Fphase1-analysis.sh`'s own `grep -vE` filter (run directly,\n   not just read), and any raw `git branch -D` that still targets one of these names is additionally\n   hard-blocked by git-kit's `git-guard-raw-destructive-cleanup.sh` PreToolUse hook\n5. **Block dirty worktree removal** - Refuse without explicit data loss acknowledgment. \"Dirty\" covers\n   gitignored content too, not just tracked\u002Funtracked-but-not-ignored changes — `git status --porcelain`\n   alone misses gitignored files entirely, so Phase 4's `--ignored` check is what actually completes this\n   rule's coverage\n6. **Unlock before removing** - A session-locked worktree (per Phase 4's lock check) gets\n   `git worktree unlock` immediately before `git worktree remove`, never `--force` as a substitute for\n   unlocking — `--force` bypasses the dirty-worktree safeguard in Safety Rule 5 too, not just the lock\n7. **Group related branches** - Don't scatter them across categories\n8. **Never delete a remote branch without live PR-merged confirmation** - Phase 3.5's fallback only\n   deletes `origin\u002F\u003Cbranch>` when `gh pr view \u003Cbranch>` confirms `state: MERGED` at the time of the\n   check, not from \"no local branch\" or \"not in Phase 1's merged list\" alone - an open PR, a closed\n   (unmerged) PR, or no PR at all always leaves that branch untouched\n9. **Never delete a rebase-backup tag whose originating branch is still active** - Phase 3.6 only\n   proposes a `*-rebase-backup-*` tag for deletion when its derived branch no longer exists locally or is\n   already merged into the default branch - an unmerged, still-active branch's backup tag is always left\n   alone, regardless of the tag's own age\n10. **Never delete a rebase-backup tag whose branch is gone or merged unless its content is verified\n    reachable** - neither \"branch no longer exists locally\" nor \"branch is merged\" is by itself evidence\n    the tag is redundant (the gone branch's deletion was never verified by this run, and a rebase rewrites\n    commit SHAs). Phase 3.6 proposes deletion only once the tag's own commit is verified reachable from the\n    default branch, by raw-SHA ancestry (`git merge-base --is-ancestor`) or, failing that, by a per-path\n    blob-AND-mode history search bounded to the tag's merge-base onward (a plain deletion instead requires\n    the path to be absent from the default branch's current tree), with every merge commit in the tag's\n    history diffed against EACH parent (`git diff-tree -m`). A tag unreachable by both signals is reported\n    separately as needing manual review, never included in \"delete all recommended\". Why each part of this\n    check exists: `references\u002Fcritical-implementation-notes.md`; the code: `delete-rebase-backup-tags.sh`'s\n    `is_tag_content_reachable`\u002F`is_path_blob_reachable`, including its fail-closed handling\n11. **Never type a tag name into a command, at all, for any reason** - a git tag name is legal with\n    almost any shell metacharacter (`git check-ref-format` accepts e.g.\n    `` `$(cmd)-rebase-backup-20260831-120000` ``), and no character-class check on a value the agent then\n    composes into a command is both shell-safe and complete against every git-legal name (a narrower\n    check tried first rejected legitimate branches like `feat\u002Fc++`, permanently blocking their cleanup).\n    Deletion always goes through `delete-rebase-backup-tags.sh`'s index-only interface instead - the\n    script re-derives the actual tag names itself from a snapshot file, so the agent only ever passes\n    back plain digit indices, never a single character of tag-name content\n\n## Rationalizations to Reject\n\nThese are common shortcuts that lead to data loss. Reject them:\n\n| Rationalization | Why It's Wrong |\n|-----------------|----------------|\n| \"The branch is old, it's probably safe to delete\" | Age doesn't indicate merge status. Old branches may contain unmerged work. |\n| \"I can recover from reflog if needed\" | Reflog entries expire. Users often don't know how to use reflog. Don't rely on it as a safety net. |\n| \"It's just a local branch, nothing important\" | Local branches may contain the only copy of work not pushed anywhere. |\n| \"The PR was merged, so the branch is safe\" | Squash merges don't preserve branch history. Verify the *specific* commits were incorporated. |\n| \"I'll just delete all the `[gone]` branches\" | `[gone]` only means the remote was deleted. The local branch may have unpushed commits. |\n| \"The user seems to want everything deleted\" | Always present analysis first. Let the user choose what to delete. |\n| \"The branch has commits not in main, so it has unpushed work\" | \"Not in main\" ≠ \"not pushed\". A branch can be synced with its remote but not merged to main. Always check `git log origin\u002F\u003Cbranch>..\u003Cbranch>`. |\n| \"It's gitignored, so it's not important\" | Gitignored means *not in git history* — it is often the only copy of a `.env`, a local override, or uncommitted scratch output. Absence from git is not evidence of unimportance. |\n| \"This remote branch has no local copy, so its PR must be merged and it's safe to delete\" | No local copy only means nobody has it checked out here — it could be an open PR someone else is working on, or a branch with no PR at all. Phase 3.5 always confirms `state: MERGED` live via `gh pr view` before ever proposing deletion. |\n| \"This rebase-backup tag is old, it's probably safe to delete\" | Age alone says nothing about whether the branch it protects is still active — a long-running feature branch can be rebased repeatedly with none of its backup tags becoming safe to delete. Phase 3.6 only proposes deletion once the derived branch is confirmed gone or merged. |\n| \"The branch is gone, so its backup tag must be redundant\" | The branch's own deletion was never verified by this skill run — it may have been force-deleted outside git-cleanup's own evidence trail. Phase 3.6 always confirms the tag's commit is reachable from the default branch (by raw-SHA ancestry, or, when a rebase rewrote the SHA, by an exact content match) before proposing deletion in this case; a tag unreachable by both signals may be the only remaining copy of its commits. |\n| \"The branch is merged, so its backup tag must be redundant\" | Rebasing rewrites commit SHAs — a merged branch's current tip being an ancestor of the default branch does not mean the tag's own pre-rebase commit is (live-verified: a plain rebase-then-merge sequence leaves the branch showing merged while the tag's exact pre-rebase commit stays unreachable by raw SHA). Phase 3.6 runs the same two-signal reachability check (raw-SHA ancestry, then per-path blob-history content match) for the merged case as for the branch-gone case — never skips it just because the branch itself is already known-safe to delete. |\n| \"The default branch reorganized this content into different commits, so a content match will never find it\" | An earlier version of this check required one single commit on the default branch to reproduce a tag commit's entire diff byte-for-byte, which genuinely couldn't see this case (disclosed as an accepted limitation in an earlier revision). The current check matches per path and per blob against that path's own history on the default branch instead — it finds the content regardless of which commit(s) it landed via (live-verified against this repo's own `feat\u002Fpr-ci-governance-rebase-backup-20260907-210042` tag, whose one commit's 13 files landed on the default branch split across two separate commits). |\n| \"The blob already matches on the default branch, so this path's change is reachable\" | Blob equality alone isn't enough — a tag commit whose only change was a mode flip (`chmod +x`, or a file\u002Fsymlink swap with byte-identical content) leaves the blob unchanged but the mode different, and a mode-only match to some unrelated historical commit at that path says nothing about whether *this specific mode change* ever landed. The check requires both blob AND mode to match at the same historical commit (`git ls-tree`, not `git rev-parse \"$commit:$path\"` alone) — found by `cross-model-review` (Codex fresh-eyes, confirmed by Claude's Phase 2 pass), which corrected an earlier, too-lenient informational classification of the same gap from this session's own `security-reviewer` dispatch. |\n| \"The default-branch lookup for a deleted path failed, so the path must be gone\" | A failed git object lookup isn't the same as \"path absent\" — `git cat-file -e \"$default_branch:$path\"` fails identically whether the path is genuinely gone or merely has an unreadable\u002Fcorrupted blob object at a path that's still very much present. The deletion check uses `git ls-tree` instead, which never needs to open the blob to answer \"does this path exist in the tree\" — found by `cross-model-review` round 2 (Codex fresh-eyes), the exact same read-failure-vs-absence anti-pattern already fixed twice elsewhere in this check, missed in this one remaining spot. |\n| \"The blob exists somewhere in the default branch's history, so it's reachable\" | Existing *anywhere* in history isn't enough — a path added then deleted from the default branch entirely BEFORE the tag's own branch diverged, then coincidentally re-added with byte-identical content on the tag's own branch, matches that stale PRE-divergence state under an unbounded search, even though the default branch never actually restored it after diverging. The check bounds the search to the tag's own merge-base with the default branch onward (plus the merge-base's own tree directly, for content genuinely inherited unchanged) — found live on the real PR by GitHub's automated Codex connector review (P1), reproduced in a scratch repo before fixing: delete a file on `main`, re-add it identically only on a feature branch, delete the branch — the unbounded search reported the backup tag reachable even though the file was never restored to `main`. |\n| \"The merge's `--cc` diff is empty, so it contributes nothing new and is safe to skip\" | `--cc` only shows a path that differs from EVERY parent — a merge that force-resolves to exactly ONE parent's state for a path is invisible to `--cc` by definition, even when that represents real content loss relative to the OTHER parent. The check now diffs a merge against EACH parent separately (`git diff-tree -m`, the same technique used elsewhere in this check) and runs every resulting record through the normal per-path check, rather than treating an empty `--cc` diff as a \"nothing to verify\" signal — found live on the real PR by GitHub's automated Codex connector review (P1 on a later commit), reproduced in a scratch repo before fixing: one parent adds a file, the other parent is a divergent branch with zero real content changes of its own, and the tag's own merge is forced to drop the file (matching the empty-change parent exactly) — `--cc` reported no diff at all, but the default branch (the parent that added the file) still had it. |\n| \"Since the tag's own FINAL state at a path matches the default branch, any EARLIER intermediate blob for that path must also be safe to skip\" | A tempting shortcut (tried and reverted before shipping, issue #317) — but blob-identity alone can't tell \"superseded on the way to an equivalent final state\" apart from \"discarded via an unrelated revert.\" Live-verified counter-example (`security-reviewer`\u002F`cross-model-review`, Codex fresh-eyes, high confidence): a tag adds unique content to a path, then a LATER commit in the SAME tag reverts that path back to the default branch's own untouched original — the tag's tip trivially matches the default branch, but the reverted-away unique content exists nowhere else and would be permanently lost. No safe narrowing of the shortcut was found that still resolves #317's own reordering case (see `is_path_blob_reachable`'s own comment for why); #317-shaped tags are correctly left \"needs review\" and resolved via the guided-manual-review feature's human-reviewed `--diff`\u002F`--force` instead. |\n\n## Testing & Validation\n\n**Verify this skill activates on:** \"clean up my old branches and worktrees\"; \"I have a bunch of stale\nbranches, help me clean up\".\n\n**Verify it does NOT activate on:** \"delete this one specific branch\" with no broader cleanup context;\nautomated or headless invocation (two user confirmations are required).\n\n**Quality gates:**\n- [ ] Nothing is deleted before both Gate 1 and Gate 2 are answered.\n- [ ] Phase 4 runs `--porcelain` and `--ignored` for every worktree, through `git -C`, never `cd`.\n- [ ] Tags are deleted only through `delete-rebase-backup-tags.sh` indices, never a typed tag name.\n\n## Reference Guide\n\n| Resource | Purpose |\n|---|---|\n| `references\u002Fcritical-implementation-notes.md` | Squash-merge `-D`, PR-history commands, Safety Rule 10 rationale |\n| `references\u002Fguided-manual-review.md` | Phase 7's full guided tag-review procedure |\n| [references\u002Ftesting-and-validation.md](references\u002Ftesting-and-validation.md) | Phase 4 and 3.6 scenarios, full quality-gates checklist |\n| `references\u002Fcleanup-report-example.md` | Phase 6 report example |\n| `assets\u002Fanalysis-report-template.md` | Gate 1 analysis layout |\n| `scripts\u002Fphase1-analysis.sh`, `scripts\u002Fdelete-rebase-backup-tags.sh` | Phase 1 analysis; tag listing and deletion |\n","# Git Cleanup\n\nSafely clean up accumulated git worktrees and local branches by categorizing them into: safely deletable (merged), potentially related (similar themes), and active work (keep).\n\n**On the `Bash(git -C:*)` grant:** this is broad by necessity, not oversight — Phase 4's dirty-state and\ngitignored-content checks run `git -C \u003Cworktree-path> status --porcelain[--ignored]` against a worktree\npath that's only known at runtime, and `Bash(prefix:*)` permission syntax can't express \"any `-C \u003Cpath>`\nbut only followed by `status`\" without a wrapper script. Reviewed 2026-08-11 (git-kit retro follow-up);\nno narrower grant is expressible with the current permission syntax.\n\n## Quick Start\n\n1. Run from a session in the primary checkout, only on the user's explicit `\u002Fgit-cleanup`.\n2. Analyze and group branches, remote leftovers and rebase-backup tags (Phases 1-3.6), then check every\n   worktree for dirty and gitignored content with `git -C`, never `cd` (Phase 4).\n3. Gate 1: present the analysis. Gate 2: confirm the exact deletions, then execute (Phase 5).\n4. Report what was deleted and what remains (Phase 6); optionally offer Phase 7's guided tag review.\n\n## When to Use\n\n- When the user has accumulated many local branches and worktrees\n- When branches have been merged but not cleaned up locally\n- When remote branches have been deleted but local tracking branches remain\n\n## When NOT to Use\n\n- Do not use for general remote branch management (this is local cleanup only) — **narrow exception:**\n  Phase 3.5's remote-branch fallback deletes a remote branch only when its own PR is live-confirmed\n  `MERGED` via `gh pr view`, as a repair for a known `gh pr merge --delete-branch` failure mode (see\n  Phase 3.5 for the mechanism). It never deletes a remote branch for any other reason — an open PR, no\n  PR at all, or \"no local counterpart\" alone are never sufficient by themselves.\n- Do not use for repository maintenance tasks like gc or prune\n- Not designed for headless or non-interactive automation (requires user confirmations at two gates)\n- Cannot run from a session sandboxed to a worktree checkout — this command needs to operate on the\n  primary checkout's branch\u002Fworktree list, and a worktree-sandboxed session cannot `cd` there. Run it from\n  a session started in the primary checkout instead. See `finishing-work`'s hand-off note for the same\n  constraint on the more common path into this skill.\n\n## Core Principle: SAFETY FIRST\n\n**Never delete anything without explicit user confirmation.** This skill uses a gated workflow where users must approve each step before any destructive action.\n\n## Critical Implementation Notes\n\nSee [references\u002Fcritical-implementation-notes.md](references\u002Fcritical-implementation-notes.md) for the\nsquash-merge `-D` requirement, the PR-history investigation commands and why Safety Rule 10's\nrebase-backup tag reachability check is built the way it is — the branch-grouping procedure\nitself is already fully covered by Phase 2 below, so the reference file doesn't restate it. Read the\nreference before Phase 3 (Categorize) for the squash-merge nuance; the PR-history commands apply\nspecifically to `[gone]` branches within Phase 2\u002F3.\n\n## Workflow\n\n### Phase 1: Comprehensive Analysis\n\nGather ALL information upfront before any categorization. Run `\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fphase1-analysis.sh\"` directly via `Bash` — it resolves the default branch, lists local branches and worktrees, fetches\u002Fprunes, gets merged-branch and recent PR-merge history, and for each non-protected branch (protected names excluded via the script's own `grep -vE` filter) reports unmerged and unpushed commits plus whether its `origin\u002F\u003Cbranch>` counterpart still exists. It also lists remote-only branches with no local counterpart at all (candidates for Phase 3.5's fallback), and every local `*-rebase-backup-*` tag left over from `git-rebase-sync`'s pre-rebase safety backup, alongside its derived branch name and that branch's current status (candidates for Phase 3.6's cleanup). Read its output rather than re-deriving these git calls by hand.\n\n**Note on branch names:** Git branch names can contain characters that break shell expansion. Always quote `\"$branch\"` in commands.\n\n### Phase 2: Group Related Branches\n\n**Do this BEFORE individual categorization.**\n\nIdentify branch groups by shared prefixes:\n\n```bash\n# List branches and extract prefixes\ngit branch --format='%(refname:short)' | sed 's\u002F-[^-]*$\u002F\u002F' | sort | uniq -c | sort -rn\n```\n\nFor each group with 2+ branches:\n\n1. **Compare commit histories** - Which branches contain commits from others?\n2. **Find merge evidence** - Which PRs incorporated work from this group?\n3. **Identify the \"final\" branch** - Usually the most recent or most complete\n4. **Mark superseded branches** - Older iterations whose work is in main or in a newer branch\n\n**SUPERSEDED requires evidence, not just shared prefix:**\n- A PR merged the work into main, OR\n- A newer branch contains all commits from the older branch\n- Name prefix alone is NOT sufficient — similarly named branches may contain independent work\n\nExample analysis for `feat\u002Fapi-*` branches:\n\n```markdown\n### Related Branch Group: feat\u002Fapi-*\n\n| Branch | Commits | PR Merged | Status |\n|--------|---------|-----------|--------|\n| feat\u002Fapi | 12 | #29 (initial API) | Superseded - work in main |\n| feat\u002Fapi-v2 | 8 | #45 (API improvements) | Superseded - work in main |\n| feat\u002Fapi-refactor | 5 | #67 (refactor) | Superseded - work in main |\n| feat\u002Fapi-final | 4 | None found | Superseded by above PRs |\n\n**Recommendation:** All 4 branches can be deleted - work incorporated via PRs #29, #45, #67\n```\n\n### Phase 3: Categorize Remaining Branches\n\nFor branches NOT in a related group, categorize individually:\n\n```\nIs branch merged into default branch?\n├─ YES → SAFE_TO_DELETE (use -d)\n└─ NO → Is tracking a remote?\n        ├─ YES → Remote deleted? ([gone])\n        │        ├─ YES → Was work squash-merged? (check main for PR)\n        │        │        ├─ YES → SQUASH_MERGED (use -D)\n        │        │        └─ NO → REMOTE_GONE (needs review)\n        │        └─ NO → Local ahead of remote? (check: git log origin\u002F\u003Cbranch>..\u003Cbranch>)\n        │                ├─ YES (has output) → UNPUSHED_WORK (keep)\n        │                └─ NO (empty output) → SYNCED_WITH_REMOTE (keep)\n        └─ NO → Has unique commits?\n                ├─ YES → LOCAL_WORK (keep)\n                └─ NO → SAFE_TO_DELETE (use -d)\n```\n\n**Category definitions:**\n\n| Category | Meaning | Delete Command |\n|----------|---------|----------------|\n| SAFE_TO_DELETE | Merged into default branch | `git branch -d` |\n| SQUASH_MERGED | Work incorporated via squash merge | `git branch -D` |\n| SUPERSEDED | Part of a group, work verified in main via PR or in newer branch | `git branch -D` |\n| REMOTE_GONE | Remote deleted, work NOT found in main | Review needed |\n| UNPUSHED_WORK | Has commits not pushed to remote | Keep |\n| LOCAL_WORK | Untracked branch with unique commits | Keep |\n| SYNCED_WITH_REMOTE | Up to date with remote | Keep |\n| STALE_REMOTE_ONLY | No local branch; remote branch's own PR is live-confirmed `MERGED` (Phase 3.5) | `gh api -X DELETE` |\n| STALE_REBASE_BACKUP_TAG | Leftover `git-rebase-sync` pre-rebase tag; originating branch is gone or merged AND the tag's own commit is verified reachable from the default branch (Phase 3.6) | `delete-rebase-backup-tags.sh \u003Cindex>` |\n\n### Phase 3.5: Remote Branch Fallback (stale `origin\u002F\u003Cbranch>` after merge)\n\n**Why this exists:** `gh pr merge --delete-branch` deletes the local and remote branch together, but its\nlocal half needs to check out the default branch first — which fails with\n`fatal: '\u003Cdefault>' is already used by worktree ...` whenever that default branch is already checked out\nelsewhere (near-guaranteed if the merged branch had its own worktree, since the primary checkout almost\nalways has the default branch checked out). When that local checkout fails, the remote branch deletion is\nsilently skipped too — `merge-pr`'s own step 7 already works around the resulting non-zero exit by\nchecking PR state instead of trusting the exit code, but that fix only avoids a false \"merge failed\"\nreport; it doesn't repair the branch-deletion gap. `finishing-work`'s own step 1.5 is the primary fix,\napplied right after the merge that caused it — this phase is the safety net for anything that slipped\npast that (an older merge, a merge run through some other path).\n\n**Two cases, both requiring live PR-state confirmation before any deletion — never inferred from branch\nexistence alone:**\n\n1. **Still-listed local branches** (from Phase 1's per-branch loop): if a branch already categorized\n   `SAFE_TO_DELETE`\u002F`SQUASH_MERGED`\u002F`SUPERSEDED` above also shows `origin\u002F\u003Cbranch>` as \"still exists on\n   origin\" in Phase 1's output, its remote counterpart gets deleted alongside the local one — no separate\n   PR check needed here, since that category assignment already required merge evidence.\n2. **Remote-only orphans** (Phase 1's \"Remote-only branches\" list — no local counterpart at all, e.g. a\n   branch a prior `git-cleanup` run already deleted locally before this fallback existed): for each one,\n   run `gh pr view \u003Cbranch> --json state,number` live. Only if `state` is exactly `MERGED`, categorize it\n   `STALE_REMOTE_ONLY`. **Any other result — `OPEN`, `CLOSED` (without merging), or no PR found at\n   all — leaves that branch untouched entirely, not even flagged for review.** This is what keeps this\n   phase a narrow repair for one specific known failure mode rather than general remote branch management:\n   a branch with no merged PR evidence is out of scope, full stop.\n\n### Phase 3.6: Rebase-Backup Tag Cleanup (leftover `git-rebase-sync` safety tags)\n\n**Why this exists:** `git-rebase-sync`'s Step 3 creates a local-only, never-pushed annotated tag\n(`{branch}-rebase-backup-{timestamp}`) immediately before every rebase, as a recovery point if the rebase\ngoes wrong. Nothing in that skill — or anywhere else in git-kit — ever deletes these tags afterward, so\nthey accumulate indefinitely once the branch they were protecting is long gone or merged.\n\nPhase 1's own tag enumeration (`=== Rebase-backup tags ===`) already lists every tag matching the exact\n`{branch}-rebase-backup-{8-digit-date}-{6-digit-time}` shape, alongside its derived branch name, that\nbranch's current status, and — whenever the branch is gone OR merged — whether the tag's own commit is\nreachable from the default branch. Categorize each one from that output — no extra git calls needed here:\n\n- **Branch exists, not merged** → leave the tag alone, no reachability check needed. The branch may still\n  need this recovery point, and the tag being merely old is not evidence otherwise (see Rationalizations\n  below).\n- **Branch gone OR merged, tag reachable from the default branch** → `STALE_REBASE_BACKUP_TAG`, safe to\n  delete — the tag's own commit already made it into the default branch, so the tag is redundant.\n- **Branch gone OR merged, tag NOT reachable from the default branch** → **never categorize as safe to\n  delete**, regardless of which of the two the branch status is. Two independent reasons this happens, not\n  just one: (1) the branch's own deletion was never verified by this run — it may have been force-deleted\n  outside this skill's own SAFE_TO_DELETE\u002FSQUASH_MERGED evidence trail; (2) **rebasing rewrites commit\n  SHAs** — a merged branch's current tip being an ancestor of the default branch says nothing about\n  whether the tag's own *pre-rebase* commit is, since the rebase created a new commit object with a\n  different parent chain (live-verified: a plain rebase-then-merge sequence leaves `git branch --merged`\n  reporting the branch merged while the pre-rebase tag's own SHA is still unreachable from the default\n  branch). Either way, this tag may be the *only* remaining reachable copy of its commits. Leave it alone\n  and report it under a distinct \"needs review — unique history\" note outside the deletable list, the same\n  treatment Phase 3's REMOTE_GONE category already gets for the analogous branch-level case; never fold it\n  into \"delete all recommended.\"\n\nFold the result into Gate 1 as its own list, the same way Phase 3.5's stale remote branches get their own\nlist — never silently merge it into the branch categories above, since a tag isn't a branch and\n`git update-ref -d` isn't `git branch -d`\u002F`-D`.\n\n**Get the deletable list from the script, not by hand-deriving it from Phase 1's raw per-tag facts.** Run\n`\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh\" --list` — it independently\nre-applies the exact rule above (branch gone or merged AND reachable) and prints only the genuinely\ndeletable tags as a numbered list, snapshotting the exact tag names to a file the delete step (Phase 5)\nreads back rather than trusting text typed into this response. **Never type a tag name into a\n`git update-ref -d` command yourself, however it was validated** — see Phase 5's Execute section for why a character-class\ncheck on a value the agent then composes into a command is never fully safe: a git-legal tag name can\ncontain almost any shell metacharacter (`git check-ref-format` accepts e.g. `$(cmd)-rebase-backup-...`,\nlive-verified), and there is no character class that is both shell-safe and complete against every\ngit-legal name (a real gap in an earlier version of this fix — a narrower validating regex rejected\nlegitimately safe-to-delete tags on branches like `feat\u002Fc++`, `git check-ref-format`-legal but outside\n`[A-Za-z0-9._\u002F-]`, permanently blocking their cleanup even once verified safe; found by `cross-model-review`\nround 2 on PR #262). Present the script's numbered list at Gate 1 for the deletable category, and Phase 1's\nraw per-tag output (still gathered in full) for the separate \"needs review — unique history\" note — the\nscript's `--list` output never includes those, so nothing further filters them out.\n\n### Phase 4: Dirty State Detection\n\nCheck ALL worktrees and current directory for uncommitted changes:\n\n```bash\n# For each worktree path: always git -C, never cd (a cd rebinds this session to that worktree); pass the\n# path as one single-quoted argument, each ' inside it written as '\\'' (here and below)\ngit -C \u003Cworktree-path> status --porcelain\n\n# For current directory\ngit status --porcelain\n```\n\n**Also check for gitignored content** — `git status --porcelain` never lists gitignored files, tracked\nor not, so a worktree can carry a `.env`, a local settings override, or other gitignored content that this\ncheck alone would silently miss:\n\n```bash\n# For each worktree path\ngit -C \u003Cworktree-path> status --porcelain --ignored\n\n# For current directory\ngit status --porcelain --ignored\n```\n\nDo not use `git clean` here — it's a destructive command with no place in an analysis-only phase of a\nskill whose Core Principle is \"never delete anything without explicit user confirmation.\" `--ignored` is\nread-only and sufficient. If the ignored-file list is long (e.g. `node_modules\u002F`, `.venv\u002F`), show only the\ntop-level entries plus a count rather than every path, so the warning stays readable.\n\n**Exclude `.claude\u002Fsettings.local.json` and any `**\u002FCLAUDE.local.md`** from this warning — `starting-work`\nnow copies both into every worktree it creates from the main worktree's own copy, so a worktree's version\nis a duplicate, not the only copy; deleting the worktree does not lose them the way an untracked `.env` or\nscratch file would. Do not list these two patterns under \"will also be deleted\" below.\n\n**Display warnings prominently:**\n\n```markdown\nWARNING: ..\u002Fproj-auth has uncommitted changes:\n  M  src\u002Fauth.js\n  ?? new-file.txt\n\nIgnored (not tracked by git, will also be deleted):\n  .env\n\nThese changes will be LOST if you remove this worktree.\n```\n\n**Check for session locks:** `git worktree list --verbose` shows `locked: \u003Creason>` for any locked\nworktree (`starting-work` locks every worktree it creates — see its own Instructions). A locked worktree\nrecommended for deletion needs an unlock step before `git worktree remove` — note this against that\nworktree in the analysis rather than only discovering it when the removal command itself fails.\n\n### GATE 1: Present Complete Analysis\n\nPresent everything in ONE comprehensive view. Group related branches together. See `assets\u002Fanalysis-report-template.md` for the full example layout (related branch groups, individual branch categories, worktrees, and summary).\n\nUse AskUserQuestion with clear options:\n- Delete all recommended (groups + merged + squash-merged + stale remote-only + stale rebase-backup tags)\n- Delete specific groups\u002Fcategories\n- Let me pick individual branches\n\n**Do not proceed until user responds.**\n\n### GATE 2: Final Confirmation with Exact Commands\n\nShow the EXACT commands that will run, with correct flags:\n\n```markdown\nI will execute:\n\n# Merged branches (safe delete)\ngit branch -d fix\u002Ftypo\n\n# Squash-merged branches (force delete - work is in main via PRs)\ngit branch -D feat\u002Flogin\ngit branch -D feat\u002Fapi\ngit branch -D feat\u002Fapi-v2\ngit branch -D feat\u002Fapi-refactor\ngit branch -D feat\u002Fapi-final\n\n# Worktrees (unlock first if session-locked, per Phase 4's lock check)\ngit worktree unlock ..\u002Fproj-auth\ngit worktree remove ..\u002Fproj-auth\n\n# Stale remote branches (Phase 3.5 — PR confirmed MERGED via gh pr view)\ngh api -X DELETE repos\u002F\u003Cowner>\u002F\u003Crepo>\u002Fgit\u002Frefs\u002Fheads\u002Ffeat\u002Fold-worktree-feature\n\n# Stale rebase-backup tags (Phase 3.6 — from delete-rebase-backup-tags.sh --list)\n# 1  feat\u002Fgone-branch-rebase-backup-20260701-093000\n\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh\" 1\n\nConfirm? (yes\u002Fno)\n```\n\n**IMPORTANT:** This is the ONLY confirmation needed for deletion. Do not add extra confirmations if `-D` is required.\n\n### Phase 5: Execute\n\nRun each deletion as a **separate command** so partial failures don't block remaining deletions. Report the result of each. Immediately before each `git branch -D` call — never earlier, since git-kit's guard hook only accepts a marker up to 60 seconds old — run `bash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup`. This writes the marker git-kit's destructive-cleanup guard requires before it will let a raw `git branch -D` targeting a protected branch name through — the same marker-handshake pattern every other git-kit skill uses before its own guarded command. Plain `git branch -d` (lowercase, already-merged-only) and plain `git worktree remove` (no `--force`) aren't guarded and need no marker; only `git worktree remove --force`\u002F`-f` does, since a plain removal already refuses on a dirty or locked worktree via git's own safeguard.\n\n```bash\ngit branch -d fix\u002Ftypo\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit branch -D feat\u002Flogin\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit branch -D feat\u002Fapi\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit branch -D feat\u002Fapi-v2\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit branch -D feat\u002Fapi-refactor\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit branch -D feat\u002Fapi-final\ngit worktree unlock ..\u002Fproj-auth\nbash \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh\" git-cleanup-destructive git-cleanup\ngit worktree remove ..\u002Fproj-auth\ngh api -X DELETE repos\u002F\u003Cowner>\u002F\u003Crepo>\u002Fgit\u002Frefs\u002Fheads\u002Ffeat\u002Fold-worktree-feature\n\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh\" 1\n```\n\nIf a deletion fails, report the error and continue with remaining deletions. If `git worktree remove`\nfails specifically because the worktree is still locked (the unlock step above was skipped, or a lock was\nadded after Phase 4's check), report this distinctly from a generic removal failure — say plainly that it's\nlocked and by which reason, rather than surfacing git's raw error text unexplained.\n\n**Stale remote branches (Phase 3.5):** no marker write needed — `gh api -X DELETE repos\u002F*\u002Fgit\u002Frefs\u002Fheads\u002F*`\nisn't guarded by any PreToolUse hook (unlike `git branch -D` against a protected name), the same reason\n`merge-pr`'s own manual-delete-branch path calls it directly. Before each call, validate the branch name\nagainst `^[A-Za-z0-9._\u002F@+=-]+$` — the same safety check `merge-pr` applies before this exact command, since\ngit ref names can otherwise contain shell metacharacters (`;&|$`, backticks, parens) that would reach a\nshell context unsafely; if a name fails this check, skip it and report why rather than attempting the call.\nResolve `\u003Cowner>\u002F\u003Crepo>` via `gh repo view --json nameWithOwner --jq .nameWithOwner` once per run, not once per branch.\n\n**Stale rebase-backup tags (Phase 3.6):** no marker write needed — `delete-rebase-backup-tags.sh`'s own\n`git update-ref -d` call isn't guarded by `git-guard-raw-destructive-cleanup.sh` (that hook only matches\n`git branch -D`\u002F`worktree remove --force`), and deleting a tag never touches a protected branch name in\nthe first place. **Never type a tag name into a `git update-ref -d` command directly, and never pass one\nas an argument to any script either** — a git tag name is legal with almost any shell metacharacter (e.g.\n`` `$(cmd)-rebase-backup-20260831-120000` `` is a git-accepted tag name, `git check-ref-format` confirms\nit), so any value the agent composes into a command — even quoted, even as a validated-looking script\nargument — is a command-injection surface; and no character-class validation can be both shell-safe and\ncomplete against every git-legal name (a real, found-in-review gap: an earlier `^[A-Za-z0-9._\u002F-]+$` check\nrejected legitimate branches like `feat\u002Fc++`, permanently blocking their tags from ever being cleaned up).\nInstead, run `\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh\" --list` —\nit independently re-derives the deletable set itself (never trusting Phase 3.6's earlier read) and\nsnapshots the exact tag names to a file; pass back only the plain digit indices shown against Gate 2's\nconfirmed selections — `\"${CLAUDE_PLUGIN_ROOT}\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh\"\n\u003Cindex> [index...]` — the same index-only interface `git-stage-selected-files.sh` already uses for staged\nfilenames, for the identical reason. The script resolves each tag's current object id via the always-safe\nfully-qualified `refs\u002Ftags\u002F\u003Cname>` form (never the bare name, which could start with a dash) and deletes\nit with `git update-ref -d refs\u002Ftags\u002F\u003Cname> \u003Cresolved-oid>` — an atomic compare-and-delete that only\nsucceeds if the ref still points at the exact object just verified safe, closing the race between that\nverification and the actual delete (PR #275) — one call per tag internally, so a partial failure part-way\nthrough still lets the rest proceed, and reports which index (if any) failed.\n\n### Phase 6: Report\n\nReport what was deleted (branches, worktrees, Phase 3.5 remote branches, Phase 3.6 tags) and what remains,\nwith each remaining branch's status. Example: [references\u002Fcleanup-report-example.md](references\u002Fcleanup-report-example.md).\n\n### Phase 7: Guided Manual Review (optional, offered after Phase 6 — rebase-backup tags only)\n\nFollow `references\u002Fguided-manual-review.md` in full. In outline: `delete-rebase-backup-tags.sh\n--list-review` already drops any candidate with a still-valid \"keep\" decision recorded and prints a\ngeneration token every later call must pass back — only if anything remains, offer via `AskUserQuestion`\nto walk through them. Per item: show raw evidence (`--diff --generation \u003Ctoken> \u003Cindex>`), ask **Delete\nnow \u002F Keep \u002F Skip**, require a second confirmation before `--force --generation \u003Ctoken> \u003Cindex>`, and use\n`--keep --generation \u003Ctoken> \u003Cindex>` to record a decision — never a hand-composed `jq`\u002F`git` command with a\ntag name in it. `REMOTE_GONE` branches are explicitly NOT covered by this phase yet (an equivalent\nname-handling mechanism doesn't exist for branches — see the reference's own \"open design problem\"\nsection); continue reporting them exactly as Phase 3 already does. Do not improvise any of this from\nmemory — the reference has the full procedure and is the only place the decision-file schema lives.\n\n## Safety Rules\n\n1. **Never invoke automatically** - Only run when user explicitly uses `\u002Fgit-cleanup`\n2. **Two confirmation gates only for the main cleanup flow** - Analysis review, then deletion\n   confirmation. Phase 7's guided review is a separate, optional, opt-in extension for residual\n   \"needs review\" items only, gated by its own offer-then-decide-then-confirm flow — it doesn't add a\n   third gate to the main flow above, since a user who declines Phase 7's offer sees no extra gate at all\n3. **Use correct delete command** - `-d` for merged, `-D` for squash-merged\u002Fsuperseded\n4. **Never touch protected branches** - main, master, develop, release\u002F* are excluded from Phase 1's\n   per-branch commit-analysis loop by `scripts\u002Fphase1-analysis.sh`'s own `grep -vE` filter (run directly,\n   not just read), and any raw `git branch -D` that still targets one of these names is additionally\n   hard-blocked by git-kit's `git-guard-raw-destructive-cleanup.sh` PreToolUse hook\n5. **Block dirty worktree removal** - Refuse without explicit data loss acknowledgment. \"Dirty\" covers\n   gitignored content too, not just tracked\u002Funtracked-but-not-ignored changes — `git status --porcelain`\n   alone misses gitignored files entirely, so Phase 4's `--ignored` check is what actually completes this\n   rule's coverage\n6. **Unlock before removing** - A session-locked worktree (per Phase 4's lock check) gets\n   `git worktree unlock` immediately before `git worktree remove`, never `--force` as a substitute for\n   unlocking — `--force` bypasses the dirty-worktree safeguard in Safety Rule 5 too, not just the lock\n7. **Group related branches** - Don't scatter them across categories\n8. **Never delete a remote branch without live PR-merged confirmation** - Phase 3.5's fallback only\n   deletes `origin\u002F\u003Cbranch>` when `gh pr view \u003Cbranch>` confirms `state: MERGED` at the time of the\n   check, not from \"no local branch\" or \"not in Phase 1's merged list\" alone - an open PR, a closed\n   (unmerged) PR, or no PR at all always leaves that branch untouched\n9. **Never delete a rebase-backup tag whose originating branch is still active** - Phase 3.6 only\n   proposes a `*-rebase-backup-*` tag for deletion when its derived branch no longer exists locally or is\n   already merged into the default branch - an unmerged, still-active branch's backup tag is always left\n   alone, regardless of the tag's own age\n10. **Never delete a rebase-backup tag whose branch is gone or merged unless its content is verified\n    reachable** - neither \"branch no longer exists locally\" nor \"branch is merged\" is by itself evidence\n    the tag is redundant (the gone branch's deletion was never verified by this run, and a rebase rewrites\n    commit SHAs). Phase 3.6 proposes deletion only once the tag's own commit is verified reachable from the\n    default branch, by raw-SHA ancestry (`git merge-base --is-ancestor`) or, failing that, by a per-path\n    blob-AND-mode history search bounded to the tag's merge-base onward (a plain deletion instead requires\n    the path to be absent from the default branch's current tree), with every merge commit in the tag's\n    history diffed against EACH parent (`git diff-tree -m`). A tag unreachable by both signals is reported\n    separately as needing manual review, never included in \"delete all recommended\". Why each part of this\n    check exists: `references\u002Fcritical-implementation-notes.md`; the code: `delete-rebase-backup-tags.sh`'s\n    `is_tag_content_reachable`\u002F`is_path_blob_reachable`, including its fail-closed handling\n11. **Never type a tag name into a command, at all, for any reason** - a git tag name is legal with\n    almost any shell metacharacter (`git check-ref-format` accepts e.g.\n    `` `$(cmd)-rebase-backup-20260831-120000` ``), and no character-class check on a value the agent then\n    composes into a command is both shell-safe and complete against every git-legal name (a narrower\n    check tried first rejected legitimate branches like `feat\u002Fc++`, permanently blocking their cleanup).\n    Deletion always goes through `delete-rebase-backup-tags.sh`'s index-only interface instead - the\n    script re-derives the actual tag names itself from a snapshot file, so the agent only ever passes\n    back plain digit indices, never a single character of tag-name content\n\n## Rationalizations to Reject\n\nThese are common shortcuts that lead to data loss. Reject them:\n\n| Rationalization | Why It's Wrong |\n|-----------------|----------------|\n| \"The branch is old, it's probably safe to delete\" | Age doesn't indicate merge status. Old branches may contain unmerged work. |\n| \"I can recover from reflog if needed\" | Reflog entries expire. Users often don't know how to use reflog. Don't rely on it as a safety net. |\n| \"It's just a local branch, nothing important\" | Local branches may contain the only copy of work not pushed anywhere. |\n| \"The PR was merged, so the branch is safe\" | Squash merges don't preserve branch history. Verify the *specific* commits were incorporated. |\n| \"I'll just delete all the `[gone]` branches\" | `[gone]` only means the remote was deleted. The local branch may have unpushed commits. |\n| \"The user seems to want everything deleted\" | Always present analysis first. Let the user choose what to delete. |\n| \"The branch has commits not in main, so it has unpushed work\" | \"Not in main\" ≠ \"not pushed\". A branch can be synced with its remote but not merged to main. Always check `git log origin\u002F\u003Cbranch>..\u003Cbranch>`. |\n| \"It's gitignored, so it's not important\" | Gitignored means *not in git history* — it is often the only copy of a `.env`, a local override, or uncommitted scratch output. Absence from git is not evidence of unimportance. |\n| \"This remote branch has no local copy, so its PR must be merged and it's safe to delete\" | No local copy only means nobody has it checked out here — it could be an open PR someone else is working on, or a branch with no PR at all. Phase 3.5 always confirms `state: MERGED` live via `gh pr view` before ever proposing deletion. |\n| \"This rebase-backup tag is old, it's probably safe to delete\" | Age alone says nothing about whether the branch it protects is still active — a long-running feature branch can be rebased repeatedly with none of its backup tags becoming safe to delete. Phase 3.6 only proposes deletion once the derived branch is confirmed gone or merged. |\n| \"The branch is gone, so its backup tag must be redundant\" | The branch's own deletion was never verified by this skill run — it may have been force-deleted outside git-cleanup's own evidence trail. Phase 3.6 always confirms the tag's commit is reachable from the default branch (by raw-SHA ancestry, or, when a rebase rewrote the SHA, by an exact content match) before proposing deletion in this case; a tag unreachable by both signals may be the only remaining copy of its commits. |\n| \"The branch is merged, so its backup tag must be redundant\" | Rebasing rewrites commit SHAs — a merged branch's current tip being an ancestor of the default branch does not mean the tag's own pre-rebase commit is (live-verified: a plain rebase-then-merge sequence leaves the branch showing merged while the tag's exact pre-rebase commit stays unreachable by raw SHA). Phase 3.6 runs the same two-signal reachability check (raw-SHA ancestry, then per-path blob-history content match) for the merged case as for the branch-gone case — never skips it just because the branch itself is already known-safe to delete. |\n| \"The default branch reorganized this content into different commits, so a content match will never find it\" | An earlier version of this check required one single commit on the default branch to reproduce a tag commit's entire diff byte-for-byte, which genuinely couldn't see this case (disclosed as an accepted limitation in an earlier revision). The current check matches per path and per blob against that path's own history on the default branch instead — it finds the content regardless of which commit(s) it landed via (live-verified against this repo's own `feat\u002Fpr-ci-governance-rebase-backup-20260907-210042` tag, whose one commit's 13 files landed on the default branch split across two separate commits). |\n| \"The blob already matches on the default branch, so this path's change is reachable\" | Blob equality alone isn't enough — a tag commit whose only change was a mode flip (`chmod +x`, or a file\u002Fsymlink swap with byte-identical content) leaves the blob unchanged but the mode different, and a mode-only match to some unrelated historical commit at that path says nothing about whether *this specific mode change* ever landed. The check requires both blob AND mode to match at the same historical commit (`git ls-tree`, not `git rev-parse \"$commit:$path\"` alone) — found by `cross-model-review` (Codex fresh-eyes, confirmed by Claude's Phase 2 pass), which corrected an earlier, too-lenient informational classification of the same gap from this session's own `security-reviewer` dispatch. |\n| \"The default-branch lookup for a deleted path failed, so the path must be gone\" | A failed git object lookup isn't the same as \"path absent\" — `git cat-file -e \"$default_branch:$path\"` fails identically whether the path is genuinely gone or merely has an unreadable\u002Fcorrupted blob object at a path that's still very much present. The deletion check uses `git ls-tree` instead, which never needs to open the blob to answer \"does this path exist in the tree\" — found by `cross-model-review` round 2 (Codex fresh-eyes), the exact same read-failure-vs-absence anti-pattern already fixed twice elsewhere in this check, missed in this one remaining spot. |\n| \"The blob exists somewhere in the default branch's history, so it's reachable\" | Existing *anywhere* in history isn't enough — a path added then deleted from the default branch entirely BEFORE the tag's own branch diverged, then coincidentally re-added with byte-identical content on the tag's own branch, matches that stale PRE-divergence state under an unbounded search, even though the default branch never actually restored it after diverging. The check bounds the search to the tag's own merge-base with the default branch onward (plus the merge-base's own tree directly, for content genuinely inherited unchanged) — found live on the real PR by GitHub's automated Codex connector review (P1), reproduced in a scratch repo before fixing: delete a file on `main`, re-add it identically only on a feature branch, delete the branch — the unbounded search reported the backup tag reachable even though the file was never restored to `main`. |\n| \"The merge's `--cc` diff is empty, so it contributes nothing new and is safe to skip\" | `--cc` only shows a path that differs from EVERY parent — a merge that force-resolves to exactly ONE parent's state for a path is invisible to `--cc` by definition, even when that represents real content loss relative to the OTHER parent. The check now diffs a merge against EACH parent separately (`git diff-tree -m`, the same technique used elsewhere in this check) and runs every resulting record through the normal per-path check, rather than treating an empty `--cc` diff as a \"nothing to verify\" signal — found live on the real PR by GitHub's automated Codex connector review (P1 on a later commit), reproduced in a scratch repo before fixing: one parent adds a file, the other parent is a divergent branch with zero real content changes of its own, and the tag's own merge is forced to drop the file (matching the empty-change parent exactly) — `--cc` reported no diff at all, but the default branch (the parent that added the file) still had it. |\n| \"Since the tag's own FINAL state at a path matches the default branch, any EARLIER intermediate blob for that path must also be safe to skip\" | A tempting shortcut (tried and reverted before shipping, issue #317) — but blob-identity alone can't tell \"superseded on the way to an equivalent final state\" apart from \"discarded via an unrelated revert.\" Live-verified counter-example (`security-reviewer`\u002F`cross-model-review`, Codex fresh-eyes, high confidence): a tag adds unique content to a path, then a LATER commit in the SAME tag reverts that path back to the default branch's own untouched original — the tag's tip trivially matches the default branch, but the reverted-away unique content exists nowhere else and would be permanently lost. No safe narrowing of the shortcut was found that still resolves #317's own reordering case (see `is_path_blob_reachable`'s own comment for why); #317-shaped tags are correctly left \"needs review\" and resolved via the guided-manual-review feature's human-reviewed `--diff`\u002F`--force` instead. |\n\n## Testing & Validation\n\n**Verify this skill activates on:** \"clean up my old branches and worktrees\"; \"I have a bunch of stale\nbranches, help me clean up\".\n\n**Verify it does NOT activate on:** \"delete this one specific branch\" with no broader cleanup context;\nautomated or headless invocation (two user confirmations are required).\n\n**Quality gates:**\n- [ ] Nothing is deleted before both Gate 1 and Gate 2 are answered.\n- [ ] Phase 4 runs `--porcelain` and `--ignored` for every worktree, through `git -C`, never `cd`.\n- [ ] Tags are deleted only through `delete-rebase-backup-tags.sh` indices, never a typed tag name.\n\n## Reference Guide\n\n| Resource | Purpose |\n|---|---|\n| `references\u002Fcritical-implementation-notes.md` | Squash-merge `-D`, PR-history commands, Safety Rule 10 rationale |\n| `references\u002Fguided-manual-review.md` | Phase 7's full guided tag-review procedure |\n| [references\u002Ftesting-and-validation.md](references\u002Ftesting-and-validation.md) | Phase 4 and 3.6 scenarios, full quality-gates checklist |\n| `references\u002Fcleanup-report-example.md` | Phase 6 report example |\n| `assets\u002Fanalysis-report-template.md` | Gate 1 analysis layout |\n| `scripts\u002Fphase1-analysis.sh`, `scripts\u002Fdelete-rebase-backup-tags.sh` | Phase 1 analysis; tag listing and deletion |\n",{"name":5,"description":7,"allowed-tools":23,"disable-model-invocation":24},"Bash(git branch:*), Bash(git worktree:*), Bash(git fetch:*), Bash(git log:*), Bash(git status:*), Bash(git symbolic-ref:*), Bash(git -C:*), Bash(gh pr view:*), Bash(gh repo view:*), Bash(gh api -X DELETE repos\u002F*\u002Fgit\u002Frefs\u002Fheads\u002F*:*), Bash(bash ${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fgit-write-marker.sh:*), Bash(*\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fphase1-analysis.sh:*), Bash(*\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh:*), Read, Grep",true,"main","ad124135f34e2c98738551682726d2a481ada583","plugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace","https:\u002F\u002Fgithub.com\u002FAndreHahm","2026-11-15 04:26:16",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":24},[33,36,39],{"tool":34,"command":35},"npx","npx skills add AndreHahm\u002Fandres-cc-marketplace --skill git-cleanup",{"tool":37,"command":38},"bunx","bunx skills add AndreHahm\u002Fandres-cc-marketplace --skill git-cleanup",{"tool":40,"command":41},"pnpm","pnpm dlx skills add AndreHahm\u002Fandres-cc-marketplace --skill git-cleanup","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002FSKILL.md",[44,50,56,60,64,68,74,78,82],{"path":45,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":48,"sourceHtmlUrl":49},"assets\u002Fanalysis-report-template.md","ASSET","资产文件",2728,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Fassets\u002Fanalysis-report-template.md",{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"references\u002Fcleanup-report-example.md","REFERENCE","参考文档",611,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Freferences\u002Fcleanup-report-example.md",{"path":57,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":58,"sourceHtmlUrl":59},"references\u002Fcritical-implementation-notes.md",4043,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Freferences\u002Fcritical-implementation-notes.md",{"path":61,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":62,"sourceHtmlUrl":63},"references\u002Fguided-manual-review.md",28088,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Freferences\u002Fguided-manual-review.md",{"path":65,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":66,"sourceHtmlUrl":67},"references\u002Ftesting-and-validation.md",80613,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Freferences\u002Ftesting-and-validation.md",{"path":69,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":72,"sourceHtmlUrl":73},"scripts\u002Fdelete-rebase-backup-tags.sh","SCRIPT","脚本",73491,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fdelete-rebase-backup-tags.sh",{"path":75,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":76,"sourceHtmlUrl":77},"scripts\u002Fphase1-analysis.sh",11926,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fphase1-analysis.sh",{"path":79,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":80,"sourceHtmlUrl":81},"scripts\u002Fsmoke_test.py",7956,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Fsmoke_test.py",{"path":83,"resourceType":70,"resourceTypeDesc":71,"sizeBytes":84,"sourceHtmlUrl":85},"scripts\u002Ftest-content-reachable.sh",87960,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fgit-kit\u002Fskills\u002Fgit-cleanup\u002Fscripts\u002Ftest-content-reachable.sh",[87,94,101,108,115,122],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":18},"01M79R0K918Z0XDM74R0EY5H3P","demo","Fixture skill used by scripts.marketplace_ci sync tests.","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Ftests\u002Fmarketplace_ci\u002Ffixtures\u002Fplugins\u002Fsample-kit\u002Fskills\u002Fdemo\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":18},"01M79R08VMDJA2FPJKH3ZM309K","export-demo","Fixture skill used by scripts.marketplace_ci export tests.","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Ftests\u002Fmarketplace_ci\u002Ffixtures\u002Fclaude\u002Fskills\u002Fexport-demo\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":18},"01M79R042FS581DS2JNW5AZ1MK","work-to-development","Validate an accepted Linear Issue's readiness for implementation (criteria, dependencies, duplicate\u002Fexisting artifacts) and request governed branch\u002Fworktree creation through git-kit:starting-work — recording work-started Git\u002FGitHub evidence and a deliberate Linear Started transition only after Git identity is read back and verified. Use when asked to start work on a Linear issue, begin development for an accepted issue, or prepare an accepted issue for implementation. Never creates a branch directly — always delegates to git-kit.","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fworkmanagement-kit\u002Fskills\u002Fwork-to-development\u002FSKILL.md",[],[],{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":18},"01M79QZZD4EHB82P72P4N92BKT","work-linking","Create and maintain stable cross-system links and authority labels between Notion and Linear records, and detect\u002Frepair drift between them. Use when asked to link a Notion record to a Linear record, check for drift between Notion and Linear, or repair a broken\u002Fstale link. Repairs only the bounded non-authoritative copy or link — never chooses by newest timestamp, and never creates a reverse-write loop against either system's own authority.","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fworkmanagement-kit\u002Fskills\u002Fwork-linking\u002FSKILL.md",[],[],{"skillNo":116,"name":117,"nameZh":6,"description":118,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":119,"categories":120,"keywords":121,"publishedAt":18},"01M79QZVFA3GTVNZMJ51NESVSP","status-and-learning","Produce a dated, explicitly non-live Linear-to-Notion progress summary, or capture an outcome\u002Flearning after work completes. Use when asked to summarize progress to Notion, report portfolio status, or capture what was learned from a completed piece of work — not to disposition open follow-up items (see open-item-management for that). Never runs automatically or continuously — every summary is a deliberate, approved snapshot, not a live sync.","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fworkmanagement-kit\u002Fskills\u002Fstatus-and-learning\u002FSKILL.md",[],[],{"skillNo":123,"name":124,"nameZh":6,"description":125,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":18},"01M79QZNSKSABK7X2PT93X8QT5","repository-gates","Discover, delegate, record, and invalidate this repository's actual Git\u002FGitHub lifecycle gates (pre-commit, pre-push, PR required checks, Codex delta review, review requirements, merge rights) and the repository-policy provider profile that maps governed operations to git-kit. Use when asked what gates apply to this repository, to discover repository policy before starting Wave 2 work, or to check whether prior gate evidence is still valid after new commits. Discovery and delegation only — never executes a gate's own internal logic, and never invents a gate the repository doesn't actually define (in particular, never assumes a \"Review Changes\" gate exists).","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fworkmanagement-kit\u002Fskills\u002Frepository-gates\u002FSKILL.md",[],[]]