git-cleanup
Safely analyzes and cleans up local git branches and worktrees by categorizing them as merged, squash-merged, superseded, or active work.
- License 许可
- Apache-2.0
- 最近更新
- 2026-11-15
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- git-cleanup
- description
- Safely analyzes and cleans up local git branches and worktrees by categorizing them as merged, squash-merged, superseded, or active work.
- allowed-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/*/git/refs/heads/*:*), Bash(bash ${CLAUDE_PLUGIN_ROOT}/scripts/git-write-marker.sh:*), Bash(*/git-kit/skills/git-cleanup/scripts/phase1-analysis.sh:*), Bash(*/git-kit/skills/git-cleanup/scripts/delete-rebase-backup-tags.sh:*), Read, Grep
- disable-model-invocation
- true
02 资源文件 9
- 资产文件assets/analysis-report-template.md2.7 KB
- 参考文档references/cleanup-report-example.md611 B
- 参考文档references/critical-implementation-notes.md3.9 KB
- 参考文档references/guided-manual-review.md27.4 KB
- 参考文档references/testing-and-validation.md78.7 KB
- 脚本scripts/delete-rebase-backup-tags.sh71.8 KB
- 脚本scripts/phase1-analysis.sh11.6 KB
- 脚本scripts/smoke_test.py7.8 KB
- 脚本scripts/test-content-reachable.sh85.9 KB
03 SKILL.md 正文
Git Cleanup
Safely clean up accumulated git worktrees and local branches by categorizing them into: safely deletable (merged), potentially related (similar themes), and active work (keep).
On the Bash(git -C:*) grant: this is broad by necessity, not oversight — Phase 4's dirty-state and
gitignored-content checks run git -C <worktree-path> status --porcelain[--ignored] against a worktree
path that's only known at runtime, and Bash(prefix:*) permission syntax can't express "any -C <path>
but only followed by status" without a wrapper script. Reviewed 2026-08-11 (git-kit retro follow-up);
no narrower grant is expressible with the current permission syntax.
Quick Start
- Run from a session in the primary checkout, only on the user's explicit
/git-cleanup. - Analyze and group branches, remote leftovers and rebase-backup tags (Phases 1-3.6), then check every
worktree for dirty and gitignored content with
git -C, nevercd(Phase 4). - Gate 1: present the analysis. Gate 2: confirm the exact deletions, then execute (Phase 5).
- Report what was deleted and what remains (Phase 6); optionally offer Phase 7's guided tag review.
When to Use
- When the user has accumulated many local branches and worktrees
- When branches have been merged but not cleaned up locally
- When remote branches have been deleted but local tracking branches remain
When NOT to Use
- Do not use for general remote branch management (this is local cleanup only) — narrow exception:
Phase 3.5's remote-branch fallback deletes a remote branch only when its own PR is live-confirmed
MERGEDviagh pr view, as a repair for a knowngh pr merge --delete-branchfailure mode (see Phase 3.5 for the mechanism). It never deletes a remote branch for any other reason — an open PR, no PR at all, or "no local counterpart" alone are never sufficient by themselves. - Do not use for repository maintenance tasks like gc or prune
- Not designed for headless or non-interactive automation (requires user confirmations at two gates)
- Cannot run from a session sandboxed to a worktree checkout — this command needs to operate on the
primary checkout's branch/worktree list, and a worktree-sandboxed session cannot
cdthere. Run it from a session started in the primary checkout instead. Seefinishing-work's hand-off note for the same constraint on the more common path into this skill.
Core Principle: SAFETY FIRST
Never delete anything without explicit user confirmation. This skill uses a gated workflow where users must approve each step before any destructive action.
Critical Implementation Notes
See references/critical-implementation-notes.md for the
squash-merge -D requirement, the PR-history investigation commands and why Safety Rule 10's
rebase-backup tag reachability check is built the way it is — the branch-grouping procedure
itself is already fully covered by Phase 2 below, so the reference file doesn't restate it. Read the
reference before Phase 3 (Categorize) for the squash-merge nuance; the PR-history commands apply
specifically to [gone] branches within Phase 2/3.
Workflow
Phase 1: Comprehensive Analysis
Gather ALL information upfront before any categorization. Run "${CLAUDE_PLUGIN_ROOT}/skills/git-cleanup/scripts/phase1-analysis.sh" directly via Bash — it resolves the default branch, lists local branches and worktrees, fetches/prunes, 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/<branch> 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.
Note on branch names: Git branch names can contain characters that break shell expansion. Always quote "$branch" in commands.
Phase 2: Group Related Branches
Do this BEFORE individual categorization.
Identify branch groups by shared prefixes:
# List branches and extract prefixes
git branch --format='%(refname:short)' | sed 's/-[^-]*$//' | sort | uniq -c | sort -rn
For each group with 2+ branches:
- Compare commit histories - Which branches contain commits from others?
- Find merge evidence - Which PRs incorporated work from this group?
- Identify the "final" branch - Usually the most recent or most complete
- Mark superseded branches - Older iterations whose work is in main or in a newer branch
SUPERSEDED requires evidence, not just shared prefix:
- A PR merged the work into main, OR
- A newer branch contains all commits from the older branch
- Name prefix alone is NOT sufficient — similarly named branches may contain independent work
Example analysis for feat/api-* branches:
### Related Branch Group: feat/api-*
| Branch | Commits | PR Merged | Status |
|--------|---------|-----------|--------|
| feat/api | 12 | #29 (initial API) | Superseded - work in main |
| feat/api-v2 | 8 | #45 (API improvements) | Superseded - work in main |
| feat/api-refactor | 5 | #67 (refactor) | Superseded - work in main |
| feat/api-final | 4 | None found | Superseded by above PRs |
**Recommendation:** All 4 branches can be deleted - work incorporated via PRs #29, #45, #67
Phase 3: Categorize Remaining Branches
For branches NOT in a related group, categorize individually:
Is branch merged into default branch?
├─ YES → SAFE_TO_DELETE (use -d)
└─ NO → Is tracking a remote?
├─ YES → Remote deleted? ([gone])
│ ├─ YES → Was work squash-merged? (check main for PR)
│ │ ├─ YES → SQUASH_MERGED (use -D)
│ │ └─ NO → REMOTE_GONE (needs review)
│ └─ NO → Local ahead of remote? (check: git log origin/<branch>..<branch>)
│ ├─ YES (has output) → UNPUSHED_WORK (keep)
│ └─ NO (empty output) → SYNCED_WITH_REMOTE (keep)
└─ NO → Has unique commits?
├─ YES → LOCAL_WORK (keep)
└─ NO → SAFE_TO_DELETE (use -d)
Category definitions:
| Category | Meaning | Delete Command |
|---|---|---|
| SAFE_TO_DELETE | Merged into default branch | git branch -d |
| SQUASH_MERGED | Work incorporated via squash merge | git branch -D |
| SUPERSEDED | Part of a group, work verified in main via PR or in newer branch | git branch -D |
| REMOTE_GONE | Remote deleted, work NOT found in main | Review needed |
| UNPUSHED_WORK | Has commits not pushed to remote | Keep |
| LOCAL_WORK | Untracked branch with unique commits | Keep |
| SYNCED_WITH_REMOTE | Up to date with remote | Keep |
| STALE_REMOTE_ONLY | No local branch; remote branch's own PR is live-confirmed MERGED (Phase 3.5) |
gh api -X DELETE |
| 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 <index> |
Phase 3.5: Remote Branch Fallback (stale origin/<branch> after merge)
Why this exists: gh pr merge --delete-branch deletes the local and remote branch together, but its
local half needs to check out the default branch first — which fails with
fatal: '<default>' is already used by worktree ... whenever that default branch is already checked out
elsewhere (near-guaranteed if the merged branch had its own worktree, since the primary checkout almost
always has the default branch checked out). When that local checkout fails, the remote branch deletion is
silently skipped too — merge-pr's own step 7 already works around the resulting non-zero exit by
checking PR state instead of trusting the exit code, but that fix only avoids a false "merge failed"
report; it doesn't repair the branch-deletion gap. finishing-work's own step 1.5 is the primary fix,
applied right after the merge that caused it — this phase is the safety net for anything that slipped
past that (an older merge, a merge run through some other path).
Two cases, both requiring live PR-state confirmation before any deletion — never inferred from branch existence alone:
- Still-listed local branches (from Phase 1's per-branch loop): if a branch already categorized
SAFE_TO_DELETE/SQUASH_MERGED/SUPERSEDEDabove also showsorigin/<branch>as "still exists on origin" in Phase 1's output, its remote counterpart gets deleted alongside the local one — no separate PR check needed here, since that category assignment already required merge evidence. - Remote-only orphans (Phase 1's "Remote-only branches" list — no local counterpart at all, e.g. a
branch a prior
git-cleanuprun already deleted locally before this fallback existed): for each one, rungh pr view <branch> --json state,numberlive. Only ifstateis exactlyMERGED, categorize itSTALE_REMOTE_ONLY. Any other result —OPEN,CLOSED(without merging), or no PR found at all — leaves that branch untouched entirely, not even flagged for review. This is what keeps this phase a narrow repair for one specific known failure mode rather than general remote branch management: a branch with no merged PR evidence is out of scope, full stop.
Phase 3.6: Rebase-Backup Tag Cleanup (leftover git-rebase-sync safety tags)
Why this exists: git-rebase-sync's Step 3 creates a local-only, never-pushed annotated tag
({branch}-rebase-backup-{timestamp}) immediately before every rebase, as a recovery point if the rebase
goes wrong. Nothing in that skill — or anywhere else in git-kit — ever deletes these tags afterward, so
they accumulate indefinitely once the branch they were protecting is long gone or merged.
Phase 1's own tag enumeration (=== Rebase-backup tags ===) already lists every tag matching the exact
{branch}-rebase-backup-{8-digit-date}-{6-digit-time} shape, alongside its derived branch name, that
branch's current status, and — whenever the branch is gone OR merged — whether the tag's own commit is
reachable from the default branch. Categorize each one from that output — no extra git calls needed here:
- Branch exists, not merged → leave the tag alone, no reachability check needed. The branch may still need this recovery point, and the tag being merely old is not evidence otherwise (see Rationalizations below).
- Branch gone OR merged, tag reachable from the default branch →
STALE_REBASE_BACKUP_TAG, safe to delete — the tag's own commit already made it into the default branch, so the tag is redundant. - Branch gone OR merged, tag NOT reachable from the default branch → never categorize as safe to
delete, regardless of which of the two the branch status is. Two independent reasons this happens, not
just one: (1) the branch's own deletion was never verified by this run — it may have been force-deleted
outside this skill's own SAFE_TO_DELETE/SQUASH_MERGED evidence trail; (2) rebasing rewrites commit
SHAs — a merged branch's current tip being an ancestor of the default branch says nothing about
whether the tag's own pre-rebase commit is, since the rebase created a new commit object with a
different parent chain (live-verified: a plain rebase-then-merge sequence leaves
git branch --mergedreporting the branch merged while the pre-rebase tag's own SHA is still unreachable from the default branch). Either way, this tag may be the only remaining reachable copy of its commits. Leave it alone and report it under a distinct "needs review — unique history" note outside the deletable list, the same treatment Phase 3's REMOTE_GONE category already gets for the analogous branch-level case; never fold it into "delete all recommended."
Fold the result into Gate 1 as its own list, the same way Phase 3.5's stale remote branches get their own
list — never silently merge it into the branch categories above, since a tag isn't a branch and
git update-ref -d isn't git branch -d/-D.
Get the deletable list from the script, not by hand-deriving it from Phase 1's raw per-tag facts. Run
"${CLAUDE_PLUGIN_ROOT}/skills/git-cleanup/scripts/delete-rebase-backup-tags.sh" --list — it independently
re-applies the exact rule above (branch gone or merged AND reachable) and prints only the genuinely
deletable tags as a numbered list, snapshotting the exact tag names to a file the delete step (Phase 5)
reads back rather than trusting text typed into this response. Never type a tag name into a
git update-ref -d command yourself, however it was validated — see Phase 5's Execute section for why a character-class
check on a value the agent then composes into a command is never fully safe: a git-legal tag name can
contain almost any shell metacharacter (git check-ref-format accepts e.g. $(cmd)-rebase-backup-...,
live-verified), and there is no character class that is both shell-safe and complete against every
git-legal name (a real gap in an earlier version of this fix — a narrower validating regex rejected
legitimately safe-to-delete tags on branches like feat/c++, git check-ref-format-legal but outside
[A-Za-z0-9._/-], permanently blocking their cleanup even once verified safe; found by cross-model-review
round 2 on PR #262). Present the script's numbered list at Gate 1 for the deletable category, and Phase 1's
raw per-tag output (still gathered in full) for the separate "needs review — unique history" note — the
script's --list output never includes those, so nothing further filters them out.
Phase 4: Dirty State Detection
Check ALL worktrees and current directory for uncommitted changes:
# For each worktree path: always git -C, never cd (a cd rebinds this session to that worktree); pass the
# path as one single-quoted argument, each ' inside it written as '\'' (here and below)
git -C <worktree-path> status --porcelain
# For current directory
git status --porcelain
Also check for gitignored content — git status --porcelain never lists gitignored files, tracked
or not, so a worktree can carry a .env, a local settings override, or other gitignored content that this
check alone would silently miss:
# For each worktree path
git -C <worktree-path> status --porcelain --ignored
# For current directory
git status --porcelain --ignored
Do not use git clean here — it's a destructive command with no place in an analysis-only phase of a
skill whose Core Principle is "never delete anything without explicit user confirmation." --ignored is
read-only and sufficient. If the ignored-file list is long (e.g. node_modules/, .venv/), show only the
top-level entries plus a count rather than every path, so the warning stays readable.
Exclude .claude/settings.local.json and any **/CLAUDE.local.md from this warning — starting-work
now copies both into every worktree it creates from the main worktree's own copy, so a worktree's version
is a duplicate, not the only copy; deleting the worktree does not lose them the way an untracked .env or
scratch file would. Do not list these two patterns under "will also be deleted" below.
Display warnings prominently:
WARNING: ../proj-auth has uncommitted changes:
M src/auth.js
?? new-file.txt
Ignored (not tracked by git, will also be deleted):
.env
These changes will be LOST if you remove this worktree.
Check for session locks: git worktree list --verbose shows locked: <reason> for any locked
worktree (starting-work locks every worktree it creates — see its own Instructions). A locked worktree
recommended for deletion needs an unlock step before git worktree remove — note this against that
worktree in the analysis rather than only discovering it when the removal command itself fails.
GATE 1: Present Complete Analysis
Present everything in ONE comprehensive view. Group related branches together. See assets/analysis-report-template.md for the full example layout (related branch groups, individual branch categories, worktrees, and summary).
Use AskUserQuestion with clear options:
- Delete all recommended (groups + merged + squash-merged + stale remote-only + stale rebase-backup tags)
- Delete specific groups/categories
- Let me pick individual branches
Do not proceed until user responds.
GATE 2: Final Confirmation with Exact Commands
Show the EXACT commands that will run, with correct flags:
I will execute:
# Merged branches (safe delete)
git branch -d fix/typo
# Squash-merged branches (force delete - work is in main via PRs)
git branch -D feat/login
git branch -D feat/api
git branch -D feat/api-v2
git branch -D feat/api-refactor
git branch -D feat/api-final
# Worktrees (unlock first if session-locked, per Phase 4's lock check)
git worktree unlock ../proj-auth
git worktree remove ../proj-auth
# Stale remote branches (Phase 3.5 — PR confirmed MERGED via gh pr view)
gh api -X DELETE repos/<owner>/<repo>/git/refs/heads/feat/old-worktree-feature
# Stale rebase-backup tags (Phase 3.6 — from delete-rebase-backup-tags.sh --list)
# 1 feat/gone-branch-rebase-backup-20260701-093000
"${CLAUDE_PLUGIN_ROOT}/skills/git-cleanup/scripts/delete-rebase-backup-tags.sh" 1
Confirm? (yes/no)
IMPORTANT: This is the ONLY confirmation needed for deletion. Do not add extra confirmations if -D is required.
Phase 5: Execute
Run 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}/scripts/git-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/-f does, since a plain removal already refuses on a dirty or locked worktree via git's own safeguard.
git branch -d fix/typo
bash "${CLAUDE_PLUGIN_ROOT}/scripts/git-write-marker.sh" git-cleanup-destructive git-cleanup
git branch -D feat/login
bash "${CLAUDE_PLUGIN_ROOT}/scripts/git-write-marker.sh" git-cleanup-destructive git-cleanup
git branch -D feat/api
bash "${CLAUDE_PLUGIN_ROOT}/scripts/git-write-marker.sh" git-cleanup-destructive git-cleanup
git branch -D feat/api-v2
bash "${CLAUDE_PLUGIN_ROOT}/scripts/git-write-marker.sh" git-cleanup-destructive git-cleanup
git branch -D feat/api-refactor
bash "${CLAUDE_PLUGIN_ROOT}/scripts/git-write-marker.sh" git-cleanup-destructive git-cleanup
git branch -D feat/api-final
git worktree unlock ../proj-auth
bash "${CLAUDE_PLUGIN_ROOT}/scripts/git-write-marker.sh" git-cleanup-destructive git-cleanup
git worktree remove ../proj-auth
gh api -X DELETE repos/<owner>/<repo>/git/refs/heads/feat/old-worktree-feature
"${CLAUDE_PLUGIN_ROOT}/skills/git-cleanup/scripts/delete-rebase-backup-tags.sh" 1
If a deletion fails, report the error and continue with remaining deletions. If git worktree remove
fails specifically because the worktree is still locked (the unlock step above was skipped, or a lock was
added after Phase 4's check), report this distinctly from a generic removal failure — say plainly that it's
locked and by which reason, rather than surfacing git's raw error text unexplained.
Stale remote branches (Phase 3.5): no marker write needed — gh api -X DELETE repos/*/git/refs/heads/*
isn't guarded by any PreToolUse hook (unlike git branch -D against a protected name), the same reason
merge-pr's own manual-delete-branch path calls it directly. Before each call, validate the branch name
against ^[A-Za-z0-9._/@+=-]+$ — the same safety check merge-pr applies before this exact command, since
git ref names can otherwise contain shell metacharacters (;&|$, backticks, parens) that would reach a
shell context unsafely; if a name fails this check, skip it and report why rather than attempting the call.
Resolve <owner>/<repo> via gh repo view --json nameWithOwner --jq .nameWithOwner once per run, not once per branch.
Stale rebase-backup tags (Phase 3.6): no marker write needed — delete-rebase-backup-tags.sh's own
git update-ref -d call isn't guarded by git-guard-raw-destructive-cleanup.sh (that hook only matches
git branch -D/worktree remove --force), and deleting a tag never touches a protected branch name in
the first place. Never type a tag name into a git update-ref -d command directly, and never pass one
as an argument to any script either — a git tag name is legal with almost any shell metacharacter (e.g.
`$(cmd)-rebase-backup-20260831-120000` is a git-accepted tag name, git check-ref-format confirms
it), so any value the agent composes into a command — even quoted, even as a validated-looking script
argument — is a command-injection surface; and no character-class validation can be both shell-safe and
complete against every git-legal name (a real, found-in-review gap: an earlier ^[A-Za-z0-9._/-]+$ check
rejected legitimate branches like feat/c++, permanently blocking their tags from ever being cleaned up).
Instead, run "${CLAUDE_PLUGIN_ROOT}/skills/git-cleanup/scripts/delete-rebase-backup-tags.sh" --list —
it independently re-derives the deletable set itself (never trusting Phase 3.6's earlier read) and
snapshots the exact tag names to a file; pass back only the plain digit indices shown against Gate 2's
confirmed selections — "${CLAUDE_PLUGIN_ROOT}/skills/git-cleanup/scripts/delete-rebase-backup-tags.sh" <index> [index...] — the same index-only interface git-stage-selected-files.sh already uses for staged
filenames, for the identical reason. The script resolves each tag's current object id via the always-safe
fully-qualified refs/tags/<name> form (never the bare name, which could start with a dash) and deletes
it with git update-ref -d refs/tags/<name> <resolved-oid> — an atomic compare-and-delete that only
succeeds if the ref still points at the exact object just verified safe, closing the race between that
verification and the actual delete (PR #275) — one call per tag internally, so a partial failure part-way
through still lets the rest proceed, and reports which index (if any) failed.
Phase 6: Report
Report what was deleted (branches, worktrees, Phase 3.5 remote branches, Phase 3.6 tags) and what remains, with each remaining branch's status. Example: references/cleanup-report-example.md.
Phase 7: Guided Manual Review (optional, offered after Phase 6 — rebase-backup tags only)
Follow references/guided-manual-review.md in full. In outline: delete-rebase-backup-tags.sh --list-review already drops any candidate with a still-valid "keep" decision recorded and prints a
generation token every later call must pass back — only if anything remains, offer via AskUserQuestion
to walk through them. Per item: show raw evidence (--diff --generation <token> <index>), ask Delete
now / Keep / Skip, require a second confirmation before --force --generation <token> <index>, and use
--keep --generation <token> <index> to record a decision — never a hand-composed jq/git command with a
tag name in it. REMOTE_GONE branches are explicitly NOT covered by this phase yet (an equivalent
name-handling mechanism doesn't exist for branches — see the reference's own "open design problem"
section); continue reporting them exactly as Phase 3 already does. Do not improvise any of this from
memory — the reference has the full procedure and is the only place the decision-file schema lives.
Safety Rules
- Never invoke automatically - Only run when user explicitly uses
/git-cleanup - Two confirmation gates only for the main cleanup flow - Analysis review, then deletion confirmation. Phase 7's guided review is a separate, optional, opt-in extension for residual "needs review" items only, gated by its own offer-then-decide-then-confirm flow — it doesn't add a third gate to the main flow above, since a user who declines Phase 7's offer sees no extra gate at all
- Use correct delete command -
-dfor merged,-Dfor squash-merged/superseded - Never touch protected branches - main, master, develop, release/* are excluded from Phase 1's
per-branch commit-analysis loop by
scripts/phase1-analysis.sh's owngrep -vEfilter (run directly, not just read), and any rawgit branch -Dthat still targets one of these names is additionally hard-blocked by git-kit'sgit-guard-raw-destructive-cleanup.shPreToolUse hook - Block dirty worktree removal - Refuse without explicit data loss acknowledgment. "Dirty" covers
gitignored content too, not just tracked/untracked-but-not-ignored changes —
git status --porcelainalone misses gitignored files entirely, so Phase 4's--ignoredcheck is what actually completes this rule's coverage - Unlock before removing - A session-locked worktree (per Phase 4's lock check) gets
git worktree unlockimmediately beforegit worktree remove, never--forceas a substitute for unlocking —--forcebypasses the dirty-worktree safeguard in Safety Rule 5 too, not just the lock - Group related branches - Don't scatter them across categories
- Never delete a remote branch without live PR-merged confirmation - Phase 3.5's fallback only
deletes
origin/<branch>whengh pr view <branch>confirmsstate: MERGEDat the time of the check, not from "no local branch" or "not in Phase 1's merged list" alone - an open PR, a closed (unmerged) PR, or no PR at all always leaves that branch untouched - Never delete a rebase-backup tag whose originating branch is still active - Phase 3.6 only
proposes a
*-rebase-backup-*tag for deletion when its derived branch no longer exists locally or is already merged into the default branch - an unmerged, still-active branch's backup tag is always left alone, regardless of the tag's own age - Never delete a rebase-backup tag whose branch is gone or merged unless its content is verified
reachable - neither "branch no longer exists locally" nor "branch is merged" is by itself evidence
the tag is redundant (the gone branch's deletion was never verified by this run, and a rebase rewrites
commit SHAs). Phase 3.6 proposes deletion only once the tag's own commit is verified reachable from the
default branch, by raw-SHA ancestry (
git merge-base --is-ancestor) or, failing that, by a per-path blob-AND-mode history search bounded to the tag's merge-base onward (a plain deletion instead requires the path to be absent from the default branch's current tree), with every merge commit in the tag's history diffed against EACH parent (git diff-tree -m). A tag unreachable by both signals is reported separately as needing manual review, never included in "delete all recommended". Why each part of this check exists:references/critical-implementation-notes.md; the code:delete-rebase-backup-tags.sh'sis_tag_content_reachable/is_path_blob_reachable, including its fail-closed handling - Never type a tag name into a command, at all, for any reason - a git tag name is legal with
almost any shell metacharacter (
git check-ref-formataccepts e.g.`$(cmd)-rebase-backup-20260831-120000`), and no character-class check on a value the agent then composes into a command is both shell-safe and complete against every git-legal name (a narrower check tried first rejected legitimate branches likefeat/c++, permanently blocking their cleanup). Deletion always goes throughdelete-rebase-backup-tags.sh's index-only interface instead - the script re-derives the actual tag names itself from a snapshot file, so the agent only ever passes back plain digit indices, never a single character of tag-name content
Rationalizations to Reject
These are common shortcuts that lead to data loss. Reject them:
| Rationalization | Why It's Wrong |
|---|---|
| "The branch is old, it's probably safe to delete" | Age doesn't indicate merge status. Old branches may contain unmerged work. |
| "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. |
| "It's just a local branch, nothing important" | Local branches may contain the only copy of work not pushed anywhere. |
| "The PR was merged, so the branch is safe" | Squash merges don't preserve branch history. Verify the specific commits were incorporated. |
"I'll just delete all the [gone] branches" |
[gone] only means the remote was deleted. The local branch may have unpushed commits. |
| "The user seems to want everything deleted" | Always present analysis first. Let the user choose what to delete. |
| "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/<branch>..<branch>. |
| "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. |
| "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. |
| "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. |
| "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. |
| "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. |
| "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/pr-ci-governance-rebase-backup-20260907-210042 tag, whose one commit's 13 files landed on the default branch split across two separate commits). |
| "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/symlink 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. |
| "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/corrupted 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. |
| "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. |
"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. |
| "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/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/--force instead. |
Testing & Validation
Verify this skill activates on: "clean up my old branches and worktrees"; "I have a bunch of stale branches, help me clean up".
Verify it does NOT activate on: "delete this one specific branch" with no broader cleanup context; automated or headless invocation (two user confirmations are required).
Quality gates:
- [ ] Nothing is deleted before both Gate 1 and Gate 2 are answered.
- [ ] Phase 4 runs
--porcelainand--ignoredfor every worktree, throughgit -C, nevercd. - [ ] Tags are deleted only through
delete-rebase-backup-tags.shindices, never a typed tag name.
Reference Guide
| Resource | Purpose |
|---|---|
references/critical-implementation-notes.md |
Squash-merge -D, PR-history commands, Safety Rule 10 rationale |
references/guided-manual-review.md |
Phase 7's full guided tag-review procedure |
| references/testing-and-validation.md | Phase 4 and 3.6 scenarios, full quality-gates checklist |
references/cleanup-report-example.md |
Phase 6 report example |
assets/analysis-report-template.md |
Gate 1 analysis layout |
scripts/phase1-analysis.sh, scripts/delete-rebase-backup-tags.sh |
Phase 1 analysis; tag listing and deletion |
04 同仓库更多 Skills
demo
Fixture skill used by scripts.marketplace_ci sync tests.
export-demo
Fixture skill used by scripts.marketplace_ci export tests.
work-to-development
Validate an accepted Linear Issue's readiness for implementation (criteria, dependencies, duplicate/existing artifacts) and request governed branch/worktree creation through git-kit:starting-work — recording work-started Git/GitHub 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.
work-linking
Create and maintain stable cross-system links and authority labels between Notion and Linear records, and detect/repair 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/stale 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.
status-and-learning
Produce a dated, explicitly non-live Linear-to-Notion progress summary, or capture an outcome/learning 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.
repository-gates
Discover, delegate, record, and invalidate this repository's actual Git/GitHub 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).