
Clean Branches
- 34 installs
- 269 repo stars
- Updated June 11, 2026
- gupsammy/claudest
Clean-branches is an agent skill that finds merged and stale git branches and flags worktree checkouts before you delete anything.
About
Clean-branches is a git hygiene agent skill built around find-candidates.sh, which scans your repository for branches that are already merged into main (or master) and branches that look stale, without immediately deleting anything. Solo builders accumulate feature branches quickly; this skill gives a labeled, machine-friendly report so you or your agent can decide what to prune. It understands git worktrees, marking any branch currently checked out in another worktree so you avoid destructive surprises. The pattern is deliberately conservative: discovery only, always exit zero, and you pair the output with your own delete or archive step. It is ideal after a merge train or before a release when you want a tidy default branch graph. Compatible with agents that can run bash in a repo with standard git and worktree support.
- find-candidates.sh emits labeled MERGED and STALE sections, one branch per line
- Auto-detects base branch as main or master before comparing merges
- Maps branches to active git worktrees and annotates lines as branch [worktree:/path]
- Optional glob pattern filter as the first script argument
- Exit 0 always—downstream tooling decides whether empty sections mean no action
Clean Branches by the numbers
- 34 all-time installs (skills.sh)
- Ranked #345 of 733 Git & Pull Requests skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/gupsammy/claudest --skill clean-branchesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 34 |
|---|---|
| repo stars | ★ 269 |
| Security audit | 3 / 3 scanners passed |
| Last updated | June 11, 2026 |
| Repository | gupsammy/claudest ↗ |
What it does
List merged and stale local git branches safely before cleanup, with worktree paths annotated so you do not delete active checkouts.
Who is it for?
Best when you're maintaining long-lived repos and want scripted branch discovery after PR merges.
Skip if: Hosted GitHub-only cleanup without a local clone, or repos with neither main nor master as the integration branch.
When should I use this skill?
You need a merged and stale branch report in a local git repo, optionally filtered by pattern, before deleting branches.
What you get
You get a MERGED and STALE candidate list with worktree annotations so you can safely plan branch cleanup.
- MERGED section listing merge-complete branches
- STALE section listing stale candidates with optional worktree annotations
By the numbers
- Two labeled output sections: MERGED and STALE
Files
Clean Git Branches
Safely remove merged and stale git branches with confirmation.
Process
If $ARGUMENTS is provided, treat it as a glob pattern to filter branch candidates (e.g., feature/*) and pass it to the candidate script in Step 1.
1. Fetch latest state
git fetch --all --pruneIf fetch fails (no remotes configured), note remote data is unavailable and continue with local analysis only.
2. Identify candidates
Run the candidate detection script, passing the optional pattern filter:
bash ${CLAUDE_PLUGIN_ROOT}/skills/clean-branches/scripts/find-candidates.sh "$PATTERN"The script outputs two labeled sections (=== MERGED === and === STALE ===), one branch per line. Branches carry two optional annotations:
[worktree:/path/to/wt]— branch is checked out in a worktree[squash-merged]— branch was merged via squash or rebase PR; git does not recognize it as merged locally (requires force-delete in Step 5)
Parse each section into its own list, preserving both annotations.
After parsing, apply these worktree rules before building the candidate lists. Process the MERGED list first, then the STALE list — a branch that appears in both (merged AND older than 30 days) is governed by the MERGED rule only; skip it when processing STALE.
- Stale branch + active worktree → move immediately to the blocked list, regardless of worktree state. A stale branch with a live worktree may still have in-progress work — never offer it for cleanup. Skip branches already classified as merged.
- Merged branch + active worktree → check whether the worktree is clean:
git -C /path/to/wt status --porcelainIf the command returns any output (uncommitted changes), move to the blocked list. If clean, keep in the merged candidate list with the worktree annotation.
3. Present results
Display branches in four groups:
- Merged (safe to delete) — branches fully merged into base; those with a clean worktree show "(+ worktree at /path)"
- Stale (no recent commits, no active worktree) — only branches without a worktree appear here
- Protected (never touch) — main, master, develop, release/*
- Blocked — branches skipped because they have an active worktree with uncommitted work, or are stale with any active worktree; list each with its worktree path so the user knows what to resolve manually
Do NOT say "will be removed" for worktrees — removal is gated on confirmation in Step 4. If both the merged and stale candidate lists are empty, report "No branches to clean" and stop.
4. Confirm before deletion
Use AskUserQuestion. For merged branches that carry a worktree annotation, the confirmation option must name both the branch and its worktree path — the user is authorizing removal of both in one selection.
Structure:
- Header: "Branch cleanup"
- For merged branches: one option per branch. If the branch has a worktree: label = "branch-name + worktree", description = "Removes branch and worktree at /path". If the branch is squash/rebase-merged: append "(squash/rebase PR — force delete)" to the description so the user knows
-Dwill be used. If no worktree and not squash-merged: label = branch name, description = "Removes local branch". Include a "Keep all merged branches" fallback. If there are multiple candidates with no worktrees, a "Delete all N" batch option is acceptable. - For stale branches: use multiSelect:true. Each option: label = branch name, description = age. (No stale branch with a worktree will appear here — they were moved to blocked in Step 2.)
- Always include a "Skip — keep all" option
The user selecting a branch-with-worktree option is explicit authorization to remove both. Never remove a worktree that was not explicitly included in a confirmed selection.
5. Execute deletion
Delete only what the user confirmed. For each confirmed branch:
1. If the branch has a [worktree:/path] annotation, remove the worktree first:
git worktree remove /path/to/wtIf the command fails (the worktree acquired changes in the window between Step 2 and now), report the error and skip that branch — do not force-remove.
2. Then delete the branch:
- Regular merged (no
[squash-merged]annotation):git branch -d <branch-name> - Squash/rebase-merged (
[squash-merged]annotation):git branch -D <branch-name>
-D is required for squash/rebase-merged branches because git does not recognise their commits as merged into base — using -d will fail. The [squash-merged] annotation on a confirmed selection is explicit user authorisation to force-delete.
3. After local deletions are complete, offer remote cleanup:
Use AskUserQuestion with multiSelect:true listing every branch that was successfully deleted locally and has a known remote (git ls-remote --heads origin <branch-name> to verify). Let the user select which remotes to also delete. If none have a remote, skip this step.
For each selected remote:
git push origin --delete <branch-name>Output
Summary of actions taken:
- Branches deleted (local)
- Branches deleted (remote, if requested)
- Branches kept
- Any errors encountered
#!/usr/bin/env bash
# find-candidates.sh — Find merged and stale git branches
# Usage: find-candidates.sh [pattern]
# Output: Two labeled sections (MERGED / STALE), one branch per line.
# Branches checked out in a worktree are annotated: branch [worktree:/path]
# Empty section = no candidates of that type.
# Exit 0 always; downstream decides what to do with empty output.
set -euo pipefail
PATTERN="${1:-}"
# Detect main branch name (prefer main, fall back to master)
if git rev-parse --verify main >/dev/null 2>&1; then
BASE="main"
elif git rev-parse --verify master >/dev/null 2>&1; then
BASE="master"
else
echo "ERROR: no main or master branch found" >&2
exit 1
fi
# Build worktree map: branch -> worktree path
# `git worktree list --porcelain` emits blocks like:
# worktree /path
# HEAD <sha>
# branch refs/heads/<name> (or "detached" for detached HEAD)
# Uses a temp file (tab-separated key/value lines) for bash 3.2 compat
# (no declare -A). Tab is safe as an in-band delimiter because
# git-check-ref-format forbids control characters in refnames.
WORKTREE_MAP_FILE=$(mktemp)
trap 'rm -f "$WORKTREE_MAP_FILE"' EXIT
current_wt=""
while IFS= read -r line; do
if [[ "$line" == worktree\ * ]]; then
current_wt="${line#worktree }"
elif [[ "$line" == branch\ refs/heads/* ]]; then
branch_name="${line#branch refs/heads/}"
printf '%s\t%s\n' "$branch_name" "$current_wt" >> "$WORKTREE_MAP_FILE"
fi
done < <(git worktree list --porcelain)
# Helper: look up branch in worktree map.
# Uses awk with exact-string comparison on field 1 to avoid regex
# metacharacter pitfalls (e.g. a `.` in a branch name matching any char)
# and `=` pitfalls (branch names legally permit `=`).
worktree_for() {
awk -F'\t' -v b="$1" '$1 == b { print $2; exit }' "$WORKTREE_MAP_FILE"
}
# --- Merged branches ---
echo "=== MERGED ==="
MERGED=$(git branch --merged "$BASE" 2>/dev/null | grep -v "^\*" | sed 's/^[+ ]*//' | grep -vE '^(main|master|develop)$' || true)
if [ -n "$PATTERN" ]; then
MERGED=$(echo "$MERGED" | grep "$PATTERN" || true)
fi
while IFS= read -r branch; do
[ -z "$branch" ] && continue
wt=$(worktree_for "$branch")
if [[ -n "$wt" ]]; then
echo "$branch [worktree:$wt]"
else
echo "$branch"
fi
done <<< "$MERGED"
# --- Squash/rebase-merged detection via GitHub PR history ---
# git branch --merged only detects true merge commits; squash and rebase merges
# rewrite commits so the branch ancestry never appears in main. gh pr list is the
# only reliable source for these.
if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
GH_MERGED=$(gh pr list --state merged --limit 300 --json headRefName --jq '.[].headRefName' 2>/dev/null || true)
if [ -n "$GH_MERGED" ]; then
while IFS= read -r branch; do
[ -z "$branch" ] && continue
# Skip protected branches
case "$branch" in main|master|develop|release/*) continue ;; esac
# Skip branches already caught by git branch --merged
echo "$MERGED" | grep -qFx "$branch" && continue
# Apply pattern filter
if [ -n "$PATTERN" ] && ! echo "$branch" | grep -q "$PATTERN"; then
continue
fi
# Confirm branch exists locally
git rev-parse --verify "$branch" >/dev/null 2>&1 || continue
# Check if a merged PR targeted this branch
echo "$GH_MERGED" | grep -qFx "$branch" || continue
wt=$(worktree_for "$branch")
if [[ -n "$wt" ]]; then
echo "$branch [worktree:$wt] [squash-merged]"
else
echo "$branch [squash-merged]"
fi
done < <(git branch --format='%(refname:short)')
fi
fi
# --- Stale branches (no commits in 30+ days) ---
# Unix timestamps used for accurate threshold — git relative dates miss edge cases
echo "=== STALE ==="
CUTOFF=$(python3 -c "import time; print(int(time.time()) - 30*86400)")
while read -r branch ts reldate; do
# Skip protected branches
case "$branch" in main|master|develop|release/*) continue ;; esac
# Apply pattern filter if provided
if [ -n "$PATTERN" ] && [[ "$branch" != $PATTERN ]]; then
continue
fi
if (( ts < CUTOFF )); then
wt=$(worktree_for "$branch")
if [[ -n "$wt" ]]; then
echo "$branch ($reldate) [worktree:$wt]"
else
echo "$branch ($reldate)"
fi
fi
done < <(git for-each-ref --sort=-committerdate \
--format='%(refname:short) %(committerdate:unix) %(committerdate:relative)' \
refs/heads/)
Related skills
How it compares
Discovery-only bash workflow—not a hosted platform auto-delete rule or interactive git GUI.
FAQ
Who is clean-branches for?
Developers and small teams using git worktrees who want an agent-guided report of merged and stale branches before manual or scripted deletion.
When should I use clean-branches?
Use it during Ship review after merging PRs, before tagging a release, or when your branch list slows down git fetch and local navigation.
Is clean-branches safe to install?
The skill only lists candidates and does not delete branches by itself; still review the Security Audits panel on this page and inspect output before running destructive git commands.