Feature work starts from an issue, and each commit names its own: a feat commit naming none is refused until Claude finds the issue, drafts one the user agrees…

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 109 lines1import type { EngineInterface, Register } from 'claude-code'
2import { featureRefused, isFeature, messageOf, waives } from './feature-commit'
3import { issueTailInBranch, missingRefViolation, subjectOf, subjectRefs, tailRefInBranch } from './issue-number'
4import { commandDir, currentTurn } from './shared/git-commands'
5import { refsInBranch, refsInText } from './shared/issue-refs'
6
7const HUMAN_ORIGINS: readonly string[] = ['composer', 'bridge', 'sdk']
8const LOOKBACK = 30
9
10type Prompt = { text: string; human: boolean; turnId?: string | undefined }
11
12let prompts: Prompt[] = []
13
14// Transcript rows carry no origin, so the engine's own user-role rows are told apart by their markup.
15const ENGINE_ROW = /<task-notification>|<local-command-(caveat|stdout|stderr)>/
16const REMINDER = /<system-reminder>[\s\S]*?<\/system-reminder>/g
17
18// Tracked prompts are exact; after a reload or resume the transcript stands in, minus the engine's rows.
19const recentPrompts = async ($: EngineInterface): Promise<Prompt[]> => {
20 if (prompts.length > 0) return prompts
21 const messages = await $.session.messages()
22 return messages
23 .filter((m) => m.role === 'user' && !m.toolResults?.length && !ENGINE_ROW.test(m.text))
24 .map((m) => ({ text: m.text.replace(REMINDER, '').trim(), human: true }))
25 .filter((p) => p.text !== '')
26 .slice(-LOOKBACK)
27}
28
29const git = async ($: EngineInterface, args: string[], cwd?: string) => {
30 const run = await $.process.run(['git', ...args], cwd === undefined ? undefined : { cwd })
31 return run.exitCode === 0 ? run.stdout.trim() : undefined
32}
33
34// The loader only admits literal $.env.get names; HOME is all a `cd ~/…` needs.
35const repoOf = async ($: EngineInterface, command: string) => {
36 const dir = commandDir(command)
37 return dir?.startsWith('~') ? `${await $.env.get('HOME')}${dir.slice(1)}` : dir
38}
39
40const messageText = async ($: EngineInterface, source: { text: string } | { file: string }, cwd?: string) => {
41 if ('text' in source) return source.text
42 if (source.file.startsWith('/')) return $.fs.read(source.file).catch(() => undefined)
43 const dir = cwd?.startsWith('/') ? cwd : [await $.session.cwd(), cwd].filter(Boolean).join('/')
44 return $.fs.read(`${dir}/${source.file}`).catch(() => undefined)
45}
46
47const currentBranch = async ($: EngineInterface, cwd?: string) => {
48 const branch = await git($, ['rev-parse', '--abbrev-ref', 'HEAD'], cwd)
49 return branch && branch !== 'HEAD' ? branch : undefined
50}
51
52// Worktrees of one repo share its common dir, so a worktree counts as the session's repo.
53const isSessionRepo = async ($: EngineInterface, cwd: string | undefined) => {
54 if (cwd === undefined) return true
55 const args = ['rev-parse', '--path-format=absolute', '--git-common-dir']
56 const [there, here] = await Promise.all([git($, args, cwd), git($, args)])
57 return there === undefined || here === undefined || there === here
58}
59
60// Refs the user named or the branch carries, newest first.
61// What the user typed is about the session's repo, so another repo's commit only answers to its branch.
62const mentionedRefs = async ($: EngineInterface, branch: string | undefined, tracked: boolean, cwd?: string) => {
63 const typed = (await isSessionRepo($, cwd)) ? (await recentPrompts($)).filter((p) => p.human).reverse() : []
64 return {
65 required: [
66 ...new Set([...(branch ? refsInBranch(branch, tracked) : []), ...typed.flatMap((p) => refsInText(p.text, tracked))]),
67 ],
68 accepted: branch ? tailRefInBranch(branch, tracked) : [],
69 }
70}
71
72export const register: Register = (on) => {
73 on('prompt.submit', ($, e, next) => {
74 prompts = [...prompts, { text: e.text, human: HUMAN_ORIGINS.includes(e.origin.kind), turnId: e.turnId }].slice(-LOOKBACK)
75 return next(e)
76 })
77
78 // No .catch: a check that throws lets the commit run, which suits a nudge better than blocking every commit.
79 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
80 const source = messageOf(e.command)
81 if (source === undefined) return next(e)
82 const cwd = await repoOf($, e.command)
83 const text = await messageText($, source, cwd)
84 if (text === undefined) return next(e)
85 const tracked = !!(await git($, ['remote'], cwd))
86 const branch = await currentBranch($, cwd)
87 const branchIssues = branch ? [...refsInBranch(branch, true), ...issueTailInBranch(branch)] : []
88 if (
89 tracked &&
90 isFeature(text) &&
91 subjectRefs(text).length === 0 &&
92 branchIssues.length === 0 &&
93 !currentTurn(prompts).some((p) => p.human && waives(p.text))
94 ) {
95 return { deny: featureRefused(subjectOf(text)) }
96 }
97 const refs = await mentionedRefs($, branch, tracked, cwd)
98 const missing = missingRefViolation(text, refs.required, refs.accepted)
99 if (missing === undefined) return next(e)
100 // A missing issue number is advice, not a block: the user sees it, the model is told to relay it and
101 // not to act on it (filing an issue is the user's call).
102 const result = await next(e)
103 if (result.deny !== undefined) return result
104 $.ui.log(`issue-first: committed without an issue number; suggestion: ${missing}`)
105 const relay = `issue-first: this commit has no issue number (${missing}). Tell the user as a recommendation; do not file an issue or rewrite the commit unless they ask.`
106 return { ...result, context: [...(result.context ?? []), relay] }
107 })
108}
109hooks/feature-commit.ts 33 lines1import { endSubject, subjectOf } from './issue-number'
2
3const COMMIT = /(?:^|[;&|\n(])\s*(?:cd\s+\S+\s*&&\s*)*git(?:\s+(?:-[cC]\s+\S+|--?[\w-]+(?:=\S+)?))*\s+commit\b/
4const FEATURE = /^feat(\([^)]*\))?!?:\s/
5const WAIVER = /\b(no|without(\s+an?)?|skip(\s+the)?)\s+issue\b/i
6
7export type MessageSource = { text: string } | { file: string } | undefined
8
9// Read only after `git commit`. A heredoc covers both `-F -` and Claude Code's `-m "$(cat <<'EOF' …)"`.
10export const messageOf = (command: string): MessageSource => {
11 const at = command.search(COMMIT)
12 if (at < 0) return undefined
13 const rest = command.slice(at)
14 if (/\s--no-edit\b/.test(rest)) return undefined
15 const heredoc = rest.match(/<<-?\s*(['"]?)(\w+)\1[^\n]*\n([\s\S]*?)\n\s*\2\b/)
16 if (heredoc?.[3] !== undefined) return { text: heredoc[3] }
17 const dashM = [...rest.matchAll(/(?:\s-[a-zA-Z]*m|\s--message)(?:\s*|=)(['"])([\s\S]*?)\1/g)].map((m) => m[2] ?? '')
18 if (dashM.length > 0) return { text: dashM.join('\n\n') }
19 const file = rest.match(/\s(?:-F|--file)(?:\s+|=)(\S+)/)?.[1]
20 return file === undefined || file === '-' ? undefined : { file }
21}
22
23export const isFeature = (message: string) => FEATURE.test(subjectOf(message))
24
25export const waives = (text: string) => WAIVER.test(text)
26
27export const featureRefused = (subject: string) =>
28 [
29 `issue-first: "${subject.slice(0, 70)}" is a feature, and neither its subject's end nor the branch names an issue (#N).`,
30 `Find the open issue this work belongs to, or draft one and show it to the user, creating it once they agree; then end the subject with its number: "${endSubject(subject, '#N')}".`,
31 'The playbook skill\'s ISSUES.md has the whole procedure. Only the user saying "no issue" lets the commit through without one.',
32 ].join('\n')
33hooks/issue-number.ts 35 lines1const BRANCH_TAIL = /(?:^|-)[a-z0-9]*[a-z][a-z0-9]*-(\d+)$/i
2const ISSUE_TAIL = /(?:^|-)[a-z0-9]*[a-z][a-z0-9]*-[a-z0-9]*[a-z][a-z0-9]*-(\d+)$/i
3const TRAILING = /(?:^|\s)((?:\(?#[A-Za-z0-9]+(?:-\d+)?\)?[.,]?\s*)+)$/
4const ENDED = /#(\d+|[A-Za-z][A-Za-z0-9]*-\d+)/g
5
6// The issue number a slug ends with (`perf/mobile-lcp-89`). Accepted as a subject's ending, never
7// demanded: in `chore/node-22` it is a version.
8export const tailRefInBranch = (branch: string, tracked: boolean): string[] => {
9 const number = tracked ? branch.split('/').at(-1)?.match(BRANCH_TAIL)?.[1] : undefined
10 return number === undefined ? [] : [`#${number}`]
11}
12
13// Enough on its own to name a feature's issue only after two or more words (`catalog-menu-107`): after one it is
14// usually a version (`react-19`, `node-22`).
15export const issueTailInBranch = (branch: string): string[] => {
16 const number = branch.split('/').at(-1)?.match(ISSUE_TAIL)?.[1]
17 return number === undefined ? [] : [`#${number}`]
18}
19
20export const subjectOf = (message: string) => message.trim().split(/\r?\n/)[0]?.trim() ?? ''
21
22// A commit names its issue at the end of its subject: "fix(web): cart total rounding #12", "(#12)", "#88 #BLK-23".
23export const subjectRefs = (message: string): string[] => {
24 const tail = subjectOf(message).match(TRAILING)?.[1] ?? ''
25 return [...tail.matchAll(ENDED)].map((m) => `#${(m[1] ?? '').toUpperCase()}`)
26}
27
28export const endSubject = (message: string, ref: string) => `${subjectOf(message)} ${ref}`
29
30export const missingRefViolation = (message: string, refs: string[], accepted: string[] = []): string | undefined => {
31 if (refs.length === 0) return undefined
32 if (subjectRefs(message).some((ref) => refs.includes(ref) || accepted.includes(ref))) return undefined
33 return `end the subject with the issue it is about: "${endSubject(message, refs[0] ?? '')}" (mentioned: ${refs.join(', ')})`
34}
35hooks/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
44