stopbar 1.0.0 → 1.1.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/doctor.js CHANGED
@@ -3,14 +3,14 @@
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 {join} from 'node:path'
6
+ import {isAbsolute, join} from 'node:path'
7
7
  import {hasChain} from './classify.js'
8
8
  import {fresh, HOOK_MATCHERS} from './commands.js'
9
- import {makeConfig} from './config.js'
9
+ import {DEFAULT_SAFE_TOOLS, makeConfig} from './config.js'
10
10
  import {decode, MACHINE} from './engine.js'
11
11
  import {runHook} from './hook.js'
12
12
  import {PKG_ROOT} from './pkg.js'
13
- import {FailClosed, findRepo, } from './repo.js'
13
+ import {FailClosed, findRepo, hasRefTree, } from './repo.js'
14
14
  import {paths, readConfig, readEvents, readState, VERSION, writeConfig, writeState} from './store.js'
15
15
 
16
16
 
@@ -49,6 +49,56 @@ function checkHooks(root , add
49
49
  }
50
50
  }
51
51
 
52
+ const STOPBAR = /stopbar(\.mjs)?"?\s+(hook|git-hook)\b/
53
+ 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' }
57
+ }
58
+ /** Commands of Stopbar hooks per event, from any nesting of {command} objects under each event. */
59
+ function stopbarCommands(events ) {
60
+ const out = {}
61
+ const walk = (ev , x ) => {
62
+ if (Array.isArray(x)) { for (const y of x) walk(ev, y); return }
63
+ if (!x || typeof x !== 'object') return
64
+ const o = x
65
+ if (typeof o.command === 'string' && STOPBAR.test(o.command)) (out[ev] ??= []).push(o.command)
66
+ if (o.hooks) walk(ev, o.hooks)
67
+ }
68
+ for (const [ev, v] of Object.entries(events ?? {})) walk(ev, v)
69
+ return out
70
+ }
71
+
72
+ /** Other clients and the git fallback. Returns how many have Stopbar hooks. */
73
+ function checkOtherClients(repo , add ) {
74
+ 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']],
80
+ ]
81
+ for (const [name, f, events, need] of clients) {
82
+ const j = readJsonOrInvalid(f)
83
+ if (j === null) continue
84
+ if (j === 'invalid') { add('FAIL', `hooks ${name}`, `${f} is not valid JSON`); found++; continue }
85
+ const cmds = stopbarCommands(events(j))
86
+ if (!Object.keys(cmds).length) continue
87
+ found++
88
+ const missing = need.filter((e) => !cmds[e]?.length)
89
+ const script = scriptOf(Object.values(cmds)[0][0])
90
+ if (missing.length) add('FAIL', `hooks ${name}`, `${f}: no Stopbar hook for ${missing.join(', ')}`)
91
+ 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`)
93
+ else add('OK', `hooks ${name}`, `${need.join(', ')} (${f.replace(/\\/g, '/').split('/').slice(-2).join('/')})`)
94
+ }
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
100
+ }
101
+
52
102
  /** The real hook pipeline (in process) on a scratch repository inside <git-dir>/stopbar/doctor-run. */
53
103
  function dryRun(base , add ) {
54
104
  const dir = join(base, 'doctor-run')
@@ -107,7 +157,8 @@ export async function doctor(o )
107
157
  try {
108
158
  const cfg = readConfig(repo); cfgOk = true
109
159
  add('OK', 'config.json', `profile ${cfg.profile}; build \`${cfg.buildCmd}\`; full tests \`${cfg.fullTestCmd}\`; maxRetries ${cfg.maxRetries}; cap ${cfg.cap}; ` +
110
- `${cfg.paths.tests.length}/${cfg.paths.testConfig.length}/${cfg.paths.secrets.length} test/config/secret patterns`)
160
+ `${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
+ if (cfg.baseRef) add(hasRefTree(repo.root, cfg.baseRef) ? 'OK' : 'FAIL', 'baseRef', hasRefTree(repo.root, cfg.baseRef) ? `${cfg.baseRef} resolves to a tree` : `${cfg.baseRef} does not resolve in git (existing-test checks will fail closed)`)
111
162
  for (const [k, v] of [['buildCmd', cfg.buildCmd], ['fullTestCmd', cfg.fullTestCmd]]) if (hasChain(v)) add('FAIL', 'config.json', `${k} has shell operators: it can never pass as a gate`)
112
163
  try {
113
164
  const s = readState(repo), v = decode(s.kernel)
@@ -122,7 +173,9 @@ export async function doctor(o )
122
173
  const same = existsSync(join(PKG_ROOT, 'dist', 'kernel.gen.js')) && sha(rt) === sha(join(PKG_ROOT, 'dist', 'kernel.gen.js'))
123
174
  add(same ? 'OK' : 'WARN', 'pinned runtime', `${join(repo.stateDir, 'runtime')}${same ? ' (same kernel as this package)' : ' differs from this package: a human runs `stopbar init --force ...` to re-pin'}`)
124
175
  } else if (cfgOk) add('WARN', 'pinned runtime', 'none: hooks run an unpinned copy (init --no-pin)')
125
- checkHooks(repo.root, add)
176
+ const others = checkOtherClients(repo, add)
177
+ 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 })
178
+ if (claudeHas || others === 0) checkHooks(repo.root, add) // without any client hooks, report the Claude Code ones as missing (v1.0 output)
126
179
  try { dryRun(repo.stateDir, add) } catch (e) { add('FAIL', 'dry run', String(e)) }
127
180
  }
128
181
  const fails = checks.filter((c) => c.status === 'FAIL').length, warns = checks.filter((c) => c.status === 'WARN').length
@@ -0,0 +1,17 @@
1
+ // Built from src/githook.ts by scripts/build.ts. Do not edit.
2
+ // `stopbar git-hook pre-commit|pre-push`: the fallback gate for tools without their own hook system. Git runs it from
3
+ // .git/hooks; it goes through the same path as an agent's `git commit` / `git push` (the generated kernel step): the
4
+ // working tree is synced, then COMMIT must be allowed (passing build and full suite at this revision, no unapproved
5
+ // test changes); a push is also a risky outbound call, paused after a secret read without a human approval.
6
+ // Exit 0 lets git go on, exit 1 aborts the commit or push (git's convention).
7
+ import {runEvent} from './hook.js'
8
+
9
+
10
+
11
+ export function gitHook(which , o ) {
12
+ if (which !== 'pre-commit' && which !== 'pre-push') return {code: 1, msg: 'usage: stopbar git-hook pre-commit|pre-push'}
13
+ const out = runEvent({hook_event_name: 'PreToolUse', cwd: o.get('repo') ?? process.cwd(), tool_name: 'Bash',
14
+ tool_input: {command: which === 'pre-commit' ? 'git commit' : 'git push'}, stopbar: {adapter: 'git', rawKeys: [], event: which}})
15
+ if (out.code === 0) return {code: 0}
16
+ return {code: 1, msg: `stopbar ${which}: ${out.msg ?? 'blocked'}`}
17
+ }
package/dist/hook.js CHANGED
@@ -1,11 +1,13 @@
1
1
  // Built from src/hook.ts by scripts/build.ts. Do not edit.
2
2
  // Claude Code hooks: PreToolUse, PostToolUse, PostToolUseFailure, Stop. JSON on stdin; exit 0 = allow,
3
3
  // exit 2 = block (stderr goes to the agent). Any wrapper error is exit 2 (fail closed).
4
+ import {existsSync} from 'node:fs'
4
5
  import {resolve} from 'node:path'
5
6
  import * as K from './classify.js'
6
-
7
+ import { DEFAULT_SAFE_TOOLS} from './config.js'
8
+ import {matchAny} from './glob.js'
7
9
  import {decode, kstep, } from './engine.js'
8
- import {changesSinceHead, countedEntries, diffEntries, differsFromHead, FailClosed, findRepo, gitCalls, inHead, markCounted, snapshot} from './repo.js'
10
+ import {changesSinceHead, countedEntries, diffEntries, differsFromHead, FailClosed, findRepo, gitCalls, inRef, markCounted, snapshot} from './repo.js'
9
11
  import {appendEvent, readConfig, readState, withLock, writeState} from './store.js'
10
12
  import {codeDirs} from './pkg.js'
11
13
 
@@ -17,7 +19,7 @@ const READ_TOOLS = new Set(['Read', 'Grep', 'Glob', 'LS'])
17
19
  const SHELL_TOOLS = new Set(['Bash', 'PowerShell'])
18
20
  const OUTBOUND = (t ) => t === 'WebFetch' || t === 'WebSearch' || t.startsWith('mcp__')
19
21
 
20
- function step(ctx , req , source ) {
22
+ function step(ctx , req , source , extra = {}) {
21
23
  const before = decode(ctx.s.kernel)
22
24
  ctx.s.kernel = kstep(ctx.s.params, ctx.s.kernel, req)
23
25
  ctx.dirty = true
@@ -25,14 +27,14 @@ function step(ctx , req , source ) {
25
27
  appendEvent(ctx.repo, {source, req, decision: after.decision, halted: after.halted, testsTainted: after.testsTainted,
26
28
  secretTainted: after.secretTainted, shellToken: after.shellToken, treeRev: after.treeRev, buildOkRev: after.buildOkRev,
27
29
  testsOkRev: after.testsOkRev, spent: after.spent, capNow: after.capNow, testFails: after.testFails, buildFails: after.buildFails,
28
- commitExecuted: after.commitExecuted})
30
+ commitExecuted: after.commitExecuted, ...extra})
29
31
  return {before, after}
30
32
  }
31
33
 
32
34
  export function whyBlocked(v , cfg ) {
33
35
  const r = []
34
- if (v.buildOkRev !== v.treeRev) r.push(`no passing build at revision ${v.treeRev} (run \`${cfg.buildCmd}\` exactly, alone)`)
35
- if (v.testsOkRev !== v.treeRev) r.push(`no passing FULL test suite at revision ${v.treeRev} (run \`${cfg.fullTestCmd}\` exactly, alone)`)
36
+ if (v.buildOkRev !== v.treeRev) r.push(`no passing build at revision ${v.treeRev} (run \`${cfg.buildCmd}\` exactly, alone, or \`npx stopbar run build\`)`)
37
+ if (v.testsOkRev !== v.treeRev) r.push(`no passing FULL test suite at revision ${v.treeRev} (run \`${cfg.fullTestCmd}\` exactly, alone, or \`npx stopbar run test\`)`)
36
38
  if (v.testsTainted) r.push(`existing tests or test config changed: a human must review and run \`stopbar approve-tests --rev ${v.treeRev}\``)
