stopbar 1.2.0 → 1.2.1

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.
@@ -31,9 +31,10 @@ const failClosed = (why ) => ({code: 2, msg: `STOPBAR FAIL-CLOSED: $
31
31
  export function handle(raw , which = 'auto', t0 = performance.now()) {
32
32
  const explicit = which === 'auto' ? null : adapterByName(which)
33
33
  if (which !== 'auto' && !explicit) return claude.render('pre-tool', failClosed(`unknown adapter ${JSON.stringify(which)}; known: auto, ${ADAPTERS.join(', ')}`), null)
34
- let input
35
- try { input = JSON.parse(raw) } catch (e) { return (explicit ?? claude).render('pre-tool', failClosed(`hook input is not JSON (${(e ).message})`), null) }
36
- if (!input || typeof input !== 'object' || Array.isArray(input)) return (explicit ?? claude).render('pre-tool', failClosed('hook input must be a JSON object'), null)
34
+ let parsed
35
+ try { parsed = JSON.parse(raw) } catch (e) { return (explicit ?? claude).render('pre-tool', failClosed(`hook input is not JSON (${(e ).message})`), null) }
36
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return (explicit ?? claude).render('pre-tool', failClosed('hook input must be a JSON object'), null)
37
+ const input = parsed
37
38
  const a = explicit ?? detect(input)
38
39
  if (!a) return claude.render('pre-tool', failClosed('unknown hook payload: no adapter recognises it (use --adapter)'), null)
39
40
  let n
@@ -27,9 +27,9 @@ export const ADAPTERS = ['claude', 'codex', 'cursor', 'gemini', '
27
27
 
28
28
 
29
29
 
30
-
30
+
31
31
 
32
-
32
+
33
33
 
34
34
 
35
35
  // ---------------------------------------------------------------- shared tool mapping
@@ -73,14 +73,14 @@ export function pathsOf(args ) {
73
73
  /** Fallback by name for tools a client adds later: shell, edit, read or outbound by keyword, else other. */
74
74
  export function byName(name , args , command ) {
75
75
  const n = name.toLowerCase()
76
- if (/shell|terminal|command|exec|bash|run_/.test(n)) return shell(commandText(command ?? (args )?.command ?? (args )?.CommandLine ?? ''))
76
+ if (/shell|terminal|command|exec|bash|run_/.test(n)) return shell(commandText(command ?? args?.command ?? args?.CommandLine ?? ''))
77
77
  if (/write|edit|delete|replace|patch|create|move|rename|remove|change|propose|blob/.test(n)) return edit(pathsOf(args))
78
78
  if (/read|view|open_file|cat|grep|search_file|find|glob|list/.test(n)) return read(pathsOf(args))
79
79
  if (/fetch|web|browser|http|url|mcp/.test(n)) return outbound(n.startsWith('mcp') ? `mcp__${name}` : name)
80
80
  return other(name)
81
81
  }
82
82
 
83
- export function make(adapter , raw , event , base , extra = {}) {
83
+ export function make(adapter , raw , event , base , extra = {}) {
84
84
  return {...base, stopbar: {adapter, rawKeys: Object.keys(raw), event, ...extra}}
85
85
  }
86
86
 
@@ -101,3 +101,6 @@ export function exitCodeIn(r , depth = 0) {
101
101
  }
102
102
 
103
103
  export const json = (o ) => JSON.stringify(o)
104
+
105
+ /** A payload field that must be a string; anything else counts as absent. */
106
+ export const str = (x ) => (typeof x === 'string' ? x : undefined)
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.2.0",
2
+ "version": "1.2.1",
3
3
  "kernelSourceSha256": "c602fc4bcf8ffb2e312bf838986e6d4b006af6d0e6c7447c8c61d5888adc5ef8",
4
4
  "machineSha256": "b397085e0cb13e2e50aa655c54de0744d08f2ebf500bf32af8ff3e8a11ba7321",
5
5
  "files": 29
package/dist/classify.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // Deterministic classification rules of the wrapper: file paths and the text of a shell command. No AST.
3
3
  // Everything here is enforced by the wrapper, not by the proof (see SECURITY.md).
4
4
 
5
+ import {posix} from 'node:path'
5
6
  import {matchAny, matchAnySuffix} from './glob.js'
6
7
 
7
8
  const norm = (p ) => p.replace(/\\/g, '/')
@@ -236,19 +237,113 @@ export const looksLikeTests = (cmd ) => TEST_RUNNER.test(cmd)
236
237
  const EXT_ONLY = /^\*\.[^/*?{}\[\]]+$/
237
238
 
238
239
 
239
- /** The first secret path named in a command (e.g. `cat .env`, `type secrets\\db.txt`), with the pattern it matched. */
240
- export function secretInCommand(cmd , paths , exists = () => true) {
240
+ // Commands that print the whole environment (tokens, keys) count as a secret read, as a file would. `env VAR=1 cmd` and a
241
+ // bare `set` do not count: the first runs a command, the second is too common in scripts (a known limit, SECURITY.md).
242
+ const ENV_DUMP = [
243
+ [/(?:^|[\s;&|(`])printenv(?![\w.\-])/i, 'env:printenv'],
244
+ [/(?:^|[\s;&|(`])(?:Get-ChildItem|gci|dir|ls|Get-Item|gi|Get-Content|gc|cat|type)\s+(?:-(?:Path|LiteralPath)\s+)?Env:/i, 'env:Get-ChildItem Env:'],
245
+ [/(?:^|[;&|(`\n])\s*env\s*(?:-0\s*)?(?=$|[;&|>)\n])/i, 'env:env'],
246
+ [/\/proc\/(?:self|\d+|\$\$)\/environ\b/i, 'env:/proc/environ'],
247
+ ]
248
+ const HAS_GLOB = /[*?[{]/
249
+
250
+ /** One path segment of a shell glob (`*`, `?`, `[...]`, `{a,b}`) as a RegExp (case-insensitive: Windows, and wider is
251
+ * safer here), or null when it cannot be read. */
252
+ export function globSegment(seg ) {
253
+ let re = '', depth = 0
254
+ for (let i = 0; i < seg.length; i++) {
255
+ const c = seg[i]
256
+ if (c === '*') re += '.*'
257
+ else if (c === '?') re += '.'
258
+ else if (c === '[') {
259
+ const j = seg.indexOf(']', i + 2)
260
+ if (j < 0) { re += '\\['; continue }
261
+ const body = seg.slice(i + 1, j).replace(/\\/g, '\\\\')
262
+ re += `[${body[0] === '!' ? '^' + body.slice(1) : body}]`
263
+ i = j
264
+ } else if (c === '{') { re += '(?:'; depth++ }
265
+ else if (c === ',' && depth) re += '|'
266
+ else if (c === '}' && depth) { re += ')'; depth-- }
267
+ else re += c.replace(/[.+^$()|\\/\]]/g, '\\$&')
268
+ }
269
+ if (depth) return null
270
+ try { return new RegExp(`^${re}$`, 'i') } catch { return null }
271
+ }
272
+
273
+ /** Names a wildcard may reach: the literal secret patterns and the `<prefix>*` ones (`.env*` gives .env and .env.local). */
274
+ function secretSamples(paths ) {
275
+ const out = []
276
+ for (const g of paths.secrets) {
277
+ const last = g.split('/').pop() ?? ''
278
+ if (!/^[^*?[{]+\*?$/.test(last)) continue
279
+ const base = last.replace(/\*$/, '')
280
+ out.push(base, ...(last.endsWith('*') ? [`${base}.local`] : []))
281
+ }
282
+ return out
283
+ }
284
+
285
+ /** The first secret path named in a command (e.g. `cat .env`, `type secrets\\db.txt`), with the pattern it matched.
286
+ * Also: a command that prints the environment (printenv, Get-ChildItem Env:), `..` segments (`src/../.env`), and a
287
+ * wildcard that reaches a secret name (`.en*`, `.en?`, `src/../.e*`). */
288
+ export function secretInCommand(cmd , paths , exists = () => true, shell = 'bash') {
241
289
  const words = (s ) => s.split(/[\s'"=(),;|&<>@:]+/).filter(Boolean)
242
- // the words as written, then as bash joins them (`.e""nv` is `.env`)
243
- for (const tok of new Set([...words(cmd), ...words(unsplice(cmd)), ...words(unquoteShellWords(cmd))])) {
244
- const hits = paths.secrets.filter((g) => matchesSecretGlob(tok, g))
245
- if (!hits.length) continue
246
- const strong = hits.find((g) => !EXT_ONLY.test(g))
247
- if (strong) return {token: tok, pattern: strong}
248
- if (/[\\/]/.test(tok) || exists(tok)) return {token: tok, pattern: hits[0]}
290
+ const texts = [cmd, unsplice(cmd), unquoteShellWords(cmd)]
291
+ if (paths.secrets.length) {
292
+ for (const t of texts) for (const [re, pattern] of ENV_DUMP) {
293
+ const m = re.exec(t)
294
+ if (m) return {token: m[0].replace(/^[\s;&|(`]+/, '').trim(), pattern}
295
+ }
296
+ }
297
+ // the words as written, then as bash joins them (`.e""nv` is `.env`); each also with its `..` segments resolved
298
+ for (const tok of new Set(texts.flatMap(words))) {
299
+ const n = posix.normalize(norm(tok))
300
+ for (const cand of n === tok ? [tok] : [tok, n]) {
301
+ const hits = paths.secrets.filter((g) => matchesSecretGlob(cand, g))
302
+ if (!hits.length) continue
303
+ const strong = hits.find((g) => !EXT_ONLY.test(g))
304
+ if (strong) return {token: tok, pattern: strong}
305
+ if (/[\\/]/.test(cand) || exists(cand)) return {token: tok, pattern: hits[0]}
306
+ }
307
+ }
308
+ // wildcards that expand: bash expands none inside quotes or after a backslash; PowerShell -Path expands them quoted too
309
+ const samples = secretSamples(paths)
310
+ for (const tok of new Set(words(shell === 'bash' ? globView(cmd) : unquoteShellWords(cmd)))) {
311
+ // the last segment: dot-leading (bash matches dotfiles only so), or after a literal prefix of 2+ chars
312
+ const last = posix.normalize(norm(tok)).split('/').pop() ?? ''
313
+ const at = last.search(HAS_GLOB)
314
+ if (at < 0 || !(last.startsWith('.') || at >= 2)) continue
315
+ const re = globSegment(last)
316
+ if (!re) continue
317
+ for (const s of samples) {
318
+ const pattern = re.test(s) ? secretPattern(s, paths) : null
319
+ if (pattern) return {token: tok, pattern}
320
+ }
249
321
  }
250
322
  return null
251
323
  }
324
+
325
+ /** The command as bash joins its words, with the glob characters that do not expand (inside quotes, after a backslash)
326
+ * replaced by \x01, so only live wildcards are left. */
327
+ function globView(cmd ) {
328
+ let out = ''
329
+ const mask = (s ) => s.replace(/[*?[\]{}]/g, '\x01')
330
+ for (let i = 0; i < cmd.length; i++) {
331
+ const c = cmd[i]
332
+ if (c === "'") {
333
+ const j = cmd.indexOf("'", i + 1)
334
+ out += mask(j < 0 ? cmd.slice(i + 1) : cmd.slice(i + 1, j))
335
+ i = j < 0 ? cmd.length : j
336
+ } else if (c === '"') {
337
+ let j = i + 1
338
+ for (; j < cmd.length && cmd[j] !== '"'; j++) {
339
+ if (cmd[j] === '\\' && j + 1 < cmd.length && '"\\$`'.includes(cmd[j + 1])) j++
340
+ out += mask(cmd[j])
341
+ }
342
+ i = j
343
+ } else if (c === '\\' && i + 1 < cmd.length) { out += mask(cmd[i + 1]); i++ } else out += c
344
+ }
345
+ return out
346
+ }
252
347
  export const mentionsSecret = (cmd , paths , exists ) => secretInCommand(cmd, paths, exists) !== null
253
348
 
254
349
 
@@ -272,7 +367,7 @@ export function classifyBash(cmd , cfg
272
367
  if (c === cfg.buildCmd.trim()) return {kind: 'build'}
273
368
  if (c === cfg.fullTestCmd.trim()) return {kind: 'fulltest'}
274
369
  }
275
- return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: secretInCommand(c, cfg.paths, exists)}
370
+ return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: secretInCommand(c, cfg.paths, exists, shell)}
276
371
  }
277
372
 
278
373
  /** Kind of a tree change from a list of (status, path) and a test for "the path exists in the reference tree"
@@ -412,6 +507,71 @@ export function withoutStdinHeredoc(cmd ) {
412
507
  return [cmd.slice(0, nl), ...lines.slice(end)].join('\n')
413
508
  }
414
509
 
510
+ // A wildcard that reaches .git or an agent settings directory (`rm -rf .g*`, `mv .cl* x`, `Remove-Item .g*`): blocked
511
+ // for the commands that delete or move, and for any command when the wildcard is followed by a path inside such a
512
+ // directory (`cp x .g*/hooks/pre-commit`). Other wildcards (`rm *.log`, a `.*` in a grep pattern) stay allowed.
513
+ const GUARDED = ['.git', '.claude', '.cursor', '.codex', '.gemini', '.agents']
514
+ const DESTRUCTIVE = /^(?:rm|rmdir|unlink|shred|mv|del|erase|rd|move|remove-item|ri|move-item|mi)$/i
515
+ const INSIDE = /^(?:hooks|config|stopbar|info|refs|head|index|objects|settings[\w.-]*\.json|hooks\.json)$/i
516
+ const globDir = (seg ) => (HAS_GLOB.test(seg) && /^[.?[]/.test(seg) ? GUARDED.find((d) => globSegment(seg)?.test(d)) ?? null : null)
517
+ /** `t`: the command with only live wildcards left (globView for bash). */
518
+ function wildcardGuardedDir(t ) {
519
+ for (const part of norm(t).split(/[;&|\n()`]+/)) {
520
+ const ws = part.split(/[\s<>='"]+/).filter(Boolean)
521
+ let k = 0
522
+ while (k < ws.length && (/^\w+=/.test(ws[k]) || /^(?:sudo|command|exec|nice|time)$/i.test(ws[k]))) k++
523
+ const destructive = DESTRUCTIVE.test((ws[k] ?? '').split('/').pop() .replace(/\.exe$/i, ''))
524
+ for (const w of ws.slice(k + 1)) {
525
+ const segs = w.split('/')
526
+ for (let i = 0; i < segs.length; i++) {
527
+ const d = globDir(segs[i])
528
+ if (d && (destructive || (i + 1 < segs.length && INSIDE.test(segs[i + 1])))) return d
529
+ }
530
+ }
531
+ }
532
+ return null
533
+ }
534
+
535
+ /** Shell words with their quotes kept; the operators ; & | ( ) and newline are words of their own. */
536
+ function shellWords(cmd ) {
537
+ const out = []
538
+ let w = ''
539
+ const flush = () => { if (w) out.push(w); w = '' }
540
+ for (let i = 0; i < cmd.length; i++) {
541
+ const c = cmd[i]
542
+ if (c === ' ' || c === '\t' || c === '\r') { flush(); continue }
543
+ if (';&|()\n'.includes(c)) { flush(); out.push(c); continue }
544
+ if (c === "'" || c === '"' || c === '`') {
545
+ let j = i + 1
546
+ for (; j < cmd.length && cmd[j] !== c; j++) if (c !== "'" && cmd[j] === '\\') j++
547
+ w += cmd.slice(i, j + 1); i = j; continue
548
+ }
549
+ if (c === '$' && cmd[i + 1] === '(') {
550
+ let j = i + 2, depth = 1
551
+ for (; j < cmd.length && depth; j++) depth += cmd[j] === '(' ? 1 : cmd[j] === ')' ? -1 : 0
552
+ w += cmd.slice(i, j); i = j - 1; continue
553
+ }
554
+ if (c === '\\' && i + 1 < cmd.length) { w += cmd.slice(i, i + 2); i++; continue }
555
+ w += c
556
+ }
557
+ flush()
558
+ return out
559
+ }
560
+ // `git $f -m x`, `p=push; git $p`, `git "${cmd}"`, git `echo push`: the subcommand comes from an expansion, so the commit
561
+ // and push gates cannot see it. A `git` inside a quoted string is one word with its quotes, so it is no command here.
562
+ const GIT_OPT_ARG = /^(?:-[cC]|--(?:git-dir|work-tree|namespace|exec-path|config-env|attr-source|super-prefix))$/
563
+ export function dynamicGitSubcommand(cmd ) {
564
+ const ws = shellWords(cmd)
565
+ for (let i = 0; i < ws.length; i++) {
566
+ if (!/^git(?:\.exe)?$/i.test(unquoteShellWords(ws[i]).replace(/\\/g, '/').split('/').pop() )) continue
567
+ let j = i + 1
568
+ while (j < ws.length && ws[j].length > 1 && ws[j].startsWith('-')) j += GIT_OPT_ARG.test(ws[j]) ? 2 : 1
569
+ const sub = ws[j]
570
+ if (sub && /^(?:"?\$|"?`)/.test(sub)) return sub
571
+ }
572
+ return null
573
+ }
574
+
415
575
  /** Shell command text. Returns the reason for a block, or null. Text matching only: see SECURITY.md.
416
576
  * Every check runs on the text as written and as bash joins quoted parts of a word (`.g""it`, `'.cl'"aude"`, `gi"t"`:
417
577
  * unsplice and unquoteShellWords). For bash, the body of
@@ -424,6 +584,10 @@ export function protectedCommand(cmd , pr , shell
424
584
  if (DOT_GIT.test(c)) return 'the command names a .git directory (Stopbar state, git hooks, git config live there)'
425
585
  for (const [re, d] of AGENT_DIRS) if (re.test(c)) return `the command names a ${d} directory (agent settings there hold the Stopbar hooks)`
426
586
  }
587
+ const g = wildcardGuardedDir(shell === 'bash' ? globView(cmd) : unquoteShellWords(cmd))
588
+ if (g) return `the command has a wildcard that reaches the ${g} directory (${g === '.git' ? 'Stopbar state, git hooks, git config live there' : 'agent settings there hold the Stopbar hooks'})`
589
+ const dyn = dynamicGitSubcommand(cmd)
590
+ if (dyn) return `the git subcommand comes from an expansion (${dyn}), which hides it from the commit and push gates; write the subcommand out`
427
591
  for (const t of texts) {
428
592
  const c = norm(t).toLowerCase()
429
593
  if (isGitConfigWrite(t)) return '`git config` writes .git/config; only reads (--get, --list) are allowed'
package/dist/commands.js CHANGED
@@ -169,7 +169,7 @@ export function secretReason(repo )
169
169
 
170
170
  /** `now`: the working tree as it is now. A change no hook has counted yet (now.id !== s.snapshot) keeps a commit blocked
171
171
  * at the next hook (pre:commit-sync), so status never says `allowed` then. */
172
- function statusText(repo , cfg , s , now ) {
172
+ function statusText(repo , cfg , s , now , differs ) {
173
173
  const v = decode(s.kernel)
174
174
  const yn = (b ) => (b ? 'yes' : 'no')
175
175
  const ok = (rev ) => (rev === v.treeRev ? `ok at revision ${rev}` : 'not at the current revision')
@@ -185,6 +185,7 @@ function statusText(repo , cfg , s , now ) {
185
185
  `build ${ok(v.buildOkRev)} (${cfg.buildCmd})`,
186
186
  `full tests ${ok(v.testsOkRev)} (${cfg.fullTestCmd})`,
187
187
  `tainted ${yn(v.testsTainted)} secret read ${v.secretTainted ? `yes (${secretReason(repo)?.text ?? 'reason not in the event log'})` : 'no'} shell approval held ${yn(v.shellToken)}`,
188
+ ...(differs === false ? [`note: no existing test or test-config file currently differs from ${cfg.baseRef}; if ${cfg.baseRef} advanced after the previous task, a human can run \`stopbar reset\` (or \`stopbar approve-tests\`)`] : []),
188
189
  `session ${v.halted ? 'HALTED' : 'running'} spent ${v.spent}/${v.capNow} test failures ${v.testFails}/${s.params.maxRetries} build failures ${v.buildFails}/${s.params.maxRetries}`,
189
190
  `commit ${commit}`,
190
191
  `stop gate ${cfg.stopGate ?? 'block'}${cfg.stopGate === 'warn' ? ' (Stop only warns; git commit and git push stay blocked until the gates pass)' : ''}`,
@@ -209,8 +210,12 @@ export function human(cmd , o ) {
209
210
  if (cmd === 'status') {
210
211
  // the working tree now (read-only for state.json, as in attest: only the private snapshot index is refreshed)
211
212
  const now = snapshot(repo)
213
+ // testsTainted with a baseRef: does the tree still change an existing test or test config against it? A hint for
214
+ // the human only (e.g. baseRef absorbed the change); the taint itself stays until reset or approve-tests (L2.2).
215
+ // Read-only; a baseRef that no longer resolves fails closed, as in the hooks.
216
+ const differs = decode(s.kernel).testsTainted && cfg.baseRef && cfg.baseRef !== 'HEAD' ? dirtyTests(repo, cfg, now).suspicious : null
212
217
  return {code: 0, msg: o.has('json') ? JSON.stringify({version: VERSION, repo: repo.root, stateDir: repo.stateDir, config: cfg, stopGate: cfg.stopGate ?? 'block', ...(cfg.requireRun ? {requireRun: true} : {}), snapshot: s.snapshot, params: s.params, kernel: decode(s.kernel),
213
- secretRead: decode(s.kernel).secretTainted ? secretReason(repo) : null, workingTreeSnapshot: now.id, workingTreeCounted: now.id === s.snapshot}, null, 1) : statusText(repo, cfg, s, now)}
218
+ secretRead: decode(s.kernel).secretTainted ? secretReason(repo) : null, workingTreeSnapshot: now.id, workingTreeCounted: now.id === s.snapshot, taintedDiffersFromBaseRef: differs}, null, 1) : statusText(repo, cfg, s, now, differs)}
214
219
  }
215
220
  let res
216
221
  if (cmd === 'approve-tests') {
package/dist/doctor.js CHANGED
@@ -3,12 +3,13 @@
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 {join} 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} from './integrations.js'
12
13
  import {PKG_ROOT} from './pkg.js'
13
14
  import {FailClosed, findRepo, hasRefTree, } from './repo.js'
14
15
  import {paths, readConfig, readEvents, readState, VERSION, writeConfig, writeState} from './store.js'
@@ -16,9 +17,12 @@ import {paths, readConfig, readEvents, readState, VERSION, writeConfig, writeSta
16
17
 
17
18
  const sha = (f ) => createHash('sha256').update(readFileSync(f)).digest('hex')
18
19
 
19
- function hooksIn(file ) {
20
+
21
+ const isObj = (x ) => !!x && typeof x === 'object' && !Array.isArray(x)
22
+
23
+ function hooksIn(file ) {
20
24
  if (!existsSync(file)) return null
21
- try { return JSON.parse(readFileSync(file, 'utf8')).hooks ?? {} } catch { return {__invalid: []} }
25
+ try { const j = JSON.parse(readFileSync(file, 'utf8')); return isObj(j) && isObj(j.hooks) ? j.hooks : {} } catch { return {__invalid: []} }
22
26
  }
23
27
 
24
28
  function checkHooks(root , add ) {
@@ -30,8 +34,11 @@ function checkHooks(root , add
30
34
  if ('__invalid' in h) { add('FAIL', 'hooks', `${f} is not valid JSON: Claude Code will not load the hooks`); continue }
31
35
  for (const [ev, entries] of Object.entries(h)) {
32
36
  for (const e of Array.isArray(entries) ? entries : []) {
33
- for (const x of Array.isArray(e?.hooks) ? e.hooks : []) {
34
- if (typeof x?.command === 'string' && /stopbar(\.mjs)?"?\s+hook\b/.test(x.command)) (merged[ev] ??= []).push({matcher: e.matcher, command: x.command, file: f})
37
+ if (!isObj(e)) continue
38
+ for (const x of Array.isArray(e.hooks) ? e.hooks : []) {
39
+ if (isObj(x) && typeof x.command === 'string' && /stopbar(\.mjs)?"?\s+hook\b/.test(x.command)) {
40
+ (merged[ev] ??= []).push({matcher: typeof e.matcher === 'string' ? e.matcher : undefined, command: x.command, file: f})
41
+ }
35
42
  }
36
43
  }
37
44
  }
@@ -51,10 +58,13 @@ function checkHooks(root , add
51
58
 
52
59
  const STOPBAR = /stopbar(\.mjs)?"?\s+(hook|git-hook)\b/
53
60
  const scriptOf = (cmd ) => /node\s+"?([^"]+?stopbar\.mjs)"?\s+(?:git-)?hook/.exec(cmd)?.[1]
54
- function readJsonOrInvalid(f ) {
55
- if (!existsSync(f)) return null
56
- try { return JSON.parse(readFileSync(f, 'utf8')) } catch { return 'invalid' }
61
+ const INVALID = Symbol('invalid JSON')
62
+ /** undefined: no file; INVALID: not JSON; else the parsed value. */
63
+ function readJsonOrInvalid(f ) {
64
+ if (!existsSync(f)) return undefined
65
+ try { return JSON.parse(readFileSync(f, 'utf8')) } catch { return INVALID }
57
66
  }
67
+ const hooksOf = (j ) => (isObj(j) && isObj(j.hooks) ? j.hooks : undefined)
58
68
  /** Commands of Stopbar hooks per event, from any nesting of {command} objects under each event. */
59
69
  function stopbarCommands(events ) {
60
70
  const out = {}
@@ -72,16 +82,16 @@ function stopbarCommands(events )
72
82
  /** Other clients and the git fallback. Returns how many clients have Stopbar hooks, and how many Stopbar git hooks exist. */
73
83
  function checkOtherClients(repo , add ) {
74
84
  let found = 0
75
- const clients = [
76
- ['cursor', join(repo.root, '.cursor', 'hooks.json'), (j) => j.hooks, ['preToolUse', 'postToolUse', 'postToolUseFailure', 'stop']],
77
- ['codex', join(repo.root, '.codex', 'hooks.json'), (j) => j.hooks, ['PreToolUse', 'PostToolUse', 'Stop']],
78
- ['gemini', join(repo.root, '.gemini', 'settings.json'), (j) => j.hooks, ['BeforeTool', 'AfterTool', 'AfterAgent']],
79
- ['antigravity', join(repo.root, '.agents', 'hooks.json'), (j) => Object.assign({}, ...Object.values(j).filter((v) => v && typeof v === 'object' && (v ).enabled !== false)), ['PreToolUse', 'PostToolUse', 'Stop']],
85
+ const clients = [
86
+ ['cursor', join(repo.root, '.cursor', 'hooks.json'), hooksOf, ['preToolUse', 'postToolUse', 'postToolUseFailure', 'stop']],
87
+ ['codex', join(repo.root, '.codex', 'hooks.json'), hooksOf, ['PreToolUse', 'PostToolUse', 'Stop']],
88
+ ['gemini', join(repo.root, '.gemini', 'settings.json'), hooksOf, ['BeforeTool', 'AfterTool', 'AfterAgent']],
89
+ ['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
90
  ]
81
91
  for (const [name, f, events, need] of clients) {
82
92
  const j = readJsonOrInvalid(f)
83
- if (j === null) continue
84
- if (j === 'invalid') { add('FAIL', `hooks ${name}`, `${f} is not valid JSON`); found++; continue }
93
+ if (j === undefined) continue
94
+ if (j === INVALID) { add('FAIL', `hooks ${name}`, `${f} is not valid JSON`); found++; continue }
85
95
  const cmds = stopbarCommands(events(j))
86
96
  if (!Object.keys(cmds).length) continue
87
97
  found++
@@ -89,15 +99,29 @@ function checkOtherClients(repo , add
89
99
  const script = scriptOf(Object.values(cmds)[0][0])
90
100
  if (missing.length) add('FAIL', `hooks ${name}`, `${f}: no Stopbar hook for ${missing.join(', ')}`)
91
101
  else if (script && !existsSync(script)) add('FAIL', `hooks ${name}`, `script not found: ${script}`)
92
- else if (name === 'cursor' && JSON.stringify(j.hooks).includes('"failClosed":false')) add('WARN', `hooks ${name}`, `${f}: failClosed is false, so a crash of the hook lets the action run`)
102
+ 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
103
  else add('OK', `hooks ${name}`, `${need.join(', ')} (${f.replace(/\\/g, '/').split('/').slice(-2).join('/')})`)
94
104
  }
95
- let dir = join(repo.gitDir, 'hooks')
96
- try { const rel = execFileSync('git', ['rev-parse', '--git-path', 'hooks'], {cwd: repo.root, encoding: 'utf8'}).trim(); dir = isAbsolute(rel) ? rel : join(repo.root, rel) } catch { /* default */ }
97
- const gh = ['pre-commit', 'pre-push'].filter((n) => existsSync(join(dir, n)) && readFileSync(join(dir, n), 'utf8').includes('stopbar.mjs" git-hook'))
105
+ let hd = {dir: join(repo.gitDir, 'hooks'), customHooksPath: null}
106
+ try { hd = gitHooksDir(repo) } catch { /* default */ }
107
+ const {dir} = hd
108
+ // a Stopbar line that is not a comment: the hook init writes, or `stopbar git-hook <name>` chained by hand (Husky, Lefthook)
109
+ const calls = (n ) => new RegExp(`^[^#\\n]*stopbar(\\.mjs)?"?\\s+git-hook\\s+${n}\\b`, 'm')
110
+ const gh = ['pre-commit', 'pre-push'].filter((n) => existsSync(join(dir, n)) && calls(n).test(readFileSync(join(dir, n), 'utf8')))
98
111
  const lacking = ['pre-commit', 'pre-push'].filter((n) => !gh.includes(n))
99
112
  // the git hooks close what an agent hook cannot see: git aliases, and on pre-push merge, cherry-pick, am and commit-tree
100
113
  if (!lacking.length) add('OK', 'hooks git', `pre-commit, pre-push in ${dir}`)
114
+ else if (hd.customHooksPath !== null) {
115
+ // the exact line for the existing hook manager (Husky, Lefthook, a shared directory): the pinned runtime, else this copy
116
+ const rt = existsSync(join(repo.stateDir, 'runtime', 'bin', 'stopbar.mjs')) ? join(repo.stateDir, 'runtime') : PKG_ROOT
117
+ const bin = join(rt, 'bin', 'stopbar.mjs').replace(/\\/g, '/')
118
+ let cli = cliOf({})
119
+ try { cli = cliOf(readConfig(repo)) } catch { /* reported by the config.json check */ }
120
+ add('WARN', 'hooks git', `no Stopbar ${lacking.join(' and ')} hook in the custom core.hooksPath (${dir}): git ${lacking.map((n) => (n === 'pre-commit' ? 'commit' : 'push')).join(' and git ')} ` +
121
+ `${lacking.length > 1 ? 'are' : 'is'} NOT gated by Stopbar in this repository. Stopbar does not write shared or tracked hooks; a human adds one line to each hook of the existing hook manager: ` +
122
+ lacking.map((n) => `${n}: node "${bin}" git-hook ${n}`).join('; ') + ` (or \`${cli} git-hook pre-commit|pre-push\`); ` +
123
+ 'or runs `stopbar upgrade --hooks git --force-hooks` to write them there, keeping a .stopbar-backup')
124
+ }
101
125
  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
126
  return {clients: found, git: gh.length}
103
127
  }
@@ -152,7 +176,7 @@ export async function doctor(o )
152
176
  try {
153
177
  const {checkGenerated} = await import('./verify.js')
154
178
  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}; ${(g.differential ).steps} steps vs interpreter, ${(g.differential ).mismatches} mismatches`)
179
+ 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
180
  } catch (e) { add('WARN', 'kernel link', `not checked: ${(e ).message}`) }
157
181
  } 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
182
 
@@ -164,7 +188,8 @@ export async function doctor(o )
164
188
  const cfg = readConfig(repo); cfgOk = true
165
189
  add('OK', 'config.json', `profile ${cfg.profile}; build \`${cfg.buildCmd}\`; full tests \`${cfg.fullTestCmd}\`; maxRetries ${cfg.maxRetries}; cap ${cfg.cap}; ` +
166
190
  `${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' : ''}`)
191
+ `stopGate ${cfg.stopGate ?? 'block'}; cli ${cliOf(cfg)}${cfg.requireRun ? '; requireRun: true' : ''}; ` +
192
+ (cfg.requireRun ? 'gates: stopbar run only (--require-run)' : 'gates: hook command text (use --require-run for exit-code-only gates)'))
168
193
  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
194
  const safe = cfg.safeTools ?? DEFAULT_SAFE_TOOLS
170
195
  const missing = DEFAULT_SAFE_TOOLS.filter((t) => !safe.includes(t))
@@ -105,14 +105,46 @@ function antigravityFile(root , command ) {
105
105
  return f
106
106
  }
107
107
 
108
- /** A foreign pre-commit or pre-push hook: 'fail' (git named in --hooks), 'backup' (--force-hooks: kept as
109
- * <name>.stopbar-backup, then replaced) or 'keep' (git added by default: the foreign hook stays, with a warning). */
110
-
111
- function gitHooks(repo , runtimeRoot , foreign , warn ) {
108
+ /** Where git runs the hooks of this repository (`git rev-parse --git-path hooks`). `customHooksPath`: the
109
+ * `core.hooksPath` value when it points outside the default <git-common-dir>/hooks (Husky, Lefthook, a shared or tracked
110
+ * hooks directory), else null. No core.hooksPath entry is no error; any other git config error fails closed. */
111
+ export function gitHooksDir(repo ) {
112
+ let configured = null
113
+ try { configured = git(repo.root, ['config', '--get', 'core.hooksPath']) || null } catch (e) {
114
+ if ((e ).status !== 1) throw new FailClosed(`git config --get core.hooksPath failed in ${repo.root}: ${(e ).message.split('\n')[0]}`)
115
+ }
112
116
  const rel = git(repo.root, ['rev-parse', '--git-path', 'hooks'])
113
117
  const dir = isAbsolute(rel) ? rel : resolve(repo.root, rel)
118
+ if (configured === null) return {dir, customHooksPath: null}
119
+ const common = git(repo.root, ['rev-parse', '--git-common-dir'])
120
+ const def = resolve(isAbsolute(common) ? common : resolve(repo.root, common), 'hooks')
121
+ const same = process.platform === 'win32' ? resolve(dir).toLowerCase() === def.toLowerCase() : resolve(dir) === def
122
+ return {dir, customHooksPath: same ? null : configured}
123
+ }
124
+
125
+
126
+ const hookBin = (runtimeRoot ) => join(runtimeRoot, 'bin', 'stopbar.mjs').replace(/\\/g, '/')
127
+ const manualHooks = (hd , bin ) =>
128
+ `add \`node "${bin}" git-hook pre-commit\` to ${join(hd.dir, 'pre-commit')} and \`node "${bin}" git-hook pre-push\` to ${join(hd.dir, 'pre-push')}`
129
+ function customHooksRefusal(hd , runtimeRoot ) {
130
+ return new FailClosed(`core.hooksPath (${hd.customHooksPath}) points git hooks outside .git/hooks, to ${hd.dir}; not writing shared or tracked hooks there`,
131
+ `chain them by hand: ${manualHooks(hd, hookBin(runtimeRoot))}; or run again with --force-hooks to write them there (a foreign hook is kept as <name>.stopbar-backup)`)
132
+ }
133
+
134
+ /** A foreign pre-commit or pre-push hook: 'fail' (git named in --hooks), 'backup' (--force-hooks: kept as
135
+ * <name>.stopbar-backup, then replaced) or 'keep' (git added by default: the foreign hook stays, with a warning).
136
+ * A custom core.hooksPath (shared or tracked hooks) is written only with 'backup'; 'keep' writes nothing there and
137
+ * warns, 'fail' refuses. */
138
+
139
+ function gitHooks(repo , runtimeRoot , foreign , warn , hd = gitHooksDir(repo)) {
140
+ const {dir} = hd
141
+ const bin = hookBin(runtimeRoot)
142
+ if (hd.customHooksPath !== null && foreign !== 'backup') {
143
+ if (foreign === 'fail') throw customHooksRefusal(hd, runtimeRoot)
144
+ 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, bin)}; to write them there directly (a foreign hook is kept as <name>.stopbar-backup): stopbar upgrade --hooks git --force-hooks`)
145
+ return []
146
+ }
114
147
  mkdirSync(dir, {recursive: true})
115
- const bin = join(runtimeRoot, 'bin', 'stopbar.mjs').replace(/\\/g, '/')
116
148
  const out = []
117
149
  for (const name of ['pre-commit', 'pre-push']) {
118
150
  const f = join(dir, name)
@@ -137,6 +169,9 @@ function gitHooks(repo , runtimeRoot , foreign , warn
137
169
  export function installHooks(repo , targets , runtimeRoot , force , o = {}) {
138
170
  const lines = []
139
171
  const foreign = force ? 'backup' : o.gitByDefault ? 'keep' : 'fail'
172
+ const hd = targets.includes('git') ? gitHooksDir(repo) : null
173
+ // a refusal (explicit --hooks git into a custom core.hooksPath) comes before any client file is written
174
+ if (hd && foreign === 'fail' && hd.customHooksPath !== null) throw customHooksRefusal(hd, runtimeRoot)
140
175
  for (const t of targets) {
141
176
  if (t === 'claude') lines.push(`claude: ${claudeFile(repo.root, 'settings.local.json', hookCommand(runtimeRoot))}`)
142
177
  else if (t === 'claude-project') lines.push(`claude: ${claudeFile(repo.root, 'settings.json', hookCommand(runtimeRoot))}`)
@@ -144,7 +179,7 @@ export function installHooks(repo , targets , runtimeRoot ,
144
179
  else if (t === 'codex') lines.push(`codex: ${codexFile(repo.root, hookCommand(runtimeRoot, 'codex'))}`)
145
180
  else if (t === 'gemini') lines.push(`gemini: ${geminiFile(repo.root, hookCommand(runtimeRoot, 'gemini'))}`)
146
181
  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}`)
182
+ else if (t === 'git') for (const f of gitHooks(repo, runtimeRoot, foreign, o.warn ?? (() => {}), hd ?? undefined)) lines.push(`git: ${f}`)
148
183
  }
149
184
  return lines
150
185
  }