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/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,123 @@ 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') {
289
+ cmd = normPwd(cmd)
241
290
  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]}
291
+ const texts = [cmd, unsplice(cmd), unquoteShellWords(cmd)]
292
+ if (paths.secrets.length) {
293
+ for (const t of texts) for (const [re, pattern] of ENV_DUMP) {
294
+ const m = re.exec(t)
295
+ if (m) return {token: m[0].replace(/^[\s;&|(`]+/, '').trim(), pattern}
296
+ }
297
+ }
298
+ // the words as written, then as bash joins them (`.e""nv` is `.env`); each also with its `..` segments resolved
299
+ for (const tok of new Set(texts.flatMap(words))) {
300
+ const n = posix.normalize(norm(tok))
301
+ for (const cand of n === tok ? [tok] : [tok, n]) {
302
+ const hits = paths.secrets.filter((g) => matchesSecretGlob(cand, g))
303
+ if (!hits.length) continue
304
+ const strong = hits.find((g) => !EXT_ONLY.test(g))
305
+ if (strong) return {token: tok, pattern: strong}
306
+ if (/[\\/]/.test(cand) || exists(cand)) return {token: tok, pattern: hits[0]}
307
+ }
308
+ }
309
+ // wildcards that expand: bash expands none inside quotes or after a backslash; PowerShell -Path expands them quoted too
310
+ const samples = secretSamples(paths)
311
+ for (const tok of new Set(words(shell === 'bash' ? globView(cmd) : unquoteShellWords(cmd)))) {
312
+ // the last segment: dot-leading (bash matches dotfiles only so), or after a literal prefix of 2+ chars
313
+ const last = posix.normalize(norm(tok)).split('/').pop() ?? ''
314
+ const at = last.search(HAS_GLOB)
315
+ if (at < 0 || !(last.startsWith('.') || at >= 2)) continue
316
+ const re = globSegment(last)
317
+ if (!re) continue
318
+ for (const s of samples) {
319
+ const pattern = re.test(s) ? secretPattern(s, paths) : null
320
+ if (pattern) return {token: tok, pattern}
321
+ }
249
322
  }
323
+ // find -name/-path <pattern> -exec ...: find expands the pattern itself; also `*.key` (a.key) and `**/x/**` (x/a)
324
+ const extra = paths.secrets.flatMap((g) => {
325
+ const last = g.split('/').pop() ?? ''
326
+ if (EXT_ONLY.test(last)) return [`a${last.slice(1)}`]
327
+ const dir = /^\*\*\/([^*?[{\/]+)\/\*\*$/.exec(g)
328
+ return dir ? [`${dir[1]}/a`] : []
329
+ })
330
+ const f = findReaches(cmd, [...samples, ...extra], false)
331
+ if (f) { const pattern = secretPattern(f.name, paths); if (pattern) return {token: `find ${f.pat}`, pattern} }
250
332
  return null
251
333
  }
334
+
335
+ /** The command as bash joins its words, with the glob characters that do not expand (inside quotes, after a backslash)
336
+ * replaced by \x01, so only live wildcards are left. */
337
+ function globView(cmd ) {
338
+ let out = ''
339
+ const mask = (s ) => s.replace(/[*?[\]{}]/g, '\x01')
340
+ for (let i = 0; i < cmd.length; i++) {
341
+ const c = cmd[i]
342
+ if (c === "'") {
343
+ const j = cmd.indexOf("'", i + 1)
344
+ out += mask(j < 0 ? cmd.slice(i + 1) : cmd.slice(i + 1, j))
345
+ i = j < 0 ? cmd.length : j
346
+ } else if (c === '"') {
347
+ let j = i + 1
348
+ for (; j < cmd.length && cmd[j] !== '"'; j++) {
349
+ if (cmd[j] === '\\' && j + 1 < cmd.length && '"\\$`'.includes(cmd[j + 1])) j++
350
+ out += mask(cmd[j])
351
+ }
352
+ i = j
353
+ } else if (c === '\\' && i + 1 < cmd.length) { out += mask(cmd[i + 1]); i++ } else out += c
354
+ }
355
+ return out
356
+ }
252
357
  export const mentionsSecret = (cmd , paths , exists ) => secretInCommand(cmd, paths, exists) !== null
253
358
 
254
359
 
@@ -272,7 +377,7 @@ export function classifyBash(cmd , cfg
272
377
  if (c === cfg.buildCmd.trim()) return {kind: 'build'}
273
378
  if (c === cfg.fullTestCmd.trim()) return {kind: 'fulltest'}
274
379
  }
275
- return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: secretInCommand(c, cfg.paths, exists)}
380
+ return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: secretInCommand(c, cfg.paths, exists, shell)}
276
381
  }
277
382
 
278
383
  /** Kind of a tree change from a list of (status, path) and a test for "the path exists in the reference tree"
@@ -304,11 +409,23 @@ export function classifyTreeChange(changes , in
304
409
 
305
410
  // ---------------------------------------------------------------- self-protection
306
411
  // Unconditional BLOCK in PreToolUse, outside the kernel. Paths are compared normalised: '/' separators, lower case.
307
-
412
+ /** `hooksDir`: the directory a custom `core.hooksPath` points to (absolute; set only when it is outside the default
413
+ * .git/hooks and not the working tree root or above it); `hooksPathRaw`: the value as written in the git config. */
414
+
308
415
 
309
416
  const lc = (p ) => norm(p).toLowerCase().replace(/\/+$/, '')
310
417
  const under = (a , dir ) => a === dir || a.startsWith(dir + '/')
311
418
 
419
+ /** The Protect fields of a custom core.hooksPath (repo.ts readHooksPath). A value that names the working tree root or a
420
+ * directory above it would protect the whole tree: then only the raw value is kept (it is ignored when it is `.`). */
421
+ export function hooksProtect(root , hp ) {
422
+ if (!hp) return {}
423
+ return under(lc(root), lc(hp.dir)) ? {hooksPathRaw: hp.raw} : {hooksDir: hp.dir, hooksPathRaw: hp.raw}
424
+ }
425
+
426
+ // the files of the git hook managers Husky and Lefthook: a tracked hook there calls `stopbar git-hook`
427
+ const HOOK_MANAGER_PATH = /(^|\/)(?:\.husky(?:\/|$)|\.lefthook(?:\/|$)|\.?lefthook(?:-local)?\.ya?ml$)/
428
+
312
429
  // the hook configuration of every supported client (project and user level)
313
430
  const AGENT_CONFIG = [
314
431
  [/(^|\/)\.claude\/[^/]*settings[^/]*\.json$/, 'Claude Code settings (.claude/settings*.json)'],
@@ -325,6 +442,8 @@ export function protectedPath(abs , root , pr )
325
442
  const tail = under(a, r) ? a.slice(r.length) : a
326
443
  if (/(^|\/)\.git(\/|$)/.test(tail) || under(a, lc(pr.gitDir)) || under(a, lc(pr.stateDir))) return 'git metadata (.git/**, Stopbar state, git hooks, git config)'
327
444
  for (const [re, what] of AGENT_CONFIG) if (re.test(a)) return `${what} hold the Stopbar hooks`
445
+ if (HOOK_MANAGER_PATH.test(tail)) return 'git hook manager files (.husky/**, lefthook*.yml, .lefthook/**) call the Stopbar git hooks'
446
+ if (pr.hooksDir && under(a, lc(pr.hooksDir))) return `the custom core.hooksPath directory (${pr.hooksPathRaw ?? pr.hooksDir}) holds the git hooks`
328
447
  for (const d of pr.codeDirs) if (under(a, lc(d))) return `Stopbar code (${d})`
329
448
  return null
330
449
  }
@@ -332,6 +451,94 @@ export function protectedPath(abs , root , pr )
332
451
  const SEG = (name ) => new RegExp(String.raw`(^|[^a-z0-9_.\-])${name.replace(/\./g, '\\.')}([^a-z0-9_\-]|$)`, 'i')
333
452
  const DOT_GIT = SEG('.git')
334
453
  const AGENT_DIRS = [[SEG('.claude'), '.claude'], [SEG('.cursor'), '.cursor'], [SEG('.codex'), '.codex'], [SEG('.gemini'), '.gemini'], [SEG('.agents'), '.agents']]
454
+ const HOOK_MANAGERS = [[SEG('.husky'), '.husky'], [SEG('.lefthook'), '.lefthook'],
455
+ [/(^|[^a-z0-9_.\-])\.?lefthook(?:-local)?\.ya?ml([^a-z0-9_\-]|$)/i, 'lefthook*.yml']]
456
+ const LEFTHOOK_FILES = ['lefthook', '.lefthook', 'lefthook-local', '.lefthook-local'].flatMap((b) => [`${b}.yml`, `${b}.yaml`])
457
+ const reEsc = (s ) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
458
+ const PATH_END = String.raw`(?=[/\s'";&|)<>]|$)`
459
+
460
+ /** The custom core.hooksPath as a relative value (`./` and trailing `/` dropped), or null when it is empty, `.`, `..`,
461
+ * `/`, absolute or above the tree. */
462
+ function relHooksPath(pr ) {
463
+ const r = norm(pr.hooksPathRaw ?? '').replace(/^(?:\.\/)+/, '').replace(/\/+$/, '')
464
+ if (!r || r === '.' || r.startsWith('../') || r === '..' || /^(?:[a-z]:)?\//i.test(r) || r.startsWith('~')) return null
465
+ return r
466
+ }
467
+ /** Regular expressions for the custom core.hooksPath in a command (lower case text): the relative value as a path from
468
+ * the working tree (at a word start or after `./`), and the absolute directory (also as Git Bash writes it, /c/...). */
469
+ function hooksPathNeedles(pr ) {
470
+ const out = []
471
+ const rel = relHooksPath(pr)
472
+ if (rel) out.push(new RegExp(String.raw`(?:^|[\s'"=(;&|<>]|\./)${reEsc(rel.toLowerCase())}${PATH_END}`))
473
+ if (pr.hooksDir) {
474
+ const abs = lc(pr.hooksDir)
475
+ for (const a of new Set([abs, abs.replace(/^([a-z]):/, '/$1')])) out.push(new RegExp(reEsc(a) + PATH_END))
476
+ }
477
+ return out
478
+ }
479
+ /** Directory names a wildcard or a `find` pattern must not reach: .git, the agent settings and hook managers, and the
480
+ * first segment of a relative custom core.hooksPath (and its last one, for find). */
481
+ function guardedNames(pr , forFind ) {
482
+ const out = [...GUARDED]
483
+ const rel = pr ? relHooksPath(pr) : null
484
+ if (rel) {
485
+ const first = rel.split('/')[0]
486
+ if (forFind || first.startsWith('.')) out.push(first)
487
+ }
488
+ if (forFind && pr?.hooksDir) out.push(norm(pr.hooksDir).replace(/\/+$/, '').split('/').pop() )
489
+ return [...new Set(out.filter(Boolean))]
490
+ }
491
+ const guardReason = (d ) => d === '.git' ? 'Stopbar state, git hooks, git config live there'
492
+ : /^\.(?:claude|cursor|codex|gemini|agents)$/.test(d) ? 'agent settings there hold the Stopbar hooks' : 'the git hooks there call Stopbar'
493
+
494
+ /** `$(pwd)`, `"$(pwd)"`, `${PWD}`, `$PWD`, `` `pwd` `` (each also in double quotes, `pwd -L|-P` too) as `.`: the current
495
+ * directory, so `rm -rf $(pwd)/.g*` reads as `rm -rf ./.g*`. For the text scans only. */
496
+ const PWD_ONE = String.raw`\$\(\s*pwd(?:\s+-[LP])?\s*\)|\$\{PWD\}|\$PWD(?!\w)|\x60\s*pwd(?:\s+-[LP])?\s*\x60`
497
+ const PWD_FORMS = new RegExp(`"(?:${PWD_ONE})"|${PWD_ONE}`, 'g')
498
+ export const normPwd = (cmd ) => cmd.replace(PWD_FORMS, '.')
499
+
500
+ // `find` with a name or path predicate and an action. `find` expands the pattern itself, so a quoted `-name '.g*'` is a
501
+ // live wildcard (unlike a quoted word for bash).
502
+ const FIND_PRED = /^-i?(?:name|path|wholename)$/i
503
+ const FIND_EXEC = /^-(?:exec|execdir|ok|okdir)$/
504
+
505
+ function findCalls(cmd ) {
506
+ const out = []
507
+ let cur = null, start = true
508
+ const ws = shellWords(cmd)
509
+ for (let i = 0; i < ws.length; i++) {
510
+ const w = ws[i]
511
+ if (w.length === 1 && ';&|()\n'.includes(w)) { cur = null; start = true; continue }
512
+ const u = unquoteShellWords(w)
513
+ if (start) {
514
+ if (/^\w+=/.test(u) || /^(?:sudo|command|exec|nice|time|xargs|env)$/i.test(u)) continue
515
+ start = false
516
+ if (/^g?find$/i.test(norm(u).split('/').pop() .replace(/\.exe$/i, ''))) { cur = {preds: [], del: false, exec: false}; out.push(cur) }
517
+ continue
518
+ }
519
+ if (!cur) continue
520
+ if (FIND_PRED.test(u) && i + 1 < ws.length) {
521
+ const pat = unquoteShellWords(ws[++i]).replace(/\\(.)/g, '$1')
522
+ const re = globSegment(pat)
523
+ if (re) cur.preds.push({path: /path|wholename/i.test(u), pat, re})
524
+ } else if (u === '-delete') cur.del = true
525
+ else if (FIND_EXEC.test(u)) cur.exec = true
526
+ }
527
+ return out
528
+ }
529
+ /** The first name a find pattern reaches (`-name` on the last segment, `-path` on the path below `.`), for the find
530
+ * calls with -exec/-execdir/-ok/-okdir (and -delete when `withDelete`). */
531
+ function findReaches(cmd , names , withDelete ) {
532
+ for (const c of findCalls(cmd)) {
533
+ if (!(c.exec || (withDelete && c.del))) continue
534
+ for (const p of c.preds) for (const n of names) {
535
+ if (!p.path && n.includes('/')) continue
536
+ const cands = p.path ? [n, `./${n}`, `./a/${n}`, `./${n}/a`, `./a/${n}/a`] : [n]
537
+ if (cands.some((x) => p.re.test(x))) return {name: n, pat: p.pat}
538
+ }
539
+ }
540
+ return null
541
+ }
335
542
  const HUMAN_ONLY = /\b(approve-tests|approve-shell)\b|\bSTOPBAR_[A-Z_]+/i
336
543
  // an admin subcommand right after the program word (`stopbar`, `stopbar.mjs`, `stopbar@1.2.0`, `.../stopbar/dist/cli.js`,
337
544
  // quoted or not): `stopbar init` is human-only, `stopbar probe init` (a prober scaffold, SKILL.md) is the agent's
@@ -412,6 +619,71 @@ export function withoutStdinHeredoc(cmd ) {
412
619
  return [cmd.slice(0, nl), ...lines.slice(end)].join('\n')
413
620
  }
414
621
 
622
+ // A wildcard that reaches .git or an agent settings directory (`rm -rf .g*`, `mv .cl* x`, `Remove-Item .g*`): blocked
623
+ // for the commands that delete or move, and for any command when the wildcard is followed by a path inside such a
624
+ // directory (`cp x .g*/hooks/pre-commit`). Other wildcards (`rm *.log`, a `.*` in a grep pattern) stay allowed.
625
+ const GUARDED = ['.git', '.claude', '.cursor', '.codex', '.gemini', '.agents', '.husky', '.lefthook']
626
+ const DESTRUCTIVE = /^(?:rm|rmdir|unlink|shred|mv|del|erase|rd|move|remove-item|ri|move-item|mi)$/i
627
+ const INSIDE = /^(?:hooks|config|stopbar|info|refs|head|index|objects|settings[\w.-]*\.json|hooks\.json|pre-commit|pre-push|_)$/i
628
+ /** `t`: the command with only live wildcards left (globView for bash). `names`: guardedNames. */
629
+ function wildcardGuardedDir(t , names = GUARDED) {
630
+ const globDir = (seg ) => (HAS_GLOB.test(seg) && /^[.?[]/.test(seg) ? names.find((d) => globSegment(seg)?.test(d)) ?? null : null)
631
+ for (const part of norm(t).split(/[;&|\n()`]+/)) {
632
+ const ws = part.split(/[\s<>='"]+/).filter(Boolean)
633
+ let k = 0
634
+ while (k < ws.length && (/^\w+=/.test(ws[k]) || /^(?:sudo|command|exec|nice|time)$/i.test(ws[k]))) k++
635
+ const destructive = DESTRUCTIVE.test((ws[k] ?? '').split('/').pop() .replace(/\.exe$/i, ''))
636
+ for (const w of ws.slice(k + 1)) {
637
+ const segs = w.split('/')
638
+ for (let i = 0; i < segs.length; i++) {
639
+ const d = globDir(segs[i])
640
+ if (d && (destructive || (i + 1 < segs.length && INSIDE.test(segs[i + 1])))) return d
641
+ }
642
+ }
643
+ }
644
+ return null
645
+ }
646
+
647
+ /** Shell words with their quotes kept; the operators ; & | ( ) and newline are words of their own. */
648
+ function shellWords(cmd ) {
649
+ const out = []
650
+ let w = ''
651
+ const flush = () => { if (w) out.push(w); w = '' }
652
+ for (let i = 0; i < cmd.length; i++) {
653
+ const c = cmd[i]
654
+ if (c === ' ' || c === '\t' || c === '\r') { flush(); continue }
655
+ if (';&|()\n'.includes(c)) { flush(); out.push(c); continue }
656
+ if (c === "'" || c === '"' || c === '`') {
657
+ let j = i + 1
658
+ for (; j < cmd.length && cmd[j] !== c; j++) if (c !== "'" && cmd[j] === '\\') j++
659
+ w += cmd.slice(i, j + 1); i = j; continue
660
+ }
661
+ if (c === '$' && cmd[i + 1] === '(') {
662
+ let j = i + 2, depth = 1
663
+ for (; j < cmd.length && depth; j++) depth += cmd[j] === '(' ? 1 : cmd[j] === ')' ? -1 : 0
664
+ w += cmd.slice(i, j); i = j - 1; continue
665
+ }
666
+ if (c === '\\' && i + 1 < cmd.length) { w += cmd.slice(i, i + 2); i++; continue }
667
+ w += c
668
+ }
669
+ flush()
670
+ return out
671
+ }
672
+ // `git $f -m x`, `p=push; git $p`, `git "${cmd}"`, git `echo push`: the subcommand comes from an expansion, so the commit
673
+ // and push gates cannot see it. A `git` inside a quoted string is one word with its quotes, so it is no command here.
674
+ const GIT_OPT_ARG = /^(?:-[cC]|--(?:git-dir|work-tree|namespace|exec-path|config-env|attr-source|super-prefix))$/
675
+ export function dynamicGitSubcommand(cmd ) {
676
+ const ws = shellWords(cmd)
677
+ for (let i = 0; i < ws.length; i++) {
678
+ if (!/^git(?:\.exe)?$/i.test(unquoteShellWords(ws[i]).replace(/\\/g, '/').split('/').pop() )) continue
679
+ let j = i + 1
680
+ while (j < ws.length && ws[j].length > 1 && ws[j].startsWith('-')) j += GIT_OPT_ARG.test(ws[j]) ? 2 : 1
681
+ const sub = ws[j]
682
+ if (sub && /^(?:"?\$|"?`)/.test(sub)) return sub
683
+ }
684
+ return null
685
+ }
686
+
415
687
  /** Shell command text. Returns the reason for a block, or null. Text matching only: see SECURITY.md.
416
688
  * Every check runs on the text as written and as bash joins quoted parts of a word (`.g""it`, `'.cl'"aude"`, `gi"t"`:
417
689
  * unsplice and unquoteShellWords). For bash, the body of
@@ -419,11 +691,21 @@ export function withoutStdinHeredoc(cmd ) {
419
691
  * .git, the agent settings directories and Stopbar code stay protected in it. */
420
692
  export function protectedCommand(cmd , pr , shell = 'bash') {
421
693
  const texts = [...new Set([cmd, unsplice(cmd), unquoteShellWords(cmd)])]
694
+ const needles = hooksPathNeedles(pr)
422
695
  for (const t of texts) {
423
696
  const c = norm(t).toLowerCase()
424
697
  if (DOT_GIT.test(c)) return 'the command names a .git directory (Stopbar state, git hooks, git config live there)'
425
698
  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)`
699
+ for (const [re, d] of HOOK_MANAGERS) if (re.test(c)) return `the command names ${d} (git hook manager files there call the Stopbar git hooks)`
700
+ if (needles.some((re) => re.test(c))) return `the command names the custom core.hooksPath directory (${pr.hooksPathRaw ?? pr.hooksDir}), which holds the git hooks`
426
701
  }
702
+ const p = normPwd(cmd)
703
+ const g = wildcardGuardedDir(shell === 'bash' ? globView(p) : unquoteShellWords(p), guardedNames(pr, false))
704
+ if (g) return `the command has a wildcard that reaches the ${g} directory (${guardReason(g)})`
705
+ const f = findReaches(p, [...guardedNames(pr, true), ...LEFTHOOK_FILES], true)
706
+ if (f) return `find ${JSON.stringify(f.pat)} with -delete, -exec, -execdir, -ok or -okdir reaches ${f.name} (${LEFTHOOK_FILES.includes(f.name) ? 'the git hook manager file calls the Stopbar git hooks' : guardReason(f.name)})`
707
+ const dyn = dynamicGitSubcommand(cmd)
708
+ 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
709
  for (const t of texts) {
428
710
  const c = norm(t).toLowerCase()
429
711
  if (isGitConfigWrite(t)) return '`git config` writes .git/config; only reads (--get, --list) are allowed'
package/dist/cli.js CHANGED
@@ -11,12 +11,13 @@ const HELP = `stopbar ${VERSION}: proven gates for coding agents (Claude Code ho
11
11
 
12
12
  stopbar init --build "<cmd>" --test "<cmd>" [--profile default|ts|python|strict] [--base-ref <ref>] [--max-retries 3] [--cap 500]
13
13
  [--cost 1] [--hooks claude,claude-project,cursor,codex,gemini,antigravity,git] [--no-pin] [--force] [--force-hooks] [--repo <dir>]
14
- [--cli "<cmd>"] [--stop-gate block|warn] [--require-run] [--no-git-hooks]
14
+ [--cli "<cmd>"] [--stop-gate block|warn] [--require-run] [--no-git-hooks] [--safe-tools "<glob>,<glob>"]
15
15
  --hooks <clients> adds the git hooks (pre-commit, pre-push) unless --no-git-hooks;
16
16
  a foreign git hook is kept with a warning (replace it: --hooks git --force-hooks)
17
17
  --cli: command that starts Stopbar in hints (default: npx --no-install stopbar)
18
18
  --stop-gate warn: Stop only warns; git commit and git push stay blocked until the gates pass
19
19
  --require-run: build and full test gates count only through stopbar run build|test
20
+ --safe-tools: local tools that are never outbound (globs; --force keeps the previous list)
20
21
  stopbar upgrade [--hooks <targets>] [--force-hooks] [--repo <dir>]
21
22
  a human re-pins the hook runtime from this package (and rewrites hooks with --hooks);
22
23
  state, gates, taint and budget stay as they are
@@ -29,7 +30,7 @@ const HELP = `stopbar ${VERSION}: proven gates for coding agents (Claude Code ho
29
30
  stopbar approve-shell a human allows ONE risky or outbound call after a secret was read
30
31
  stopbar resume --extra N a human lifts a halt and adds N to the budget
31
32
  stopbar reset a human starts a fresh kernel state (config and event log stay)
32
- stopbar doctor [--json] environment, config, state, hooks and a dry run
33
+ stopbar doctor [--json] [--strict] environment, config, state, hooks and a dry run; --strict: a [WARN] fails (exit 1)
33
34
 
34
35
  Four pillars:
35
36
  PROVE stopbar prove [--out f.json] [--lean f.lean] inductive proof of the kernel and the 10 mutants
@@ -53,7 +54,7 @@ Four pillars:
53
54
  GATE init, upgrade, hook, status, approve-tests, approve-shell, resume, reset, doctor (above)
54
55
  ATTEST stopbar attest [--format json|md] deterministic attestation: HEAD, tree, gates, human actions, log sha256,
55
56
  probe evidence (the latest probe:result per target, and whether it was taken at the current snapshot)
56
- All commands take --repo <dir> (default: the current directory). 'verify' is an alias of 'prove'.`
57
+ All commands take --repo <dir> (default: the current directory) and --help / -h. 'verify' is an alias of 'prove'.`
57
58
 
58
59
  function opts(a ) {
59
60
  const get = (name ) => { const i = a.indexOf(`--${name}`); return i >= 0 && i + 1 < a.length ? a[i + 1] : undefined }
@@ -67,7 +68,14 @@ function opts(a ) {
67
68
  }
68
69
  }
69
70
 
71
+ // flags that take a value: a --help right after one of them is that value (e.g. --cmd --help), not a request for help
72
+ const VALUE_FLAGS = new Set(['build', 'test', 'profile', 'base-ref', 'max-retries', 'cap', 'cost', 'hooks', 'repo', 'cli', 'stop-gate', 'safe-tools', 'rev', 'extra',
73
+ 'target', 'cmd', 'target-file', 'cmd-timeout', 'runs', 'seed', 'jobs', 'work', 'out', 'regressions', 'mutant-runs', 'lang', 'name', 'format', 'lean', 'adapter', 'worker', 'worker-file'].map((f) => `--${f}`))
74
+ /** --help or -h as a word of its own after the subcommand: print the help, run nothing. */
75
+ const wantsHelp = (a ) => a.some((x, i) => (x === '--help' || x === '-h') && !VALUE_FLAGS.has(a[i - 1] ?? ''))
76
+
70
77
  async function main() {
78
+ if (wantsHelp(argv.slice(1))) return {code: 0, msg: HELP}
71
79
  if (cmd === 'hook') {
72
80
  const {handle} = await import('./adapters/index.js')
73
81
  const i = argv.indexOf('--adapter')
@@ -87,7 +95,7 @@ async function main() {
87
95
  if (cmd === 'init') return (await import('./commands.js')).init(o)
88
96
  if (cmd === 'upgrade') return (await import('./commands.js')).upgrade(o)
89
97
  if (['status', 'approve-tests', 'approve-shell', 'resume', 'reset'].includes(cmd)) return (await import('./commands.js')).human(cmd, o)
90
- if (cmd === 'doctor') return (await import('./doctor.js')).doctor({repo: o.get('repo'), json: o.has('json')})
98
+ if (cmd === 'doctor') return (await import('./doctor.js')).doctor({repo: o.get('repo'), json: o.has('json'), strict: o.has('strict')})
91
99
  if (cmd === 'prove' || cmd === 'verify') {
92
100
  const r = await (await import('./verify.js')).verify({out: o.get('out'), lean: o.get('lean')})
93
101
  return {code: r.ok ? 0 : 1}
package/dist/commands.js CHANGED
@@ -83,11 +83,18 @@ export function init(o ) {
83
83
  for (const [k, v] of [['--build', buildCmd], ['--test', fullTestCmd]]) {
84
84
  if (hasChain(v)) return {code: 1, msg: `${k} ${JSON.stringify(v)} has shell operators; put it in one script (e.g. an npm script) so its exit status is the gate`}
85
85
  }
86
- for (const f of ['cli', 'stop-gate', 'hooks']) if (o.has(f) && o.get(f) === undefined) return {code: 1, msg: `--${f} needs a value`}
86
+ for (const f of ['cli', 'stop-gate', 'hooks', 'safe-tools']) if (o.has(f) && o.get(f) === undefined) return {code: 1, msg: `--${f} needs a value`}
87
+ // safeTools: --safe-tools, else (with --force) the list of a readable previous config.json, else the default
88
+ const safeOpt = o.get('safe-tools')
89
+ let safeTools = safeOpt === undefined ? undefined : safeOpt.split(',').map((x) => x.trim()).filter(Boolean)
90
+ let keptSafe = false
91
+ if (safeTools === undefined && o.has('force') && existsSync(paths(repo).config)) {
92
+ try { safeTools = readConfig(repo).safeTools; keptSafe = safeTools !== undefined } catch { /* a damaged config.json never blocks --force */ }
93
+ }
87
94
  let cfg
88
95
  try {
89
96
  cfg = makeConfig({buildCmd, fullTestCmd, profile: o.get('profile'), maxRetries: o.int('max-retries', 3), cap: o.int('cap', 500), costPerCall: o.int('cost', 1), baseRef: o.get('base-ref'),
90
- cliCmd: o.get('cli'), stopGate: o.get('stop-gate'), requireRun: o.has('require-run')})
97
+ cliCmd: o.get('cli'), stopGate: o.get('stop-gate'), requireRun: o.has('require-run'), safeTools})
91
98
  } catch (e) { if (e instanceof ConfigError) return {code: 1, msg: e.message}; throw e }
92
99
  if (existsSync(paths(repo).config) && !o.has('force')) return {code: 1, msg: `already initialised (${paths(repo).config}); use --force to replace config and state`}
93
100
  const pin = !o.has('no-pin')
@@ -116,16 +123,28 @@ export function init(o ) {
116
123
  writeState(repo, s)
117
124
  const runtime = pin ? pinRuntime(repo) : PKG_ROOT
118
125
  const command = hookCommand(runtime)
119
- appendEvent(repo, {source: 'human:init', cfg, runtime, version: VERSION, kernel: MACHINE, ...(targets.length ? {hooks: targets} : {})})
126
+ const warns = [], gitHooksWritten = []
127
+ let written = [], failed
128
+ if (targets.length) {
129
+ try { written = installHooks(repo, targets, runtime, o.has('force-hooks'), {gitByDefault, warn: (w) => warns.push(w), cli: cliOf(cfg), gitHooksWritten}) } catch (e) { failed = e }
130
+ }
131
+ // the log names the git hooks Stopbar wrote: `stopbar doctor` reports [FAIL] when one of them disappears later
132
+ appendEvent(repo, {source: 'human:init', cfg, runtime, version: VERSION, kernel: MACHINE, ...(targets.length ? {hooks: targets, gitHooksWritten} : {})})
133
+ if (failed !== undefined) throw failed
120
134
  const warn = countDirtyTests(repo, s, dirty, 'init:dirty-tests')
121
135
  const lines = [`Stopbar ${VERSION} initialised in ${repo.stateDir}`, ` profile ${cfg.profile}; build: ${cfg.buildCmd}; full tests: ${cfg.fullTestCmd}${cfg.baseRef ? `; base ref: ${cfg.baseRef}` : ''}`,
122
136
  ` stop gate: ${cfg.stopGate ?? 'block'}; gate hints use: ${cliOf(cfg)} run build|test${cfg.requireRun ? '; requireRun: true (gates count only through stopbar run build|test)' : ''}`,
123
137
  ` hooks run: ${command}`]
124
- const warns = []
125
- if (targets.length) for (const l of installHooks(repo, targets, runtime, o.has('force-hooks'), {gitByDefault, warn: (w) => warns.push(w)})) lines.push(` hooks written: ${l}`)
138
+ const safe = cfg.safeTools ?? DEFAULT_SAFE_TOOLS
139
+ if (JSON.stringify(safe) !== JSON.stringify(DEFAULT_SAFE_TOOLS)) lines.push(` safeTools ${keptSafe ? 'kept from the previous config.json' : 'from --safe-tools'}: ${JSON.stringify(safe)}`)
140
+ if (targets.length) for (const l of written) lines.push(` hooks written: ${l}`)
126
141
  else lines.push(' add these hooks to .claude/settings.local.json (or run init again with --hooks claude,cursor,codex,gemini,antigravity,git):', JSON.stringify(hooksConfig(command), null, 2))
127
142
  if (gitByDefault) lines.push(' git hooks (pre-commit, pre-push) were added to --hooks by default; pass --no-git-hooks to skip them')
128
143
  else if (named.length && o.has('no-git-hooks')) lines.push(' WARN: --no-git-hooks: git aliases, merge, cherry-pick, am and commit-tree are not gated before a push; stopbar doctor reports it')
144
+ if (!cfg.requireRun) {
145
+ if (targets.includes('codex')) lines.push(` NOTE: Codex CLI does not pass the exit status of a shell command to its hooks, so the gates count through \`${cliOf(cfg)} run build|test\`; run init again with --require-run to count them only that way`)
146
+ lines.push(' tip: for CI or a strict setup use --require-run (gates count only through `stopbar run build|test`) and `stopbar doctor --strict` (a warning fails)')
147
+ }
129
148
  lines.push(...warns.map((w) => ` ${w}`), ...warn, 'Next: restart the agent in this repository and run `stopbar doctor`.')
130
149
  return {code: 0, msg: lines.join('\n')}
131
150
  })
@@ -144,9 +163,13 @@ export function upgrade(o ) {
144
163
  readState(repo) // a missing or damaged state fails closed here, with the fix
145
164
  const had = existsSync(join(repo.stateDir, 'runtime'))
146
165
  const runtime = pinRuntime(repo)
147
- appendEvent(repo, {source: 'human:upgrade', version: VERSION, runtime, kernel: MACHINE, ...(targets.length ? {hooks: targets} : {})})
166
+ const gitHooksWritten = []
167
+ let written = [], failed
168
+ if (targets.length) { try { written = installHooks(repo, targets, runtime, o.has('force-hooks'), {cli: cliOf(cfg), gitHooksWritten}) } catch (e) { failed = e } }
169
+ appendEvent(repo, {source: 'human:upgrade', version: VERSION, runtime, kernel: MACHINE, ...(targets.length ? {hooks: targets, gitHooksWritten} : {})})
170
+ if (failed !== undefined) throw failed
148
171
  const lines = [`Stopbar ${VERSION}: hook runtime re-pinned in ${runtime}`, ' state.json, config.json and the snapshots are unchanged (revision, gates, taint, budget)']
149
- if (targets.length) for (const l of installHooks(repo, targets, runtime, o.has('force-hooks'))) lines.push(` hooks written: ${l}`)
172
+ if (targets.length) for (const l of written) lines.push(` hooks written: ${l}`)
150
173
  else if (!had) lines.push(` there was no pinned runtime (init --no-pin): the hooks still run what they ran; add --hooks <targets> to point them at ${hookCommand(runtime)}`)
151
174
  const missing = DEFAULT_SAFE_TOOLS.filter((t) => !(cfg.safeTools ?? DEFAULT_SAFE_TOOLS).includes(t))
152
175
  if (missing.length) lines.push(` hint: config.safeTools lacks the default ${missing.join(', ')}; a human adds them to config.json (stopbar doctor shows it)`)
@@ -169,7 +192,7 @@ export function secretReason(repo )
169
192
 
170
193
  /** `now`: the working tree as it is now. A change no hook has counted yet (now.id !== s.snapshot) keeps a commit blocked
171
194
  * at the next hook (pre:commit-sync), so status never says `allowed` then. */
172
- function statusText(repo , cfg , s , now ) {
195
+ function statusText(repo , cfg , s , now , differs ) {
173
196
  const v = decode(s.kernel)
174
197
  const yn = (b ) => (b ? 'yes' : 'no')
175
198
  const ok = (rev ) => (rev === v.treeRev ? `ok at revision ${rev}` : 'not at the current revision')
@@ -185,6 +208,7 @@ function statusText(repo , cfg , s , now ) {
185
208
  `build ${ok(v.buildOkRev)} (${cfg.buildCmd})`,
186
209
  `full tests ${ok(v.testsOkRev)} (${cfg.fullTestCmd})`,
187
210
  `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)}`,
211
+ ...(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
212
  `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
213
  `commit ${commit}`,
190
214
  `stop gate ${cfg.stopGate ?? 'block'}${cfg.stopGate === 'warn' ? ' (Stop only warns; git commit and git push stay blocked until the gates pass)' : ''}`,
@@ -209,8 +233,12 @@ export function human(cmd , o ) {
209
233
  if (cmd === 'status') {
210
234
  // the working tree now (read-only for state.json, as in attest: only the private snapshot index is refreshed)
211
235
  const now = snapshot(repo)
236
+ // testsTainted with a baseRef: does the tree still change an existing test or test config against it? A hint for
237
+ // the human only (e.g. baseRef absorbed the change); the taint itself stays until reset or approve-tests (L2.2).
238
+ // Read-only; a baseRef that no longer resolves fails closed, as in the hooks.
239
+ const differs = decode(s.kernel).testsTainted && cfg.baseRef && cfg.baseRef !== 'HEAD' ? dirtyTests(repo, cfg, now).suspicious : null
212
240
  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)}
241
+ 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
242
  }
215
243
  let res
216
244
  if (cmd === 'approve-tests') {
package/dist/config.js CHANGED
@@ -35,7 +35,9 @@ const TEST_JS = ['**/*.test.*', '**/*.spec.*', '**/e2e/**']
35
35
  const TEST_PY = ['**/test_*.py', '**/*_test.py']
36
36
  const TEST_OTHER = ['**/*_test.go', '**/*_test.rs', '**/*Test.java', '**/*Tests.cs']
37
37
 
38
- const CFG_COMMON = ['.gitignore', '.gitattributes', '.github/workflows/**', '.gitlab-ci.yml', '.pre-commit-config.yaml', 'Makefile']
38
+ // the git hook managers (Husky, Lefthook): a change made outside the agent hooks still taints (defense in depth)
39
+ const CFG_COMMON = ['.gitignore', '.gitattributes', '.github/workflows/**', '.gitlab-ci.yml', '.pre-commit-config.yaml', 'Makefile',
40
+ '.husky/**', 'lefthook*.yml', '.lefthook*.yml', 'lefthook*.yaml', '.lefthook*.yaml', '.lefthook/**']
39
41
  const CFG_JS = ['package.json', 'tsconfig*.json', '.eslint*', 'eslint.config.*', 'vitest.config.*', 'vitest.workspace.*',
40
42
  'jest.config.*', 'playwright.config.*', '.mocharc*', 'ava.config.*', 'biome.json', '.c8rc*', '.nycrc*']
41
43
  const CFG_PY = ['pyproject.toml', 'pytest.ini', 'conftest.py', 'tox.ini', 'setup.cfg', 'noxfile.py', '.coveragerc',
@@ -113,9 +115,9 @@ export function validateConfig(c ) {
113
115
  return o
114
116
  }
115
117
 
116
- // A path segment such as .git or .claude. Self-protection (classify.ts protectedCommand) blocks every shell command that
117
- // names one, so a hint `<cliCmd> run test` with such a segment could never run.
118
- const PROTECTED_SEGMENT = /(^|[^a-z0-9_.\-])\.(git|claude|cursor|codex|gemini|agents)([^a-z0-9_\-]|$)/i
118
+ // A path segment such as .git, .claude or .husky. Self-protection (classify.ts protectedCommand) blocks every shell
119
+ // command that names one, so a hint `<cliCmd> run test` with such a segment could never run.
120
+ const PROTECTED_SEGMENT = /(^|[^a-z0-9_.\-])\.(git|claude|cursor|codex|gemini|agents|husky|lefthook)([^a-z0-9_\-]|$)/i
119
121
 
120
122
  /** Why a cliCmd value cannot be used, or null. */
121
123
  export function cliCmdProblem(cmd ) {
@@ -135,7 +137,7 @@ export function isSafeRef(ref ) {
135
137
  }
136
138
 
137
139
  export function makeConfig(a
138
- ) {
140
+ ) {
139
141
  const profile = a.profile ?? 'default'
140
142
  const paths = PROFILES[profile]
141
143
  if (!paths) throw new ConfigError(`unknown profile ${JSON.stringify(profile)}; known: ${Object.keys(PROFILES).join(', ')}`)
@@ -145,7 +147,7 @@ export function makeConfig(a
145
147
  version: 1, profile, buildCmd: a.buildCmd.trim(), fullTestCmd: a.fullTestCmd.trim(),
146
148
  maxRetries: a.maxRetries ?? DEFAULTS.maxRetries, cap: a.cap ?? DEFAULTS.cap, costPerCall: a.costPerCall ?? DEFAULTS.costPerCall,
147
149
  paths: {tests: [...paths.tests], testConfig: [...paths.testConfig], secrets: [...paths.secrets]},
148
- safeTools: [...DEFAULT_SAFE_TOOLS],
150
+ safeTools: [...(a.safeTools ?? DEFAULT_SAFE_TOOLS)],
149
151
  ...(baseRef && baseRef !== 'HEAD' ? {baseRef} : {}),
150
152
  ...(cliCmd !== undefined ? {cliCmd} : {}),
151
153
  ...(a.stopGate !== undefined ? {stopGate: a.stopGate} : {}),