stopbar 1.1.3 → 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.
package/dist/commands.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import {cpSync, existsSync, mkdirSync, rmSync} from 'node:fs'
5
5
  import {join} from 'node:path'
6
6
  import {hasChain, protectedCommand} from './classify.js'
7
- import {CLAUDE_POST_MATCHER, claudeHooks, hookCommand, installHooks, parseTargets} from './integrations.js'
7
+ import {CLAUDE_POST_MATCHER, claudeHooks, hookCommand, installHooks, parseTargets, } from './integrations.js'
8
8
  import {cliOf, ConfigError, DEFAULT_SAFE_TOOLS, makeConfig, PROFILES} from './config.js'
9
9
  import {decode, initKernel, kstep, MACHINE, } from './engine.js'
10
10
  import {classifyChanges, whyBlocked} from './hook.js'
@@ -67,7 +67,8 @@ export function pinRuntime(r ) {
67
67
  const dst = join(r.stateDir, 'runtime')
68
68
  rmSync(dst, {recursive: true, force: true})
69
69
  mkdirSync(dst, {recursive: true})
70
- for (const n of ['bin', 'dist']) cpSync(join(PKG_ROOT, n), join(dst, n), {recursive: true})
70
+ // the .d.ts files in dist/ only type the tests (npm run typecheck); the runtime never loads them
71
+ for (const n of ['bin', 'dist']) cpSync(join(PKG_ROOT, n), join(dst, n), {recursive: true, filter: (f) => !f.endsWith('.d.ts')})
71
72
  for (const n of ['package.json', 'LICENSE']) if (existsSync(join(PKG_ROOT, n))) cpSync(join(PKG_ROOT, n), join(dst, n))
72
73
  return dst
73
74
  }
@@ -82,11 +83,11 @@ export function init(o ) {
82
83
  for (const [k, v] of [['--build', buildCmd], ['--test', fullTestCmd]]) {
83
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`}
84
85
  }
85
- for (const f of ['cli', 'stop-gate']) 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']) if (o.has(f) && o.get(f) === undefined) return {code: 1, msg: `--${f} needs a value`}
86
87
  let cfg
87
88
  try {
88
89
  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'),
89
- cliCmd: o.get('cli'), stopGate: o.get('stop-gate')})
90
+ cliCmd: o.get('cli'), stopGate: o.get('stop-gate'), requireRun: o.has('require-run')})
90
91
  } catch (e) { if (e instanceof ConfigError) return {code: 1, msg: e.message}; throw e }
91
92
  if (existsSync(paths(repo).config) && !o.has('force')) return {code: 1, msg: `already initialised (${paths(repo).config}); use --force to replace config and state`}
92
93
  const pin = !o.has('no-pin')
@@ -101,7 +102,12 @@ export function init(o ) {
101
102
  return {code: 1, msg: `--base-ref ${JSON.stringify(cfg.baseRef)} does not resolve to a commit/tree in ${repo.root}`}
102
103
  }
103
104
  const hooksOpt = o.get('hooks')
104
- const targets = hooksOpt === undefined ? [] : parseTargets(hooksOpt) // validated before anything is written
105
+ const named = hooksOpt === undefined ? [] : parseTargets(hooksOpt) // validated before anything is written
106
+ if (o.has('no-git-hooks') && named.includes('git')) return {code: 1, msg: '--no-git-hooks and --hooks ...git exclude each other'}
107
+ // the git hooks close what an agent hook cannot see (git aliases, merge, cherry-pick, am, commit-tree before a push):
108
+ // added to every --hooks <client> unless --no-git-hooks
109
+ const gitByDefault = named.length > 0 && !named.includes('git') && !o.has('no-git-hooks')
110
+ const targets = gitByDefault ? [...named, 'git'] : named
105
111
  mkdirSync(repo.stateDir, {recursive: true})
106
112
  return withLock(repo, () => {
107
113
  const {s, snap} = freshWithSnap(repo, cfg)
@@ -110,14 +116,17 @@ export function init(o ) {
110
116
  writeState(repo, s)
111
117
  const runtime = pin ? pinRuntime(repo) : PKG_ROOT
112
118
  const command = hookCommand(runtime)
113
- appendEvent(repo, {source: 'human:init', cfg, runtime, version: VERSION, kernel: MACHINE})
119
+ appendEvent(repo, {source: 'human:init', cfg, runtime, version: VERSION, kernel: MACHINE, ...(targets.length ? {hooks: targets} : {})})
114
120
  const warn = countDirtyTests(repo, s, dirty, 'init:dirty-tests')
115
121
  const lines = [`Stopbar ${VERSION} initialised in ${repo.stateDir}`, ` profile ${cfg.profile}; build: ${cfg.buildCmd}; full tests: ${cfg.fullTestCmd}${cfg.baseRef ? `; base ref: ${cfg.baseRef}` : ''}`,
116
- ` stop gate: ${cfg.stopGate ?? 'block'}; gate hints use: ${cliOf(cfg)} run build|test`,
122
+ ` 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)' : ''}`,
117
123
  ` hooks run: ${command}`]
