/cleanup after a PR merges: switch to the default branch, pull, and delete the merged branch and its worktree, after one confirmation.

Small TypeScript mods that live inside Claude Code: a pane that knows your next step, one-click replies, a rate-limit countdown that resumes for you, your repo's pull requests and issues beside the conversation, a shelf of paths you use every day, presets that switch the model and the effort with one press, a chime when a long turn ends, a guard for the Office file you left open, a question before a commit or push on the default branch, a question before Claude reads a
.envor key file, a list of the files this session made, a list of the ones it read, a check that keeps banned claims out of a pull request, a gate that runs your checks and hands back only the failures, a nudge to fetch fresh tab IDs when a browser tab is gone, a name for the session from its first prompt, and one dialog for every mod's settings.
claude-mods is one developer's personal toolbox of Claude Code mods, shared as a plugin marketplace so anyone can install them. The mods are built for the author's own workflow first, and you are a welcome guest: install one, install all twenty, or read the source and write your own.
A mod is a plugin of function hooks: TypeScript that runs inside Claude Code and changes what it shows (a pane in the side panel, a band of buttons above the prompt, the status line) or what it does between turns. The mod's own code decides when to act, even when what it does is send the model a prompt.
| Runs as | Who decides when it acts | |
|---|---|---|
| Mod | TypeScript function hooks inside Claude Code | The mod's own code |
| Skill | Instructions the model reads | The model |
| Plain plugin | Commands, agents or shell hooks | You, or a shell script |
| Mod | Where it shows | What it does |
|---|---|---|
| 🧭 whats-next | Pane in the side panel | Lists the next steps of your workflow, each with a prompt ready to paste |
| ⚡ quick-reply | Band above the prompt | One-click replies, including the options Claude just offered, Pass, Fail and Skip for a verdict, and the next wayfinder ticket |
| ⏳ auto-resume | Band and status line | Counts down to a rate limit's reset, then sends "continue" |
| 🐙 github-panel | Pane in the side panel | The repo's open pull requests and issues, one click from the browser or from /implement and /wayfinder in the prompt; the issue a /wayfinder run works on, pinned with its next ticket; a toast when your branch's checks turn green or red |
| 📚 shelf | Band above the prompt | Named folders and files; one click drops a path into what you are typing |
| 🔔 turn-chime | Sound and toast | Tells you when a long turn ends or Claude stops to ask you something |
| 🔒 open-file-guard | Question dialog | Asks you to close a Word, Excel or PowerPoint file before Claude uses it |
| 🌿 branch-guard | Question dialog | Asks you before Claude commits or pushes on the default branch |
| 🔑 env-guard | Question dialog | Asks you before Claude reads a .env or key file, and refuses when no one is there to answer |
| 🩹 bash-quoting-rescue | Refused tool call | Stops a shell command that does not parse, such as an unclosed quote, before any of it runs |
| 📂 outputs | Pane in the side panel | The files this session made or changed, newest first; click one to open it |
| 🔎 sources | Pane in the side panel | The files Claude read, grouped by where they came from, with a lock to the project folder |
| 📊 hud | Two lines under the prompt | Model, effort, context window, rate limits, turn timer, tool calls, agents, git state, worktree, cost, session length and folder, each named and in colour |
| 🧹 post-merge-cleanup | Question dialog and toast | After a PR merges, /cleanup switches to the default branch, pulls and deletes the branch |
| 🧾 pre-pr-claims-check | Refusal Claude reads | Refuses gh pr create and gh pr edit while the pull request cites a file and line, holds a placeholder, or spells out a count |
| 🚦 lint-test-gate | Band above the prompt | Runs your checks on a press and before Claude's git commit, and hands back only the failures |
| 🔄 chrome-tab-self-heal | Note after a browser tool's error | When a Claude in Chrome tab is gone, tells Claude to fetch the current tab IDs before it tries again |
| 🏷 session-auto-namer | Band above the prompt | Suggests a name for the session from its first prompt; one press renames it |
| 🧠 model-effort-presets | Band above the prompt | Plan and execute presets: one press switches the model and the effort together |
| ⚙ mod-settings | Gear on each pane; a dialog | Change and save any mod's settings without leaving the session |
When more than one mod has a pane open, Claude Code shows them as tabs in the side panel.
A pane listing the next steps of your workflow for the project folder, kept between sessions. A skill of your choosing answers "what's next" in a headless run beside your session, and the mod turns the answer into steps.
What's next refresh
updated 3 min ago
Fix the failing parse test
working on it done
The check is red, so nothing else can merge.
Open a pull request for the fix
Review comes before the next feature starts.
Triage the two new issues
They arrived while you were heads-down.
flowchart LR
A[Skill answers<br/>what's next] --> B[Steps in the pane]
B --> C[You read a step's prompt<br/>and send it yourself]
C --> D[Step glows:<br/>working on it]
D --> E{Laya, Jev or Haiku:<br/>is the step finished?}
E -- not yet --> D
E -- yes --> F[Step leaves the list]
d to drop it yourself.git push, git config, git -c, gh api and --output are always denied.| Command or key | What it does |
|---|---|
/whats-next | Bring the pane to the front |
/whats-next refresh | Ask the skill again |
r | Refresh |
1 to 9 | Show that step's prompt in the pane |
p, n, c | Paste the shown prompt, paste it after /clear (and the prime command, once its turn ends), or copy it |
b | Back to the list |
d | Mark the active step done |
| Setting | Key | Default | Meaning |
|---|---|---|---|
| Skill | skill | /ask-sean | The skill that answers "what's next", written as you would run it: / followed by letters, digits, _, :, . or - |
| Most steps | maxSteps | 5 | How many steps to ask for (1-9) |
| Refresh on start | refreshOnStart | on | Ask for a fresh list when a session starts in a git repository |
| Tools the headless run may use | allowedTools | empty: the read-only set | Comma-separated permission rules for the headless run |
| Model | model | empty: your default | Model for the headless run, as an alias (haiku) or a full id |
| Prime command | primeCommand | empty: none | A slash command, with any arguments, run after /clear and before the paste (/lril:prime); the prompt is filled once the turn it starts ends, finished or not. A value that is not one slash command on one line is never run, and the step view says so |
| System One models | modelChoice | local only | Which System One model judges whether a turn finished the active step: local only (Laya on this machine, or Haiku as before), local first (Laya, and TypeSafe's hosted Jev while Laya is unavailable) or hosted first (Jev, and Laya while Jev is unavailable) |
| Jev API key | jevApiKey | empty | Your key for Jev, from console.typesafe.ai, kept in secure storage. Sent only to https://api.typesafe.ai, and only while System One models allows Jev |
| Laya port | layaPort | 8000 | The port your laya-serve listens on at 127.0.0.1 (1-65535) |
/ask-sean is the author's own skill, so point the Skill setting at a skill of yours that answers "what should I do next?" (how to set it):
echo '{"skill": "/next-steps", "maxSteps": "3", "model": "haiku"}' | claude plugin configure whats-next@claude-mods --values-stdin
The read-only set, used while Tools is empty, is Bash(git status:*), Bash(git log:*), Bash(git diff:*), Bash(git show:*), Bash(git rev-parse:*), Bash(git branch --show-current), Bash(git branch -vv), Bash(git remote -v), Bash(gh issue list:*), Bash(gh issue view:*), Bash(gh pr list:*), Bash(gh pr view:*), Bash(gh pr checks:*), Bash(gh run list:*), Read, Glob and Grep.
(...). One rule that is not, such as one starting with -, discards your whole list and the read-only set is used.Skill, so a skill that calls another still works. MCP servers load only when a rule names an mcp__ tool.What the judge sends to a System One model, once after each answered turn while a step is active:
Needs: the claude CLI on the PATH, and the skill named in the Skill setting. Laya and a Jev key are optional: with neither, the judge is Haiku, as before.
One row of buttons above the prompt after each answer. When Claude ends on a question, the band offers the choices Claude asked you to pick from, then your replies to a question. After any other answer it offers your other replies. You set both lists in the settings below.
Reply: [a: Keep the copies] [b: Add a sync script] [Yes] [Go with your recommendation] [No]
Verdicts. When Claude asks for a pass/fail verdict on a test or a check, as a UAT or /gsd:verify-work step does ("Pass or fail?", "Did it pass?", "Type pass or describe what's wrong"), the band offers a verdict in place of your replies:
Reply: [Pass] [Fail…] [Skip]
Pass sends "pass" and Skip sends "skip", as your own message. Fail… sends nothing: it puts "Fail: " in the prompt, where you say what went wrong and can paste a screenshot. A test's numbered steps are not offered as choices, and a question that only mentions passing ("Shall I make the tests pass?") gets your usual replies.
Next ticket. When you work a map with the wayfinder skill, the band leads with the next ticket after each turn that closes one or charts the map:
Reply: [Next ticket: /wayfinder 135] [Continue] [Commit and push]
One press runs /clear and then /wayfinder 135, the loop you would otherwise type. It is offered only in a session that ran the wayfinder skill, after a turn whose gh issue close worked; after charting it names the map the turn created. A close made some other way (gh api, the web) is not seen, so no button shows, and once a turn closes the map itself the loop ends.
| Setting | Key | Default | Meaning | |||
|---|---|---|---|---|---|---|
| Replies to a question | questionReplies | `Yes\ | Go with your recommendation\ | No` | Shown after Claude asks something, separated by `\ | `; empty shows only the choices Claude offered |
| Replies otherwise | idleReplies | `Continue\ | Commit and push` | Shown after any other answer; empty hides the band then, except for Next ticket | ||
| Offer the next wayfinder ticket | wayfinderNext | true | After a wayfinder turn closes a ticket or charts a map, offer Next ticket | |||
| System One models | modelChoice | local only | Which System One model reads how each answer ends: local only (Laya on this machine, or the band's own reading as before), local first (Laya, and TypeSafe's hosted Jev while Laya is unavailable) or hosted first (Jev, and Laya while Jev is unavailable) | |||
| Jev API key | jevApiKey | empty | Your key for Jev, from console.typesafe.ai, kept in secure storage. Sent only to https://api.typesafe.ai, and only while System One models allows Jev | |||
| Laya port | layaPort | 8000 | The port your laya-serve listens on at 127.0.0.1 (1-65535) |
Each list holds up to six replies. A reply longer than 120 characters is cut short, and a repeat is dropped. For example, to answer questions with your own three replies and hide the band after other answers (how to set it):
echo '{"questionReplies": "Yes|No|Explain that first", "idleReplies": ""}' | claude plugin configure quick-reply@claude-mods --values-stdin
What the band sends to a System One model, once after each answered turn:
Laya and a Jev key are optional: with neither, the band reads each answer as before.
When a turn dies on a rate limit or an overloaded API, auto-resume counts down to the reset and sends "continue" for you. Go to lunch, and come back to finished work.
⏳ rate limited: sending "continue" in 1 h 12 min [Resume now] [Cancel]
| Command | What it does |
|---|---|
/auto-resume | Say what is waiting, if anything |
/auto-resume now | Send the resume now |
/auto-resume cancel | Cancel the wait |
/auto-resume in <minutes> | Schedule a resume yourself (1 to 1440) |
| Setting | Key | Default | Meaning |
|---|---|---|---|
| Resume prompt | text | continue | What is sent when the wait is over; empty sends continue |
| Grace after reset (s) | graceSeconds | 60 | Extra seconds to wait past the limit's reset time (0-900) |
| Retry overloaded/server errors | retryOverloaded | on | Also resume after an overloaded or server error, backing off from one minute |
| Most retries in a row | maxRetries | 5 | Give up after this many resumes without a successful answer (1-20) |
For example, to send a longer prompt and wait two minutes past the reset (how to set it):
echo '{"text": "continue where you left off", "graceSeconds": "120"}' | claude plugin configure auto-resume@claude-mods --values-stdin
A GitHub pane beside What's next listing the repo's open pull requests and issues. Click one to open it in the browser. Under each issue, implement and wayfinder put /implement or /wayfinder and the issue's URL in the prompt. Nothing is sent. While a /wayfinder effort is under way, its issue is pinned at the top, with the next ticket to take.
octocat/hello-world refresh
updated just now
Decide how shared code is copied unpin
3 done · 1 takeable · 1 claimed · 2 blocked
next: Pick the drift check decision
work next
Pull requests 2 all
#41 Add a drift check for copied guards
draft · @octocat
#40 Bring the asked pane to the front
✗ checks failing · @hubot fix
Issues 2 all
#39 Share the headless-session check
blocked by #12 · ready… implement wayfinder
#12 Decide how shared code is copied
needs-triage · @hubot implement wayfinder
implement and wayfinder buttons take a line of their own.r.fix button. It fills the prompt box with the failed checks' names, the last 40 lines of the failed run's log, and "Fix it." Nothing is sent: you read it and send it yourself. The log is fetched only when you press fix; when gh cannot fetch it, such as while the run is still going, the prompt holds the names alone./wayfinder on an issue of this repo (/wayfinder 12, /wayfinder #12 or the issue's URL) pins that issue and brings the pane to the front. Anything else, such as prose or another repo's issue, pins nothing. The pin is kept for the repo across sessions, one at a time: a run on another issue replaces it. It goes when you press unpin, or once the issue is closed.next is the first takeable ticket in the order the issue lists its sub-issues, with its wayfinder: type label; click it to open it on GitHub. With nothing takeable it says so; an issue with no sub-issues yet says no tickets yet.work next fills /wayfinder and the pinned issue's URL into the prompt, without sending it, so the skill takes the frontier ticket fresh when it runs.| Command or key | What it does |
|---|---|
/github | Bring the pane to the front and refresh it |
r | Refresh |
all | Open the whole list on GitHub |
implement, wayfinder | Fill the command and the issue's URL into the prompt, without sending it |
fix | Fill a request to fix the current branch's failing checks into the prompt box |
unpin | Drop the pinned issue |
work next | Fill /wayfinder and the pinned issue's URL into the prompt, without sending it |
| Setting | Key | Default | Meaning |
|---|---|---|---|
| Most items per list | limit | 30 | How many open pull requests and issues to list each (1-100) |
| Refresh every (minutes) | refreshMinutes | 5 | How often to refresh (0-120); 0 refreshes only on open, after turns and on r |
| Implement button fills | implementCommand | /implement | The slash command the implement button fills before the issue's URL; empty hides the button |
| Wayfinder button fills | wayfinderCommand | /wayfinder | The slash command the wayfinder and work next buttons fill before the issue's URL, and the skill whose runs pin an issue; empty hides the button and turns pinning off |
A command must start with / and hold no spaces. Any other value falls back to the default, and a message says so when the session starts. A button is labelled with its command, without the /.
For example, to list fifty of each and stop the timer (how to set it):
echo '{"limit": "50", "refreshMinutes": "0"}' | claude plugin configure github-panel@claude-mods --values-stdin
Needs: the GitHub CLI, logged in, and a folder with a GitHub remote.
A row of named folders and files above the prompt, for the paths you type again and again. Click a name and its path lands at the cursor in what you are typing. Nothing is sent.
Shelf: [brand] [records] [kb]
/shelf always lists them all.| Command | What it does |
|---|---|
/shelf | List the shelf with each path |
/shelf add <name> [path] | Put a path on the shelf; with no path, the project folder |
/shelf remove <name> | Take one off |
The shelf has no settings: you fill it with /shelf add.
/shelf add brand "N:/Marketing/Brand Kit"
/shelf add records N:/RECORDS
/shelf add kb
/shelf remove brand
hooks/register.ts 214 lines1import { atom, update } from 'claude-code'
2import type { EngineInterface, ProcessRunResult, Register } from 'claude-code'
3
4import {
5 decide,
6 isSamePath,
7 lastLine,
8 missingRequirement,
9 NEEDS_GH,
10 NEEDS_GIT,
11 NOT_A_REPO,
12 parsePrs,
13 parseWorktrees,
14 pickPr,
15 PR_FIELDS,
16 question,
17 summary,
18} from './plan'
19import type { Checkout, Facts, PullRequest, Step } from './plan'
20
21const COMMAND = 'cleanup'
22const GO = 'Go'
23const CANCEL = 'Cancel'
24/** A pull or a prune talks to the remote; give it longer than the 30 s default. */
25const STEP_TIMEOUT_MS = 120_000
26/** The start-up suggestion stays long enough to read the command in it. */
27const SUGGEST_MS = 8_000
28
29const hasChecked = atom({ plugin: 'post-merge-cleanup', key: 'hasChecked' } as const, false)
30
31/** A requirement the mod lacks, carrying the sentence that names it. */
32class Missing extends Error {}
33
34/**
35 * Whether any surface shows the session right now. Asked before the start-up
36 * check, never kept. Each mod carries its own copy (ADR-0001).
37 */
38async function isShown($: EngineInterface): Promise<boolean> {
39 return (await $.session.surfaces()).length > 0
40}
41
42/** Runs git or gh by bare name; one that cannot start is a missing requirement. */
43async function run($: EngineInterface, argv: readonly string[], cwd?: string): Promise<ProcessRunResult> {
44 try {
45 return await $.process.run(argv, cwd === undefined ? {} : { cwd })
46 } catch (error) {
47 // A timeout rejects too; tell it from a missing tool by whether the tool starts at all.
48 const tool = argv[0] ?? ''
49 if (!(await canStart($, tool))) throw new Missing(tool === 'gh' ? NEEDS_GH : NEEDS_GIT)
50 throw error
51 }
52}
53
54async function canStart($: EngineInterface, tool: string): Promise<boolean> {
55 try {
56 await $.process.run([tool, '--version'])
57 return true
58 } catch {
59 return false
60 }
61}
62
63/** Runs a command that must succeed and answers its trimmed output. */
64async function ask($: EngineInterface, argv: readonly string[], cwd?: string): Promise<string> {
65 const result = await run($, argv, cwd)
66 if (result.exitCode !== 0) {
67 if (argv[0] === 'gh') {
68 const missing = missingRequirement(result.exitCode, result.stderr)
69 if (missing !== undefined) throw new Missing(missing)
70 }
71 throw new Error(`${argv.slice(0, 3).join(' ')} failed: ${lastLine(result.stderr) || `exit ${result.exitCode}`}`)
72 }
73 return result.stdout.trim()
74}
75
76async function defaultBranch($: EngineInterface): Promise<string> {
77 return ask($, ['gh', 'repo', 'view', '--json', 'defaultBranchRef', '--jq', '.defaultBranchRef.name'])
78}
79
80async function findPr($: EngineInterface, branch: string): Promise<PullRequest | undefined> {
81 const json = await ask($, ['gh', 'pr', 'list', '--head', branch, '--state', 'all', '--limit', '10', '--json', PR_FIELDS])
82 return pickPr(parsePrs(json))
83}
84
85/** The local branch's tip, or '' when there is no such branch. */
86async function tipOf($: EngineInterface, branch: string): Promise<string> {
87 const result = await run($, ['git', 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}`])
88 return result.exitCode === 0 ? result.stdout.trim() : ''
89}
90
91async function isClean($: EngineInterface, cwd?: string): Promise<boolean> {
92 return (await ask($, ['git', 'status', '--porcelain'], cwd)) === ''
93}
94
95/** Everything decide() needs, read from git and gh; nothing here changes the checkout. */
96async function gather($: EngineInterface, args: string): Promise<Facts> {
97 const top = await run($, ['git', 'rev-parse', '--show-toplevel'])
98 if (top.exitCode !== 0) throw new Missing(NOT_A_REPO)
99 const sessionPath = top.stdout.trim()
100 const currentBranch = await ask($, ['git', 'branch', '--show-current'])
101 const branch = args.trim() === '' ? currentBranch : args.trim()
102 const base = await defaultBranch($)
103 if (branch === '' || branch === base) {
104 return { branch, currentBranch, defaultBranch: base, pr: undefined, tip: '', isTreeClean: true, checkout: undefined }
105 }
106
107 const [pr, tip, isTreeClean, worktrees] = await Promise.all([
108 findPr($, branch),
109 tipOf($, branch),
110 isClean($),
111 ask($, ['git', 'worktree', 'list', '--porcelain']).then(parseWorktrees),
112 ])
113 const index = worktrees.findIndex(worktree => worktree.branch === branch)
114 let checkout: Checkout | undefined
115 if (index >= 0) {
116 const path = worktrees[index]!.path
117 const isSession = isSamePath(path, sessionPath)
118 const isMain = index === 0
119 // Only a worktree that would be removed needs its own check.
120 checkout = { path, isMain, isSession, isClean: isSession || isMain ? true : await isClean($, path) }
121 }
122 return { branch, currentBranch, defaultBranch: base, pr, tip, isTreeClean, checkout }
123}
124
125/** Runs the steps in order, stopping at the first failure; answers what to tell the person. */
126async function carryOut($: EngineInterface, branch: string, steps: readonly Step[]): Promise<string> {
127 for (const step of steps) {
128 let result: ProcessRunResult
129 try {
130 result = await $.process.run(step.argv, { timeoutMs: STEP_TIMEOUT_MS })
131 } catch (error) {
132 return `Cleanup stopped at "${step.todo}": ${error instanceof Error ? error.message : String(error)}`
133 }
134 if (result.exitCode !== 0) {
135 return `Cleanup stopped at "${step.todo}": ${lastLine(result.stderr) || lastLine(result.stdout) || `exit ${result.exitCode}`}`
136 }
137 }
138 return summary(branch, steps)
139}
140
141async function cleanup($: EngineInterface, args: string): Promise<string> {
142 const facts = await gather($, args)
143 const decision = decide(facts)
144 if ('refuse' in decision) return decision.refuse
145
146 let answer: string
147 try {
148 answer = await $.ui.ask(question(decision.pr, decision.steps), { options: [GO, CANCEL], header: 'Cleanup' })
149 } catch {
150 // Dismissed, or nobody to ask (a -p run).
151 return 'Cleanup cancelled; nothing was changed.'
152 }
153 if (answer !== GO) return 'Cleanup cancelled; nothing was changed.'
154
155 const said = await carryOut($, facts.branch, decision.steps)
156 $.ui.toast(said)
157 return said
158}
159
160/** The start-up check: one look at the session's branch, and a toast when its PR has merged. */
161async function suggest($: EngineInterface): Promise<void> {
162 const branch = await ask($, ['git', 'branch', '--show-current'])
163 if (branch === '') return
164 const [base, pr] = await Promise.all([defaultBranch($), findPr($, branch)])
165 if (branch === base || pr?.state !== 'MERGED') return
166 $.ui.toast(`PR #${pr.number} for ${branch} merged. Run /${COMMAND} to switch to ${base}, pull and delete the branch.`, {
167 timeoutMs: SUGGEST_MS,
168 })
169}
170
171/** Runs the start-up check once per session, and only while a surface shows it. */
172async function checkOnce($: EngineInterface): Promise<void> {
173 if (!(await isShown($))) return
174 let isFirst = false
175 await update($, hasChecked, was => {
176 isFirst = !was
177 return true
178 })
179 if (isFirst) await suggest($)
180}
181
182/** Quiet on failure: a missing gh is named when the person runs /cleanup, not at start. */
183function logQuietly($: EngineInterface): (error: unknown) => void {
184 return error => $.ui.log(`post-merge-cleanup: start-up check: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
185}
186
187export const register: Register = on => {
188 on('session.start', async ($, e, next) => {
189 await $.command.register({
190 name: COMMAND,
191 description: 'After a PR merges: switch to the default branch, pull, and delete the branch and its worktree',
192 argumentHint: '[branch]',
193 })
194 const done = await next(e)
195 void checkOnce($).catch(logQuietly($))
196 return done
197 })
198
199 // A session that started headless checks once when a surface first shows it.
200 on('session.attach', async ($, e, next) => {
201 const done = await next(e)
202 void checkOnce($).catch(logQuietly($))
203 return done
204 })
205
206 on('command.run', { command: COMMAND }, async ($, e) => {
207 try {
208 return { text: await cleanup($, e.args) }
209 } catch (error) {
210 return { text: error instanceof Missing ? error.message : `Cleanup failed: ${error instanceof Error ? error.message : String(error)}` }
211 }
212 })
213}
214hooks/plan.ts 188 lines1/** The fields asked of `gh pr list`; parsePrs reads these. */
2export const PR_FIELDS = 'number,state,headRefOid'
3
4export type PullRequest = {
5 number: number
6 state: 'OPEN' | 'CLOSED' | 'MERGED'
7 /** The commit the PR's head pointed at: for a merged PR, the commit it merged. */
8 headRefOid: string
9}
10
11/** One entry of `git worktree list --porcelain`; `branch` is '' for a detached head. */
12export type Worktree = { path: string; branch: string }
13
14/** Where the branch to clean up is checked out, if anywhere. */
15export type Checkout = {
16 path: string
17 /** The main checkout: the first worktree git lists. It is never removed. */
18 isMain: boolean
19 /** The checkout this session runs in. */
20 isSession: boolean
21 /** Nothing staged, unstaged or untracked; only asked of a worktree that would be removed. */
22 isClean: boolean
23}
24
25/** What the mod found before deciding: every answer is git's or gh's. */
26export type Facts = {
27 /** The branch to clean up: the argument, or the session's branch. */
28 branch: string
29 /** The session's branch; '' for a detached head. */
30 currentBranch: string
31 defaultBranch: string
32 pr: PullRequest | undefined
33 /** The local branch's tip; '' when there is no such local branch. */
34 tip: string
35 /** The session's tree has nothing staged, unstaged or untracked. */
36 isTreeClean: boolean
37 checkout: Checkout | undefined
38}
39
40/** One git command of the cleanup, run in the session's folder. */
41export type Step = {
42 /** What it will do, for the question. */
43 todo: string
44 /** What it did, for the closing toast. */
45 done: string
46 argv: string[]
47}
48
49export type Decision = { refuse: string } | { pr: number; steps: Step[] }
50
51function isRecord(value: unknown): value is Record<string, unknown> {
52 return typeof value === 'object' && value !== null && !Array.isArray(value)
53}
54
55/** Parses `gh pr list --json PR_FIELDS`, dropping malformed rows; throws on output that is not a list. */
56export function parsePrs(json: string): PullRequest[] {
57 const rows: unknown = JSON.parse(json)
58 if (!Array.isArray(rows)) throw new Error('gh pr list did not answer a list')
59 return rows.flatMap((row): PullRequest[] => {
60 if (!isRecord(row)) return []
61 const { number, state, headRefOid } = row
62 if (typeof number !== 'number' || typeof headRefOid !== 'string') return []
63 if (state !== 'OPEN' && state !== 'CLOSED' && state !== 'MERGED') return []
64 return [{ number, state, headRefOid }]
65 })
66}
67
68/** The PR that speaks for a branch: a merged one first, then an open one, then any. gh lists the newest first. */
69export function pickPr(prs: readonly PullRequest[]): PullRequest | undefined {
70 return prs.find(pr => pr.state === 'MERGED') ?? prs.find(pr => pr.state === 'OPEN') ?? prs[0]
71}
72
73/** Parses `git worktree list --porcelain`: blocks of `worktree <path>`, then `branch refs/heads/<name>` or `detached`. */
74export function parseWorktrees(porcelain: string): Worktree[] {
75 const worktrees: Worktree[] = []
76 for (const line of porcelain.split(/\r?\n/)) {
77 if (line.startsWith('worktree ')) worktrees.push({ path: line.slice('worktree '.length), branch: '' })
78 const last = worktrees[worktrees.length - 1]
79 if (line.startsWith('branch refs/heads/') && last !== undefined) last.branch = line.slice('branch refs/heads/'.length)
80 }
81 return worktrees
82}
83
84/** Whether two paths git printed name the same folder: slashes folded, and case too for a Windows drive path. */
85export function isSamePath(a: string, b: string): boolean {
86 const fold = (path: string) => {
87 const slashed = path.replace(/\\/g, '/').replace(/\/+$/, '')
88 return /^[a-z]:\//i.test(slashed) ? slashed.toLowerCase() : slashed
89 }
90 return fold(a) === fold(b)
91}
92
93/**
94 * Decides from the facts: a refusal naming the first check that failed, or the
95 * steps to run. Nothing here changes the checkout; the steps run only after the
96 * person says Go.
97 */
98export function decide(facts: Facts): Decision {
99 const { branch, currentBranch, defaultBranch, pr, tip, checkout } = facts
100 if (branch === '') return { refuse: 'Not on a branch. Run /cleanup <branch> to name the branch to clean up.' }
101 if (branch === defaultBranch) return { refuse: `${branch} is the default branch; there is nothing to clean up.` }
102 if (pr === undefined) return { refuse: `${branch} has no pull request, so nothing was changed.` }
103 if (pr.state === 'OPEN') return { refuse: `PR #${pr.number} for ${branch} is still open, so nothing was changed.` }
104 if (pr.state === 'CLOSED') {
105 return { refuse: `PR #${pr.number} for ${branch} was closed without merging, so nothing was changed.` }
106 }
107 if (tip === '') return { refuse: `There is no local branch ${branch}, so there is nothing to delete.` }
108 if (tip !== pr.headRefOid) {
109 return {
110 refuse: `${branch} has commits that are not in PR #${pr.number}: its tip is not the commit the PR merged. Push or drop them first.`,
111 }
112 }
113 if (checkout?.isSession === true && !checkout.isMain) {
114 return {
115 refuse: `This session runs inside ${branch}'s own worktree. Run /cleanup ${branch} from the main checkout.`,
116 }
117 }
118 if (checkout?.isMain === true && !checkout.isSession) {
119 return { refuse: `${branch} is checked out in the main checkout at ${checkout.path}. Run /cleanup there.` }
120 }
121 if (!facts.isTreeClean) {
122 return { refuse: 'The working tree has uncommitted or untracked changes. Commit, stash or remove them first.' }
123 }
124 if (checkout !== undefined && !checkout.isSession && !checkout.isClean) {
125 return {
126 refuse: `The worktree at ${checkout.path} has uncommitted or untracked changes. Commit, stash or remove them first.`,
127 }
128 }
129
130 const steps: Step[] = []
131 if (currentBranch !== defaultBranch) {
132 steps.push({ todo: `switch to ${defaultBranch}`, done: `switched to ${defaultBranch}`, argv: ['git', 'switch', defaultBranch] })
133 }
134 steps.push({ todo: `pull ${defaultBranch}`, done: `pulled ${defaultBranch}`, argv: ['git', 'pull', '--ff-only'] })
135 if (checkout !== undefined && !checkout.isSession) {
136 steps.push({
137 todo: `remove the worktree at ${checkout.path}`,
138 done: `removed the worktree at ${checkout.path}`,
139 argv: ['git', 'worktree', 'remove', checkout.path],
140 })
141 }
142 // -D, not -d: a squash merge leaves the branch unmerged in git's eyes. The tip check above is what makes it safe.
143 steps.push({
144 todo: `delete ${branch} (PR #${pr.number} merged)`,
145 done: `deleted ${branch}`,
146 argv: ['git', 'branch', '-D', branch],
147 })
148 steps.push({ todo: 'prune remote-tracking branches', done: 'pruned', argv: ['git', 'fetch', '--prune'] })
149 return { pr: pr.number, steps }
150}
151
152/** The one question asked before anything changes. */
153export function question(pr: number, steps: readonly Step[]): string {
154 return `PR #${pr} merged. Clean up: ${steps.map(step => step.todo).join(', ')}?`
155}
156
157/** What the closing toast says. */
158export function summary(branch: string, steps: readonly Step[]): string {
159 return `Cleaned up ${branch}: ${steps.map(step => step.done).join(', ')}.`
160}
161
162/** What the person sees when gh cannot start. */
163export const NEEDS_GH = 'post-merge-cleanup needs the GitHub CLI (gh). Install it from cli.github.com, then run /cleanup again.'
164/** What the person sees when git cannot start. */
165export const NEEDS_GIT = 'post-merge-cleanup needs git. Install it from git-scm.com, then run /cleanup again.'
166/** What the person sees when gh is not logged in. */
167export const NOT_LOGGED_IN = 'gh is not logged in. Run gh auth login in a terminal, then run /cleanup again.'
168/** What the person sees outside a git repository. */
169export const NOT_A_REPO = 'This folder is not a git repository, so there is nothing to clean up.'
170/** What the person sees when the repository has no GitHub remote. */
171export const NOT_A_GITHUB_REPO = 'This repository has no GitHub remote, so gh cannot tell whether a PR merged.'
172
173/** gh's exit code for a command that needs authentication (`gh help exit-codes`). */
174const GH_AUTH_EXIT = 4
175
176/** The requirement a failed gh call names, or undefined when the failure is something else. */
177export function missingRequirement(exitCode: number, stderr: string): string | undefined {
178 if (exitCode === GH_AUTH_EXIT || /gh auth login|not logged in/i.test(stderr)) return NOT_LOGGED_IN
179 if (/no git remotes|none of the git remotes|not a git repository/i.test(stderr)) return NOT_A_GITHUB_REPO
180 return undefined
181}
182
183/** The last non-empty line of a command's output, cut short, for a toast. */
184export function lastLine(output: string): string {
185 const lines = output.trim().split(/\r?\n/)
186 return lines[lines.length - 1]?.slice(0, 200) ?? ''
187}
188types/index.d.ts 11 lines1/** Whether this session's start-up check for a merged PR has run: at start, or at the first attach. */
2export type HasChecked = boolean
3
4declare module 'claude-code' {
5 interface PluginState {
6 'post-merge-cleanup': {
7 hasChecked: HasChecked
8 }
9 }
10}
11