stopbar 1.2.0 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +88 -0
- package/README.md +112 -114
- package/SECURITY.md +106 -68
- package/bin/stopbar.mjs +0 -0
- package/dist/adapters/antigravity.js +6 -6
- package/dist/adapters/claude.js +1 -1
- package/dist/adapters/codex.js +7 -7
- package/dist/adapters/cursor.js +6 -6
- package/dist/adapters/gemini.js +7 -7
- package/dist/adapters/index.js +4 -3
- package/dist/adapters/types.js +7 -4
- package/dist/build-info.json +1 -1
- package/dist/classify.js +293 -11
- package/dist/cli.js +12 -4
- package/dist/commands.js +37 -9
- package/dist/config.js +8 -6
- package/dist/doctor.js +109 -33
- package/dist/hook.js +10 -5
- package/dist/integrations.js +94 -22
- package/dist/probe/index.js +39 -16
- package/dist/probe/init.js +1 -1
- package/dist/probe/sdk.js +1 -1
- package/dist/probe/stdio.js +25 -13
- package/dist/probe/wrapper.js +1 -1
- package/dist/repo.js +62 -0
- package/dist/run.js +12 -1
- package/dist/store.js +5 -3
- package/dist/verify.js +34 -26
- package/docs/probe.md +94 -0
- package/package.json +3 -2
- package/skills/stopbar/SKILL.md +2 -1
- package/src/probe/sdk.ts +2 -2
package/dist/doctor.js
CHANGED
|
@@ -3,22 +3,27 @@
|
|
|
3
3
|
import {execFileSync} from 'node:child_process'
|
|
4
4
|
import {createHash} from 'node:crypto'
|
|
5
5
|
import {existsSync, mkdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs'
|
|
6
|
-
import {isAbsolute, join} from 'node:path'
|
|
6
|
+
import {isAbsolute, join, relative} from 'node:path'
|
|
7
7
|
import {hasChain} from './classify.js'
|
|
8
8
|
import {fresh, HOOK_MATCHERS} from './commands.js'
|
|
9
9
|
import {cliOf, DEFAULT_SAFE_TOOLS, makeConfig} from './config.js'
|
|
10
10
|
import {decode, MACHINE} from './engine.js'
|
|
11
11
|
import {runHook} from './hook.js'
|
|
12
|
+
import {gitHooksDir, portableHookHint} from './integrations.js'
|
|
12
13
|
import {PKG_ROOT} from './pkg.js'
|
|
13
|
-
import {FailClosed, findRepo, hasRefTree, } from './repo.js'
|
|
14
|
-
import {paths, readConfig, readEvents, readState, VERSION, writeConfig, writeState} from './store.js'
|
|
14
|
+
import {FailClosed, findRepo, git, hasRefTree, } from './repo.js'
|
|
15
|
+
import { paths, readConfig, readEvents, readState, VERSION, writeConfig, writeState} from './store.js'
|
|
15
16
|
|
|
16
17
|
|
|
18
|
+
|
|
17
19
|
const sha = (f ) => createHash('sha256').update(readFileSync(f)).digest('hex')
|
|
18
20
|
|
|
19
|
-
|
|
21
|
+
|
|
22
|
+
const isObj = (x ) => !!x && typeof x === 'object' && !Array.isArray(x)
|
|
23
|
+
|
|
24
|
+
function hooksIn(file ) {
|
|
20
25
|
if (!existsSync(file)) return null
|
|
21
|
-
try {
|
|
26
|
+
try { const j = JSON.parse(readFileSync(file, 'utf8')); return isObj(j) && isObj(j.hooks) ? j.hooks : {} } catch { return {__invalid: []} }
|
|
22
27
|
}
|
|
23
28
|
|
|
24
29
|
function checkHooks(root , add ) {
|
|
@@ -30,8 +35,11 @@ function checkHooks(root , add
|
|
|
30
35
|
if ('__invalid' in h) { add('FAIL', 'hooks', `${f} is not valid JSON: Claude Code will not load the hooks`); continue }
|
|
31
36
|
for (const [ev, entries] of Object.entries(h)) {
|
|
32
37
|
for (const e of Array.isArray(entries) ? entries : []) {
|
|
33
|
-
|
|
34
|
-
|
|
38
|
+
if (!isObj(e)) continue
|
|
39
|
+
for (const x of Array.isArray(e.hooks) ? e.hooks : []) {
|
|
40
|
+
if (isObj(x) && typeof x.command === 'string' && /stopbar(\.mjs)?"?\s+hook\b/.test(x.command)) {
|
|
41
|
+
(merged[ev] ??= []).push({matcher: typeof e.matcher === 'string' ? e.matcher : undefined, command: x.command, file: f})
|
|
42
|
+
}
|
|
35
43
|
}
|
|
36
44
|
}
|
|
37
45
|
}
|
|
@@ -51,10 +59,13 @@ function checkHooks(root , add
|
|
|
51
59
|
|
|
52
60
|
const STOPBAR = /stopbar(\.mjs)?"?\s+(hook|git-hook)\b/
|
|
53
61
|
const scriptOf = (cmd ) => /node\s+"?([^"]+?stopbar\.mjs)"?\s+(?:git-)?hook/.exec(cmd)?.[1]
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
62
|
+
const INVALID = Symbol('invalid JSON')
|
|
63
|
+
/** undefined: no file; INVALID: not JSON; else the parsed value. */
|
|
64
|
+
function readJsonOrInvalid(f ) {
|
|
65
|
+
if (!existsSync(f)) return undefined
|
|
66
|
+
try { return JSON.parse(readFileSync(f, 'utf8')) } catch { return INVALID }
|
|
57
67
|
}
|
|
68
|
+
const hooksOf = (j ) => (isObj(j) && isObj(j.hooks) ? j.hooks : undefined)
|
|
58
69
|
/** Commands of Stopbar hooks per event, from any nesting of {command} objects under each event. */
|
|
59
70
|
function stopbarCommands(events ) {
|
|
60
71
|
const out = {}
|
|
@@ -70,18 +81,18 @@ function stopbarCommands(events )
|
|
|
70
81
|
}
|
|
71
82
|
|
|
72
83
|
/** Other clients and the git fallback. Returns how many clients have Stopbar hooks, and how many Stopbar git hooks exist. */
|
|
73
|
-
function checkOtherClients(repo , add ) {
|
|
84
|
+
function checkOtherClients(repo , ev , add ) {
|
|
74
85
|
let found = 0
|
|
75
|
-
const clients
|
|
76
|
-
['cursor', join(repo.root, '.cursor', 'hooks.json'),
|
|
77
|
-
['codex', join(repo.root, '.codex', 'hooks.json'),
|
|
78
|
-
['gemini', join(repo.root, '.gemini', 'settings.json'),
|
|
79
|
-
['antigravity', join(repo.root, '.agents', 'hooks.json'), (j) => Object.assign({}, ...Object.values(j).filter((v) => v &&
|
|
86
|
+
const clients = [
|
|
87
|
+
['cursor', join(repo.root, '.cursor', 'hooks.json'), hooksOf, ['preToolUse', 'postToolUse', 'postToolUseFailure', 'stop']],
|
|
88
|
+
['codex', join(repo.root, '.codex', 'hooks.json'), hooksOf, ['PreToolUse', 'PostToolUse', 'Stop']],
|
|
89
|
+
['gemini', join(repo.root, '.gemini', 'settings.json'), hooksOf, ['BeforeTool', 'AfterTool', 'AfterAgent']],
|
|
90
|
+
['antigravity', join(repo.root, '.agents', 'hooks.json'), (j) => (isObj(j) ? Object.assign({}, ...Object.values(j).filter((v) => isObj(v) && v.enabled !== false)) : undefined), ['PreToolUse', 'PostToolUse', 'Stop']],
|
|
80
91
|
]
|
|
81
92
|
for (const [name, f, events, need] of clients) {
|
|
82
93
|
const j = readJsonOrInvalid(f)
|
|
83
|
-
if (j ===
|
|
84
|
-
if (j ===
|
|
94
|
+
if (j === undefined) continue
|
|
95
|
+
if (j === INVALID) { add('FAIL', `hooks ${name}`, `${f} is not valid JSON`); found++; continue }
|
|
85
96
|
const cmds = stopbarCommands(events(j))
|
|
86
97
|
if (!Object.keys(cmds).length) continue
|
|
87
98
|
found++
|
|
@@ -89,19 +100,79 @@ function checkOtherClients(repo , add
|
|
|
89
100
|
const script = scriptOf(Object.values(cmds)[0][0])
|
|
90
101
|
if (missing.length) add('FAIL', `hooks ${name}`, `${f}: no Stopbar hook for ${missing.join(', ')}`)
|
|
91
102
|
else if (script && !existsSync(script)) add('FAIL', `hooks ${name}`, `script not found: ${script}`)
|
|
92
|
-
else if (name === 'cursor' && JSON.stringify(j
|
|
103
|
+
else if (name === 'cursor' && JSON.stringify(hooksOf(j) ?? {}).includes('"failClosed":false')) add('WARN', `hooks ${name}`, `${f}: failClosed is false, so a crash of the hook lets the action run`)
|
|
93
104
|
else add('OK', `hooks ${name}`, `${need.join(', ')} (${f.replace(/\\/g, '/').split('/').slice(-2).join('/')})`)
|
|
94
105
|
}
|
|
95
|
-
let dir
|
|
96
|
-
try {
|
|
97
|
-
const
|
|
98
|
-
|
|
106
|
+
let hd = {dir: join(repo.gitDir, 'hooks'), customHooksPath: null}
|
|
107
|
+
try { hd = gitHooksDir(repo) } catch { /* default */ }
|
|
108
|
+
const {dir} = hd
|
|
109
|
+
// a Stopbar line that is not a comment: the hook init writes, or `stopbar git-hook <name>` chained by hand (Husky, Lefthook)
|
|
110
|
+
const calls = (n ) => new RegExp(`^[^#\\n]*stopbar(\\.mjs)?"?\\s+git-hook\\s+${n}\\b`, 'm')
|
|
111
|
+
const NAMES = ['pre-commit', 'pre-push']
|
|
112
|
+
const gh = NAMES.filter((n) => existsSync(join(dir, n)) && calls(n).test(readFileSync(join(dir, n), 'utf8')))
|
|
113
|
+
const lacking = NAMES.filter((n) => !gh.includes(n))
|
|
114
|
+
const verb = (ns ) => `git ${ns.map((n) => (n === 'pre-commit' ? 'commit' : 'push')).join(' and git ')} ${ns.length > 1 ? 'are' : 'is'}`
|
|
99
115
|
// the git hooks close what an agent hook cannot see: git aliases, and on pre-push merge, cherry-pick, am and commit-tree
|
|
100
|
-
if (!lacking.length) add('OK', 'hooks git', `pre-commit, pre-push in ${dir}`)
|
|
101
|
-
|
|
116
|
+
if (!lacking.length) { add('OK', 'hooks git', `pre-commit, pre-push in ${dir}`); return {clients: found, git: gh.length} }
|
|
117
|
+
let cli = cliOf({})
|
|
118
|
+
try { cli = cliOf(readConfig(repo)) } catch { /* reported by the config.json check */ }
|
|
119
|
+
const pinned = existsSync(join(repo.stateDir, 'runtime', 'bin', 'stopbar.mjs'))
|
|
120
|
+
const hint = portableHookHint(dir, repo.root, cli, pinned, lacking)
|
|
121
|
+
// a git hook that was there and is gone is a FAIL (an agent or a tool removed the gate); never configured is a WARN
|
|
122
|
+
const gone = lacking.map((n) => ({n, why: hookWasThere(repo, dir, n, ev, calls(n), gh.length === 1)})).filter((x) => x.why)
|
|
123
|
+
if (gone.length) {
|
|
124
|
+
add('FAIL', 'hooks git', `the Stopbar ${gone.map((g) => g.n).join(' and ')} hook ${gone.length > 1 ? 'were' : 'was'} configured and ${gone.length > 1 ? 'are' : 'is'} gone from ${dir} ` +
|
|
125
|
+
`(${gone.map((g) => `${g.n}: ${g.why}`).join('; ')}): ${verb(gone.map((g) => g.n))} NOT gated by Stopbar. A human restores ${hd.customHooksPath !== null ? `the line: ${hint}` : 'it: `stopbar upgrade --hooks git`'}`)
|
|
126
|
+
} else if (hd.customHooksPath !== null) {
|
|
127
|
+
add('WARN', 'hooks git', `no Stopbar ${lacking.join(' and ')} hook in the custom core.hooksPath (${dir}): ${verb(lacking)} NOT gated by Stopbar in this repository. ` +
|
|
128
|
+
`Stopbar does not write shared or tracked hooks; a human chains them in the existing hook manager: ${hint}; ` +
|
|
129
|
+
'or runs `stopbar upgrade --hooks git --force-hooks` to write them there, keeping a .stopbar-backup')
|
|
130
|
+
} else add('WARN', 'hooks git', `no Stopbar ${lacking.join(' and ')} hook in ${dir}: the git hooks close git aliases, and on pre-push merge, cherry-pick, am and commit-tree, which an agent hook does not see; a human runs \`stopbar upgrade --hooks git\``)
|
|
102
131
|
return {clients: found, git: gh.length}
|
|
103
132
|
}
|
|
104
133
|
|
|
134
|
+
/** Why the git hook `n` counts as configured before (so its absence is a FAIL), or null:
|
|
135
|
+
* - the last `human:init`, or an upgrade after it, wrote it (event field gitHooksWritten, since 1.2.2);
|
|
136
|
+
* - a `git-hook` run of it is logged since the last init or reset;
|
|
137
|
+
* - a tracked hook file (custom core.hooksPath inside the tree) calls it in HEAD;
|
|
138
|
+
* - the other hook is in place and the log does not say that Stopbar left this one out (`partial`).
|
|
139
|
+
* Reads only: the event log is never written here. */
|
|
140
|
+
function hookWasThere(repo , dir , n , ev , call , partial ) {
|
|
141
|
+
let lastInit = -1, lastStart = -1
|
|
142
|
+
ev.forEach((e, i) => { if (e.source === 'human:init') lastInit = i; if (e.source === 'human:init' || e.source === 'human:reset') lastStart = i })
|
|
143
|
+
let wroteBy = null, skipped = false
|
|
144
|
+
for (const e of ev.slice(Math.max(lastInit, 0))) {
|
|
145
|
+
if ((e.source !== 'human:init' && e.source !== 'human:upgrade') || !Array.isArray(e.gitHooksWritten)) continue
|
|
146
|
+
if ((e.gitHooksWritten ).includes(n)) wroteBy = e.source === 'human:upgrade' ? 'upgrade' : 'init'
|
|
147
|
+
else if (e.source === 'human:init') skipped = true
|
|
148
|
+
}
|
|
149
|
+
if (wroteBy) return `written by stopbar ${wroteBy}`
|
|
150
|
+
if (ev.slice(lastStart + 1).some((e) => e.source === 'hook-timing' && e.adapter === 'git' && e.gitHook === n)) return 'it ran since the last init or reset'
|
|
151
|
+
const rel = relative(repo.root, join(dir, n))
|
|
152
|
+
if (rel && !rel.startsWith('..') && !isAbsolute(rel)) {
|
|
153
|
+
try { if (call.test(git(repo.root, ['show', `HEAD:${rel.replace(/\\/g, '/')}`]))) return `HEAD:${rel.replace(/\\/g, '/')} calls it` } catch { /* not tracked */ }
|
|
154
|
+
}
|
|
155
|
+
if (partial && !skipped) return 'only the other hook is in place'
|
|
156
|
+
return null
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** On Windows, a gate command `bash ...` with a bare `bash` may start WSL's bash (System32 or WindowsApps) instead of Git
|
|
160
|
+
* Bash: another file system and PATH, so the gate fails or tests something else. */
|
|
161
|
+
export function wslBashWarning(cmds , whereBash , platform = process.platform) {
|
|
162
|
+
if (platform !== 'win32' || !cmds.some((c) => /^bash(?:\.exe)?\s/i.test(c.trim()))) return null
|
|
163
|
+
const first = whereBash()
|
|
164
|
+
if (!first || !/\\(?:WindowsApps|System32)\\bash\.exe$/i.test(first)) return null
|
|
165
|
+
return `buildCmd or fullTestCmd starts with a bare \`bash\`, and the first bash on PATH is WSL (${first}): the gate runs in WSL, not in Git Bash. ` +
|
|
166
|
+
'A human runs `stopbar init --force` with the full path to Git Bash in --build / --test (e.g. "C:/Program Files/Git/bin/bash.exe" ...)'
|
|
167
|
+
}
|
|
168
|
+
function checkWslBash(cmds , add ) {
|
|
169
|
+
const where = () => {
|
|
170
|
+
try { return execFileSync('where', ['bash'], {encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true}).split(/\r?\n/)[0].trim() || null } catch { return null }
|
|
171
|
+
}
|
|
172
|
+
const w = wslBashWarning(cmds, where)
|
|
173
|
+
if (w) add('WARN', 'gate shell', w)
|
|
174
|
+
}
|
|
175
|
+
|
|
105
176
|
/** The real hook pipeline (in process) on a scratch repository inside <git-dir>/stopbar/doctor-run. */
|
|
106
177
|
function dryRun(base , add ) {
|
|
107
178
|
const dir = join(base, 'doctor-run')
|
|
@@ -138,7 +209,8 @@ function dryRun(base , add
|
|
|
138
209
|
}
|
|
139
210
|
}
|
|
140
211
|
|
|
141
|
-
|
|
212
|
+
/** `strict`: a [WARN] fails too (exit 1), for CI. The repository's event log is only read (attest hashes it). */
|
|
213
|
+
export async function doctor(o ) {
|
|
142
214
|
const checks = []
|
|
143
215
|
const add = (status , name , detail ) => { checks.push({status, name, detail}) }
|
|
144
216
|
const [maj, min] = process.versions.node.split('.').map(Number)
|
|
@@ -152,7 +224,7 @@ export async function doctor(o )
|
|
|
152
224
|
try {
|
|
153
225
|
const {checkGenerated} = await import('./verify.js')
|
|
154
226
|
const g = await checkGenerated(500)
|
|
155
|
-
add(g.ok ? 'OK' : 'FAIL', 'kernel link', `compileJs(kernel.ts) == dist/kernel.gen.js: ${g.sameMachine}; kernel.ts hash: ${g.sameSource}; ${
|
|
227
|
+
add(g.ok ? 'OK' : 'FAIL', 'kernel link', `compileJs(kernel.ts) == dist/kernel.gen.js: ${g.sameMachine}; kernel.ts hash: ${g.sameSource}; ${g.differential.steps} steps vs interpreter, ${g.differential.mismatches} mismatches`)
|
|
156
228
|
} catch (e) { add('WARN', 'kernel link', `not checked: ${(e ).message}`) }
|
|
157
229
|
} else add('WARN', 'kernel link', 'gdp-wired cannot be resolved from this copy (a pinned runtime has no node_modules): run `stopbar prove` in the package')
|
|
158
230
|
|
|
@@ -164,13 +236,15 @@ export async function doctor(o )
|
|
|
164
236
|
const cfg = readConfig(repo); cfgOk = true
|
|
165
237
|
add('OK', 'config.json', `profile ${cfg.profile}; build \`${cfg.buildCmd}\`; full tests \`${cfg.fullTestCmd}\`; maxRetries ${cfg.maxRetries}; cap ${cfg.cap}; ` +
|
|
166
238
|
`${cfg.paths.tests.length}/${cfg.paths.testConfig.length}/${cfg.paths.secrets.length} test/config/secret patterns; safeTools ${JSON.stringify(cfg.safeTools ?? DEFAULT_SAFE_TOOLS)}${cfg.baseRef ? `; baseRef ${cfg.baseRef}` : ''}; ` +
|
|
167
|
-
`stopGate ${cfg.stopGate ?? 'block'}; cli ${cliOf(cfg)}${cfg.requireRun ? '; requireRun: true' : ''}`
|
|
239
|
+
`stopGate ${cfg.stopGate ?? 'block'}; cli ${cliOf(cfg)}${cfg.requireRun ? '; requireRun: true' : ''}; ` +
|
|
240
|
+
(cfg.requireRun ? 'gates: stopbar run only (--require-run)' : 'gates: hook command text (use --require-run for exit-code-only gates)'))
|
|
168
241
|
if (cfg.stopGate === 'warn') add('WARN', 'stopGate', 'warn: Stop does not block a turn with unverified changes (logged as stop:warn); git commit and git push stay blocked until the gates pass')
|
|
169
242
|
const safe = cfg.safeTools ?? DEFAULT_SAFE_TOOLS
|
|
170
243
|
const missing = DEFAULT_SAFE_TOOLS.filter((t) => !safe.includes(t))
|
|
171
244
|
if (missing.length) add('WARN', 'safeTools', `missing default ${missing.join(', ')}: these local tools count as outbound after a secret read; add them to config.safeTools or run \`stopbar init --force ...\``)
|
|
172
245
|
if (cfg.baseRef) add(hasRefTree(repo.root, cfg.baseRef) ? 'OK' : 'FAIL', 'baseRef', hasRefTree(repo.root, cfg.baseRef) ? `${cfg.baseRef} resolves to a tree` : `${cfg.baseRef} does not resolve in git (existing-test checks will fail closed)`)
|
|
173
246
|
for (const [k, v] of [['buildCmd', cfg.buildCmd], ['fullTestCmd', cfg.fullTestCmd]]) if (hasChain(v)) add('FAIL', 'config.json', `${k} has shell operators: it can never pass as a gate`)
|
|
247
|
+
checkWslBash([cfg.buildCmd, cfg.fullTestCmd], add)
|
|
174
248
|
try {
|
|
175
249
|
const s = readState(repo), v = decode(s.kernel)
|
|
176
250
|
add(v.halted ? 'WARN' : 'OK', 'state.json', `revision ${v.treeRev}; ${v.halted ? 'HALTED' : 'running'}; spent ${v.spent}/${v.capNow}; tainted ${v.testsTainted}`)
|
|
@@ -184,7 +258,7 @@ export async function doctor(o )
|
|
|
184
258
|
const same = existsSync(join(PKG_ROOT, 'dist', 'kernel.gen.js')) && sha(rt) === sha(join(PKG_ROOT, 'dist', 'kernel.gen.js'))
|
|
185
259
|
add(same ? 'OK' : 'WARN', 'pinned runtime', `${join(repo.stateDir, 'runtime')}${same ? ' (same kernel as this package)' : ' differs from this package: a human runs `stopbar upgrade` to re-pin (state and gates are kept)'}`)
|
|
186
260
|
} else if (cfgOk) add('WARN', 'pinned runtime', 'none: hooks run an unpinned copy (init --no-pin)')
|
|
187
|
-
const others = checkOtherClients(repo, add)
|
|
261
|
+
const others = checkOtherClients(repo, ev.events, add)
|
|
188
262
|
const claudeHas = ['settings.json', 'settings.local.json'].some((n) => { const h = hooksIn(join(repo .root, '.claude', n)); return h !== null && Object.keys(stopbarCommands(h)).length > 0 })
|
|
189
263
|
// Claude Code hooks named at the last init or upgrade must be there, also when other hooks (now the git hooks by
|
|
190
264
|
// default) exist; without any client hooks, the Claude Code ones are reported as missing (v1.0 output)
|
|
@@ -194,8 +268,10 @@ export async function doctor(o )
|
|
|
194
268
|
try { dryRun(repo.stateDir, add) } catch (e) { add('FAIL', 'dry run', String(e)) }
|
|
195
269
|
}
|
|
196
270
|
const fails = checks.filter((c) => c.status === 'FAIL').length, warns = checks.filter((c) => c.status === 'WARN').length
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
271
|
+
const strictFail = o.strict === true && warns > 0
|
|
272
|
+
const ok = fails === 0 && !strictFail
|
|
273
|
+
const msg = o.json ? JSON.stringify({version: VERSION, ok, fails, warns, ...(o.strict ? {strict: true} : {}), checks}, null, 1)
|
|
274
|
+
: [`stopbar doctor (Stopbar ${VERSION})${o.strict ? ' --strict' : ''}`, ...checks.map((c) => `[${c.status.padEnd(4)}] ${c.name.padEnd(18)} ${c.detail}`),
|
|
275
|
+
`RESULT: ${fails ? `FAIL (${fails} problem(s), ${warns} warning(s))` : strictFail ? `FAIL (strict: ${warns} warning(s))` : `OK (${warns} warning(s))`}`].join('\n')
|
|
276
|
+
return {code: ok ? 0 : 1, msg}
|
|
201
277
|
}
|
package/dist/hook.js
CHANGED
|
@@ -7,7 +7,7 @@ import * as K from './classify.js'
|
|
|
7
7
|
import {cliOf, DEFAULT_SAFE_TOOLS} from './config.js'
|
|
8
8
|
import {matchAny} from './glob.js'
|
|
9
9
|
import {decode, kstep, } from './engine.js'
|
|
10
|
-
import {changesSinceHead, countedEntries, diffEntries, differsFromHead, FailClosed, findRepo, gitCalls, markCounted, oidOf, refEntries, snapshot} from './repo.js'
|
|
10
|
+
import {changesSinceHead, countedEntries, diffEntries, differsFromHead, FailClosed, findRepo, gitCalls, markCounted, oidOf, readHooksPath, refEntries, snapshot} from './repo.js'
|
|
11
11
|
import {appendEvent, readConfig, readState, withLock, writeState} from './store.js'
|
|
12
12
|
import {codeDirs} from './pkg.js'
|
|
13
13
|
|
|
@@ -16,7 +16,7 @@ import {codeDirs} from './pkg.js'
|
|
|
16
16
|
/** A hook event: Claude Code's JSON object (adapters translate other clients into it). Fields are read with guards. */
|
|
17
17
|
|
|
18
18
|
/** Stopbar's own fields on an event: set by the adapters and by `stopbar run`, never by the agent's client. */
|
|
19
|
-
|
|
19
|
+
|
|
20
20
|
|
|
21
21
|
const obj = (x ) => (x && typeof x === 'object' && !Array.isArray(x) ? x : {})
|
|
22
22
|
const strings = (...xs ) => xs.flatMap((x) => (Array.isArray(x) ? x : [x])).filter((x) => typeof x === 'string' && x.length > 0)
|
|
@@ -28,6 +28,7 @@ function metaOf(x ) {
|
|
|
28
28
|
...(typeof m.expectedSnapshot === 'string' ? {expectedSnapshot: m.expectedSnapshot} : {}),
|
|
29
29
|
...(typeof m.expectedRev === 'number' ? {expectedRev: m.expectedRev} : {}),
|
|
30
30
|
...(m.requireExitCode === true ? {requireExitCode: true} : {}),
|
|
31
|
+
...(typeof m.event === 'string' ? {event: m.event} : {}),
|
|
31
32
|
}
|
|
32
33
|
}
|
|
33
34
|
|
|
@@ -296,6 +297,10 @@ export function runHook(raw , t0 = performance.now()) {
|
|
|
296
297
|
return runEvent(input , t0)
|
|
297
298
|
}
|
|
298
299
|
|
|
300
|
+
/** Self-protection of this repository: .git, the Stopbar state and code, and a custom core.hooksPath read from the git
|
|
301
|
+
* config files (no git process). */
|
|
302
|
+
export const protectOf = (repo ) => ({gitDir: repo.gitDir, stateDir: repo.stateDir, codeDirs: codeDirs(), ...K.hooksProtect(repo.root, readHooksPath(repo))})
|
|
303
|
+
|
|
299
304
|
/** One normalised hook event (Claude Code's shape; adapters translate other clients into it). Never throws. */
|
|
300
305
|
export function runEvent(input , t0 = performance.now()) {
|
|
301
306
|
try {
|
|
@@ -303,14 +308,14 @@ export function runEvent(input , t0 = performance.now()) {
|
|
|
303
308
|
const g0 = gitCalls
|
|
304
309
|
return withLock(repo, () => {
|
|
305
310
|
const cfg = readConfig(repo)
|
|
306
|
-
const ctx = {repo, cfg, s: readState(repo), protect:
|
|
307
|
-
const ev = input.hook_event_name
|
|
311
|
+
const ctx = {repo, cfg, s: readState(repo), protect: protectOf(repo), dirty: false}
|
|
312
|
+
const ev = input.hook_event_name, meta = metaOf(input.stopbar)
|
|
308
313
|
const res = ev === 'PreToolUse' ? pre(ctx, input)
|
|
309
314
|
: ev === 'PostToolUse' ? post(ctx, input, false)
|
|
310
315
|
: ev === 'PostToolUseFailure' ? post(ctx, input, true)
|
|
311
316
|
: ev === 'Stop' ? stop(ctx, input) : {code: 0}
|
|
312
317
|
if (ctx.dirty) writeState(repo, ctx.s)
|
|
313
|
-
appendEvent(repo, {source: 'hook-timing', event: ev, tool: input.tool_name, ...(
|
|
318
|
+
appendEvent(repo, {source: 'hook-timing', event: ev, tool: input.tool_name, ...(meta.adapter ? {adapter: meta.adapter} : {}), ...(meta.adapter === 'git' && meta.event ? {gitHook: meta.event} : {}), exit: res.code, gitCalls: gitCalls - g0,
|
|
314
319
|
handlerMs: Math.round(performance.now() - t0), processMs: Math.round(process.uptime() * 1000)})
|
|
315
320
|
return res
|
|
316
321
|
})
|
package/dist/integrations.js
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
// and other hooks stay; earlier Stopbar entries are replaced). Targets: claude (alias local), claude-project (alias
|
|
4
4
|
// project), cursor, codex, gemini, antigravity (alias agy), git; several at once, comma separated.
|
|
5
5
|
import {chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync} from 'node:fs'
|
|
6
|
-
import {dirname, isAbsolute, join, resolve} from 'node:path'
|
|
6
|
+
import {dirname, isAbsolute, join, relative, resolve} from 'node:path'
|
|
7
|
+
import {DEFAULT_CLI} from './config.js'
|
|
7
8
|
import {FailClosed, git, } from './repo.js'
|
|
8
9
|
|
|
9
10
|
export const TARGETS = ['claude', 'claude-project', 'cursor', 'codex', 'gemini', 'antigravity', 'git']
|
|
@@ -36,19 +37,33 @@ export function claudeHooks(command ) {
|
|
|
36
37
|
}
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
|
|
40
|
+
|
|
41
|
+
const isJson = (x ) => !!x && typeof x === 'object' && !Array.isArray(x)
|
|
42
|
+
/** A JSON file as an object ({} when missing or empty). Not JSON: fails closed and the file is not overwritten. */
|
|
43
|
+
function readJson(f ) {
|
|
40
44
|
if (!existsSync(f)) return {}
|
|
41
45
|
const raw = readFileSync(f, 'utf8')
|
|
42
|
-
|
|
46
|
+
let v
|
|
47
|
+
try { v = raw.trim() ? JSON.parse(raw) : {} } catch (e) {
|
|
43
48
|
throw new FailClosed(`${f} is not valid JSON (${(e ).message}); not overwriting it`, 'fix the file by hand, then run init again')
|
|
44
49
|
}
|
|
50
|
+
return isJson(v) ? v : {}
|
|
51
|
+
}
|
|
52
|
+
/** The object under `key` of `o`; a missing value or one that is not an object is replaced by {}. */
|
|
53
|
+
function objAt(o , key ) {
|
|
54
|
+
const v = o[key]
|
|
55
|
+
if (isJson(v)) return v
|
|
56
|
+
const fresh = {}
|
|
57
|
+
o[key] = fresh
|
|
58
|
+
return fresh
|
|
45
59
|
}
|
|
46
60
|
function writeJson(f , o ) { mkdirSync(dirname(f), {recursive: true}); writeFileSync(f, JSON.stringify(o, null, 2) + '\n') }
|
|
47
61
|
const mentions = (x ) => STOPBAR_HOOK.test(JSON.stringify(x ?? ''))
|
|
48
62
|
/** Event arrays: drop earlier Stopbar entries, append ours. */
|
|
49
|
-
function mergeEvents(hooks
|
|
63
|
+
function mergeEvents(hooks , want ) {
|
|
50
64
|
for (const [ev, entries] of Object.entries(want)) {
|
|
51
|
-
const
|
|
65
|
+
const cur = hooks[ev]
|
|
66
|
+
const kept = Array.isArray(cur) ? (cur ).filter((x) => !mentions(x)) : []
|
|
52
67
|
hooks[ev] = [...kept, ...entries]
|
|
53
68
|
}
|
|
54
69
|
}
|
|
@@ -56,8 +71,7 @@ function mergeEvents(hooks , want ) {
|
|
|
56
71
|
function claudeFile(root , file , command ) {
|
|
57
72
|
const f = join(root, '.claude', file)
|
|
58
73
|
const cur = readJson(f)
|
|
59
|
-
cur
|
|
60
|
-
mergeEvents(cur.hooks, claudeHooks(command))
|
|
74
|
+
mergeEvents(objAt(cur, 'hooks'), claudeHooks(command))
|
|
61
75
|
writeJson(f, cur)
|
|
62
76
|
return f
|
|
63
77
|
}
|
|
@@ -66,9 +80,8 @@ function cursorFile(root , command ) {
|
|
|
66
80
|
const f = join(root, '.cursor', 'hooks.json')
|
|
67
81
|
const cur = readJson(f)
|
|
68
82
|
cur.version = cur.version ?? 1
|
|
69
|
-
cur.hooks = cur.hooks && typeof cur.hooks === 'object' ? cur.hooks : {}
|
|
70
83
|
const e = (timeout ) => [{command, timeout, failClosed: true}]
|
|
71
|
-
mergeEvents(cur
|
|
84
|
+
mergeEvents(objAt(cur, 'hooks'), {preToolUse: e(30), postToolUse: e(60), postToolUseFailure: e(60), stop: e(30)})
|
|
72
85
|
writeJson(f, cur)
|
|
73
86
|
return f
|
|
74
87
|
}
|
|
@@ -76,9 +89,8 @@ function cursorFile(root , command ) {
|
|
|
76
89
|
function codexFile(root , command ) {
|
|
77
90
|
const f = join(root, '.codex', 'hooks.json')
|
|
78
91
|
const cur = readJson(f)
|
|
79
|
-
cur.hooks = cur.hooks && typeof cur.hooks === 'object' ? cur.hooks : {}
|
|
80
92
|
const h = (timeout ) => [{hooks: [{type: 'command', command, timeout}]}]
|
|
81
|
-
mergeEvents(cur
|
|
93
|
+
mergeEvents(objAt(cur, 'hooks'), {PreToolUse: h(30), PostToolUse: h(60), Stop: h(30)})
|
|
82
94
|
writeJson(f, cur)
|
|
83
95
|
return f
|
|
84
96
|
}
|
|
@@ -86,9 +98,8 @@ function codexFile(root , command ) {
|
|
|
86
98
|
function geminiFile(root , command ) {
|
|
87
99
|
const f = join(root, '.gemini', 'settings.json')
|
|
88
100
|
const cur = readJson(f)
|
|
89
|
-
cur.hooks = cur.hooks && typeof cur.hooks === 'object' ? cur.hooks : {}
|
|
90
101
|
const h = (timeout ) => [{matcher: '*', hooks: [{name: 'stopbar', type: 'command', command, timeout}]}]
|
|
91
|
-
mergeEvents(cur
|
|
102
|
+
mergeEvents(objAt(cur, 'hooks'), {BeforeTool: h(30000), AfterTool: h(60000), AfterAgent: h(30000)})
|
|
92
103
|
writeJson(f, cur)
|
|
93
104
|
return f
|
|
94
105
|
}
|
|
@@ -105,16 +116,67 @@ function antigravityFile(root , command ) {
|
|
|
105
116
|
return f
|
|
106
117
|
}
|
|
107
118
|
|
|
108
|
-
/**
|
|
109
|
-
*
|
|
110
|
-
|
|
111
|
-
function
|
|
119
|
+
/** Where git runs the hooks of this repository (`git rev-parse --git-path hooks`). `customHooksPath`: the
|
|
120
|
+
* `core.hooksPath` value when it points outside the default <git-common-dir>/hooks (Husky, Lefthook, a shared or tracked
|
|
121
|
+
* hooks directory), else null. No core.hooksPath entry is no error; any other git config error fails closed. */
|
|
122
|
+
export function gitHooksDir(repo ) {
|
|
123
|
+
let configured = null
|
|
124
|
+
try { configured = git(repo.root, ['config', '--get', 'core.hooksPath']) || null } catch (e) {
|
|
125
|
+
if ((e ).status !== 1) throw new FailClosed(`git config --get core.hooksPath failed in ${repo.root}: ${(e ).message.split('\n')[0]}`)
|
|
126
|
+
}
|
|
112
127
|
const rel = git(repo.root, ['rev-parse', '--git-path', 'hooks'])
|
|
113
128
|
const dir = isAbsolute(rel) ? rel : resolve(repo.root, rel)
|
|
129
|
+
if (configured === null) return {dir, customHooksPath: null}
|
|
130
|
+
const common = git(repo.root, ['rev-parse', '--git-common-dir'])
|
|
131
|
+
const def = resolve(isAbsolute(common) ? common : resolve(repo.root, common), 'hooks')
|
|
132
|
+
const same = process.platform === 'win32' ? resolve(dir).toLowerCase() === def.toLowerCase() : resolve(dir) === def
|
|
133
|
+
return {dir, customHooksPath: same ? null : configured}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
const hookBin = (runtimeRoot ) => join(runtimeRoot, 'bin', 'stopbar.mjs').replace(/\\/g, '/')
|
|
138
|
+
const GIT_HOOK_NAMES = ['pre-commit', 'pre-push']
|
|
139
|
+
|
|
140
|
+
/** The lines a human adds to a shared or tracked hook (Husky, Lefthook, a custom core.hooksPath): first `<cli> git-hook
|
|
141
|
+
* <name>` (works on every machine with Stopbar in node_modules), then, without a local node_modules, the pinned runtime
|
|
142
|
+
* named relative to the repository's git dir (the state dir is <git-dir>/stopbar, also in a linked worktree), never an
|
|
143
|
+
* absolute path into .git. `pinned`: the hooks run the pinned runtime (init without --no-pin). */
|
|
144
|
+
export function portableHookLines(cli , pinned ) {
|
|
145
|
+
return {
|
|
146
|
+
primary: (n) => `${cli} git-hook ${n}`,
|
|
147
|
+
alt: pinned ? (n) => `node "$(git rev-parse --git-dir)/stopbar/runtime/bin/stopbar.mjs" git-hook ${n}` : null,
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** One sentence: which line goes into which hook file. `names`: the hooks that lack it. */
|
|
151
|
+
export function portableHookHint(dir , root , cli , pinned , names = GIT_HOOK_NAMES) {
|
|
152
|
+
const l = portableHookLines(cli, pinned)
|
|
153
|
+
const rel = (n ) => { const p = relative(root, join(dir, n)); return (p && !p.startsWith('..') && !isAbsolute(p) ? p : join(dir, n)).replace(/\\/g, '/') }
|
|
154
|
+
return `add the line \`${l.primary(names[0])}\` to ${rel(names[0])}` + names.slice(1).map((n) => ` and \`${l.primary(n)}\` to ${rel(n)}`).join('') +
|
|
155
|
+
(l.alt ? `; without Stopbar in the local node_modules use \`${l.alt(names[0])}\`${names.length > 1 ? ` (and ${names.slice(1).join(', ')})` : ''} instead` : '')
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const manualHooks = (hd , o ) => portableHookHint(hd.dir, o.root, o.cli, o.pinned)
|
|
159
|
+
function customHooksRefusal(hd , o ) {
|
|
160
|
+
return new FailClosed(`core.hooksPath (${hd.customHooksPath}) points git hooks outside .git/hooks, to ${hd.dir}; not writing shared or tracked hooks there`,
|
|
161
|
+
`chain them by hand: ${manualHooks(hd, o)}; or run again with --force-hooks to write them there (a foreign hook is kept as <name>.stopbar-backup)`)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** A foreign pre-commit or pre-push hook: 'fail' (git named in --hooks), 'backup' (--force-hooks: kept as
|
|
165
|
+
* <name>.stopbar-backup, then replaced) or 'keep' (git added by default: the foreign hook stays, with a warning).
|
|
166
|
+
* A custom core.hooksPath (shared or tracked hooks) is written only with 'backup'; 'keep' writes nothing there and
|
|
167
|
+
* warns, 'fail' refuses. */
|
|
168
|
+
|
|
169
|
+
function gitHooks(repo , runtimeRoot , foreign , warn , hd , ho , written ) {
|
|
170
|
+
const {dir} = hd
|
|
171
|
+
const bin = hookBin(runtimeRoot)
|
|
172
|
+
if (hd.customHooksPath !== null && foreign !== 'backup') {
|
|
173
|
+
if (foreign === 'fail') throw customHooksRefusal(hd, ho)
|
|
174
|
+
warn(`WARN: this repository uses a custom core.hooksPath (${hd.customHooksPath} -> ${dir}); Stopbar did not touch those shared or tracked hooks, so git commit and git push are not gated by Stopbar here. To chain them by hand, ${manualHooks(hd, ho)}; to write them there directly (a foreign hook is kept as <name>.stopbar-backup): stopbar upgrade --hooks git --force-hooks`)
|
|
175
|
+
return []
|
|
176
|
+
}
|
|
114
177
|
mkdirSync(dir, {recursive: true})
|
|
115
|
-
const bin = join(runtimeRoot, 'bin', 'stopbar.mjs').replace(/\\/g, '/')
|
|
116
178
|
const out = []
|
|
117
|
-
for (const name of
|
|
179
|
+
for (const name of GIT_HOOK_NAMES) {
|
|
118
180
|
const f = join(dir, name)
|
|
119
181
|
const body = `#!/bin/sh\n# Stopbar fallback gate, written by \`stopbar init --hooks git\`.\nexec node "${bin}" git-hook ${name}\n`
|
|
120
182
|
if (existsSync(f) && !readFileSync(f, 'utf8').includes('stopbar.mjs" git-hook')) {
|
|
@@ -128,15 +190,25 @@ function gitHooks(repo , runtimeRoot , foreign , warn
|
|
|
128
190
|
writeFileSync(f, body)
|
|
129
191
|
chmodSync(f, 0o755)
|
|
130
192
|
out.push(f)
|
|
193
|
+
written.push(name)
|
|
131
194
|
}
|
|
132
195
|
return out
|
|
133
196
|
}
|
|
134
197
|
|
|
135
198
|
/** Installs every target; returns one line per written file. `gitByDefault`: git was not named in --hooks but added by
|
|
136
|
-
* init, so a foreign git hook is kept with a warning (`warn`) instead of failing; --force-hooks still replaces it.
|
|
137
|
-
|
|
199
|
+
* init, so a foreign git hook is kept with a warning (`warn`) instead of failing; --force-hooks still replaces it.
|
|
200
|
+
* `cli`: the command in the hint for shared or tracked hooks (config.cliCmd). `gitHooksWritten` receives the name of
|
|
201
|
+
* each git hook as it is written, also when a later target fails (the event log of init and upgrade keeps it, so
|
|
202
|
+
* `stopbar doctor` knows which git hooks Stopbar wrote). */
|
|
203
|
+
export function installHooks(repo , targets , runtimeRoot , force ,
|
|
204
|
+
o = {}) {
|
|
138
205
|
const lines = []
|
|
139
206
|
const foreign = force ? 'backup' : o.gitByDefault ? 'keep' : 'fail'
|
|
207
|
+
const hd = targets.includes('git') ? gitHooksDir(repo) : null
|
|
208
|
+
const ho = {cli: o.cli ?? DEFAULT_CLI, root: repo.root, pinned: resolve(runtimeRoot) === resolve(repo.stateDir, 'runtime')}
|
|
209
|
+
const written = o.gitHooksWritten ?? []
|
|
210
|
+
// a refusal (explicit --hooks git into a custom core.hooksPath) comes before any client file is written
|
|
211
|
+
if (hd && foreign === 'fail' && hd.customHooksPath !== null) throw customHooksRefusal(hd, ho)
|
|
140
212
|
for (const t of targets) {
|
|
141
213
|
if (t === 'claude') lines.push(`claude: ${claudeFile(repo.root, 'settings.local.json', hookCommand(runtimeRoot))}`)
|
|
142
214
|
else if (t === 'claude-project') lines.push(`claude: ${claudeFile(repo.root, 'settings.json', hookCommand(runtimeRoot))}`)
|
|
@@ -144,7 +216,7 @@ export function installHooks(repo , targets , runtimeRoot ,
|
|
|
144
216
|
else if (t === 'codex') lines.push(`codex: ${codexFile(repo.root, hookCommand(runtimeRoot, 'codex'))}`)
|
|
145
217
|
else if (t === 'gemini') lines.push(`gemini: ${geminiFile(repo.root, hookCommand(runtimeRoot, 'gemini'))}`)
|
|
146
218
|
else if (t === 'antigravity') lines.push(`antigravity: ${antigravityFile(repo.root, hookCommand(runtimeRoot, 'antigravity'))}`)
|
|
147
|
-
else if (t === 'git') for (const f of gitHooks(repo, runtimeRoot, foreign, o.warn ?? (() => {}))) lines.push(`git: ${f}`)
|
|
219
|
+
else if (t === 'git' && hd) for (const f of gitHooks(repo, runtimeRoot, foreign, o.warn ?? (() => {}), hd, ho, written)) lines.push(`git: ${f}`)
|
|
148
220
|
}
|
|
149
221
|
return lines
|
|
150
222
|
}
|