37
39
  return r.join('; ') || 'kernel decision'
38
40
  }
@@ -52,8 +54,8 @@ function syncTree(ctx , cost , source ) {
52
54
  appendEvent(repo, {source: `${source}:fallback-diff`, note: 'counted snapshot copy missing; diff against HEAD'})
53
55
  }
54
56
  const testPaths = changes.map((c) => c.path).filter((p) => K.isTestPath(p, cfg.paths) && !K.isTestConfigPath(p, cfg.paths))
55
- const head = testPaths.length ? inHead(repo.root, testPaths) : new Set ()
56
- const cls = K.classifyTreeChange(changes, (p) => head.has(p), cfg.paths)
57
+ const existing = testPaths.length ? inRef(repo.root, cfg.baseRef ?? 'HEAD', testPaths) : new Set ()
58
+ const cls = K.classifyTreeChange(changes, (p) => existing.has(p), cfg.paths)
57
59
  const {before, after} = step(ctx, {op: cls.op, suspicious: cls.suspicious, cost}, `${source}:tree ${cls.why.join(', ') || `${changes.length} file(s)`}`)
58
60
  // not executed (halted or over budget): the change stays pending and is counted later
59
61
  if (after.treeRev > before.treeRev) { s.snapshot = snap.id; markCounted(repo); ctx.dirty = true }