118
- if (targets.length) for (const l of installHooks(repo, targets, runtime, o.has('force-hooks'))) lines.push(` hooks written: ${l}`)
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}`)
119
126
  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))
120
- lines.push(...warn, 'Next: restart the agent in this repository and run `stopbar doctor`.')
127
+ if (gitByDefault) lines.push(' git hooks (pre-commit, pre-push) were added to --hooks by default; pass --no-git-hooks to skip them')
128
+ 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')
129
+ lines.push(...warns.map((w) => ` ${w}`), ...warn, 'Next: restart the agent in this repository and run `stopbar doctor`.')
121
130
  return {code: 0, msg: lines.join('\n')}
122
131
  })
123
132
  }
@@ -158,21 +167,29 @@ export function secretReason(repo )
158
167
  return {text: `matched ${pattern} (${path}) in ${tool} at rev ${hit.treeRev}`, pattern, path, tool, revision: hit.treeRev}
159
168
  }
160
169
 
161
- function statusText(repo , cfg , s ) {
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
+ * at the next hook (pre:commit-sync), so status never says `allowed` then. */
172
+ function statusText(repo , cfg , s , now , differs ) {
162
173
  const v = decode(s.kernel)
163
174
  const yn = (b ) => (b ? 'yes' : 'no')
164
175
  const ok = (rev ) => (rev === v.treeRev ? `ok at revision ${rev}` : 'not at the current revision')
165
- const commit = v.halted ? 'blocked: session halted' : v.buildOkRev === v.treeRev && v.testsOkRev === v.treeRev && !v.testsTainted ? 'allowed' : `blocked: ${whyBlocked(v, cfg)}`
176
+ const uncounted = now.id !== s.snapshot
177
+ const green = v.buildOkRev === v.treeRev && v.testsOkRev === v.treeRev && !v.testsTainted
178
+ const commit = v.halted ? 'blocked: session halted' : !green ? `blocked: ${whyBlocked(v, cfg)}`
179
+ : uncounted ? 'blocked: uncommitted working-tree changes not yet counted (run build and full tests on the current tree)' : 'allowed'
166
180
  const torn = readEvents(repo).torn.length
167
181
  return [
168
182
  `Stopbar ${VERSION} repo ${repo.root}`,
169
183
  `revision ${v.treeRev} (tree ${s.snapshot.slice(0, 12)})${cfg.baseRef ? ` base ref ${cfg.baseRef}` : ''}`,
184
+ ...(uncounted ? [` working tree has uncounted changes since revision ${v.treeRev}; gates will be re-checked on the next hook`] : []),
170
185
  `build ${ok(v.buildOkRev)} (${cfg.buildCmd})`,
171
186
  `full tests ${ok(v.testsOkRev)} (${cfg.fullTestCmd})`,
172
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\`)`] : []),
173
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}`,
174
190
  `commit ${commit}`,
175
191
  `stop gate ${cfg.stopGate ?? 'block'}${cfg.stopGate === 'warn' ? ' (Stop only warns; git commit and git push stay blocked until the gates pass)' : ''}`,
192
+ ...(cfg.requireRun ? ['requireRun true (the build and full test gates count only through stopbar run build|test)'] : []),
176
193
  ...(torn ? [`event log ${torn} torn line(s) kept as they are (see stopbar doctor)`] : []),
177
194
  ].join('\n')
178
195
  }
@@ -191,8 +208,14 @@ export function human(cmd , o ) {
191
208
  }
192
209
  const s = readState(repo)
193
210
  if (cmd === 'status') {
194
- return {code: 0, msg: o.has('json') ? JSON.stringify({version: VERSION, repo: repo.root, stateDir: repo.stateDir, config: cfg, stopGate: cfg.stopGate ?? 'block', snapshot: s.snapshot, params: s.params, kernel: decode(s.kernel),
195
- secretRead: decode(s.kernel).secretTainted ? secretReason(repo) : null}, null, 1) : statusText(repo, cfg, s)}
211
+ // the working tree now (read-only for state.json, as in attest: only the private snapshot index is refreshed)
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
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),
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)}
196
219
  }
197
220
  let res
198
221
  if (cmd === 'approve-tests') {
package/dist/config.js CHANGED
@@ -21,13 +21,16 @@ import {globToRegExp} from './glob.js'
21
21
 
22
22
 
23
23
 
24
+
25
+
26
+
24
27
 
25
28
 
26
29
  export const STOP_GATES = ['block', 'warn']
27
30
  /** Hint command when config.cliCmd is not set: uses an installed stopbar only, never downloads it from the registry. */
28
31
  export const DEFAULT_CLI = 'npx --no-install stopbar'
29
32
 
30
- const TEST_COMMON = ['**/tests/**', '**/test/**', '**/__tests__/**']
33
+ const TEST_COMMON = ['**/tests/**', '**/test/**', '**/__tests__/**', 'scripts/*test*']
31
34
  const TEST_JS = ['**/*.test.*', '**/*.spec.*', '**/e2e/**']
32
35
  const TEST_PY = ['**/test_*.py', '**/*_test.py']
33
36
  const TEST_OTHER = ['**/*_test.go', '**/*_test.rs', '**/*Test.java', '**/*Tests.cs']
@@ -106,6 +109,7 @@ export function validateConfig(c ) {
106
109
  if (o.stopGate !== undefined && !STOP_GATES.includes(o.stopGate )) {
107
110
  throw new ConfigError(`config.stopGate must be ${STOP_GATES.map((g) => JSON.stringify(g)).join(' or ')}, got ${JSON.stringify(o.stopGate)}`)
108
111
  }
112
+ if (o.requireRun !== undefined && typeof o.requireRun !== 'boolean') throw new ConfigError(`config.requireRun must be true or false, got ${JSON.stringify(o.requireRun)}`)
109
113
  return o
110
114
  }
111
115
 
@@ -131,7 +135,7 @@ export function isSafeRef(ref ) {
131
135
  }
132
136
 
133
137
  export function makeConfig(a
134
- ) {
138
+ ) {
135
139
  const profile = a.profile ?? 'default'
136
140
  const paths = PROFILES[profile]
137
141
  if (!paths) throw new ConfigError(`unknown profile ${JSON.stringify(profile)}; known: ${Object.keys(PROFILES).join(', ')}`)
@@ -145,5 +149,6 @@ export function makeConfig(a
145
149
  ...(baseRef && baseRef !== 'HEAD' ? {baseRef} : {}),
146
150
  ...(cliCmd !== undefined ? {cliCmd} : {}),
147
151
  ...(a.stopGate !== undefined ? {stopGate: a.stopGate} : {}),
152
+ ...(a.requireRun === true ? {requireRun: true} : {}),
148
153
  })
149
154
  }
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 = {}
@@ -69,19 +79,19 @@ function stopbarCommands(events )
69
79
  return out
70
80
  }
71
81
 
72
- /** Other clients and the git fallback. Returns how many have Stopbar hooks. */
73
- function checkOtherClients(repo , add ) {
82
+ /** Other clients and the git fallback. Returns how many clients have Stopbar hooks, and how many Stopbar git hooks exist. */
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,14 +99,31 @@ 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'))
98
- if (gh.length) { found++; add(gh.length === 2 ? 'OK' : 'WARN', 'hooks git', `${gh.join(', ')} in ${dir}${gh.length === 2 ? '' : ' (one of pre-commit, pre-push is missing)'}`) }
99
- return found
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')))
111
+ const lacking = ['pre-commit', 'pre-push'].filter((n) => !gh.includes(n))
112
+ // the git hooks close what an agent hook cannot see: git aliases, and on pre-push merge, cherry-pick, am and commit-tree
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
+ }
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\``)
126
+ return {clients: found, git: gh.length}
100
127
  }
