Runs the project's checks from a band button, and before Claude's git commit, and hands back only the failures.

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.tsx 167 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Failure, GateState } from '../types'
5import {
6 duration,
7 failureReport,
8 isGitCommit,
9 label,
10 NEEDS_NODE,
11 NOTHING_TO_RUN,
12 npmCliBeside,
13 parseConfig,
14 refusal,
15 scriptNames,
16 tail,
17} from './gate'
18import type { Check, Config } from './gate'
19
20const gate = atom({ plugin: 'lint-test-gate', key: 'gate' } as const, { kind: 'idle' } as GateState)
21
22/**
23 * Whether any surface shows the session right now. Asked before each run the
24 * mod starts and never kept. Each mod carries its own copy (ADR-0001).
25 */
26async function isShown($: EngineInterface): Promise<boolean> {
27 return (await $.session.surfaces()).length > 0
28}
29
30function report($: EngineInterface): (error: unknown) => void {
31 return error => $.ui.toast(`lint-test-gate: ${message(error)}`)
32}
33
34function message(error: unknown): string {
35 return error instanceof Error ? error.message : String(error)
36}
37
38/**
39 * How to start npm, by bare name as every program is started. On Windows npm
40 * is a .cmd shim, which a start without a shell cannot run, so npm's own CLI
41 * script runs under node instead, with no cmd.exe in the argument vector.
42 */
43async function npmArgv($: EngineInterface): Promise<{ argv: string[] } | { problem: string }> {
44 if ((await $.env.get('OS')) !== 'Windows_NT') return { argv: ['npm'] }
45 const node = await $.process.run(['node', '-p', 'process.execPath']).catch(() => undefined)
46 if (node === undefined || node.exitCode !== 0) return { problem: NEEDS_NODE }
47 const cli = npmCliBeside(node.stdout.trim())
48 if (!(await $.fs.exists(cli).catch(() => false))) {
49 return { problem: `lint-test-gate cannot find npm's own CLI script at ${cli}, beside node. List the checks in the setting instead.` }
50 }
51 return { argv: ['node', cli] }
52}
53
54/** The setting's checks, else the package.json scripts; or why there is nothing to run. */
55async function findChecks($: EngineInterface, config: Config, root: string): Promise<Check[] | string> {
56 if (config.problem !== undefined) return config.problem
57 if (config.argvs.length > 0) return config.argvs.map(argv => ({ name: argv.join(' '), argv }))
58 const packageJson = await $.fs.read(`${root}/package.json`).catch(() => '')
59 const scripts = scriptNames(packageJson)
60 if (scripts.length === 0) return NOTHING_TO_RUN
61 const npm = await npmArgv($)
62 return scripts.map(name => ('problem' in npm ? { name, problem: npm.problem } : { name, argv: [...npm.argv, 'run', name] }))
63}
64
65/** Runs one check in the project folder; undefined when it passed. */
66async function runCheck($: EngineInterface, check: Check, root: string, timeoutMs: number): Promise<Failure | undefined> {
67 if ('problem' in check) return { name: check.name, why: `could not start: ${check.problem}`, tail: '' }
68 const startedAt = await $.clock.now()
69 try {
70 const result = await $.process.run(check.argv, { cwd: root, timeoutMs })
71 if (result.exitCode === 0) return undefined
72 return { name: check.name, why: `exit ${result.exitCode}`, tail: tail([result.stdout, result.stderr].join('\n')) }
73 } catch (error) {
74 // A start that fails rejects at once; a run past its limit rejects at the limit, with what it wrote lost.
75 if ((await $.clock.now()) - startedAt >= timeoutMs) return { name: check.name, why: `timed out after ${duration(timeoutMs)}`, tail: '' }
76 return { name: check.name, why: `could not start: ${message(error)}`, tail: '' }
77 }
78}
79
80async function outcome($: EngineInterface, config: Config): Promise<GateState> {
81 const root = await $.session.root()
82 const checks = await findChecks($, config, root)
83 if (typeof checks === 'string') return { kind: 'empty', why: checks }
84 const failures: Failure[] = []
85 for (const check of checks) {
86 const failure = await runCheck($, check, root, config.timeoutMs)
87 if (failure !== undefined) failures.push(failure)
88 }
89 return failures.length === 0 ? { kind: 'passed' } : { kind: 'failed', failures }
90}
91
92// One run at a time: two runs of the same scripts in one folder would trip over each other.
93let queue: Promise<unknown> = Promise.resolve()
94
95/** Runs the checks after any run under way, showing the state on the band. */
96function runGate($: EngineInterface, config: Config): Promise<GateState> {
97 const run = queue.then(async () => {
98 await update($, gate, () => ({ kind: 'running' }))
99 const state = await outcome($, config).catch(async (error: unknown) => {
100 await update($, gate, () => ({ kind: 'idle' }))
101 throw error
102 })
103 await update($, gate, () => state)
104 return state
105 })
106 queue = run.catch(() => undefined)
107 return run
108}
109
110async function press($: EngineInterface, config: Config): Promise<void> {
111 if ((await read($, gate)).kind === 'running') return
112 const state = await runGate($, config)
113 if (state.kind === 'empty') $.ui.toast(state.why)
114}
115
116async function fill($: EngineInterface, failures: readonly Failure[]): Promise<void> {
117 // Nothing is sent: the failures join the draft, after what the person typed, and the person sends it.
118 const draft = (await $.prompt.read()).text
119 const text = draft === '' ? failureReport(failures) : `\n\n${failureReport(failures)}`
120 const filled = await $.prompt.fill({ text, mode: 'append' })
121 if (!filled.isFilled) $.ui.toast('lint-test-gate: the prompt box could not take the failures.')
122}
123
124export const register: Register = (on, options) => {
125 const config = parseConfig(options)
126
127 on('session.start', async ($, e, next) => {
128 const started = await next(e)
129 if (config.problem !== undefined && (await isShown($))) $.ui.toast(config.problem)
130 return started
131 })
132
133 // Matched by pattern: which shell tools a session has depends on the machine.
134 on('tool.call', { tool: /^(Bash|PowerShell)$/ }, async ($, e, next) => {
135 const command = 'command' in e && typeof e.command === 'string' ? e.command : ''
136 if (!isGitCommit(command) || !(await isShown($))) return next(e)
137 const state = await runGate($, config)
138 return state.kind === 'failed' ? { deny: refusal(state.failures) } : next(e)
139 })
140
141 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
142 // Whatever is beneath (another mod's band, the engine's own) keeps its row under the gate.
143 const beneath = await next(e)
144 if (e.props.hasSurvey || e.props.view.agentId !== undefined) return beneath
145 const state = await read($, gate)
146 const { Box, Button } = $.ui.resolve(e)
147
148 // The outer Box takes no width: the engine refuses its own band under a Box that sets one.
149 return (
150 <Box flexDirection="column">
151 <Box flexDirection="row" columnGap={1} width={e.props.bodyColumns}>
152 <Button
153 key="gate"
154 label={label(state)}
155 variant={state.kind === 'failed' ? 'primary' : 'secondary'}
156 onPress={() => void press($, config).catch(report($))}
157 />
158 {state.kind === 'failed' && (
159 <Button key="fill" label="fill failures" onPress={() => void fill($, state.failures).catch(report($))} />
160 )}
161 </Box>
162 {beneath}
163 </Box>
164 )
165 })
166}
167hooks/gate.ts 147 lines1import type { Failure, GateState } from '../types'
2
3/** The package.json scripts run when the setting lists no checks, in this order. */
4export const SCRIPT_NAMES = ['lint', 'typecheck', 'check', 'test'] as const
5
6/** `$.process.run`'s longest time limit, and the default. */
7const MAX_TIMEOUT_MINUTES = 10
8
9/** A failing check's output is cut to its last TAIL_LINES lines, and to at most TAIL_CHARS characters of them. */
10export const TAIL_LINES = 40
11export const TAIL_CHARS = 4000
12
13export type Config = {
14 /** The checks the setting lists, each an argument vector; empty runs the package.json scripts. */
15 argvs: string[][]
16 timeoutMs: number
17 /** Why the checks setting was refused; the gate then has nothing to run. */
18 problem: string | undefined
19}
20
21/** One check to run: its argument vector, or why it cannot start. */
22export type Check = { name: string; argv: string[] } | { name: string; problem: string }
23
24const EXAMPLE = '[["npx","eslint","."],["pytest","-q"]]'
25
26function isArgv(value: unknown): value is string[] {
27 return Array.isArray(value) && value.length > 0 && value.every(arg => typeof arg === 'string' && arg !== '' && !/\p{Cc}/u.test(arg))
28}
29
30/** Parses the checks setting: a JSON list of argument lists, never a shell string. */
31function parseChecks(setting: unknown): { argvs: string[][] } | { problem: string } {
32 if (typeof setting !== 'string' || setting.trim() === '') return { argvs: [] }
33 let parsed: unknown
34 try {
35 parsed = JSON.parse(setting)
36 } catch {
37 return { problem: `lint-test-gate: the checks setting is not JSON. Write a list of commands, each a list of its arguments, such as ${EXAMPLE}.` }
38 }
39 if (!Array.isArray(parsed)) {
40 return { problem: `lint-test-gate: the checks setting is not a list. Write a list of commands, each a list of its arguments, such as ${EXAMPLE}.` }
41 }
42 const bad = parsed.findIndex(argv => !isArgv(argv))
43 if (bad >= 0) {
44 return {
45 problem: `lint-test-gate: check ${bad + 1} of the checks setting is not a list of non-empty strings. Write each command as a list of its arguments, such as ${EXAMPLE}.`,
46 }
47 }
48 return { argvs: parsed as string[][] }
49}
50
51/** Parses the manifest's userConfig values; a time limit out of range falls back to ten minutes. */
52export function parseConfig(options: Readonly<Record<string, unknown>>): Config {
53 const minutes = options.timeoutMinutes
54 const timeoutMinutes =
55 typeof minutes === 'number' && Number.isInteger(minutes) && minutes >= 1 && minutes <= MAX_TIMEOUT_MINUTES ? minutes : MAX_TIMEOUT_MINUTES
56 const checks = parseChecks(options.checks)
57 return {
58 argvs: 'argvs' in checks ? checks.argvs : [],
59 timeoutMs: timeoutMinutes * 60_000,
60 problem: 'problem' in checks ? checks.problem : undefined,
61 }
62}
63
64/** The scripts of SCRIPT_NAMES that package.json defines, in that order; none for a file that is not JSON. */
65export function scriptNames(packageJson: string): string[] {
66 let parsed: unknown
67 try {
68 parsed = JSON.parse(packageJson)
69 } catch {
70 return []
71 }
72 const scripts = typeof parsed === 'object' && parsed !== null ? (parsed as { scripts?: unknown }).scripts : undefined
73 if (typeof scripts !== 'object' || scripts === null) return []
74 return SCRIPT_NAMES.filter(name => typeof (scripts as Record<string, unknown>)[name] === 'string')
75}
76
77/** npm's own CLI script in a Windows Node.js install: `node_modules\npm\bin\npm-cli.js` beside node.exe. */
78export function npmCliBeside(nodePath: string): string {
79 const sep = nodePath.includes('\\') ? '\\' : '/'
80 const folder = nodePath.replace(/[\\/][^\\/]*$/, '')
81 return [folder, 'node_modules', 'npm', 'bin', 'npm-cli.js'].join(sep)
82}
83
84/**
85 * Whether a shell command runs `git commit`: `git`, any global options
86 * (`-C <path>`, `-c <name>=<value>`, `--flag`), then `commit` as the
87 * subcommand. Found by pattern, so a `git commit` inside a quoted string counts too.
88 */
89export function isGitCommit(command: string): boolean {
90 return /(?<![\w./\\-])git(?:\.exe)?(?:\s+(?:-[Cc]\s+(?:"[^"]*"|'[^']*'|\S+)|--?[\w-]+(?:=\S+)?))*\s+commit(?![\w-])/.test(command)
91}
92
93/** Colour and cursor sequences a check may print; a prompt shows them as junk. */
94// eslint-disable-next-line no-control-regex -- the escape character is what the pattern matches
95const ANSI = /\u001b\[[0-9;?]*[A-Za-z]/g
96
97/** The end of a check's output: its last TAIL_LINES lines, then at most TAIL_CHARS characters, starting at a line. */
98export function tail(output: string): string {
99 const lines = output.replace(ANSI, '').replace(/\r\n?/g, '\n').trimEnd().split('\n')
100 const kept = lines.slice(-TAIL_LINES).join('\n').replace(/^\n+/, '')
101 if (kept.length <= TAIL_CHARS) return kept
102 const cut = kept.slice(-TAIL_CHARS)
103 const start = cut.indexOf('\n')
104 return start < 0 ? cut : cut.slice(start + 1)
105}
106
107/** A time limit as a person reads it. */
108export function duration(ms: number): string {
109 return `${ms / 60_000} min`
110}
111
112/** The failures, each by name and why, with the end of its output: what the fill button and a refused commit hand over. */
113export function failureReport(failures: readonly Failure[]): string {
114 const count = failures.length === 1 ? '1 check failed' : `${failures.length} checks failed`
115 const sections = failures.map(failure =>
116 failure.tail === '' ? `${failure.name} (${failure.why})` : `${failure.name} (${failure.why}):\n\`\`\`\n${failure.tail}\n\`\`\``,
117 )
118 return [`${count}:`, ...sections].join('\n\n')
119}
120
121/** Why a model's commit is refused. */
122export function refusal(failures: readonly Failure[]): string {
123 return `lint-test-gate refused the commit: ${failureReport(failures)}\n\nFix the failures, then commit again.`
124}
125
126/** The gate button's label. */
127export function label(state: GateState): string {
128 switch (state.kind) {
129 case 'idle':
130 return 'gate'
131 case 'running':
132 return 'gate: running'
133 case 'passed':
134 return 'gate: passed'
135 case 'failed':
136 return `gate: ${state.failures.length} failing`
137 case 'empty':
138 return 'gate: nothing to run'
139 }
140}
141
142/** What the person sees when nothing is set and package.json has none of SCRIPT_NAMES. */
143export const NOTHING_TO_RUN = `lint-test-gate: nothing to run. The checks setting is empty, and package.json has no ${SCRIPT_NAMES.join(', ')} script.`
144
145/** What a script check says when node cannot start, on Windows, where npm runs through it. */
146export const NEEDS_NODE = 'lint-test-gate runs npm scripts on Windows through node, which did not start. Put node on the PATH, or list the checks in the setting.'
147types/index.d.ts 18 lines1/** One check that did not pass: its name, why (an exit code, a timeout, a start that failed) and the end of its output. */
2export type Failure = { name: string; why: string; tail: string }
3
4/** Where the gate stands: what its band button shows. */
5export type GateState =
6 | { kind: 'idle' }
7 | { kind: 'running' }
8 | { kind: 'passed' }
9 | { kind: 'failed'; failures: Failure[] }
10 /** There was nothing to run; `why` says what the mod looked for, or why the setting was refused. */
11 | { kind: 'empty'; why: string }
12
13declare module 'claude-code' {
14 interface PluginState {
15 'lint-test-gate': { gate: GateState }
16 }
17}
18