@@ -62,21 +64,31 @@ function syncTree(ctx , cost , source ) {
62
64
 
63
65
  const block = (reason ) => ({code: 2, msg: `BLOCK (stopbar): ${reason}`})
64
66
 
67
+ function isBackgroundInput(ti ) {
68
+ return ti?.run_in_background === true || ti?.run_in_background === 'true' || ti?.background === true
69
+ }
70
+ function isBackgroundResponse(tr ) {
71
+ if (!tr || typeof tr !== 'object') return false
72
+ return (typeof tr.backgroundTaskId === 'string' && tr.backgroundTaskId.length > 0) ||
73
+ (typeof tr.background_task_id === 'string' && tr.background_task_id.length > 0) ||
74
+ tr.isAsync === true || tr.background === true
75
+ }
76
+
65
77
  // ---------------------------------------------------------------- PreToolUse
66
78
  function pre(ctx , input ) {
67
79
  const tool = String(input.tool_name ?? ''), ti = input.tool_input ?? {}
68
80
  const {repo, cfg} = ctx
69
81
  // self-protection: unconditional, before the kernel, also when halted
70
82
  if (EDIT_TOOLS.has(tool)) {
71
- for (const p of [ti.file_path, ti.notebook_path, ti.path].filter((x) => typeof x === 'string' && x)) {
83
+ const list = [ti.file_path, ti.notebook_path, ti.path, ...(Array.isArray(ti.file_paths) ? ti.file_paths : [])]
84
+ for (const p of list.filter((x) => typeof x === 'string' && x)) {
72
85
  const why = K.protectedPath(resolve(repo.root, p), repo.root, ctx.protect)
73
86
  if (why) { appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: why, path: p}); return block(`writing ${p} is not allowed: ${why}. Ask the human.`) }
74
87
  }
75
88
  }
76
89
  if (SHELL_TOOLS.has(tool)) {
77
90
  const cmd = String(ti.command ?? '')
78
- const hd = tool === 'Bash' ? K.parseSafeHeredocCommit(cmd.trim()) : null
79
- const why = K.protectedCommand(hd ? hd.prefix : cmd, ctx.protect)
91
+ const why = K.protectedCommand(K.commandForSelfProtect(cmd, tool === 'PowerShell' ? 'powershell' : 'bash'), ctx.protect)
80
92
  if (why) { appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: why}); return block(`${why}. Ask the human.`) }
81
93
  }
82
94
  const v = decode(ctx.s.kernel)
@@ -86,14 +98,19 @@ function pre(ctx , input ) {
86
98
  }
87
99
  const cost = cfg.costPerCall
88
100
  if (READ_TOOLS.has(tool)) {
89
- const ps = [ti.file_path, ti.path, ti.glob, ti.pattern].filter((x) => typeof x === 'string' && x)
90
- if (ps.some((p ) => K.isSecretPath(p, cfg.paths))) step(ctx, {op: 'READ_SECRET', cost}, `pre:${tool}`)
101
+ 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)
102
+ for (const p of ps) {
103
+ const pattern = K.secretPattern(p, cfg.paths)
104
+ if (pattern) { step(ctx, {op: 'READ_SECRET', cost}, `pre:${tool}`, {secret: {pattern, path: p, tool}}); break }
105
+ }
91
106
  return {code: 0}
92
107
  }
93
108
  if (EDIT_TOOLS.has(tool)) return {code: 0} // cost and tree change are counted in PostToolUse
94
109
  if (SHELL_TOOLS.has(tool)) {
95
110
  const cmd = String(ti.command ?? '')
96
- const k = K.classifyBash(cmd, cfg, tool === 'PowerShell' ? 'powershell' : 'bash')
111
+ const base = typeof input.cwd === 'string' && input.cwd ? input.cwd : repo.root
112
+ const exists = (t ) => existsSync(resolve(base, t)) || existsSync(resolve(repo.root, t))
113
+ const k = K.classifyBash(cmd, cfg, tool === 'PowerShell' ? 'powershell' : 'bash', exists)
97
114
  if (k.kind === 'commit-chained') {
98
115
  appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: `chained commit (${k.reason})`})
99
116
  return block(`run \`git commit\` / \`git push\` as a single command (${k.reason}): no &&, ;, |, redirections or $(...). ` +
@@ -103,7 +120,15 @@ function pre(ctx , input ) {
103
120
  appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: `chained gate command (${k.reason})`})
104
121
  return block(`run \`${k.gate}\` exactly as configured, alone: no ;, &&, ||, |, redirections or $(...). Chained operators hide its exit status.`)
105
122
  }