101
128
 
102
129
  /** The real hook pipeline (in process) on a scratch repository inside <git-dir>/stopbar/doctor-run. */
@@ -142,13 +169,16 @@ export async function doctor(o )
142
169
  add(maj > 22 || (maj === 22 && min >= 18) ? 'OK' : 'FAIL', 'node', `v${process.versions.node} (needs >= 22.18)`)
143
170
  try { add('OK', 'git', execFileSync('git', ['--version'], {encoding: 'utf8'}).trim()) } catch { add('FAIL', 'git', 'git not found on PATH') }
144
171
  add(MACHINE.name === 'stopbar_kernel_none' ? 'OK' : 'FAIL', 'kernel', `${MACHINE.name}, kernel.ts sha256 ${MACHINE.kernelSha256.slice(0, 16)}, machine sha256 ${MACHINE.machineSha256.slice(0, 16)}`)
145
- if (existsSync(join(PKG_ROOT, 'node_modules', 'gdp-wired')) && existsSync(join(PKG_ROOT, 'dist', 'kernel.js'))) {
172
+ // npm may hoist gdp-wired next to this package (npm install stopbar): resolve it as Node does, never by a fixed path
173
+ let prover = false
174
+ try { import.meta.resolve('gdp-wired/machine'); prover = true } catch { /* not resolvable: a pinned runtime has no node_modules */ }
175
+ if (prover && existsSync(join(PKG_ROOT, 'dist', 'kernel.js'))) {
146
176
  try {
147
177
  const {checkGenerated} = await import('./verify.js')
148
178
  const g = await checkGenerated(500)
149
- 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`)
150
180
  } catch (e) { add('WARN', 'kernel link', `not checked: ${(e ).message}`) }
151
- } else add('WARN', 'kernel link', 'gdp-wired not installed next to this copy (pinned runtime): run `stopbar prove` in the package')
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')
152
182
 
153
183
  let repo = null
154
184
  try { repo = findRepo(o.repo ?? process.cwd()); add('OK', 'repository', `${repo.root} (state in ${repo.stateDir})`) } catch (e) { add('FAIL', 'repository', (e ).message) }
@@ -158,7 +188,8 @@ export async function doctor(o )
158
188
  const cfg = readConfig(repo); cfgOk = true
159
189
  add('OK', 'config.json', `profile ${cfg.profile}; build \`${cfg.buildCmd}\`; full tests \`${cfg.fullTestCmd}\`; maxRetries ${cfg.maxRetries}; cap ${cfg.cap}; ` +
160
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}` : ''}; ` +
161
- `stopGate ${cfg.stopGate ?? 'block'}; cli ${cliOf(cfg)}`)
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)'))
162
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')
163
194
  const safe = cfg.safeTools ?? DEFAULT_SAFE_TOOLS
