Cleans up after merged work, once it shipped: removing a branch needs git, the forge or the user to say it merged; removing it or filling in its issue waits…

Bakhtiyar Ospanov's agent skills, and Claude Code mods: plugins built on function hooks.
For any agent the skills CLI supports:
npx skills add bahaospanov/skills --skill <skill>
Or in Claude Code, all of them as one plugin, invoked as /bahaospanov-skills:<skill>:
/plugin marketplace add bahaospanov/skills
/plugin install bahaospanov-skills@bahaospanov
Pick one: installing both leaves every skill twice.
Reachable only when you type them (Claude Code: disable-model-invocation: true; Codex: policy.allow_implicit_invocation: false in agents/openai.yaml).
Model- or user-reachable.
### Playbook block of its AGENTS.md. Its MR description is mattpocock/skills pr (MIT), whose Summary visuals come from Dex Horthy's HumanLayer show-me (MIT).prototype (MIT), its UI branch reworked: whole flows, options grouped by stage in a one-click panel.Early access; the API changes between releases.
One mod per purpose. Why each one and each of its rules exists: STORY.md.
| Mod | Purpose |
|---|---|
| git-gates | Git work happens on the user's word |
| git-tidy | Git history stays tidy |
| git-cleanup | Merged work is cleaned up once it shipped |
| issue-first | Feature work starts from an issue, and each commit names its own |
| lean-docs | Docs worth keeping |
| lean-comments | Comments worth keeping |
| lean-scripts | Scripts worth keeping |
| close-countdown | A Herdr pane counts down before it closes |
| traffic-light | The band says whether the session's work is done |
Haiku reviews are gated in code first, so a call that cannot fail the review costs no model call. End-of-turn checks read the git diff of repos the turn touched, Bash edits included, and show at most two one-line notices a session; the report reaches Claude with your next message and is acted on when you ask.
Pushing is a deploy, so the agent needs the user's word in the current turn: the prompt that opened it or one typed while it ran. If a consent check itself fails, the call is blocked.
| Check | Runs on | Needs | Then |
|---|---|---|---|
| consent | git commit, push, with or without git's own options (git -C dir push); opening a PR/MR; PR/MR merge | commit, push, ship, deploy, pr, mr, tag or release typed in the current turn (a message typed while it runs or a background task's report does not withdraw it); a push needs one of them other than commit; opening needs pr, mr, pull request, merge request or ship; merge needs "merge", and "merge request" is not it; a protected branch must be named. A negated keyword ("don't push") does not count, and a no to the act itself refuses it, standing grant included, unless the turn also asks for it | Call denied |
| grants | Later commits in the session | A message asking for a commit per task, or the grant tool after an authorizing message | Commits spend the grant; pushes never |
Protected branches come from a repo's own push policy file. Integration branches are the protected ones; with no policy, the remote's default branch and any of dev, develop, main, master that exist. Deleting a branch on origin needs no keyword when origin's head of it already sits in an integration branch.
The rules' text lives in the playbook; the commit-order, follow-up and feature refusals name the part.
| Check | Runs on | Needs | Then |
|---|---|---|---|
| messages | A git commit | Conventional Commits subject, no Co-Authored-By trailer naming Claude or Anthropic (in the message or a --trailer flag) and no "Generated with Claude Code" line | Commit denied |
| message advice | A git commit | No reviewer pre-answers ("no X changed"); then Haiku: a body only when the cause is subtle | Commit runs; the user gets the advice |
| fresh base | Opening an MR/PR: gh pr create, glab mr create, a GitLab API POST to merge_requests | The source branch, as origin has it, contains the target's latest commit, fetched first; skipped when the message says not to rebase | Call denied |
| landed branch | A git push | The branch's pushed head already sits in a protected branch, and the message names no new MR | Push denied |
| every commit works | A git push of 2 to 15 commits no remote has | Sonnet: no commit removes something a later one stops using, or uses something a later one adds; skipped when the message says the order is fine | Push denied |
| one commit per change | A git push of new commits to a branch whose commits not yet in an integration branch number 2 to 15, pushed or not | No fixup!, squash! or amend! subject; then Sonnet: no later commit spends most of its diff fixing, reworking or extending lines an earlier one added, or matches an earlier one's API contract change in another app; skipped when the message says to keep the commits | Push held: the agent shows the user the reason and asks; any answer lets the same commits through |
| one feature per MR | A git push of new commits to a branch whose commits not yet in an integration branch number 1 to 15, pushed or not | Its commit messages name at most one issue; then Sonnet: no piece of it could ship alone apart from the rest; skipped when the message says one MR or to keep them together | Push held: the agent shows the user the features, recommends a branch and MR each, and asks; any answer lets the branch through for the session |
Integration branches are found as git-gates finds them.
Merged is not shipped: a branch is cleaned up and its issue filled in only once the pipeline holding the merge has passed. Closing the issue is left to you.
| Check | Runs on | Needs | Then |
|---|---|---|---|
| merged first | Removing a branch, local or on origin; removing a worktree keeps its branch and is not held | The branch sits in an integration branch, a merged PR/MR has it as source branch, or the current turn's message says it merged (or to abandon it) | Call denied |
| pipeline first | Removing a worktree or branch, local or on origin; rewriting an issue's body (checklist ticks, How to test) | The work (the branch, the commit a squash merge landed as, or the newest integration commit naming the issue) landed and a pipeline holding it passed; skipped when the message says not to wait | Call denied while it runs or after it failed; a GitLab pipeline parked at manual or skipped holds nothing back |
| stale work | The end of a turn | A branch the session committed to or pushed that sits in an integration branch, its worktree clean, no pipeline holding it still running or failed | Removes the worktree and the branch, local and on origin, fast-forwards a local integration branch behind origin, and prints one line saying what went; the worktree the session works in stays |
Integration branches are found as git-gates finds them. A branch sits in an integration branch when its head does, or when every commit of it has a copy there (a rebase merge). Pipelines are read with gh on GitHub and, on GitLab, with the gitlab_token option: a read_api token, asked when the plugin is enabled, kept in the keychain on macOS and in ~/.claude/.credentials.json elsewhere. With no token or no pipeline holding the work, the pipeline check holds nothing back and a log line says why; merged first still applies, and on GitLab sees a squash merge only with the token.
| Check | Runs on | Needs | Then |
|---|---|---|---|
| feature issue | A feat commit | An issue (#107, #BLK-23) at the end of the subject, or in the branch name (feat/catalog-menu-107), or "no issue" typed by the user in the current turn | Commit denied; Claude looks for the issue, else drafts one and asks the user before creating it |
| issue number | A git commit | The issue or ticket your messages or the branch name, at the end of the subject | Commit runs; the user gets the suggestion |
A repo with no remote has no issue tracker: feature issue is skipped, and only a ticket (#BLK-23) counts as an issue. Issues you typed bind only commits in the session's repo and its worktrees; a branch ending in its issue number (perf/mobile-lcp-89) lets the subject end with that one instead. Enabled in a repo's own .claude/settings.json, it applies to everyone working there.
| Check | Runs on | Flags | Then |
|---|---|---|---|
| docs-review | A doc grown in a git checkout | Haiku: text nobody reads after the task (runbooks, setup pages, narration) | Claude gets the reason |
| docs-no-repeat-code | A doc line being written | Identifiers that already appear together in one code file | Claude gets the hint; the write goes ahead |
| limit-docs | The end of a turn | New or grown docs, prose outweighing code, doc lines repeating code | A one-line notice; say "trim docs" to act on it |
No check reads a skill's folder, the one holding SKILL.md, or anything under it: a skill is read again on every use.
Media and marketing work is out of scope too: a file its own checkout ignores (a local reels/ or renders/ folder) or one under a folder holding a .lean-skip file.
No comments by default: keep the ones that record a measured number, a trap or an invariant, cut the ones that restate the code or narrate the change.
| Check | Runs on | Flags | Then |
|---|---|---|---|
| limit-edits | A Write or Edit | More than 3 added comment lines, or a comment-heavy region around an edit that adds comments | Claude gets the guidance |
| limit-turns | The end of a turn | More than 3 new comment lines per file in the turn's diff | A one-line notice; say "trim comments" to act on it |
No check reads a file installed under ~/.agents/skills, ~/.claude/skills or ~/.claude/plugins: it is someone else's code. A link from there into a checkout is followed, and the file is checked.
Media and marketing work is out of scope too: a file its own checkout ignores (a local reels/ or renders/ folder) or one under a folder holding a .lean-skip file.
| Check | Runs on | Flags | Then |
|---|---|---|---|
| scripts-review | A script written or grown in a git checkout | Haiku: scripts you could just type again when needed | Claude gets the reason |
A script is a shell file, a file in a scripts, bin, tools or ops folder, or one starting with a shebang. A skill's folder is skipped: the skill runs its scripts on every use.
Media and marketing work is out of scope too: a file its own checkout ignores (a local reels/ or renders/ folder) or one under a folder holding a .lean-skip file.
A Herdr subtask closing its own pane shows it first, so whoever watches can stop it.
| Part | What it does |
|---|---|
close_pane_later tool | Closes this session's Herdr pane, or pane, after seconds (default 60) and returns at once; note is shown beside the countdown |
| The band | ⏻ Closing this pane in 42s · <note> [ ✋ Keep open ] [ ❌ Close now ] above the prompt, a draining bar under it |
| Cancel | A message typed into the session, ✋ Keep open or /keep-open; ❌ Close now closes the pane at once |
It runs herdr pane close, so the session needs herdr on its PATH and a Herdr pane (HERDR_PANE_ID).
A band above the prompt says whether you can leave the session.
| Light | When |
|---|---|
| 🟢 safe to leave | The PR is merged into dev, develop, main or master and every GitHub Actions run of that push passed; a run a newer push cancelled is judged by the newer one |
| 🟡 waiting on PR | The PR is open, failing checks included, or merged with its pipeline still running |
| 🔴 working | Claude is asking you, a turn is running where the light would be green, the repo holds uncommitted or unpushed work, there is no PR, it closed unmerged or merged elsewhere, the pipeline failed, or work began after the PR merged |
The repo is the one Claude last edited a file in. A feature branch is judged by its own PR; on an integration branch, or once the worktree is gone, by the PR a gh pr command last printed. A turn that changes nothing, such as a question, ends green again. A turn that edits a file git does not ignore, or creates a commit, branch, worktree, issue or PR, leaves that merged PR unable to turn the light green: green waits for the new work's PR. The light refreshes after git and gh commands, and every 30 seconds while yellow. /traffic-light prints it; /traffic-light demo shows each color.
It runs git and gh, so the session needs both on its PATH and gh signed in.
Mods load only with function hooks enabled, so export this in your shell profile first:
export CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1
Without it Claude Code skips the mods silently. Then, in Claude Code:
/plugin marketplace add bahaospanov/skills
/plugin install <mod>@bahaospanov
One folder per mod. tsconfig.json and types/ are shared. An installed mod carries only its own folder, so code two mods share is copied into each one's hooks/shared/.
CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude --plugin-dir ./<mod> --debug
Saving a file under <mod>/hooks/ reloads the mod. Repeat --plugin-dir to load several.
npm run typecheck # tsc over every mod and its tests
npm run check:shared # hooks/shared/ copies are identical across mods
npm run check:continuations # every mod sending follow-up prompts is named where git-gates reads them
npm run check:version # every plugin.json carries package.json's version
claude plugin validate ./<mod> # what the engine sees the module hook and call
claude plugin test ./<mod> # the mod's tests/
types/ is written by /plugin-types types, run inside a session started as above. Regenerate, never edit, when:
head -1 types/claude-code.d.ts vs claude --version)$ is enabled or disabledCommit the result; git diff types/ shows what the update changed.
hooks/register.ts 323 lines1import type { EngineInterface, Register } from 'claude-code'
2import { forgeMergeOf, saysMerged, unmergedRefused } from './merged-first'
3import {
4 acknowledgesPipeline,
5 cleanupOf,
6 coverageOf,
7 githubPipelines,
8 gitlabPipelines,
9 issuesEditedBy,
10 pipelineRefused,
11 remoteOf,
12 type Coverage,
13 type Pipeline,
14} from './pipeline-first'
15import {
16 branchesOf,
17 commandDir,
18 currentTurn,
19 defaultBranchOf,
20 deletedBranches,
21 FALLBACK_BASES,
22 pushTargets,
23 verbOf,
24 type Verb,
25} from './shared/git-commands'
26import { refsInText } from './shared/issue-refs'
27import { cleanupSteps, removedNotice, worktreesOf, type BehindBase, type Stale } from './stale-work'
28
29const HUMAN_ORIGINS: readonly string[] = ['composer', 'bridge', 'sdk']
30const LOOKBACK = 30
31const MAX_STALE_FOLLOW_UPS = 2
32const FETCH_TIMEOUT_MS = 20_000
33const PIPELINE_PAGE = 20
34const ISSUE_LOOKBACK = 200
35
36type Prompt = { text: string; turnId?: string | undefined }
37type Held =
38 | { kind: 'pipeline'; what: string; base: string; coverage: Exclude<Coverage, { kind: 'green' | 'unknown' }> }
39 | { kind: 'unmerged'; branch: string; bases: string[] }
40
41let typed: Prompt[] = []
42let gitlabToken: string | undefined
43// Branches this session committed to or pushed, by repo: the only work the stale check tidies.
44const worked = new Map<string, { dir: string | undefined; branches: Set<string> }>()
45const reportedStale = new Set<string>()
46let staleFollowUps = 0
47
48const firstLine = (text: string) => text.split('\n')[0] ?? ''
49
50const git = async ($: EngineInterface, args: string[], cwd?: string) => {
51 const run = await $.process.run(['git', ...args], cwd === undefined ? undefined : { cwd })
52 return run.exitCode === 0 ? run.stdout.trim() : undefined
53}
54
55// The loader only admits literal $.env.get names; HOME is all a `cd ~/…` needs.
56const repoOf = async ($: EngineInterface, command: string) => {
57 const dir = commandDir(command)
58 return dir?.startsWith('~') ? `${await $.env.get('HOME')}${dir.slice(1)}` : dir
59}
60
61const currentBranch = async ($: EngineInterface, cwd?: string) => {
62 const branch = await git($, ['rev-parse', '--abbrev-ref', 'HEAD'], cwd)
63 return branch && branch !== 'HEAD' ? branch : undefined
64}
65
66// `git()` swallows a non-zero exit, and that exit is the answer here.
67const isAncestor = async ($: EngineInterface, commit: string, of: string, cwd?: string) => {
68 const run = await $.process.run(['git', 'merge-base', '--is-ancestor', commit, of], cwd === undefined ? undefined : { cwd })
69 return run.exitCode === 0
70}
71
72// A rebase merge lands copies, never the branch's own commits; `git cherry` matches them by patch.
73const holds = async ($: EngineInterface, upstream: string, head: string, cwd?: string) => {
74 if (await isAncestor($, head, upstream, cwd)) return true
75 const cherry = await git($, ['cherry', upstream, head], cwd)
76 return cherry !== undefined && !cherry.split('\n').some((line) => line.startsWith('+'))
77}
78
79const integrationBases = async ($: EngineInterface, cwd?: string) => {
80 const top = await git($, ['rev-parse', '--show-toplevel'], cwd)
81 const policy = top ? await $.fs.read(`${top}/.claude/push-policy.json`).catch(() => undefined) : undefined
82 const protectedBranches = policy === undefined ? [] : branchesOf(policy)
83 if (protectedBranches.length > 0) return protectedBranches
84 const head = defaultBranchOf(await git($, ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'], cwd))
85 const bases: string[] = []
86 for (const base of new Set([...(head ? [head] : []), ...FALLBACK_BASES])) {
87 if ((await git($, ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${base}`], cwd)) !== undefined) bases.push(base)
88 }
89 return bases
90}
91
92const landedBase = async ($: EngineInterface, commit: string, bases: string[], cwd?: string) => {
93 for (const base of bases) if (await holds($, `refs/remotes/origin/${base}`, commit, cwd)) return base
94 return undefined
95}
96
97const pipelinesOf = async ($: EngineInterface, base: string, cwd?: string): Promise<Pipeline[] | string> => {
98 const url = await git($, ['remote', 'get-url', 'origin'], cwd)
99 const remote = url === undefined ? undefined : remoteOf(url)
100 if (remote === undefined) return 'origin is no forge this check reads'
101 if (remote.host === 'github.com') {
102 const argv = ['gh', 'run', 'list', '--branch', base, '--limit', String(PIPELINE_PAGE), '--json', 'databaseId,headSha,status,conclusion,url']
103 const run = await $.process.run(argv, cwd === undefined ? undefined : { cwd }).catch(() => undefined)
104 if (run?.exitCode !== 0) return `gh run list failed: ${firstLine(run?.stderr ?? 'gh not found')}`
105 return githubPipelines(run.stdout) ?? 'gh run list answered no list'
106 }
107 if (gitlabToken === undefined) return 'no gitlab_token in git-cleanup options'
108 const api = `https://${remote.host}/api/v4/projects/${encodeURIComponent(remote.path)}/pipelines`
109 const response = await $.http.fetch(`${api}?ref=${encodeURIComponent(base)}&per_page=${PIPELINE_PAGE}`, {
110 headers: { 'PRIVATE-TOKEN': gitlabToken },
111 })
112 if (!response.ok) return `GitLab answered ${response.status}`
113 return gitlabPipelines(response.text) ?? 'GitLab answered no list'
114}
115
116// Pipelines run on a linear base, so the ones holding the work are the newest few: stop at the first that does not.
117const coverage = async ($: EngineInterface, head: string, base: string, cwd?: string): Promise<Coverage> => {
118 const pipelines = await pipelinesOf($, base, cwd)
119 if (typeof pipelines === 'string') return { kind: 'unknown', why: pipelines }
120 const marked: (Pipeline & { covers: boolean })[] = []
121 for (const pipeline of pipelines) {
122 const covers = await holds($, pipeline.sha, head, cwd)
123 marked.push({ ...pipeline, covers })
124 if (!covers) break
125 }
126 return coverageOf(marked)
127}
128
129const issueLanding = async ($: EngineInterface, ref: string, bases: string[], cwd?: string) => {
130 for (const base of bases) {
131 const log = await git($, ['log', `refs/remotes/origin/${base}`, `-n${ISSUE_LOOKBACK}`, '--format=%H%x09%s'], cwd)
132 for (const line of log?.split('\n') ?? []) {
133 const [sha, subject] = line.split('\t')
134 if (sha && subject && refsInText(subject, true).includes(ref)) return { head: sha, base, subject }
135 }
136 }
137 return undefined
138}
139
140// Covers squash merges, whose commits `git cherry` cannot match.
141const forgeMerge = async ($: EngineInterface, branch: string, cwd?: string) => {
142 const url = await git($, ['remote', 'get-url', 'origin'], cwd)
143 const remote = url === undefined ? undefined : remoteOf(url)
144 if (remote === undefined) return undefined
145 if (remote.host === 'github.com') {
146 const argv = ['gh', 'pr', 'list', '--head', branch, '--state', 'merged', '--limit', '1', '--json', 'number,mergeCommit']
147 const run = await $.process.run(argv, cwd === undefined ? undefined : { cwd }).catch(() => undefined)
148 return run?.exitCode === 0 ? forgeMergeOf(run.stdout) : undefined
149 }
150 if (gitlabToken === undefined) return undefined
151 const api = `https://${remote.host}/api/v4/projects/${encodeURIComponent(remote.path)}/merge_requests`
152 const response = await $.http.fetch(`${api}?source_branch=${encodeURIComponent(branch)}&state=merged&per_page=1`, {
153 headers: { 'PRIVATE-TOKEN': gitlabToken },
154 })
155 return response.ok ? forgeMergeOf(response.text) : undefined
156}
157
158const heldWork = async ($: EngineInterface, command: string, saidMerged: boolean): Promise<Held | undefined> => {
159 const cleanup = cleanupOf(command)
160 const branches = [...(cleanup?.branches ?? []), ...(deletedBranches(command) ?? [])]
161 const issues = issuesEditedBy(command)
162 if (branches.length === 0 && issues.length === 0 && !cleanup?.worktrees.length) return undefined
163 const cwd = await repoOf($, command)
164 const checkedOut: string[] = []
165 if (cleanup?.worktrees.length) {
166 const trees = worktreesOf((await git($, ['worktree', 'list', '--porcelain'], cwd)) ?? '')
167 for (const path of cleanup.worktrees) {
168 const tail = path.replace(/^\.\//, '').replace(/\/$/, '')
169 const tree = trees.find((wt) => wt.path === tail || wt.path.endsWith(`/${tail}`))
170 if (tree?.branch !== undefined) checkedOut.push(tree.branch)
171 }
172 }
173 await $.process.run(['git', 'fetch', '--quiet', 'origin'], { ...(cwd === undefined ? {} : { cwd }), timeoutMs: FETCH_TIMEOUT_MS }).catch(() => undefined)
174 const bases = await integrationBases($, cwd)
175 const work: { what: string; head: string; base: string }[] = []
176 for (const branch of new Set([...branches, ...checkedOut])) {
177 if (bases.includes(branch)) continue
178 const head =
179 (await git($, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], cwd)) ??
180 (await git($, ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branch}`], cwd))
181 if (head === undefined) continue
182 const base = await landedBase($, head, bases, cwd)
183 if (base !== undefined) {
184 work.push({ what: `'${branch}'`, head, base })
185 continue
186 }
187 const merge = await forgeMerge($, branch, cwd)
188 // A squash merge lands as a new commit, and the pipeline holding that commit is the one to wait for.
189 const squashed = merge?.sha === undefined ? undefined : await landedBase($, merge.sha, bases, cwd)
190 if (merge?.sha !== undefined && squashed !== undefined) work.push({ what: `'${branch}'`, head: merge.sha, base: squashed })
191 // Removing a worktree keeps its branch, so only removing the branch itself can lose its commits.
192 else if (merge === undefined && branches.includes(branch) && !saidMerged) return { kind: 'unmerged', branch, bases }
193 }
194 for (const ref of issues) {
195 const landing = await issueLanding($, ref, bases, cwd)
196 if (landing !== undefined) work.push({ what: `the work on ${ref} (${landing.subject})`, head: landing.head, base: landing.base })
197 }
198 for (const item of work) {
199 const shipped = await coverage($, item.head, item.base, cwd)
200 if (shipped.kind === 'unknown') $.ui.log(`git-cleanup (pipeline first): ${item.what}: pipeline unknown (${shipped.why}); not gating`)
201 if (shipped.kind === 'waiting' || shipped.kind === 'failed') return { kind: 'pipeline', what: item.what, base: item.base, coverage: shipped }
202 }
203 return undefined
204}
205
206const recordWork = async ($: EngineInterface, command: string, verb: Verb) => {
207 if (deletedBranches(command) !== undefined) return
208 const dir = await repoOf($, command)
209 const common = await git($, ['rev-parse', '--path-format=absolute', '--git-common-dir'], dir)
210 if (common === undefined) return
211 const current = await currentBranch($, dir)
212 const branches = verb === 'push' ? (pushTargets(command, current) ?? []) : current ? [current] : []
213 const repo = worked.get(common) ?? { dir, branches: new Set<string>() }
214 for (const branch of branches) if (branch !== '*') repo.branches.add(branch)
215 worked.set(common, repo)
216}
217
218const staleWork = async ($: EngineInterface) => {
219 const reports: { main: string; items: Stale[]; behind: BehindBase[] }[] = []
220 for (const [common, repo] of worked) {
221 const trees = worktreesOf((await git($, ['worktree', 'list', '--porcelain'], repo.dir)) ?? '')
222 const main = trees[0]?.path
223 if (main === undefined) continue
224 await $.process.run(['git', 'fetch', '--quiet', '--prune', 'origin'], { cwd: main, timeoutMs: FETCH_TIMEOUT_MS }).catch(() => undefined)
225 const bases = await integrationBases($, main)
226 const items: Stale[] = []
227 for (const branch of repo.branches) {
228 if (bases.includes(branch) || reportedStale.has(`${common}\0${branch}`)) continue
229 const local = await git($, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], main)
230 const remote = await git($, ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branch}`], main)
231 const head = local ?? remote
232 if (head === undefined) continue
233 const base = await landedBase($, head, bases, main)
234 if (base === undefined) continue
235 if (remote !== undefined && remote !== head && (await landedBase($, remote, bases, main)) === undefined) continue
236 const tree = trees.slice(1).find((wt) => wt.branch === branch)
237 if (tree !== undefined && (await git($, ['status', '--porcelain'], tree.path)) !== '') continue
238 const shipped = await coverage($, head, base, main)
239 if (shipped.kind === 'waiting' || shipped.kind === 'failed') continue
240 reportedStale.add(`${common}\0${branch}`)
241 items.push({ branch, base, worktree: tree?.path, local: local !== undefined, remote: remote !== undefined })
242 }
243 if (items.length === 0) continue
244 // Only a local base origin can fast-forward is offered; a diverged one is the user's to sort out.
245 const behind: BehindBase[] = []
246 for (const base of new Set(items.map((s) => s.base))) {
247 const local = await git($, ['rev-parse', '--verify', '--quiet', `refs/heads/${base}`], main)
248 const origin = await git($, ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${base}`], main)
249 if (local === undefined || origin === undefined || local === origin) continue
250 if (!(await isAncestor($, local, `refs/remotes/origin/${base}`, main))) continue
251 behind.push({ base, checkout: trees.find((wt) => wt.branch === base)?.path })
252 }
253 reports.push({ main, items, behind })
254 }
255 return reports
256}
257
258// The worktree this session works in stays, and so does its branch: removing it would pull the floor from under it.
259const removeStale = async ($: EngineInterface, reports: { main: string; items: Stale[]; behind: BehindBase[] }[]) => {
260 const cwd = await $.session.cwd()
261 const removed: string[] = []
262 const failed: string[] = []
263 for (const report of reports) {
264 const items = report.items.filter((s) => s.worktree === undefined || !(cwd === s.worktree || cwd.startsWith(`${s.worktree}/`)))
265 const stuck = new Set<string>()
266 for (const step of cleanupSteps(items, report.main, report.behind)) {
267 const run = await $.process.run(step.argv, { cwd: step.cwd, timeoutMs: FETCH_TIMEOUT_MS }).catch(() => undefined)
268 if (run?.exitCode === 0) continue
269 if (step.branch !== undefined) stuck.add(step.branch)
270 failed.push(`${step.argv.slice(1).join(' ')} (${firstLine(run?.stderr || 'did not start')})`)
271 }
272 removed.push(...items.map((s) => s.branch).filter((branch) => !stuck.has(branch)))
273 }
274 return removedNotice(removed, failed)
275}
276
277export const register: Register = (on, options) => {
278 gitlabToken = typeof options.gitlab_token === 'string' && options.gitlab_token !== '' ? options.gitlab_token : undefined
279
280 on('prompt.submit', ($, e, next) => {
281 if (HUMAN_ORIGINS.includes(e.origin.kind)) typed = [...typed, { text: e.text, turnId: e.turnId }].slice(-LOOKBACK)
282 return next(e)
283 })
284
285 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
286 const turn = currentTurn(typed)
287 const held = await heldWork($, e.command, turn.some((p) => saysMerged(p.text)))
288 if (held === undefined) return next(e)
289 if (held.kind === 'unmerged') {
290 $.ui.log(`git-cleanup (merged first): nothing says '${held.branch}' is merged`)
291 return { deny: unmergedRefused(e.command, held.branch, held.bases) }
292 }
293 if (turn.some((p) => acknowledgesPipeline(p.text))) return next(e)
294 $.ui.log(`git-cleanup (pipeline first): ${held.what} waits on its pipeline`)
295 return { deny: pipelineRefused(e.command, held.what, held.base, held.coverage) }
296 }).catch(($, e, next) => {
297 $.ui.log(`git-cleanup: the cleanup check failed (${next.error.message ?? next.error.kind}); not gating`)
298 return undefined
299 })
300
301 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
302 const verb = verbOf(e.command)
303 const result = await next(e)
304 if (verb !== 'commit' && verb !== 'push') return result
305 if ('deny' in result && result.deny !== undefined) return result
306 await recordWork($, e.command, verb).catch(() => undefined)
307 return result
308 })
309
310 on('turn.complete', async ($, e, next) => {
311 const result = await next(e)
312 if (e.agentId !== undefined || e.reason !== 'answer' || worked.size === 0 || staleFollowUps >= MAX_STALE_FOLLOW_UPS) {
313 return result
314 }
315 const reports = await staleWork($).catch(() => [])
316 if (reports.length === 0) return result
317 staleFollowUps++
318 const notice = await removeStale($, reports)
319 if (notice !== '') $.ui.log(notice)
320 return result
321 })
322}
323hooks/merged-first.ts 34 lines1const SAYS_MERGED = /(^|[^\p{L}])(merged)(?!\p{L})/iu
2const DENIES_MERGED = /(\bnot|n't|\bnever|\bun)[\s-]*(yet\s+)?merged/iu
3const LETS_GO = /\b(abandon(ed)?|discard(ed)?|throw (it )?away|delete (it )?(anyway|unmerged))\b/iu
4
5export const saysMerged = (text: string) => (SAYS_MERGED.test(text) && !DENIES_MERGED.test(text)) || LETS_GO.test(text)
6
7const shaIn = (value: unknown) => (typeof value === 'string' && value !== '' ? value : undefined)
8
9// A forge's list of merged PRs or MRs for one branch: undefined when it lists none, else the commit the merge
10// landed as, a squash merge's new commit included, when the forge says.
11export const forgeMergeOf = (json: string): { sha: string | undefined } | undefined => {
12 try {
13 const parsed: unknown = JSON.parse(json)
14 if (!Array.isArray(parsed) || parsed.length === 0) return undefined
15 const first: unknown = parsed[0]
16 if (typeof first !== 'object' || first === null) return { sha: undefined }
17 const fields = first as Record<string, unknown>
18 const commit = fields.mergeCommit
19 const oid = typeof commit === 'object' && commit !== null ? (commit as Record<string, unknown>).oid : undefined
20 return { sha: shaIn(fields.squash_commit_sha) ?? shaIn(fields.merge_commit_sha) ?? shaIn(oid) }
21 } catch {
22 return undefined
23 }
24}
25
26export const unmergedRefused = (command: string, branch: string, bases: string[]) =>
27 `git-cleanup (merged first): blocking '${command}' — nothing says '${branch}' is merged.
28
29Its commits are not in ${bases.map((b) => `origin/${b}`).join(', ') || 'any integration branch'}, and no merged
30PR or MR has it as its source branch. Removing it loses that work.
31
32If it is merged where git cannot see it (a squash merge), or the user wants it
33gone anyway, they say so ("it's merged", "abandon it") and this check steps aside.`
34hooks/pipeline-first.ts 164 lines1// Observed 2026-10-05: right after an MR merged, the agent removed its worktree and branch
2// and ticked the issue while the pipeline deploying the merge still ran.
3
4export type PipelineState = 'success' | 'running' | 'idle' | 'failed'
5export type Pipeline = { id: string; sha: string; state: PipelineState; status: string; url?: string | undefined }
6export type Coverage =
7 | { kind: 'green' }
8 | { kind: 'waiting' | 'failed'; pipeline: Pipeline }
9 | { kind: 'unknown'; why: string }
10export type Cleanup = { branches: string[]; worktrees: string[] }
11
12const SEPARATORS = ['&&', '||', ';', '|']
13// Anything neither success, in flight nor idle (canceled, failed) did not ship.
14const RUNNING = new Set([
15 'created', 'waiting_for_resource', 'preparing', 'pending', 'running', 'scheduled',
16 'queued', 'in_progress', 'requested', 'waiting',
17])
18// GitLab parks a pipeline at manual (a job waits for a click) or skipped (CI did not run it): nothing
19// runs or fails any more, so waiting for it would hold the cleanup forever.
20const IDLE = new Set(['manual', 'skipped'])
21const GITHUB_PASS = new Set(['success', 'skipped', 'neutral'])
22
23const segmentsOf = (command: string) => {
24 const tokens = command.replace(/\n/g, ' ; ').split(/\s+/).filter(Boolean)
25 const segments: string[][] = [[]]
26 for (const token of tokens) {
27 if (SEPARATORS.includes(token)) segments.push([])
28 else segments.at(-1)?.push(token)
29 }
30 return segments
31}
32
33export const cleanupOf = (command: string): Cleanup | undefined => {
34 const cleanup: Cleanup = { branches: [], worktrees: [] }
35 for (const [git, sub, ...rest] of segmentsOf(command)) {
36 if (git !== 'git') continue
37 if (sub === 'branch' && rest.some((t) => t === '-d' || t === '-D' || t === '--delete')) {
38 if (rest.some((t) => t === '-r' || t === '--remotes')) continue
39 cleanup.branches.push(...rest.filter((t) => !t.startsWith('-')))
40 }
41 if (sub === 'worktree' && rest[0] === 'remove') cleanup.worktrees.push(...rest.slice(1).filter((t) => !t.startsWith('-')))
42 }
43 return cleanup.branches.length + cleanup.worktrees.length > 0 ? cleanup : undefined
44}
45
46const REST_ISSUE = /\/issues\/(\d+)(?=['"\s?]|$)/g
47const REST_BODY = /(?<![\w-])description\s*[=:"']|"description"\s*:|(?<![\w-])body\s*=|"body"\s*:/
48const CLI_ISSUE = /(?:^|[\s&;|(])(gh|glab)\s+issue\s+(edit|update)\s+#?(\d+)\b([^&;|\n]*)/g
49const CLI_BODY = /--body(?:-file)?\b|--description\b|(?<![\w-])-[bd]\b/
50
51// A rewritten body (checklist ticks, How to test) says the work shipped; closing is the user's, a comment says nothing.
52export const issuesEditedBy = (command: string): string[] => {
53 const found = new Set<string>()
54 if (REST_BODY.test(command)) for (const m of command.matchAll(REST_ISSUE)) found.add(`#${m[1]}`)
55 for (const m of command.matchAll(CLI_ISSUE)) if (CLI_BODY.test(m[4] ?? '')) found.add(`#${m[3]}`)
56 return [...found]
57}
58
59export const remoteOf = (url: string): { host: string; path: string } | undefined => {
60 const trimmed = url.trim().replace(/\.git$/, '').replace(/\/$/, '')
61 const scp = trimmed.match(/^[\w.-]+@([\w.-]+):(?!\/)(.+)$/)
62 if (scp) return { host: scp[1] ?? '', path: scp[2] ?? '' }
63 const full = trimmed.match(/^(?:ssh|https?|git):\/\/(?:[^@/]+@)?([\w.-]+)(?::\d+)?\/(.+)$/)
64 return full ? { host: full[1] ?? '', path: full[2] ?? '' } : undefined
65}
66
67const stateOf = (status: string): PipelineState =>
68 status === 'success' ? 'success' : RUNNING.has(status) ? 'running' : IDLE.has(status) ? 'idle' : 'failed'
69
70const parse = (json: string): unknown => {
71 try {
72 return JSON.parse(json)
73 } catch {
74 return undefined
75 }
76}
77
78const field = (value: unknown, key: string): unknown =>
79 typeof value === 'object' && value !== null && key in value ? (value as Record<string, unknown>)[key] : undefined
80
81export const gitlabPipelines = (json: string): Pipeline[] | undefined => {
82 const list = parse(json)
83 if (!Array.isArray(list)) return undefined
84 return list.flatMap((p) => {
85 const id = field(p, 'id')
86 const sha = field(p, 'sha')
87 const status = field(p, 'status')
88 if (typeof sha !== 'string' || typeof status !== 'string') return []
89 const url = field(p, 'web_url')
90 return [{ id: `#${String(id)}`, sha, state: stateOf(status), status, url: typeof url === 'string' ? url : undefined }]
91 })
92}
93
94// One entry per workflow run, so a sha is green only when every run on it passed.
95export const githubPipelines = (json: string): Pipeline[] | undefined => {
96 const list = parse(json)
97 if (!Array.isArray(list)) return undefined
98 const bySha = new Map<string, Pipeline>()
99 for (const run of list) {
100 const sha = field(run, 'headSha')
101 const status = field(run, 'status')
102 if (typeof sha !== 'string' || typeof status !== 'string') continue
103 const conclusion = String(field(run, 'conclusion') ?? '')
104 const own: PipelineState =
105 status !== 'completed' ? 'running' : GITHUB_PASS.has(conclusion) ? 'success' : 'failed'
106 const seen = bySha.get(sha)
107 if (seen === undefined) {
108 const url = field(run, 'url')
109 bySha.set(sha, {
110 id: `run ${String(field(run, 'databaseId'))}`,
111 sha,
112 state: own,
113 status: status === 'completed' ? conclusion : status,
114 url: typeof url === 'string' ? url : undefined,
115 })
116 } else if (seen.state !== 'failed' && own !== 'success') {
117 bySha.set(sha, { ...seen, state: own, status: status === 'completed' ? conclusion : status })
118 }
119 }
120 return [...bySha.values()]
121}
122
123// Newest first. None holding the work is a commit CI skipped or one whose pipeline is not created yet,
124// which this check cannot tell apart.
125export const coverageOf = (pipelines: (Pipeline & { covers: boolean })[]): Coverage => {
126 const covering = pipelines.filter((p) => p.covers)
127 if (covering.some((p) => p.state === 'success')) return { kind: 'green' }
128 const newest = covering[0]
129 if (newest === undefined) {
130 return { kind: 'unknown', why: pipelines.length === 0 ? 'the branch has no pipelines' : 'no pipeline holds this work' }
131 }
132 const running = covering.find((p) => p.state === 'running')
133 if (running !== undefined) return { kind: 'waiting', pipeline: running }
134 if (newest.state === 'idle') return { kind: 'unknown', why: `pipeline ${newest.id} is ${newest.status}` }
135 return { kind: 'failed', pipeline: newest }
136}
137
138const ACKNOWLEDGES =
139 /\b(skip|ignore|without(\s+waiting\s+for)?|don'?t\s+wait\s+for|no\s+need\s+to\s+wait\s+for)\s+(the\s+)?(ci|pipeline)\b|\b(ci|pipeline)\s+(doesn'?t\s+matter|is\s+irrelevant)\b/i
140
141export const acknowledgesPipeline = (text: string) => ACKNOWLEDGES.test(text)
142
143const named = (p: Pipeline) => `${p.id}${p.url ? ` (${p.url})` : ''}`
144
145export const pipelineRefused = (command: string, what: string, base: string, coverage: Exclude<Coverage, { kind: 'green' | 'unknown' }>) => {
146 const state =
147 coverage.kind === 'waiting'
148 ? `pipeline ${named(coverage.pipeline)} is still ${coverage.pipeline.status}`
149 : `its newest pipeline, ${named(coverage.pipeline)}, ended ${coverage.pipeline.status}`
150 const step =
151 coverage.kind === 'waiting'
152 ? `Wait for it in the background (a loop on its status that exits on success,
153failed or canceled), check the change where it deploys, then retry.`
154 : `Find out why and get a green pipeline first.`
155 return `git-cleanup (pipeline first): blocking '${command}' — ${what} landed in '${base}', and ${state}.
156
157Removing a branch or filling in its issue says the work is done. It is not
158until the pipeline that ships it passes and the change is checked live.
159${step}
160
161If the user wants it done regardless, they say so ("skip the pipeline") and
162this check steps aside.`
163}
164hooks/shared/git-commands.ts 200 lines1export type Verb = 'merge' | 'push' | 'commit'
2
3const MERGE = /(merge_requests\/[0-9]+\/merge|pulls\/[0-9]+\/merge|(^|[\s&;|(])(gh\s+pr|glab\s+mr)\s+merge(\s|$))/m
4// git's own options before the subcommand (`git -C dir push`, `git -c k=v commit`) must not hide it.
5const VALUED_GLOBALS = ['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--config-env']
6const GLOBALS = String.raw`(?:\s+(?:-[Cc]\s+\S+|--(?:git-dir|work-tree|namespace|exec-path|config-env)(?:=\S+|\s+\S+)?|--?[a-z][a-z-]*))*`
7const PUSH = new RegExp(String.raw`(^|[\s&;|(])git${GLOBALS}\s+push(\s|$)`, 'm')
8const COMMIT = new RegExp(String.raw`(^|[\s&;|(])git${GLOBALS}\s+commit(\s|$)`, 'm')
9
10// With no push policy a repo's integration branches are guessed: the remote's default branch, then these.
11export const FALLBACK_BASES: readonly string[] = ['dev', 'develop', 'main', 'master']
12
13// A quoted string becomes one placeholder word: a message quoting `git push` is not a push, and `-C "a b"` keeps its value.
14const unquoted = (command: string) => command.replace(/'[^']*'/g, 'Q').replace(/"[^"]*"/g, 'Q')
15
16export const verbOf = (command: string): Verb | undefined => {
17 if (MERGE.test(command)) return 'merge'
18 const plain = unquoted(command)
19 if (PUSH.test(plain)) return 'push'
20 if (COMMIT.test(plain)) return 'commit'
21 return undefined
22}
23
24const tokensOf = (command: string) =>
25 [...command.replace(/\n/g, ' ; ').matchAll(/(?:"[^"]*"|'[^']*'|[^\s"'])+/g)].map((m) => m[0])
26
27const pushAt = (tokens: string[], at: number): number | undefined => {
28 if (tokens[at] !== 'git') return undefined
29 let i = at + 1
30 while ((tokens[i] ?? '').startsWith('-')) i += VALUED_GLOBALS.includes(tokens[i] ?? '') ? 2 : 1
31 return tokens[i] === 'push' ? i : undefined
32}
33
34// A prompt typed over a running turn joins the one that opened that turn, so a quick follow-up cannot withdraw its word.
35export const currentTurn = <P extends { turnId?: string | undefined }>(prompts: P[]): P[] => {
36 const last = prompts.at(-1)
37 if (last === undefined) return []
38 if (last.turnId === undefined) return [last]
39 let start = prompts.length - 1
40 while (start > 0 && prompts[start - 1]?.turnId === last.turnId) start--
41 return prompts.slice(Math.max(0, start - 1))
42}
43
44export const branchesOf = (policy: string): string[] => {
45 try {
46 const parsed: unknown = JSON.parse(policy)
47 const branches = typeof parsed === 'object' && parsed !== null && 'protected_branches' in parsed ? parsed.protected_branches : []
48 return Array.isArray(branches) ? branches.filter((b): b is string => typeof b === 'string' && b !== '') : []
49 } catch {
50 return []
51 }
52}
53
54export const defaultBranchOf = (symref: string | undefined) => symref?.trim().replace(/^refs\/remotes\/origin\//, '') || undefined
55
56// Every branch the command's `git push`es write to; `*` for --all/--mirror, undefined when one cannot be known.
57export const pushTargets = (command: string, current: string | undefined): string[] | undefined => {
58 const tokens = tokensOf(command)
59 const targets: string[] = []
60 let found = false
61 let i = 0
62 while (i < tokens.length) {
63 const push = pushAt(tokens, i)
64 if (push === undefined) {
65 i++
66 continue
67 }
68 found = true
69 i = push + 1
70 let remoteSeen = false
71 let all = false
72 const refs: string[] = []
73 for (; i < tokens.length; i++) {
74 const token = tokens[i] ?? ''
75 if (['&&', '||', ';', '|'].includes(token)) break
76 if (token === '--all' || token === '--mirror') all = true
77 else if (['--repo', '--push-option', '--receive-pack', '--exec', '-o'].includes(token)) i++
78 else if (token.startsWith('-')) continue
79 else if (!remoteSeen) remoteSeen = true
80 else refs.push(token)
81 }
82 if (all) {
83 targets.push('*')
84 } else if (refs.length === 0) {
85 if (current === undefined) return undefined
86 targets.push(current)
87 } else {
88 for (const ref of refs) {
89 let branch = ref.replace(/^\+/, '')
90 branch = branch.slice(branch.lastIndexOf(':') + 1).replace(/^refs\/heads\//, '')
91 if (branch === 'HEAD') {
92 if (current === undefined) return undefined
93 branch = current
94 }
95 if (branch !== '') targets.push(branch)
96 }
97 }
98 }
99 return found ? targets : undefined
100}
101
102export const deletedBranches = (command: string): string[] | undefined => {
103 const tokens = tokensOf(command)
104 const deleted: string[] = []
105 let found = false
106 let i = 0
107 while (i < tokens.length) {
108 const push = pushAt(tokens, i)
109 if (push === undefined) {
110 i++
111 continue
112 }
113 found = true
114 i = push + 1
115 let remoteSeen = false
116 let deleting = false
117 const refs: string[] = []
118 for (; i < tokens.length; i++) {
119 const token = tokens[i] ?? ''
120 if (['&&', '||', ';', '|'].includes(token)) break
121 if (token === '--delete' || token === '-d') deleting = true
122 else if (['--repo', '--push-option', '--receive-pack', '--exec', '-o'].includes(token)) i++
123 else if (token.startsWith('-')) continue
124 else if (!remoteSeen) remoteSeen = true
125 else refs.push(token)
126 }
127 if (refs.length === 0) return undefined
128 for (const ref of refs) {
129 if (!deleting && !ref.startsWith(':')) return undefined
130 const branch = ref.replace(/^:/, '').replace(/^refs\/heads\//, '')
131 if (branch === '' || branch.includes(':')) return undefined
132 deleted.push(branch)
133 }
134 }
135 return found && deleted.length > 0 ? deleted : undefined
136}
137
138const DIR = String.raw`("[^"]*"|'[^']*'|[^\s;&|()]+)`
139const CD_STEP = new RegExp(String.raw`(?:^|[;&|\n(])\s*cd\s+${DIR}`, 'g')
140const GIT_DIR = new RegExp(String.raw`^git\s+-C\s+${DIR}`)
141
142const unquote = (value: string) => value.replace(/^(["'])([\s\S]*)\1$/, '$2')
143const joinDir = (base: string | undefined, dir: string) =>
144 base === undefined || dir.startsWith('/') || dir.startsWith('~') ? dir : `${base.replace(/\/$/, '')}/${dir}`
145
146// The directory a command's first `git` runs in, from the `cd` steps before it and its `-C`;
147// undefined when that is the session's own. `~` is left for the caller to expand.
148export const commandDir = (command: string): string | undefined => {
149 const at = command.search(/\bgit\s/)
150 if (at < 0) return undefined
151 let dir: string | undefined
152 for (const step of command.slice(0, at).matchAll(CD_STEP)) dir = joinDir(dir, unquote(step[1] ?? ''))
153 const flag = command.slice(at).match(GIT_DIR)?.[1]
154 return flag === undefined ? dir : joinDir(dir, unquote(flag))
155}
156
157export type MrOpening = { target?: string | undefined; source?: string | undefined }
158
159const GH_CREATE = /(?:^|[\s&;|(])gh\s+pr\s+create\b/
160const GLAB_CREATE = /(?:^|[\s&;|(])glab\s+mr\s+create\b/
161const CURL = /(?:^|[\s&;|(])curl\s/
162// The collection, not one MR (`/merge_requests/42/merge`): only a POST there opens one.
163const MR_COLLECTION = /\/merge_requests(?![\w/])/
164const METHOD = /(?:^|\s)(?:-X|--request)[\s=]*['"]?([A-Za-z]+)/
165const SENDS_BODY = /(?:^|\s)(?:-F|--form|-d|--data(?:-raw|-binary|-urlencode|-ascii)?)[\s=]/
166
167const escaped = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
168
169const flagValue = (command: string, flags: string[]) => {
170 for (const flag of flags) {
171 const value = command.match(new RegExp(`(?:^|\\s)${escaped(flag)}(?:=|\\s+)['"]?([^\\s'"]+)`))?.[1]
172 if (value !== undefined) return value
173 }
174 return undefined
175}
176
177const param = (command: string, name: string) =>
178 command.match(new RegExp(`\\b${name}["']?\\s*[=:]\\s*["']?([^\\s"'&,}]+)`))?.[1]
179
180// curl sends POST when it has a body and no other method is named.
181const posts = (command: string) => {
182 const method = command.match(METHOD)?.[1]
183 return method === undefined ? SENDS_BODY.test(command) : method.toUpperCase() === 'POST'
184}
185
186// Quotes are stripped to find the command, so a message quoting `gh pr create` is not one; values are read from the whole.
187export const mrOpeningOf = (command: string): MrOpening | undefined => {
188 const unquoted = command.replace(/'[^']*'/g, '').replace(/"[^"]*"/g, '')
189 if (GH_CREATE.test(unquoted)) {
190 return { target: flagValue(command, ['--base', '-B']), source: flagValue(command, ['--head', '-H'])?.replace(/^[^:]+:/, '') }
191 }
192 if (GLAB_CREATE.test(unquoted)) {
193 return { target: flagValue(command, ['--target-branch', '-b']), source: flagValue(command, ['--source-branch', '-s']) }
194 }
195 if (CURL.test(unquoted) && MR_COLLECTION.test(command) && posts(command)) {
196 return { target: param(command, 'target_branch'), source: param(command, 'source_branch') }
197 }
198 return undefined
199}
200hooks/shared/issue-refs.ts 44 lines1const NUMBER = /(?<![\w&#/])#([1-9]\d*)\b/g
2const ISSUE_URL = /\/(?:-\/)?(?:issues|pull|merge_requests)\/(\d+)\b/g
3const KEY = /(?<![\w-])#?([A-Z][A-Z0-9]{1,9})-(\d+)(?![\w-])/g
4const BRANCH_KEY = /^([a-z][a-z0-9]{1,9})-(\d+)(?:-|$)/i
5const BRANCH_NUMBER = /^(\d+)-[a-z]/i
6
7// Shaped like tracker keys but naming standards, so "UTF-8" or "SHA-256" in a message is not a ticket.
8const NOT_TRACKERS = new Set([
9 'AES', 'ANSI', 'ASCII', 'BASE', 'CP', 'CRC', 'CVE', 'COVID', 'ECMA', 'ES', 'GMT', 'GPT', 'HTTP', 'IEEE', 'IPV',
10 'ISO', 'KOI', 'MD', 'PEP', 'RFC', 'RSA', 'SHA', 'SSL', 'TCP', 'TLS', 'UDP', 'USB', 'UTC', 'UTF', 'WCAG', 'WIN',
11])
12
13const ticket = (key: string, n: string) => (NOT_TRACKERS.has(key.toUpperCase()) ? undefined : `#${key.toUpperCase()}-${n}`)
14
15const unique = (refs: (string | undefined)[]) => [...new Set(refs.filter((r): r is string => r !== undefined))]
16
17// Claude Code's labels for attachments in a prompt ("[Image #2]", "[Pasted text #1 +12 lines]"), not issues.
18const ATTACHMENT = /\[(?:Image|Pasted text)[^\]\n]*\]/g
19
20// `tracked` is whether the repo has a remote: without one, "#87" cannot point at an issue.
21export const refsInText = (prompt: string, tracked: boolean): string[] => {
22 const text = prompt.replace(ATTACHMENT, ' ')
23 const found: { at: number; ref: string | undefined }[] = [...text.matchAll(KEY)].map((m) => ({
24 at: m.index,
25 ref: ticket(m[1] ?? '', m[2] ?? ''),
26 }))
27 if (tracked) {
28 for (const m of [...text.matchAll(NUMBER), ...text.matchAll(ISSUE_URL)]) found.push({ at: m.index, ref: `#${m[1]}` })
29 }
30 return unique(found.sort((a, b) => a.at - b.at).map((f) => f.ref))
31}
32
33export const refsInBranch = (branch: string, tracked: boolean): string[] =>
34 unique(
35 branch.split('/').map((segment) => {
36 const key = segment.match(BRANCH_KEY)
37 // A key is written in capitals or leads a slug (`blk-23-chat`); a bare lowercase `react-19` is a version.
38 if (key && (segment.length > key[0].length || /[A-Z]/.test(key[1] ?? ''))) return ticket(key[1] ?? '', key[2] ?? '')
39 const number = segment.match(BRANCH_NUMBER)?.[1]
40 return tracked && number !== undefined ? `#${number}` : undefined
41 }),
42 )
43
44hooks/stale-work.ts 46 lines1// Observed 2026-10-05: a merged, checked branch kept its worktree, its local branch and its origin branch,
2// and nothing in the session's flow ever came back for them.
3
4export type Worktree = { path: string; branch?: string | undefined }
5
6export type Stale = { branch: string; base: string; worktree?: string | undefined; local: boolean; remote: boolean }
7
8export type BehindBase = { base: string; checkout?: string | undefined }
9
10export const worktreesOf = (porcelain: string): Worktree[] =>
11 porcelain
12 .split(/\n\s*\n/)
13 .map((block): Worktree | undefined => {
14 const lines = block.split('\n')
15 const path = lines.find((line) => line.startsWith('worktree '))?.slice('worktree '.length)
16 const branch = lines.find((line) => line.startsWith('branch refs/heads/'))?.slice('branch refs/heads/'.length)
17 return path === undefined ? undefined : { path, branch }
18 })
19 .filter((wt): wt is Worktree => wt !== undefined)
20
21export type Step = { argv: string[]; cwd: string; branch?: string | undefined }
22
23// The git calls that remove merged, clean work and bring a local base that lags behind up to origin.
24// `branch -D`: a rebase merge leaves copies in the base, so `-d` would call the branch unmerged.
25export const cleanupSteps = (items: Stale[], main: string, behind: BehindBase[] = []): Step[] => [
26 // `git fetch origin b:b` refuses a branch checked out in any worktree; that one moves by a merge in its checkout.
27 ...behind.map((b) =>
28 b.checkout === undefined
29 ? { argv: ['git', 'fetch', 'origin', `${b.base}:${b.base}`], cwd: main }
30 : { argv: ['git', 'merge', '--ff-only', `origin/${b.base}`], cwd: b.checkout },
31 ),
32 ...items.flatMap((s) => [
33 ...(s.worktree ? [{ argv: ['git', 'worktree', 'remove', s.worktree], cwd: main, branch: s.branch }] : []),
34 ...(s.local ? [{ argv: ['git', 'branch', '-D', s.branch], cwd: main, branch: s.branch }] : []),
35 ...(s.remote ? [{ argv: ['git', 'push', 'origin', '--delete', s.branch], cwd: main, branch: s.branch }] : []),
36 ]),
37]
38
39export const removedNotice = (removed: string[], failed: string[]) =>
40 [
41 removed.length > 0 ? `git-cleanup: removed ${removed.join(', ')}` : undefined,
42 failed.length > 0 ? `git-cleanup: could not remove ${failed.join(', ')}` : undefined,
43 ]
44 .filter(Boolean)
45 .join('\n')
46