106
- if (k.kind === 'build' || k.kind === 'fulltest') return {code: 0} // the result is recorded in PostToolUse
123
+ if (k.kind === 'build' || k.kind === 'fulltest') {
124
+ if (isBackgroundInput(ti)) {
125
+ const which = k.kind === 'build' ? 'build' : 'test'
126
+ const gate = k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd
127
+ appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: `background gate command (${k.kind})`})
128
+ return block(`do not run \`${gate}\` in the background (run_in_background): the hook fires before the process finishes, so its exit status is unknown. Run \`${gate}\` in the foreground, or start \`npx stopbar run ${which}\` in the background so Stopbar records the real exit status only when it finishes.`)
129
+ }
130
+ return {code: 0} // the result is recorded in PostToolUse
131
+ }
107
132
  if (k.kind === 'commit') {
108
133
  syncTree(ctx, 0, 'pre:commit-sync') // a change nobody reported (background job, human edit) is counted first
109
134
  const {after} = step(ctx, {op: 'COMMIT', cost}, `pre:${tool}:commit${k.heredoc ? ':heredoc' : ''}`)
@@ -114,7 +139,7 @@ function pre(ctx , input ) {
114
139
  }
115
140
  return {code: 0}
116
141
  }
117
- if (k.secret) step(ctx, {op: 'READ_SECRET'}, `pre:${tool}:secret-mention`)
142
+ if (k.secret) step(ctx, {op: 'READ_SECRET'}, `pre:${tool}:secret-mention`, {secret: {pattern: k.secret.pattern, path: k.secret.token, tool}})
118
143
  const {after} = step(ctx, {op: 'SHELL', risky: k.risky, cost}, `pre:${tool}`)