164
195
  const missing = DEFAULT_SAFE_TOOLS.filter((t) => !safe.includes(t))
@@ -180,7 +211,11 @@ export async function doctor(o )
180
211
  } else if (cfgOk) add('WARN', 'pinned runtime', 'none: hooks run an unpinned copy (init --no-pin)')
181
212
  const others = checkOtherClients(repo, add)
182
213
  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 })
183
- if (claudeHas || others === 0) checkHooks(repo.root, add) // without any client hooks, report the Claude Code ones as missing (v1.0 output)
214
+ // Claude Code hooks named at the last init or upgrade must be there, also when other hooks (now the git hooks by
215
+ // default) exist; without any client hooks, the Claude Code ones are reported as missing (v1.0 output)
216
+ const named = ev.events.filter((e) => (e.source === 'human:init' || e.source === 'human:upgrade') && Array.isArray(e.hooks)).at(-1)?.hooks
217
+ const wantClaude = !!named?.some((t) => t === 'claude' || t === 'claude-project')
218
+ if (claudeHas || (others.clients === 0 && (others.git === 0 || wantClaude))) checkHooks(repo.root, add)
184
219
  try { dryRun(repo.stateDir, add) } catch (e) { add('FAIL', 'dry run', String(e)) }
185
220
  }
186
221
  const fails = checks.filter((c) => c.status === 'FAIL').length, warns = checks.filter((c) => c.status === 'WARN').length
