/git-cleanup:git-cleanup [--all] [--dry-run]from git-cleanup
Audit local branches and worktrees against GitHub PR state, auto-clean unambiguously safe branches, prompt on the rest. Conservative, with `--all` sweep across ~/Workspace and `--dry-run`. Use when user types `/git-cleanup` or asks to audit branches, clean up branches or PRs, prune stale branches, check what branches can be deleted, or tidy a repo.
Ships in git-cleanup. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Audit local branches and worktrees against GitHub PR state. Auto-clean the unambiguously safe set. Prompt on the ambiguous set. Never touch the current branch, default branch, branches with open or draft PRs, or worktrees with uncommitted changes.
| Invocation | Scope | Destructive? |
|---|---|---|
/git-cleanup | Current repo at $PWD | Yes (auto-clean + prompted) |
/git-cleanup --all | Every repo under ~/Workspace/<owner>/<repo> | Yes (auto-clean + prompted, batched) |
/git-cleanup --dry-run | Audit only, prints plan, exits | No |
/git-cleanup --all --dry-run | Audit sweep across ~/Workspace, prints plan, exits | No |
Conservative posture only. There is no --aggressive flag.
Two read-only Node helpers ship in scripts/ next to this file. Use them instead of hand-writing per-run classification: they do the whole truth table in one call with no permission prompts, because the plugin lives under ~/.claude/plugins/ and the node <plugins-path>/* invocation is allowlisted. Both are read-only (no deletes, no ref writes, no fetch) so the destructive-git guardrail keeps gating actual removals.
Invoke by absolute path to this skill's scripts/ dir (call it SKILL_SCRIPTS), e.g. node "$SKILL_SCRIPTS/audit.mjs" … where $SKILL_SCRIPTS is the directory containing this SKILL.md plus /scripts.
audit.mjs: the whole Classify phase in one pass. Enumerates branches (git for-each-ref), worktrees with dirty state and ignored files (git worktree list --porcelain + git status --ignored), pulls gh pr list, applies the truth table and worktree guards below, prints the grouped AUTO/PROMPT/NEVER plan. --json for machine output; skips the PR rows if gh is unavailable. Does not fetch: run git fetch --prune first.
node "$SKILL_SCRIPTS/audit.mjs" [--repo owner/repo] [--cwd DIR] [--json]
Everything it wraps (git *, gh *, jq *) is independently allowlisted, so any step can also be run inline. Never reach for python3, standalone VAR=, $(…), or a heredoc piped into gh: all of those escalate to a permission prompt.
Run unconditionally before classification, in this order:
git fetch --prune (refreshes [gone] markers and merge state).git worktree prune (clears orphaned .git/worktrees/<name> metadata).In --dry-run, run git fetch --prune only. Skip git worktree prune (it deletes worktree metadata) and all destructive actions.
For each local branch, evaluate the rules top-down and stop at the first match. Action is one of AUTO, PROMPT, NEVER.
PR match takes precedence over upstream tracking state. A merged PR proves the work landed on master regardless of where the local branch's upstream points. A closed-not-merged PR proves the work was abandoned, regardless of whether [gone] was set on the upstream.
"PR match" means: the cached PR list contains a PR whose headRefName equals the local branch name or, when the local branch's upstream is [gone], equals the gone-upstream's branch name parsed from git branch -vv (e.g., for [origin/api-gateway-v0-envelope: gone] the candidate name is api-gateway-v0-envelope). Match by local name takes precedence; fall back to upstream name. The reason printed cites the matched name, e.g., PR #917 closed (was tracking origin/api-gateway-v0-envelope).
| # | Condition | Action | Reason printed |
|---|---|---|---|
| 1 | Branch checked out in the audited ($PWD) worktree | NEVER | current branch |
| 2 | main, master, or the resolved default branch | NEVER | default branch |
| 3 | Worktree's git -C <wt> status --porcelain returns non-empty | NEVER | uncommitted changes in worktree |
| 4 | PR matches by headRefName AND PR state is OPEN or DRAFT | NEVER | PR #N open/draft |
| 5 | PR matches, state MERGED or CLOSED, AND the local tip is neither the PR's headRefOid nor an ancestor of it (git merge-base --is-ancestor) | PROMPT | PR #N merged/closed, local tip not in PR head |
| 6 | PR matches AND PR state is MERGED | AUTO local; PROMPT remote-delete if git ls-remote --heads origin <branch> returns a ref | PR #N merged |
| 7 | PR matches AND PR state is CLOSED (not merged) | PROMPT | PR #N closed |
| 8 | No PR match (neither local name nor gone-upstream name) AND upstream is [gone] AND git rev-list <branch> --not --remotes is empty | AUTO | upstream gone, no PR |
| 9 | No PR match AND upstream is [gone] AND the branch has commits on no remote ref | PROMPT | upstream gone, no PR, N commits on no remote |
| 10 | No PR match AND branch has unpushed commits (ahead of origin/<this-branch>) | PROMPT | N unpushed commits |
| 11 | No PR match AND no upstream (never pushed) | PROMPT | no PR, never pushed |
| 12 | No PR match AND upstream tracks a ref that is not origin/<this-branch> | PROMPT | no PR, tracks <ref> |
| 13 | No PR match AND in sync with or behind origin/<this-branch> | PROMPT | no PR, in sync with origin (or the track state, e.g. [behind 2]) |
Resolved default branch: the origin/HEAD target; if origin/HEAD is unset, origin/main or origin/master when that ref exists; otherwise git config init.defaultBranch, else main. Row 2 protects main and master regardless of what resolves.
Row 5 catches a branch name reused for new work after an old PR on that name was merged or closed. A branch force-pushed by a rebase can also land here (its local tip is a pre-rebase state); PROMPT is the intended outcome.
Tie-break: if a branch matches multiple PRs (rare; closed-then-reopened), pick the most recent by updatedAt.
Row 6 detail: the remote-delete prompt fires per-branch at the end of the AUTO sweep, batched (see step 8 of the single-repo flow). Probe with git ls-remote --heads origin <branch> rather than relying on git branch -vv markers, because the local tracking ref may be stale or absent.
After the truth table, two worktree guards run on any branch a worktree holds (NEVER results are left alone):
; worktree path missing (prunable). On confirm, run git worktree prune instead of worktree remove, then git branch -D.git -C <wt> status --ignored --porcelain, !! lines): demote to PROMPT, reason suffixed ; worktree has N ignored paths (...), because git worktree remove --force deletes ignored files such as gitignored tmp/ notes. Paths under node_modules, .turbo, .next, .cache, dist, or bin count as regenerable build caches and are not counted. Neither does a *.local.conf whose first line is a # Managed by ... do not edit marker, such as the per-worktree database overlays a repo's scripts/worktree-setup.sh writes; an unmarked *.local.conf may hold hand edits and still counts.Then:
git worktree remove --force <path>), then git branch -D <name>.gh pr list --state all --limit 1000 --json number,state,headRefName,headRefOid,updatedAt --repo <owner/repo> per repo. Cache results for the run.--author @me. Match by headRefName client-side so co-authored branches are covered.gh pr list --head <ref> --state all --json number,state,headRefName,headRefOid,updatedAt query, for the local name and then the gone-upstream name. A failed per-branch query classifies the branch PROMPT (per-branch PR lookup failed).gh is unavailable or unauthenticated, or there is no origin remote to derive owner/repo from: skip rows 4-7 (they depend on PR match) and apply rows 1-3 and 8-13. Print one-line notice./git-cleanup)Preflight.
$PWD is a git repo: git -C "$PWD" rev-parse --is-inside-work-tree.git -C "$PWD" branch --show-current.git -C "$PWD" symbolic-ref refs/remotes/origin/HEAD | sed 's|^refs/remotes/origin/||', with the fallbacks under the truth table when origin/HEAD is unset.git -C "$PWD" worktree list --porcelain. Note which branch each worktree holds.git -C "$PWD" worktree prune (skipped in --dry-run).Refresh state. git -C "$PWD" fetch --prune.
Enumerate + Classify. Run node "$SKILL_SCRIPTS/audit.mjs" --cwd "$PWD" --json (see Helper scripts). One call enumerates branches, worktrees with dirty state and ignored files, pulls gh pr list, applies the truth table and worktree guards, and returns rows[] with action, reason, worktree path, and ignored paths per branch. Fall back to the inline commands below only if the script is unavailable:
git -C "$PWD" for-each-ref --format='%(refname:short)\t%(upstream:short)\t%(upstream:track)' refs/heads/.git -C "$PWD" worktree list --porcelain (cross-reference worktree paths).gh pr list --state all --limit 1000 --json number,state,headRefName,headRefOid,updatedAt --repo <owner/repo> once; cache by headRefName.Bucket the PROMPT set by reason for step 7: closed PR (row 7), PR head mismatch (row 5), unpushed commits (rows 9-10), no PR (rows 11 and 13), non-origin tracked (row 12), worktree guard (missing path or ignored files), PR lookup failed.
Print the plan. Always, before executing any destructive action:
git-cleanup audit: <repo-name>
================================
AUTO (N): branch-a [reason] | branch-b [reason] | ...
PROMPT (N): branch-c [reason] | branch-d [reason] | ...
NEVER (N): branch-e [reason] | branch-f [reason] | ...
Execute AUTO set. For each AUTO branch, in order:
git -C "$PWD" worktree remove --force <worktree-path>.git -C "$PWD" branch -D <branch>.[AUTO] deleted <branch> (and worktree at <path>).Walk PROMPT set, one batch per reason bucket. For each bucket with N items:
<N> <bucket-reason>: delete all? [y/N/i]ndividual.y: delete all in the bucket (worktree-remove first, then branch -D).N: skip the entire bucket.i: fall through to per-branch [y/N/s]kip prompts.Remote-deletion sub-prompt (only for branches deleted via row 6, merged PR, whose origin/<branch> still exists). After the main loop:
git ls-remote --heads origin <branch>. Collect those that return a non-empty result.Push-delete <N> merged remote branches on origin? [y/N/i].git -C "$PWD" push origin --delete <branch> per branch.Stale-worktree sub-prompt. Collect worktrees with detached HEAD, missing on-disk paths, or already-deleted branches. Ask: Prune <N> stale worktree paths? [y/N/i]. On confirm: git -C "$PWD" worktree remove --force <path> for paths that exist; git -C "$PWD" worktree prune to clean metadata for missing paths.
Final summary. Print counts: deleted (AUTO), deleted (PROMPT-confirmed), kept (PROMPT-declined), never-touched, errors.
/git-cleanup --dry-run)Behaves like the single-repo flow with these differences:
Runs git fetch --prune and gh pr list. Does not run git worktree prune.
Prints the full plan exactly as in step 5 of the single-repo flow.
Exits before steps 6-10 with the message:
dry-run: nothing changed. Re-run without --dry-run to execute.
--dry-run composes with --all.
/git-cleanup --all)Walks every directory matching ~/Workspace/<owner>/<repo> exactly two levels deep.
find ~/Workspace -mindepth 2 -maxdepth 2 -type d
For each candidate path:
<path>/.git does not exist.<path>/.git is a file (git submodule checkout)..worktree/ subdirs (handled by their parent repo, never enumerated as a top-level repo).For each discovered repo, in sequence:
<repo>: AUTO <n>, PROMPT <n>, NEVER <n> or <repo>: skipped (<reason>).<repo>: <branch> [reason].fetch failed, no origin remote, gh unavailable.After Pass 1 completes for all repos, walk the global PROMPT queue once, grouped by reason bucket (not by repo):
i falls through to per-item prompts in the form <repo>: <branch> [reason], delete? [y/N/s]kip.
After all branch deletions across all repos:
Print a table grouped by repo:
repo AUTO PROMPT-yes PROMPT-no NEVER errors
acme/api 3 2 1 5 0
webrpc 1 0 0 3 0
...
[AUTO], [PROMPT], [NEVER], [SKIP], [ERROR]. No emoji.feat-x [PR #918 merged, local == remote].y / n / i / s.| Failure | Behavior |
|---|---|
| Not in a git repo (single mode) | Abort with message |
gh not installed or not authenticated | Skip rows 4-7 (they depend on PR match); apply rows 1-3 and 8-13. One-line notice. |
git fetch network failure | Abort (classification depends on fresh state). Single mode: exit. Sweep mode: skip the repo with reason fetch failed. |
| Worktree path no longer on disk | Branch demoted to PROMPT by the worktree guard; a detached one goes to the stale-worktree prompt. Not an error. |
| Currently inside a worktree on an otherwise-deletable branch | Mark NEVER. Print: cd to main repo at <path> and re-run to delete <branch>. |
Repo with no origin remote | No owner/repo to query, so handled as gh unavailable: skip rows 4-7. |
gh pr list returns the full 1000 PRs | Per-branch gh pr list --head <branch> for unmatched branches; a failed lookup classifies PROMPT. |
$PWD worktree. A branch checked out in another clean worktree is eligible; its worktree is removed first (rail 3).git branch -D before removing the worktree pointing at it.--all sweep without classifying first; no "delete first, ask later".The skill does not:
TODO.local.md or ~/TODO.md.origin remotes beyond classifying their branches as PROMPT.origin is a fork and PRs live on upstream). PR matching will miss; affected branches degrade to the no-PR rows (8-13).--all sweep.What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub klaidliadon/claude-plugins --plugin git-cleanup