119
144
  if (after.decision === 'PAUSE') {
120
145
  return {code: 2, msg: after.halted ? 'PAUSE (stopbar): budget reached; a human must run `stopbar resume --extra <n>`'
@@ -123,6 +148,7 @@ function pre(ctx , input ) {
123
148
  return {code: 0}
124
149
  }
125
150
  if (OUTBOUND(tool)) {
151
+ if (matchAny(tool, cfg.safeTools ?? DEFAULT_SAFE_TOOLS)) return {code: 0} // local tools listed in config.safeTools
126
152
  const {after} = step(ctx, {op: 'SHELL', risky: true, cost}, `pre:${tool}`)
127
153
  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\``}
128
154
  }
@@ -145,15 +171,38 @@ function post(ctx , input , failure ) {
145
171
  if (SHELL_TOOLS.has(tool)) {
146
172
  const k = K.classifyBash(String(ti.command ?? ''), cfg, tool === 'PowerShell' ? 'powershell' : 'bash')
147
173
  const tr = input.tool_response
148
- appendEvent(repo, {source: `payload:${input.hook_event_name}`, tool, inputKeys: Object.keys(input),
174
+ const meta = input.stopbar ?? {}
175
+ appendEvent(repo, {source: `payload:${input.hook_event_name}`, tool, ...(meta.adapter ? {adapter: meta.adapter, rawKeys: meta.rawKeys} : {inputKeys: Object.keys(input)}),
149
176
  toolResponseKeys: tr && typeof tr === 'object' ? Object.keys(tr) : typeof tr})
177
+ const bg = isBackgroundInput(ti) || isBackgroundResponse(tr)
178
+ const staleRun = typeof meta.expectedSnapshot === 'string' &&
179
+ (meta.expectedSnapshot !== ctx.s.snapshot || (typeof meta.expectedRev === 'number' && meta.expectedRev !== decode(ctx.s.kernel).treeRev))
150
180
  const code = exitCodeOf(tr)
151
181
  const flagged = input.is_error === true || tr?.is_error === true || tr?.interrupted === true
152
- const passed = failure ? false : code !== undefined ? code === 0 : !flagged
153
- const note = failure ? ' (PostToolUseFailure)' : code !== undefined ? ` (exit ${code})` : ` (no exit code; is_error/interrupted=${flagged})`
182
+ // some clients send the same post event for success and failure: then only an explicit exit code 0 is a pass
183
+ const unknown = meta.requireExitCode === true && code === undefined
184
+ const passed = failure ? false : code !== undefined ? code === 0 : !flagged && !unknown
185
+ const note = failure ? ' (PostToolUseFailure)' : code !== undefined ? ` (exit ${code})` : unknown ? ' (no exit code: not counted as a pass)' : ` (no exit code; is_error/interrupted=${flagged})`
154
186
  if (failure && input.is_interrupt === true) {
155
187
  // Ctrl+C by the user: not a failed gate and not a retry; the tree is still checked below
156
188
  appendEvent(repo, {source: 'post:user-interrupt', tool, kind: k.kind})
189
+ } else if (!failure && bg && (k.kind === 'build' || k.kind === 'fulltest' || (k.kind === 'shell' && k.partialTests))) {
190
+ // a background launch fires PostToolUse before the process finishes (e.g. Claude Code backgroundTaskId): never count it
191
+ appendEvent(repo, {source: 'post:background-gate-ignored', tool, kind: k.kind === 'shell' ? 'partial-tests' : k.kind,
192
+ ...(typeof tr?.backgroundTaskId === 'string' ? {backgroundTaskId: tr.backgroundTaskId} : typeof tr?.background_task_id === 'string' ? {backgroundTaskId: tr.background_task_id} : {})})
193
+ if (k.kind !== 'shell') {
194
+ const which = k.kind === 'build' ? 'build' : 'test'
195
+ const gate = k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd
196
+ msgs.push(`BLOCK (stopbar): \`${gate}\` was started in the background, so its exit status is not known yet and the run is not recorded. Run \`${gate}\` in the foreground, or start \`npx stopbar run ${which}\` in the background.`)
197
+ }
198
+ } else if (staleRun && (k.kind === 'build' || k.kind === 'fulltest')) {
199
+ const curRev = decode(ctx.s.kernel).treeRev
200
+ appendEvent(repo, {source: 'post:stale-gate-run', tool, kind: k.kind, expectedRev: meta.expectedRev, currentRev: curRev})
201
+ msgs.push(`NOTE (stopbar): working tree changed while \`${k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd}\` was running (started at revision ${meta.expectedRev}, now ${curRev}), so the result was not recorded. Re-run on the current tree.`)
202
+ } else if (!failure && unknown && (k.kind === 'build' || k.kind === 'fulltest' || (k.kind === 'shell' && k.partialTests))) {
203
+ // no exit status in the client's post event: neither a pass nor a failure is recorded (no evidence either way)
204
+ appendEvent(repo, {source: 'post:gate-without-exit-code', tool, kind: k.kind})
205
+ if (k.kind !== 'shell') msgs.push(`NOTE (stopbar): this client does not report the exit status of \`${k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd}\`, so the run is not recorded. Run \`npx stopbar run ${k.kind === 'build' ? 'build' : 'test'}\` instead: it runs the same command and records its real exit status.`)
157
206
  } else if (k.kind === 'build') {
158
207
  step(ctx, {op: 'RUN_BUILD', passed, cost: cfg.costPerCall}, `post:build${note}`)
159
208
  } else if (k.kind === 'fulltest') {
@@ -188,11 +237,16 @@ export function failMsg(e ) {
188
237
  return `STOPBAR FAIL-CLOSED: ${e instanceof Error ? e.message : String(e)}`
189
238
  }
190
239
 
191
- /** One hook call. `raw` is the JSON Claude Code writes on stdin. Never throws. */
240
+ /** One hook call with Claude Code's JSON on stdin (the v1.0 interface). Never throws. */
192
241
  export function runHook(raw , t0 = performance.now()) {
193
242
  let input
194
243
  try { input = JSON.parse(raw) } catch (e) { return {code: 2, msg: `STOPBAR FAIL-CLOSED: hook input is not JSON (${(e ).message})`} }
195
244
  if (!input || typeof input !== 'object') return {code: 2, msg: 'STOPBAR FAIL-CLOSED: hook input must be a JSON object'}
245
+ return runEvent(input, t0)
246
+ }
247
+
248
+ /** One normalised hook event (Claude Code's shape; adapters translate other clients into it). Never throws. */
249
+ export function runEvent(input , t0 = performance.now()) {
196
250
  try {
197
251
  const repo = findRepo(typeof input.cwd === 'string' && input.cwd ? input.cwd : process.cwd())
198
252
  const g0 = gitCalls
@@ -205,7 +259,7 @@ export function runHook(raw , t0 = performance.now()) {
205
259
  : ev === 'PostToolUseFailure' ? post(ctx, input, true)
206
260
  : ev === 'Stop' ? stop(ctx, input) : {code: 0}
207
261
  if (ctx.dirty) writeState(repo, ctx.s)
208
- appendEvent(repo, {source: 'hook-timing', event: ev, tool: input.tool_name, exit: res.code, gitCalls: gitCalls - g0,
262
+ appendEvent(repo, {source: 'hook-timing', event: ev, tool: input.tool_name, ...(input.stopbar?.adapter ? {adapter: input.stopbar.adapter} : {}), exit: res.code, gitCalls: gitCalls - g0,
209
263
  handlerMs: Math.round(performance.now() - t0), processMs: Math.round(process.uptime() * 1000)})
210
264
  return res
211
265
  })
@@ -0,0 +1,141 @@
1
+ // Built from src/integrations.ts by scripts/build.ts. Do not edit.
2
+ // `stopbar init --hooks <targets>`: writes the hook configuration of each client, merging into existing files (other keys
3
+ // and other hooks stay; earlier Stopbar entries are replaced). Targets: claude (alias local), claude-project (alias
4
+ // project), cursor, codex, gemini, antigravity (alias agy), git; several at once, comma separated.
5
+ import {chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync} from 'node:fs'
6
+ import {dirname, isAbsolute, join, resolve} from 'node:path'
7
+ import {FailClosed, git, } from './repo.js'
8
+
9
+ export const TARGETS = ['claude', 'claude-project', 'cursor', 'codex', 'gemini', 'antigravity', 'git']
10
+
11
+ const ALIAS = {local: 'claude', project: 'claude-project', agy: 'antigravity'}
12
+
13
+ export function parseTargets(s ) {
14
+ const out = []
15
+ for (const raw of s.split(',').map((x) => x.trim()).filter(Boolean)) {
16
+ const t = (ALIAS[raw] ?? raw)
17
+ if (!TARGETS.includes(t)) throw new FailClosed(`unknown --hooks target ${JSON.stringify(raw)}; known: ${TARGETS.join(', ')} (aliases: local, project, agy)`)
18
+ if (!out.includes(t)) out.push(t)
19
+ }
20
+ if (!out.length) throw new FailClosed('--hooks needs at least one target')
21
+ return out
22
+ }
23
+
24
+ export const STOPBAR_HOOK = /stopbar(\.mjs)?\\?"?\s+(hook|git-hook)\b/
25
+ export const hookCommand = (runtimeRoot , adapter ) =>
26
+ `node "${join(runtimeRoot, 'bin', 'stopbar.mjs').replace(/\\/g, '/')}" hook${adapter ? ` --adapter ${adapter}` : ''}`
27
+
28
+ export const CLAUDE_POST_MATCHER = 'Edit|Write|MultiEdit|NotebookEdit|Bash|PowerShell'
29
+ export function claudeHooks(command ) {
30
+ const h = (timeout ) => [{type: 'command', command, timeout}]
31
+ return {
32
+ PreToolUse: [{matcher: '*', hooks: h(30)}],
33
+ PostToolUse: [{matcher: CLAUDE_POST_MATCHER, hooks: h(60)}],
34
+ PostToolUseFailure: [{matcher: CLAUDE_POST_MATCHER, hooks: h(60)}],
35
+ Stop: [{hooks: h(30)}],
36
+ }
37
+ }
38
+
39
+ function readJson(f ) {
40
+ if (!existsSync(f)) return {}
41
+ const raw = readFileSync(f, 'utf8')
42
+ try { return raw.trim() ? JSON.parse(raw) : {} } catch (e) {
43
+ throw new FailClosed(`${f} is not valid JSON (${(e ).message}); not overwriting it`, 'fix the file by hand, then run init again')
44
+ }
45
+ }
46
+ function writeJson(f , o ) { mkdirSync(dirname(f), {recursive: true}); writeFileSync(f, JSON.stringify(o, null, 2) + '\n') }
47
+ const mentions = (x ) => STOPBAR_HOOK.test(JSON.stringify(x ?? ''))
48
+ /** Event arrays: drop earlier Stopbar entries, append ours. */
49
+ function mergeEvents(hooks , want ) {
50
+ for (const [ev, entries] of Object.entries(want)) {
51
+ const kept = Array.isArray(hooks[ev]) ? hooks[ev].filter((x ) => !mentions(x)) : []
52
+ hooks[ev] = [...kept, ...entries]
53
+ }
54
+ }
55
+
56
+ function claudeFile(root , file , command ) {
57
+ const f = join(root, '.claude', file)
58
+ const cur = readJson(f)
59
+ cur.hooks = cur.hooks && typeof cur.hooks === 'object' ? cur.hooks : {}
60
+ mergeEvents(cur.hooks, claudeHooks(command))
61
+ writeJson(f, cur)
62
+ return f
63
+ }
64
+
65
+ function cursorFile(root , command ) {
66
+ const f = join(root, '.cursor', 'hooks.json')
67
+ const cur = readJson(f)
68
+ cur.version = cur.version ?? 1
69
+ cur.hooks = cur.hooks && typeof cur.hooks === 'object' ? cur.hooks : {}
70
+ const e = (timeout ) => [{command, timeout, failClosed: true}]
71
+ mergeEvents(cur.hooks, {preToolUse: e(30), postToolUse: e(60), postToolUseFailure: e(60), stop: e(30)})
72
+ writeJson(f, cur)
73
+ return f
74
+ }
75
+
76
+ function codexFile(root , command ) {
77
+ const f = join(root, '.codex', 'hooks.json')
78
+ const cur = readJson(f)
79
+ cur.hooks = cur.hooks && typeof cur.hooks === 'object' ? cur.hooks : {}
80
+ const h = (timeout ) => [{hooks: [{type: 'command', command, timeout}]}]
81
+ mergeEvents(cur.hooks, {PreToolUse: h(30), PostToolUse: h(60), Stop: h(30)})
82
+ writeJson(f, cur)
83
+ return f
84
+ }
85
+
86
+ function geminiFile(root , command ) {
87
+ const f = join(root, '.gemini', 'settings.json')
88
+ const cur = readJson(f)
89
+ cur.hooks = cur.hooks && typeof cur.hooks === 'object' ? cur.hooks : {}
90
+ const h = (timeout ) => [{matcher: '*', hooks: [{name: 'stopbar', type: 'command', command, timeout}]}]
91
+ mergeEvents(cur.hooks, {BeforeTool: h(30000), AfterTool: h(60000), AfterAgent: h(30000)})
92
+ writeJson(f, cur)
93
+ return f
94
+ }
95
+
96
+ function antigravityFile(root , command ) {
97
+ const f = join(root, '.agents', 'hooks.json')
98
+ const cur = readJson(f)
99
+ cur.stopbar = {
100
+ PreToolUse: [{matcher: '*', hooks: [{type: 'command', command, timeout: 30}]}],
101
+ PostToolUse: [{matcher: '*', hooks: [{type: 'command', command, timeout: 60}]}],
102
+ Stop: [{type: 'command', command, timeout: 30}],
103
+ }
104
+ writeJson(f, cur)
105
+ return f
106
+ }
107
+
108
+ function gitHooks(repo , runtimeRoot , force ) {
109
+ const rel = git(repo.root, ['rev-parse', '--git-path', 'hooks'])
110
+ const dir = isAbsolute(rel) ? rel : resolve(repo.root, rel)
111
+ mkdirSync(dir, {recursive: true})
112
+ const bin = join(runtimeRoot, 'bin', 'stopbar.mjs').replace(/\\/g, '/')
113
+ const out = []
114
+ for (const name of ['pre-commit', 'pre-push']) {
115
+ const f = join(dir, name)
116
+ const body = `#!/bin/sh\n# Stopbar fallback gate, written by \`stopbar init --hooks git\`.\nexec node "${bin}" git-hook ${name}\n`
117
+ if (existsSync(f) && !readFileSync(f, 'utf8').includes('stopbar.mjs" git-hook')) {
118
+ if (!force) throw new FailClosed(`${f} exists and is not a Stopbar hook; not overwriting it`, 'remove it, chain it by hand, or run init again with --force-hooks (the old hook is kept as <name>.stopbar-backup)')
119
+ renameSync(f, `${f}.stopbar-backup`)
120
+ }
121
+ writeFileSync(f, body)
122
+ chmodSync(f, 0o755)
123
+ out.push(f)
124
+ }
125
+ return out
126
+ }
127
+
128
+ /** Installs every target; returns one line per written file. */
129
+ export function installHooks(repo , targets , runtimeRoot , force ) {
130
+ const lines = []
131
+ for (const t of targets) {
132
+ if (t === 'claude') lines.push(`claude: ${claudeFile(repo.root, 'settings.local.json', hookCommand(runtimeRoot))}`)
133
+ else if (t === 'claude-project') lines.push(`claude: ${claudeFile(repo.root, 'settings.json', hookCommand(runtimeRoot))}`)
134
+ else if (t === 'cursor') lines.push(`cursor: ${cursorFile(repo.root, hookCommand(runtimeRoot, 'cursor'))}`)
135
+ else if (t === 'codex') lines.push(`codex: ${codexFile(repo.root, hookCommand(runtimeRoot, 'codex'))}`)
136
+ else if (t === 'gemini') lines.push(`gemini: ${geminiFile(repo.root, hookCommand(runtimeRoot, 'gemini'))}`)
137
+ else if (t === 'antigravity') lines.push(`antigravity: ${antigravityFile(repo.root, hookCommand(runtimeRoot, 'antigravity'))}`)
138
+ else if (t === 'git') for (const f of gitHooks(repo, runtimeRoot, force)) lines.push(`git: ${f}`)
139
+ }
140
+ return lines
141
+ }
@@ -19,8 +19,8 @@ import {runHook} from '../hook.js'
19
19
 
20
20
 
21
21
 
22
-
23
-
22
+
23
+
24
24
 
25
25
 
26
26
 
@@ -57,8 +57,8 @@ function genRun(seed ) {
57
57
  [4, () => ({t: 'shellEdit', file: anyFile(), content: content()})],
58
58
  [2, () => ({t: 'shellDelete', file: anyFile()})],
59
59
  [2, () => ({t: 'humanEdit', file: anyFile(), content: content()})],
60
- [10, () => ({t: 'build', outcome: pick(['pass', 'pass', 'pass', 'fail', 'interrupt', 'interrupted'] )})],
61
- [10, () => ({t: 'fulltest', outcome: pick(['pass', 'pass', 'pass', 'fail', 'fail', 'interrupt', 'interrupted'] )})],
60
+ [10, () => ({t: 'build', outcome: pick(['pass', 'pass', 'pass', 'fail', 'interrupt', 'interrupted', 'bgPre', 'bgPost'] )})],
61
+ [10, () => ({t: 'fulltest', outcome: pick(['pass', 'pass', 'pass', 'fail', 'fail', 'interrupt', 'interrupted', 'bgPre', 'bgPost'] )})],
62
62
  [3, () => ({t: 'partial', pass: r() < 0.6})],
63
63
  [5, () => ({t: 'shell', cmd: pick(['ls -la', 'curl --version', 'cat .env', 'git status'] )})],
64
64
  [4, () => ({t: 'read', file: pick(['.env', 'src/c0.mjs', 'secrets/key.txt', 'README.md'])})],
@@ -189,8 +189,19 @@ async function execute(run , dir ) {
189
189
  case 'humanEdit': put(a.file, a.content); break
190
190
  case 'build': case 'fulltest': {
191
191
  const command = a.t === 'build' ? 'node build.mjs' : 'node --test'
192
+ if (a.outcome === 'bgPre') {
193
+ expCode = 2
194
+ gotCode = hook('PreToolUse', 'Bash', {command, run_in_background: true})
195
+ break
196
+ }
192
197
  expCode = expectPre(); gotCode = hook('PreToolUse', 'Bash', {command})
193
198
  if (gotCode !== 0 || expCode !== 0) break
199
+ if (a.outcome === 'bgPost') {
200
+ mSync(0)
201
+ expCode = 2
202
+ gotCode = hook('PostToolUse', 'Bash', {command}, {tool_response: {...okResp.tool_response, backgroundTaskId: 'bg-task-1'}})
203
+ break
204
+ }
194
205
  const op = a.t === 'build' ? 'RUN_BUILD' : 'RUN_TESTS'
195
206
  if (a.outcome !== 'interrupt') kstep({op, passed: a.outcome === 'pass', fullSuite: a.t === 'fulltest', cost})
196
207
  expCode = postCode(mSync(0))
package/dist/repo.js CHANGED
@@ -167,11 +167,23 @@ export function differsFromHead(r , now ) {
167
167
  }
168
168
  }
169
169
 
170
- /** Which of `paths` exist in HEAD (one git process, only when test files changed). */
171
- export function inHead(root , paths ) {
170
+ /** Does `ref` resolve to a git tree? */
171
+ export function hasRefTree(root , ref ) {
172
+ try { git(root, ['rev-parse', '-q', '--verify', `${ref}^{tree}`]); return true } catch { return false }
173
+ }
174
+
175
+ /** Which of `paths` exist in `ref` (one git process, only when test files changed).
176
+ * For an explicit non-HEAD ref, fails closed if the ref cannot be resolved so existing tests are never treated as new. */
177
+ export function inRef(root , ref , paths ) {
172
178
  if (!paths.length) return new Set()
173
179
  try {
174
- const out = git(root, ['--literal-pathspecs', '-c', 'core.quotepath=false', 'ls-tree', '-r', '-z', '--name-only', '--full-tree', 'HEAD', '--', ...paths])
180
+ const out = git(root, ['--literal-pathspecs', '-c', 'core.quotepath=false', 'ls-tree', '-r', '-z', '--name-only', '--full-tree', ref, '--', ...paths])
175
181
  return new Set(out.split('\0').filter(Boolean))
176
- } catch { return new Set() }
182
+ } catch {
183
+ if (ref === 'HEAD') return new Set()
184
+ throw new FailClosed(`baseRef ${JSON.stringify(ref)} could not be resolved in git`, 'a human restores the ref or runs `stopbar init --force ... --base-ref <ref>`')
185
+ }
177
186
  }
187
+
188
+ /** Which of `paths` exist in HEAD (one git process, only when test files changed). */
189
+ export const inHead = (root , paths ) => inRef(root, 'HEAD', paths)
package/dist/run.js ADDED
@@ -0,0 +1,34 @@
1
+ // Built from src/run.ts by scripts/build.ts. Do not edit.
2
+ // `stopbar run build|test`: runs the configured gate command itself and records its real exit status in the kernel.
3
+ // For agents without hooks (with the git fallback) this is how a build or full test run counts. The working tree is
4
+ // synced before the run; the result is recorded at that revision and a change made during the run is counted after it,
5
+ // so a run never passes a revision it did not see.
6
+ import {spawnSync} from 'node:child_process'
7
+ import {decode} from './engine.js'
8
+ import {runEvent} from './hook.js'
9
+ import {findRepo} from './repo.js'
10
+ import {readConfig, readState} from './store.js'
11
+
12
+
13
+
14
+ export function runGate(which , o ) {
15
+ if (which !== 'build' && which !== 'test') return {code: 1, msg: 'usage: stopbar run build|test'}
16
+ const cwd = o.get('repo') ?? process.cwd()
17
+ const repo = findRepo(cwd)
18
+ const cfg = readConfig(repo)
19
+ const command = which === 'build' ? cfg.buildCmd : cfg.fullTestCmd
20
+ const meta = (event ) => ({adapter: 'run', rawKeys: [], event})
21
+ const before = runEvent({hook_event_name: 'PostToolUse', cwd: repo.root, tool_name: 'Bash', tool_input: {command: ':'}, tool_response: {exitCode: 0}, stopbar: meta('sync')})
22
+ if (before.code !== 0 && /FAIL-CLOSED|halted/.test(before.msg ?? '')) return {code: 2, msg: before.msg}
23
+ const s0 = readState(repo)
24
+ const expectedSnapshot = s0.snapshot, expectedRev = decode(s0.kernel).treeRev
25
+ const r = spawnSync(command, {cwd: repo.root, shell: true, stdio: 'inherit'})
26
+ const exit = r.status ?? 1
27
+ const after = runEvent({hook_event_name: exit === 0 ? 'PostToolUse' : 'PostToolUseFailure', cwd: repo.root, tool_name: 'Bash', tool_input: {command},
28
+ tool_response: {exitCode: exit}, stopbar: {...meta(which), expectedSnapshot, expectedRev}})
29
+ const stale = /working tree changed while/.test(after.msg ?? '')
30
+ const msg = stale
31
+ ? `stopbar run ${which}: \`${command}\` exited ${exit}, but was not recorded\n${after.msg}`
32
+ : `stopbar run ${which}: \`${command}\` exited ${exit}; recorded as ${exit === 0 ? 'a pass' : 'a failure'}${after.msg ? `\n${after.msg}` : ''}`
33
+ return {code: !stale && exit === 0 && after.code === 0 ? 0 : exit || 2, msg}
34
+ }
package/dist/store.js CHANGED
@@ -6,7 +6,7 @@ import { ConfigError, validateConfig} from './config.js'
6
6
  import {CODEC} from './kernel.gen.js'
7
7
  import {FailClosed, } from './repo.js'
8
8
 
9
- export const VERSION = '1.0.0'
9
+ export const VERSION = '1.1.1'
10
10
 
11
11
 
12
12
 
package/package.json CHANGED
@@ -1,9 +1,17 @@
1
1
  {
2
2
  "name": "stopbar",
3
- "version": "1.0.0",
4
- "description": "Proven gates for coding agents: no commit without a passing build and a full passing test suite, no silent test weakening, no exfiltration after a secret read. Claude Code hooks backed by a formally proven kernel.",
3
+ "version": "1.1.1",
4
+ "description": "A formally proven execution gate for AI coding agents: hooks for Claude Code, Cursor, Codex CLI, Gemini CLI and Antigravity CLI, plus git hooks. No commit without a passing build and full test suite, no silent test weakening, no exfiltration after a secret read.",
5
5
  "author": "Paweł Olszewski <kontakt@polszewski.com>",
6
6
  "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/polszewski-pl/stopbar.git"
10
+ },
11
+ "homepage": "https://github.com/polszewski-pl/stopbar#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/polszewski-pl/stopbar/issues"
14
+ },
7
15
  "type": "module",
8
16
  "bin": {
9
17
  "stopbar": "bin/stopbar.mjs"
@@ -35,6 +43,11 @@
35
43
  },
36
44
  "keywords": [
37
45
  "claude-code",
46
+ "cursor",
47
+ "codex",
48
+ "gemini-cli",
49
+ "antigravity",
50
+ "ai-agents",
38
51
  "hooks",
39
52
  "coding-agent",
40
53
  "guardrails",