package/dist/hook.js CHANGED
@@ -13,6 +13,23 @@ import {codeDirs} from './pkg.js'
13
13
 
14
14
 
15
15
 
16
+ /** A hook event: Claude Code's JSON object (adapters translate other clients into it). Fields are read with guards. */
17
+
18
+ /** Stopbar's own fields on an event: set by the adapters and by `stopbar run`, never by the agent's client. */
19
+
20
+
21
+ const obj = (x ) => (x && typeof x === 'object' && !Array.isArray(x) ? x : {})
22
+ const strings = (...xs ) => xs.flatMap((x) => (Array.isArray(x) ? x : [x])).filter((x) => typeof x === 'string' && x.length > 0)
23
+ function metaOf(x ) {
24
+ const m = obj(x)
25
+ return {
26
+ ...(typeof m.adapter === 'string' ? {adapter: m.adapter} : {}),
27
+ ...(m.rawKeys !== undefined ? {rawKeys: m.rawKeys} : {}),
28
+ ...(typeof m.expectedSnapshot === 'string' ? {expectedSnapshot: m.expectedSnapshot} : {}),
29
+ ...(typeof m.expectedRev === 'number' ? {expectedRev: m.expectedRev} : {}),
30
+ ...(m.requireExitCode === true ? {requireExitCode: true} : {}),
31
+ }
32
+ }
16
33
 
17
34
  const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
18
35
  const READ_TOOLS = new Set(['Read', 'Grep', 'Glob', 'LS'])
