|
| 1 | +--- |
| 2 | +name: stale-worktree-cleanup |
| 3 | +description: Use when cleaning up old git worktrees, removing worktrees whose branches have merged or been abandoned, or dropping orphaned compdev_* Postgres databases. Triggers on "clean up worktrees", "delete stale worktrees", "worktrees piling up", "orphaned databases", "remove unused worktree". |
| 4 | +--- |
| 5 | + |
| 6 | +# Stale Worktree Cleanup |
| 7 | + |
| 8 | +## Overview |
| 9 | + |
| 10 | +This repo's `.githooks/post-checkout` creates a per-worktree Postgres database (`compdev_<slug>`) on every `git worktree add`. Git has no `pre-worktree-remove` hook, so dead databases pile up over time. This skill defines a safe, reversible process to reap both the worktree directories and their dangling databases together. |
| 11 | + |
| 12 | +**Core principle**: never delete work the user might still want. Classify first, ask second, remove last. |
| 13 | + |
| 14 | +## When to Use |
| 15 | + |
| 16 | +- User says "clean up worktrees", "delete stale worktrees", "remove old worktrees", "worktrees piling up" |
| 17 | +- User mentions orphaned `compdev_*` DBs or running out of disk space from dead `node_modules` |
| 18 | +- Starting a new feature and noticing many old worktree dirs |
| 19 | + |
| 20 | +## When NOT to Use |
| 21 | + |
| 22 | +- User wants to remove ONE specific worktree (just run `git worktree remove <path>` + drop its DB directly — don't load the whole process) |
| 23 | +- User is actively working in a worktree (never touch active work) |
| 24 | + |
| 25 | +## Process |
| 26 | + |
| 27 | +### Step 1 — Inventory |
| 28 | + |
| 29 | +Run these four commands (parallel-safe) and capture the output: |
| 30 | + |
| 31 | +```sh |
| 32 | +git worktree list --porcelain |
| 33 | +gh pr list --author @me --state all --limit 50 --json headRefName,state,url,number |
| 34 | +git branch --no-color | cat |
| 35 | +``` |
| 36 | + |
| 37 | +Then query the DB for `compdev_*` databases. The management URL is the main worktree's `DATABASE_URL` with the database path swapped to `postgres`: |
| 38 | + |
| 39 | +```sh |
| 40 | +bun -e ' |
| 41 | + import { Client } from "pg"; |
| 42 | + const raw = require("fs").readFileSync("packages/db/.env", "utf8"); |
| 43 | + const url = raw.match(/^DATABASE_URL=(.*)$/m)[1].replace(/^["\x27]|["\x27]$/g, ""); |
| 44 | + const mgmt = url.replace(/\/[^/?]+(\?|$)/, "/postgres$1"); |
| 45 | + const c = new Client({ connectionString: mgmt }); |
| 46 | + await c.connect(); |
| 47 | + const r = await c.query("SELECT datname FROM pg_database WHERE datname LIKE \x27compdev\\\\_%\x27 ORDER BY 1"); |
| 48 | + for (const row of r.rows) console.log(row.datname); |
| 49 | + await c.end(); |
| 50 | +' |
| 51 | +``` |
| 52 | + |
| 53 | +### Step 2 — Classify each worktree |
| 54 | + |
| 55 | +For each worktree (skip the main one): |
| 56 | + |
| 57 | +| Signal | Classification | |
| 58 | +|---|---| |
| 59 | +| Branch merged to main AND clean working tree AND no unpushed commits | **safe** | |
| 60 | +| PR is `CLOSED` (not merged) | **needs-confirm** | |
| 61 | +| Uncommitted changes OR unpushed commits | **needs-confirm** | |
| 62 | +| No matching PR, no merge, has local commits | **keep** (user may still be working on it) | |
| 63 | +| Is the main worktree | **skip** | |
| 64 | + |
| 65 | +Gather per worktree: |
| 66 | +- `cd <path> && git status --porcelain | wc -l` — uncommitted changes count |
| 67 | +- `cd <path> && git log @{upstream}..HEAD --oneline 2>/dev/null | wc -l` — unpushed commits (0 if no upstream) |
| 68 | +- Branch → PR lookup from step 1 |
| 69 | + |
| 70 | +### Step 3 — Present to user |
| 71 | + |
| 72 | +Show a table and explicit recommendations. Example: |
| 73 | + |
| 74 | +``` |
| 75 | +Path Branch PR state Changes Recommendation |
| 76 | +.worktrees/sale-45-… mariano/sale-45-… MERGED 0 / 0 ✅ safe to remove |
| 77 | +.worktrees/old-experiment mariano/scratch — 3 / 0 ⚠ uncommitted — confirm first |
| 78 | +.worktrees/worktree-env-auto-link mariano/worktree-env-auto-link OPEN 0 / 0 ⏳ keep (PR open) |
| 79 | +
|
| 80 | +Orphan databases (no worktree dir): |
| 81 | + compdev_abandoned_feature |
| 82 | + compdev_old_migration_test |
| 83 | +``` |
| 84 | + |
| 85 | +Then ask: **"Remove the items marked ✅? Confirm by listing anything you want me to also nuke from the ⚠ / ⏳ set."** |
| 86 | + |
| 87 | +### Step 4 — Remove confirmed items |
| 88 | + |
| 89 | +For each worktree the user approved: |
| 90 | + |
| 91 | +```sh |
| 92 | +# 1. Remove the worktree dir (use --force only if user confirmed dirty-removal) |
| 93 | +git worktree remove "<path>" # clean case |
| 94 | +git worktree remove --force "<path>" # only after explicit user OK |
| 95 | + |
| 96 | +# 2. Derive the slug and drop the database |
| 97 | +slug=$(basename "<path>" | tr '[:upper:]' '[:lower:]' | tr '-' '_' | tr -cd 'a-z0-9_') |
| 98 | +bun -e ' |
| 99 | + import { Client } from "pg"; |
| 100 | + const raw = require("fs").readFileSync("packages/db/.env", "utf8"); |
| 101 | + const url = raw.match(/^DATABASE_URL=(.*)$/m)[1].replace(/^["\x27]|["\x27]$/g, ""); |
| 102 | + const mgmt = url.replace(/\/[^/?]+(\?|$)/, "/postgres$1"); |
| 103 | + const c = new Client({ connectionString: mgmt }); |
| 104 | + await c.connect(); |
| 105 | + await c.query(`DROP DATABASE IF EXISTS "compdev_'"$slug"'"`); |
| 106 | + await c.end(); |
| 107 | + console.log("dropped compdev_'"$slug"'"); |
| 108 | +' |
| 109 | +``` |
| 110 | + |
| 111 | +For orphan databases (no matching worktree dir), just drop them — no worktree to remove. |
| 112 | + |
| 113 | +**Do NOT** delete the local branch unless the user explicitly asked. Branches can be recreated from `origin` cheaply; worktrees cannot. |
| 114 | + |
| 115 | +### Step 5 — Verify and report |
| 116 | + |
| 117 | +```sh |
| 118 | +git worktree list |
| 119 | +# then re-run the compdev_* query from step 1 |
| 120 | +``` |
| 121 | + |
| 122 | +Report back: |
| 123 | +- Worktrees removed (paths) |
| 124 | +- Databases dropped (names) |
| 125 | +- Anything skipped and why |
| 126 | +- What's left (still-active worktrees) |
| 127 | + |
| 128 | +## Safety Rules |
| 129 | + |
| 130 | +- **Never remove the main worktree.** Its path is always the first line of `git worktree list --porcelain`. |
| 131 | +- **Never `--force` without confirmation.** Dirty worktrees can contain un-stashed work. |
| 132 | +- **Never `DROP DATABASE` on anything not matching `^compdev_[a-z0-9_]+$`.** Never drop `comp`, `postgres`, or any production-looking name. |
| 133 | +- **Never delete a local branch** as part of cleanup unless the user explicitly asks. Orphaned branches are cheap; lost work isn't. |
| 134 | +- **Never run this inside a worktree you're about to delete.** `cd` to the main worktree first. |
| 135 | + |
| 136 | +## Common Mistakes |
| 137 | + |
| 138 | +| Mistake | Fix | |
| 139 | +|---|---| |
| 140 | +| Dropping the DB but leaving the worktree dir | Run `git worktree prune` then `git worktree remove` | |
| 141 | +| Removing the worktree but leaving the DB (accumulates orphans) | Always do both in the same pass | |
| 142 | +| Using hyphens in the DB name | The hook slug rule is `tr '-' '_'` — always underscores | |
| 143 | +| Running from inside a doomed worktree | `cd` to the main worktree before starting the process | |
| 144 | +| Using `gh pr list` on a branch with no PR | Missing data is not "abandoned" — needs `needs-confirm` classification | |
| 145 | + |
| 146 | +## Red Flags |
| 147 | + |
| 148 | +If any of these show up mid-process, **stop and ask the user**: |
| 149 | + |
| 150 | +- A worktree has unpushed commits AND no PR → might be unreleased work |
| 151 | +- The classification returned >10 "safe to remove" items → unusual volume, double-check |
| 152 | +- `git worktree remove` errors with "working tree is not clean" → never retry with `--force` without explicit consent |
| 153 | +- A `compdev_*` name has weird characters or unexpected format → don't drop |
| 154 | + |
| 155 | +## Quick Reference |
| 156 | + |
| 157 | +```sh |
| 158 | +# List everything |
| 159 | +git worktree list --porcelain |
| 160 | +gh pr list --author @me --state all --limit 50 --json headRefName,state |
| 161 | + |
| 162 | +# Per-worktree inspection |
| 163 | +git -C <path> status --porcelain |
| 164 | +git -C <path> log @{upstream}..HEAD --oneline 2>/dev/null |
| 165 | + |
| 166 | +# Clean removal |
| 167 | +git worktree remove <path> |
| 168 | + |
| 169 | +# Dirty removal (requires user confirmation first) |
| 170 | +git worktree remove --force <path> |
| 171 | + |
| 172 | +# Database drop (run from main worktree) |
| 173 | +# See the bun -e snippets above for the exact invocation |
| 174 | +``` |
0 commit comments