@@ -77,42 +94,48 @@ function syncTree(ctx , cost , source ) {
77
94
 
78
95
  const block = (reason ) => ({code: 2, msg: `BLOCK (stopbar): ${reason}`})
79
96
 
80
- function isBackgroundInput(ti ) {
81
- return ti?.run_in_background === true || ti?.run_in_background === 'true' || ti?.background === true
97
+ function isBackgroundInput(ti ) {
98
+ return ti.run_in_background === true || ti.run_in_background === 'true' || ti.background === true
82
99
  }
83
- function isBackgroundResponse(tr ) {
84
- if (!tr || typeof tr !== 'object') return false
85
- return (typeof tr.backgroundTaskId === 'string' && tr.backgroundTaskId.length > 0) ||
86
- (typeof tr.background_task_id === 'string' && tr.background_task_id.length > 0) ||
87
- tr.isAsync === true || tr.background === true
100
+ function isBackgroundResponse(tr ) {
101
+ const r = obj(tr)
102
+ return (typeof r.backgroundTaskId === 'string' && r.backgroundTaskId.length > 0) ||
103
+ (typeof r.background_task_id === 'string' && r.background_task_id.length > 0) ||
104
+ r.isAsync === true || r.background === true
88
105
  }
89
106
 
90
107
  // ---------------------------------------------------------------- PreToolUse
91
- function pre(ctx , input ) {
92
- const tool = String(input.tool_name ?? ''), ti = input.tool_input ?? {}
108
+ function pre(ctx , input ) {
109
+ const tool = String(input.tool_name ?? ''), ti = obj(input.tool_input)
93
110
  const {repo, cfg} = ctx
111
+ const shell = tool === 'PowerShell' ? 'powershell' : 'bash'
94
112
  // self-protection: unconditional, before the kernel, also when halted
95
113
  if (EDIT_TOOLS.has(tool)) {
96
- const list = [ti.file_path, ti.notebook_path, ti.path, ...(Array.isArray(ti.file_paths) ? ti.file_paths : [])]
97
- for (const p of list.filter((x) => typeof x === 'string' && x)) {
114
+ for (const p of strings(ti.file_path, ti.notebook_path, ti.path, ti.file_paths)) {
98
115
  const why = K.protectedPath(resolve(repo.root, p), repo.root, ctx.protect)
99
116
  if (why) { appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: why, path: p}); return block(`writing ${p} is not allowed: ${why}. Ask the human.`) }
100
117
  }
101
118
  }
102
119
  if (SHELL_TOOLS.has(tool)) {
103
120
  const cmd = String(ti.command ?? '')
104
- const why = K.protectedCommand(K.commandForSelfProtect(cmd, tool === 'PowerShell' ? 'powershell' : 'bash'), ctx.protect)
121
+ const why = K.protectedCommand(K.commandForSelfProtect(cmd, shell), ctx.protect, shell)
105
122
  if (why) { appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: why}); return block(`${why}. Ask the human.`) }
106
123
  }
107
124
  const v = decode(ctx.s.kernel)
125
+ // local tools in config.safeTools (task list, turn summary, messages between local sessions) never take a kernel step,
126
+ // so they stay allowed while halted: the agent can still ask a human for `stopbar resume`. File, shell and every
127
+ // other tool stay paused.
128
+ if (!EDIT_TOOLS.has(tool) && !READ_TOOLS.has(tool) && !SHELL_TOOLS.has(tool) && matchAny(tool, cfg.safeTools ?? DEFAULT_SAFE_TOOLS)) {
129
+ if (v.halted) appendEvent(repo, {source: 'pre', tool, wrapper: 'ALLOW', reason: 'safe tool while halted'})
130
+ return {code: 0}
131
+ }
108
132
  if (v.halted) {
109
133
  appendEvent(repo, {source: 'pre', tool, wrapper: 'PAUSE', reason: 'halted'})
110
134
  return {code: 2, msg: `PAUSE (stopbar): the session is halted (testFails=${v.testFails}, buildFails=${v.buildFails}, spent=${v.spent}/${v.capNow}). A human must run: stopbar resume --extra <n>`}
111
135
  }
112
136
  const cost = cfg.costPerCall
113
137
  if (READ_TOOLS.has(tool)) {
114
- const ps = [ti.file_path, ti.path, ti.glob, ti.pattern, ...(Array.isArray(ti.file_paths) ? ti.file_paths : [])].filter((x) => typeof x === 'string' && x)
115
- for (const p of ps) {
138
+ for (const p of strings(ti.file_path, ti.path, ti.glob, ti.pattern, ti.file_paths)) {
116
139
  const pattern = K.secretPattern(p, cfg.paths)
117
140
  if (pattern) { step(ctx, {op: 'READ_SECRET', cost}, `pre:${tool}`, {secret: {pattern, path: p, tool}}); break }
118
141
  }
@@ -123,7 +146,7 @@ function pre(ctx , input ) {
123
146
  const cmd = String(ti.command ?? '')
124
147
  const base = typeof input.cwd === 'string' && input.cwd ? input.cwd : repo.root
125
148
  const exists = (t ) => existsSync(resolve(base, t)) || existsSync(resolve(repo.root, t))
126
- const k = K.classifyBash(cmd, cfg, tool === 'PowerShell' ? 'powershell' : 'bash', exists)
149
+ const k = K.classifyBash(cmd, cfg, shell, exists)
127
150
  if (k.kind === 'commit-chained') {
128
151
  appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: `chained commit (${k.reason})`})
129
152
  return block(`run \`git commit\` / \`git push\` as a single command (${k.reason}): no &&, ;, |, redirections or $(...). ` +
@@ -160,8 +183,7 @@ function pre(ctx , input ) {
160
183
  }
161
184
  return {code: 0}
162
185
  }
163
- if (OUTBOUND(tool)) {
164
- if (matchAny(tool, cfg.safeTools ?? DEFAULT_SAFE_TOOLS)) return {code: 0} // local tools listed in config.safeTools
186
+ if (OUTBOUND(tool)) { // tools in config.safeTools returned above
165
187
  const {after} = step(ctx, {op: 'SHELL', risky: true, cost}, `pre:${tool}`)
166
188
  if (after.decision === 'PAUSE') return {code: 2, msg: `PAUSE (stopbar): ${tool} is outbound and a secret was read (or the budget is spent); a human runs \`stopbar approve-shell\` or \`stopbar resume\``}
167
189
  }
@@ -171,27 +193,27 @@ function pre(ctx , input ) {
171
193
  // ---------------------------------------------------------------- PostToolUse / PostToolUseFailure
172
194
  // Claude Code sends PostToolUse after success and PostToolUseFailure after an error (non-zero exit of Bash).
173
195
  // PostToolUse carries no exit code: success unless is_error / interrupted. Failure is the event type itself.
174
- function exitCodeOf(tr ) {
175
- if (!tr || typeof tr !== 'object') return undefined
176
- for (const k of ['exitCode', 'exit_code', 'returnCode', 'code']) if (typeof tr[k] === 'number') return tr[k]
196
+ function exitCodeOf(tr ) {
197
+ const r = obj(tr)
198
+ for (const k of ['exitCode', 'exit_code', 'returnCode', 'code']) { const v = r[k]; if (typeof v === 'number') return v }
177
199
  return undefined
178
200
  }
179
201
 
180
- function post(ctx , input , failure ) {
181
- const tool = String(input.tool_name ?? ''), ti = input.tool_input ?? {}
202
+ function post(ctx , input , failure ) {
203
+ const tool = String(input.tool_name ?? ''), ti = obj(input.tool_input)
182
204
  const {repo, cfg} = ctx
183
205
  const msgs = []
184
206
  if (SHELL_TOOLS.has(tool)) {
185
207
  const k = K.classifyBash(String(ti.command ?? ''), cfg, tool === 'PowerShell' ? 'powershell' : 'bash')
186
- const tr = input.tool_response
187
- const meta = input.stopbar ?? {}
188
- appendEvent(repo, {source: `payload:${input.hook_event_name}`, tool, ...(meta.adapter ? {adapter: meta.adapter, rawKeys: meta.rawKeys} : {inputKeys: Object.keys(input)}),
208
+ const tr = input.tool_response, r = obj(tr)
209
+ const meta = metaOf(input.stopbar)
210
+ appendEvent(repo, {source: `payload:${String(input.hook_event_name)}`, tool, ...(meta.adapter ? {adapter: meta.adapter, rawKeys: meta.rawKeys} : {inputKeys: Object.keys(input)}),
189
211
  toolResponseKeys: tr && typeof tr === 'object' ? Object.keys(tr) : typeof tr})
190
212
  const bg = isBackgroundInput(ti) || isBackgroundResponse(tr)
191
213
  const staleRun = typeof meta.expectedSnapshot === 'string' &&
192
214
  (meta.expectedSnapshot !== ctx.s.snapshot || (typeof meta.expectedRev === 'number' && meta.expectedRev !== decode(ctx.s.kernel).treeRev))
193
215
  const code = exitCodeOf(tr)
194
- const flagged = input.is_error === true || tr?.is_error === true || tr?.interrupted === true
216
+ const flagged = input.is_error === true || r.is_error === true || r.interrupted === true
195
217
  // some clients send the same post event for success and failure: then only an explicit exit code 0 is a pass
196
218
  const unknown = meta.requireExitCode === true && code === undefined
197
219
  const passed = failure ? false : code !== undefined ? code === 0 : !flagged && !unknown
@@ -199,10 +221,15 @@ function post(ctx , input , failure ) {
199
221
  if (failure && input.is_interrupt === true) {
200
222
  // Ctrl+C by the user: not a failed gate and not a retry; the tree is still checked below
201
223
  appendEvent(repo, {source: 'post:user-interrupt', tool, kind: k.kind})
224
+ } else if (cfg.requireRun === true && meta.adapter !== 'run' && (k.kind === 'build' || k.kind === 'fulltest')) {
225
+ // config.requireRun: a gate counts only through `stopbar run build|test`, never from the agent's own shell
226
+ const which = k.kind === 'build' ? 'build' : 'test'
227
+ appendEvent(repo, {source: 'post:require-run', tool, kind: k.kind, ...(meta.adapter ? {adapter: meta.adapter} : {})})
228
+ msgs.push(`NOTE (stopbar): this repository records gates only through \`${runHint(cfg, which)}\` (config.requireRun), so \`${k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd}\` run from the agent's shell is not recorded. Run \`${runHint(cfg, which)}\` instead: it runs the same command and records its real exit status.`)
202
229
  } else if (!failure && bg && (k.kind === 'build' || k.kind === 'fulltest' || (k.kind === 'shell' && k.partialTests))) {
203
230
  // a background launch fires PostToolUse before the process finishes (e.g. Claude Code backgroundTaskId): never count it
204
231
  appendEvent(repo, {source: 'post:background-gate-ignored', tool, kind: k.kind === 'shell' ? 'partial-tests' : k.kind,
205
- ...(typeof tr?.backgroundTaskId === 'string' ? {backgroundTaskId: tr.backgroundTaskId} : typeof tr?.background_task_id === 'string' ? {backgroundTaskId: tr.background_task_id} : {})})
232
+ ...(typeof r.backgroundTaskId === 'string' ? {backgroundTaskId: r.backgroundTaskId} : typeof r.background_task_id === 'string' ? {backgroundTaskId: r.background_task_id} : {})})
206
233
  if (k.kind !== 'shell') {
207
234
  const which = k.kind === 'build' ? 'build' : 'test'
208
235
  const gate = k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd
@@ -237,7 +264,7 @@ function post(ctx , input , failure ) {
237
264
  // ---------------------------------------------------------------- Stop: "I am done" = the COMMIT gate when the tree differs from HEAD
238
265
  // stopGate 'warn': the turn may end with unverified changes (e.g. to ask the human a question). Only the Stop hook
239
266
  // changes: no COMMIT step is taken, so `git commit` / `git push` in PreToolUse and the git hooks stay fully gated.
240
- function stop(ctx , input ) {
267
+ function stop(ctx , input ) {
241
268
  if (input.stop_hook_active) return {code: 0}
242
269
  syncTree(ctx, 0, 'stop:sync')
243
270
  if (!differsFromHead(ctx.repo, ctx.now .entries)) return {code: 0}
@@ -263,14 +290,14 @@ export function failMsg(e ) {
263
290
 
264
291
  /** One hook call with Claude Code's JSON on stdin (the v1.0 interface). Never throws. */
265
292
  export function runHook(raw , t0 = performance.now()) {
266
- let input
293
+ let input
267
294
  try { input = JSON.parse(raw) } catch (e) { return {code: 2, msg: `STOPBAR FAIL-CLOSED: hook input is not JSON (${(e ).message})`} }
268
295
  if (!input || typeof input !== 'object') return {code: 2, msg: 'STOPBAR FAIL-CLOSED: hook input must be a JSON object'}
269
- return runEvent(input, t0)
296
+ return runEvent(input , t0)
270
297
  }
271
298
 
272
299
  /** One normalised hook event (Claude Code's shape; adapters translate other clients into it). Never throws. */
273
- export function runEvent(input , t0 = performance.now()) {
300
+ export function runEvent(input , t0 = performance.now()) {
274
301
  try {
275
302
  const repo = findRepo(typeof input.cwd === 'string' && input.cwd ? input.cwd : process.cwd())
276
303
  const g0 = gitCalls
@@ -283,7 +310,7 @@ export function runEvent(input , t0 = performance.now()) {
283
310
  : ev === 'PostToolUseFailure' ? post(ctx, input, true)
284
311
  : ev === 'Stop' ? stop(ctx, input) : {code: 0}
285
312
  if (ctx.dirty) writeState(repo, ctx.s)
286
- appendEvent(repo, {source: 'hook-timing', event: ev, tool: input.tool_name, ...(input.stopbar?.adapter ? {adapter: input.stopbar.adapter} : {}), exit: res.code, gitCalls: gitCalls - g0,
313
+ appendEvent(repo, {source: 'hook-timing', event: ev, tool: input.tool_name, ...(metaOf(input.stopbar).adapter ? {adapter: metaOf(input.stopbar).adapter} : {}), exit: res.code, gitCalls: gitCalls - g0,
287
314
  handlerMs: Math.round(performance.now() - t0), processMs: Math.round(process.uptime() * 1000)})
288
315
  return res
289
316
  })