stopbar 1.1.3 → 1.2.0

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.
@@ -0,0 +1,242 @@
1
+ // Built from src/probe/sdk.ts by scripts/build.ts. Do not edit.
2
+ // stopbar/probe: the SDK for PROBE targets of any TS/JS project. A target describes a model as a list of actions
3
+ // (each with a generator of pure JSON data and a run that drives the real thing and checks it), invariants that hold
4
+ // after every step, and optional mutants (a damaged system under test) that the prober must catch.
5
+ // `stopbar probe --target <file>` loads the file (default export or export `target`) and runs it as any other target.
6
+ // This module has no imports besides node:util, so its source ships as the type declaration of `stopbar/probe`.
7
+ import {isDeepStrictEqual} from 'node:util'
8
+
9
+ // ---------------------------------------------------------------- the target contract (shared with the runner)
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+ // ---------------------------------------------------------------- deterministic random numbers
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+ /** xorshift32 on 32-bit integer arithmetic only: the same seed gives the same numbers on every platform. */
37
+ export function createRng(seed ) {
38
+ if (!Number.isFinite(seed)) throw new TypeError(`createRng: seed must be a finite number, got ${seed}`)
39
+ let x = Math.imul(Math.trunc(seed) | 0, 0x9e3779b1) >>> 0 || 7
40
+ const next = () => { x ^= x << 13; x >>>= 0; x ^= x >>> 17; x ^= x << 5; x >>>= 0; return x / 2 ** 32 }
41
+ const int = (min , max ) => {
42
+ if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || max < min) throw new RangeError(`rng.int: need integers min <= max, got ${min}, ${max}`)
43
+ return min + Math.floor(next() * (max - min + 1))
44
+ }
45
+ return {
46
+ next, int,
47
+ bool: (p = 0.5) => next() < p,
48
+ pick: (xs ) => {
49
+ if (!xs.length) throw new RangeError('rng.pick: empty list')
50
+ return xs[Math.floor(next() * xs.length)]
51
+ },
52
+ weighted: (xs ) => {
53
+ const w = xs.map((e) => e.weight ?? 1)
54
+ if (w.some((v) => !Number.isFinite(v) || v < 0)) throw new RangeError('rng.weighted: weights must be finite numbers >= 0')
55
+ const total = w.reduce((s, v) => s + v, 0)
56
+ if (!(total > 0)) throw new RangeError('rng.weighted: no value with a weight > 0')
57
+ let r = next() * total
58
+ for (let i = 0; i < xs.length; i++) { if (w[i] > 0 && r < w[i]) return xs[i].value; r -= w[i] }
59
+ for (let i = xs.length - 1; ; i--) if (w[i] > 0) return xs[i].value // rounding at the upper end
60
+ },
61
+ }
62
+ }
63
+
64
+ // ---------------------------------------------------------------- checks
65
+ /** Thrown by a failed check; `execute` turns it into `{ok: false, mismatch}` with the step and the action. */
66
+ export class MismatchError extends Error {
67
+ what
68
+ expected
69
+ actual
70
+ constructor(what , expected , actual ) {
71
+ super(`${what}: expected ${show(expected)}, actual ${show(actual)}`)
72
+ this.name = 'MismatchError'
73
+ this.what = what; this.expected = expected; this.actual = actual
74
+ }
75
+ }
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+ export const check = {
86
+ ok(what, cond, ...rest ) {
87
+ if (!cond) throw new MismatchError(what, rest.length >= 2 ? rest[1] : 'truthy', rest.length >= 1 ? rest[0] : cond)
88
+ },
89
+ eq(what, actual, expected) { if (!isDeepStrictEqual(actual, expected)) throw new MismatchError(what, expected, actual) },
90
+ fail(what, expected, actual) { throw new MismatchError(what, expected, actual) },
91
+ }
92
+
93
+ function show(v ) {
94
+ try { return JSON.stringify(v, jsonSafe) ?? String(v) } catch { return String(v) }
95
+ }
96
+ function jsonSafe(_k , v ) {
97
+ if (typeof v === 'bigint') return `${v}n`
98
+ if (v instanceof Map) return {Map: [...v.entries()]}
99
+ if (v instanceof Set) return {Set: [...v.values()]}
100
+ if (typeof v === 'function' || typeof v === 'symbol') return String(v)
101
+ return v
102
+ }
103
+ /** Values of a mismatch travel as JSON between processes: make them plain data (BigInt, Map, Set, cycles). */
104
+ function plain(v ) {
105
+ if (v === undefined) return undefined
106
+ try { const s = JSON.stringify(v, jsonSafe); return s === undefined ? String(v) : JSON.parse(s) } catch { return String(v) }
107
+ }
108
+ function errorText(e ) {
109
+ if (e instanceof Error) return `${e.name}: ${e.message}`
110
+ return `thrown ${show(e)}`
111
+ }
112
+
113
+ // ---------------------------------------------------------------- defineModel
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+ const NAT = (n ) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0
145
+
146
+ export function defineModel (spec ) {
147
+ const bad = (why ) => { throw new TypeError(`defineModel(${JSON.stringify(spec?.name)}): ${why}`) }
148
+ if (!spec || typeof spec !== 'object') bad('spec must be an object')
149
+ if (typeof spec.name !== 'string' || !spec.name) bad('name must be a non-empty string')
150
+ if (typeof spec.description !== 'string') bad('description must be a string')
151
+ if (typeof spec.setup !== 'function') bad('setup must be a function')
152
+ if (spec.teardown !== undefined && typeof spec.teardown !== 'function') bad('teardown must be a function')
153
+ if (!Array.isArray(spec.actions) || !spec.actions.length) bad('actions must be a non-empty array')
154
+ const byName = new Map ()
155
+ for (const a of spec.actions) {
156
+ if (!a || typeof a.name !== 'string' || !a.name || typeof a.gen !== 'function' || typeof a.run !== 'function') bad('every action needs a name, gen(r) and run(state, args, check)')
157
+ if (byName.has(a.name)) bad(`action ${JSON.stringify(a.name)} is defined twice`)
158
+ if (a.weight !== undefined && !(Number.isFinite(a.weight) && a.weight >= 0)) bad(`action ${a.name}: weight must be a number >= 0`)
159
+ byName.set(a.name, a)
160
+ }
161
+ if (!spec.actions.some((a) => (a.weight ?? 1) > 0)) bad('at least one action needs a weight > 0')
162
+ const minSteps = spec.minSteps ?? 15, maxSteps = spec.maxSteps ?? 40
163
+ if (!NAT(minSteps) || !NAT(maxSteps) || minSteps > maxSteps) bad('minSteps and maxSteps must be integers with 0 <= minSteps <= maxSteps')
164
+ const invariants = (spec.invariants ?? []).map((inv, i) => {
165
+ if (typeof inv === 'function') return {name: '', check: inv}
166
+ if (inv && typeof inv.check === 'function' && typeof inv.name === 'string') return inv
167
+ return bad(`invariant ${i} must be a function or {name, check}`)
168
+ })
169
+ const mutants = new Map ()
170
+ for (const [name, m] of Object.entries(spec.mutants ?? {})) {
171
+ if (typeof m === 'function') mutants.set(name, m)
172
+ else if (m && typeof m.setup === 'function') mutants.set(name, (ctx) => m.setup(ctx))
173
+ else bad(`mutant ${name} must be a setup function or {setup}`)
174
+ }
175
+ const weighted = spec.actions.map((a) => ({weight: a.weight ?? 1, value: a}))
176
+
177
+ return {
178
+ name: spec.name,
179
+ description: spec.description,
180
+ mutants: [...mutants.keys()],
181
+ generate(seed ) {
182
+ const r = createRng(seed)
183
+ const n = r.int(minSteps, maxSteps)
184
+ const actions = []
185
+ for (let i = 0; i < n; i++) {
186
+ const a = r.weighted(weighted)
187
+ const args = a.gen(r)
188
+ // the run in memory must equal its JSON copy (a saved reproduction replays exactly what was found)
189
+ actions.push(args === undefined ? {t: a.name} : {t: a.name, args: JSON.parse(JSON.stringify(args))})
190
+ }
191
+ return {seed, actions}
192
+ },
193
+ async execute(run , dir , mutant ) {
194
+ const ctx = mutant === undefined ? {seed: run.seed, dir} : {seed: run.seed, dir, mutant}
195
+ const cov = {}
196
+ let step = -1, action = null, state , ready = false
197
+ const mismatch = (e , prefix = '') => e instanceof MismatchError
198
+ ? {ok: false, mismatch: {step, action, what: prefix + e.what, expected: plain(e.expected), actual: plain(e.actual)}}
199
+ : {ok: false, mismatch: {step, action, what: prefix ? `${prefix}exception` : 'exception', expected: 'no error', actual: errorText(e)}}
200
+ const checkAll = async () => {
201
+ for (const inv of invariants) {
202
+ try { await inv.check(state , check) } catch (e) { throw new Tagged(e, inv.name ? `invariant ${inv.name}: ` : '') }
203
+ }
204
+ }
205
+ let out
206
+ try {
207
+ let setup = spec.setup
208
+ if (mutant !== undefined) {
209
+ const m = mutants.get(mutant)
210
+ if (!m) throw new MismatchError('unknown mutant', [...mutants.keys()], mutant)
211
+ setup = m
212
+ }
213
+ state = await setup(mutant === undefined ? ctx : {seed: run.seed, dir})
214
+ ready = true
215
+ await checkAll()
216
+ for (let i = 0; i < run.actions.length; i++) {
217
+ step = i; action = run.actions[i]
218
+ const a = run.actions[i]
219
+ const def = a && typeof a === 'object' ? byName.get(a.t) : undefined
220
+ if (!def) throw new MismatchError('unknown action', [...byName.keys()], a)
221
+ cov[def.name] = (cov[def.name] ?? 0) + 1
222
+ await def.run(state , a.args, check)
223
+ await checkAll()
224
+ }
225
+ out = {ok: true, steps: run.actions.length, cov}
226
+ } catch (e) {
227
+ out = e instanceof Tagged ? mismatch(e.cause, e.prefix) : mismatch(e)
228
+ }
229
+ if (ready && spec.teardown) {
230
+ try { await spec.teardown(state , ctx) } catch (e) { if (out.ok) out = mismatch(e, 'teardown: ') }
231
+ }
232
+ return out
233
+ },
234
+ }
235
+ }
236
+
237
+ /** An error from an invariant, with the invariant's name for the report. */
238
+ class Tagged {
239
+ cause
240
+ prefix
241
+ constructor(cause , prefix ) { this.cause = cause; this.prefix = prefix }
242
+ }
@@ -0,0 +1,207 @@
1
+ // Built from src/probe/stdio.ts by scripts/build.ts. Do not edit.
2
+ // PROBE targets in any language: `stopbar probe --cmd "<command>"` starts the command once per worker and speaks
3
+ // line-delimited JSON (NDJSON) with it on stdin/stdout, one request and one answer per line, in order:
4
+ // {"op":"info"} -> {"name":"...","description":"...","mutants":["M1",...]}
5
+ // {"op":"generate","seed":123} -> {"seed":123,"actions":[...]}
6
+ // {"op":"execute","run":{...},"dir":"...","mutant":"M1"} -> an Outcome ({"ok":true,"steps":N,"cov":{...}} or
7
+ // {"ok":false,"mismatch":{"step","action","what","expected","actual"}})
8
+ // Any answer may be {"error":"..."} instead. stdout carries only the protocol; the program logs to stderr. A process
9
+ // that exits, closes stdout, answers with something that is not JSON or does not answer within the timeout is an
10
+ // error (ProbeError with the end of its stderr), never a hung worker.
11
+ import {spawn, spawnSync, } from 'node:child_process'
12
+ import {existsSync, statSync} from 'node:fs'
13
+ import {resolve} from 'node:path'
14
+
15
+
16
+ /** A refusal of the user's input (unknown file, bad export, no mutants, a broken --cmd): the CLI exits 1 with it. */
17
+ export class ProbeError extends Error {}
18
+
19
+
20
+
21
+
22
+ /** Splits a command line into words: whitespace separates, '...' and "..." group (no escapes inside '...'). */
23
+ export function splitCommand(cmd ) {
24
+ const out = []
25
+ let cur = '', inWord = false, q = null
26
+ for (let i = 0; i < cmd.length; i++) {
27
+ const c = cmd[i]
28
+ if (q) {
29
+ if (c === q) q = null
30
+ else if (q === '"' && c === '\\' && (cmd[i + 1] === '"' || cmd[i + 1] === '\\')) cur += cmd[++i]
31
+ else cur += c
32
+ } else if (c === '"' || c === "'") { q = c; inWord = true } else if (/\s/.test(c)) { if (inWord) out.push(cur); cur = ''; inWord = false } else { cur += c; inWord = true }
33
+ }
34
+ if (inWord) out.push(cur)
35
+ return out
36
+ }
37
+
38
+ /** The file a command runs: the first word after the interpreter that names an existing file (relative to `cwd`). */
39
+ export function commandFile(cmd , cwd = process.cwd()) {
40
+ for (const w of splitCommand(cmd).slice(1)) {
41
+ if (w.startsWith('-')) continue
42
+ const f = resolve(cwd, w)
43
+ try { if (existsSync(f) && statSync(f).isFile()) return f } catch { /* not a file */ }
44
+ }
45
+ return null
46
+ }
47
+
48
+ const NAT = (n ) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0
49
+ const isObj = (x ) => !!x && typeof x === 'object' && !Array.isArray(x)
50
+
51
+ /** One long-lived process of a --cmd target. Requests go one at a time; `close` ends stdin and kills it if needed. */
52
+ export class CmdClient {
53
+ cmd
54
+ ch = null
55
+ buf = ''
56
+ err = ''
57
+ exited = null
58
+ waiting = null
59
+ chain = Promise.resolve()
60
+ cwd
61
+ timeoutMs
62
+
63
+ constructor(cmd , o = {}) {
64
+ if (!cmd.trim()) throw new ProbeError('--cmd needs a command, e.g. --cmd "python my_probe.py"')
65
+ this.cmd = cmd; this.cwd = o.cwd ?? process.cwd(); this.timeoutMs = o.timeoutMs ?? 300_000
66
+ }
67
+
68
+ stderrTail() {
69
+ const t = this.err.trim()
70
+ return t ? `; stderr: ${t.length > 600 ? '...' + t.slice(-600) : t}` : '; stderr: (empty)'
71
+ }
72
+
73
+ fail(why ) {
74
+ const w = this.waiting
75
+ this.waiting = null
76
+ if (w) { if (w.timer) clearTimeout(w.timer); w.bad(new ProbeError(`probe command ${JSON.stringify(this.cmd)} ${why} (waiting for the answer to ${w.op})${this.stderrTail()}`)) }
77
+ }
78
+
79
+ start() {
80
+ if (this.ch && this.exited === null) return this.ch
81
+ this.buf = ''; this.err = ''; this.exited = null
82
+ // a shell, so the command line works as typed (python, py -3, npx tsx, a script with a #!)
83
+ const ch = spawn(this.cmd, {cwd: this.cwd, shell: true, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32'})
84
+ this.ch = ch
85
+ ch.stdout .setEncoding('utf8'); ch.stderr .setEncoding('utf8')
86
+ const live = () => this.ch === ch // handlers of an earlier process of this client do nothing
87
+ ch.stderr .on('data', (d ) => { if (live()) this.err = (this.err + d).slice(-4000) })
88
+ ch.stdout .on('data', (d ) => {
89
+ if (!live()) return
90
+ this.buf += d
91
+ for (let i = this.buf.indexOf('\n'); i >= 0; i = this.buf.indexOf('\n')) {
92
+ const line = this.buf.slice(0, i).trim()
93
+ this.buf = this.buf.slice(i + 1)
94
+ if (!line) continue
95
+ const w = this.waiting
96
+ if (!w) { this.err += `\n[stopbar] unexpected line on stdout: ${line.slice(0, 200)}`; continue }
97
+ let v
98
+ try { v = JSON.parse(line) } catch {
99
+ this.fail(`printed a line that is not JSON: ${JSON.stringify(line.slice(0, 200))} (stdout is for the protocol only; log to stderr)`)
100
+ this.kill(); return
101
+ }
102
+ this.waiting = null
103
+ if (w.timer) clearTimeout(w.timer)
104
+ w.ok(v)
105
+ }
106
+ })
107
+ const gone = () => { if (live() && this.waiting) this.fail(this.exited ? `${this.exited} before answering` : 'closed stdout') }
108
+ // stdout may end before 'exit' arrives: wait a moment so the error names the exit code
109
+ ch.stdout .on('end', () => setTimeout(gone, 100))
110
+ ch.stdin .on('error', () => { /* EPIPE after an exit: reported below */ })
111
+ ch.on('error', (e) => { if (!live()) return; this.exited = `failed to start: ${e.message}`; this.fail(this.exited) })
112
+ ch.on('exit', (code, sig) => { if (live()) this.exited = `exited with ${sig ? `signal ${sig}` : `code ${code}`}` })
113
+ ch.on('close', gone)
114
+ return ch
115
+ }
116
+
117
+ /** Sends one request and waits for its answer line (requests are queued, one at a time). */
118
+ request(msg ) {
119
+ const go = () => new Promise ((ok, bad) => {
120
+ const ch = this.start()
121
+ const op = String(msg.op)
122
+ this.waiting = {op, ok, bad}
123
+ if (this.timeoutMs > 0) this.waiting.timer = setTimeout(() => { this.fail(`did not answer within ${this.timeoutMs} ms`); this.kill() }, this.timeoutMs)
124
+ try { ch.stdin .write(JSON.stringify(msg) + '\n') } catch (e) { this.fail(`does not read stdin: ${(e ).message}`) }
125
+ })
126
+ const p = this.chain.then(go, go)
127
+ this.chain = p.catch(() => undefined)
128
+ return p
129
+ }
130
+
131
+ async ask(msg ) {
132
+ const v = await this.request(msg)
133
+ if (isObj(v) && typeof v.error === 'string') throw new ProbeError(`probe command ${JSON.stringify(this.cmd)} answered ${msg.op} with an error: ${v.error}${this.stderrTail()}`)
134
+ if (!isObj(v)) throw new ProbeError(`probe command ${JSON.stringify(this.cmd)}: the answer to ${msg.op} is not a JSON object: ${JSON.stringify(v)?.slice(0, 200)}`)
135
+ return v
136
+ }
137
+
138
+ bad(op , why , v ) {
139
+ throw new ProbeError(`probe command ${JSON.stringify(this.cmd)}: bad answer to ${op}: ${why}; got ${JSON.stringify(v)?.slice(0, 300)}`)
140
+ }
141
+
142
+ async info() {
143
+ const v = await this.ask({op: 'info'})
144
+ if (typeof v.name !== 'string' || !v.name) this.bad('info', 'name must be a non-empty string', v)
145
+ if (typeof v.description !== 'string') this.bad('info', 'description must be a string', v)
146
+ if (v.mutants !== undefined && v.mutants !== null && !(Array.isArray(v.mutants) && v.mutants.every((m ) => typeof m === 'string' && m))) this.bad('info', 'mutants must be a list of names', v)
147
+ return {name: v.name, description: v.description, ...(Array.isArray(v.mutants) ? {mutants: v.mutants} : {})}
148
+ }
149
+
150
+ async generate(seed ) {
151
+ const v = await this.ask({op: 'generate', seed})
152
+ if (v.seed !== seed) this.bad('generate', `seed must be ${seed}`, v)
153
+ if (!Array.isArray(v.actions)) this.bad('generate', 'actions must be a list', v)
154
+ return {...v, seed, actions: v.actions}
155
+ }
156
+
157
+ async execute(run , dir , mutant ) {
158
+ const v = await this.ask({op: 'execute', run, dir, ...(mutant === undefined ? {} : {mutant})})
159
+ if (v.ok === true) {
160
+ if (!NAT(v.steps)) this.bad('execute', 'steps must be an integer >= 0', v)
161
+ const cov = v.cov ?? {}
162
+ if (!isObj(cov) || !Object.values(cov).every(NAT)) this.bad('execute', 'cov must map names to integers >= 0', v)
163
+ return {ok: true, steps: v.steps, cov}
164
+ }
165
+ if (v.ok === false) {
166
+ const m = v.mismatch
167
+ if (!isObj(m) || !Number.isSafeInteger(m.step) || m.step < -1 || typeof m.what !== 'string' || !m.what) this.bad('execute', 'mismatch needs step (integer >= -1) and what (non-empty string)', v)
168
+ return {ok: false, mismatch: {step: m.step, action: m.action ?? null, what: m.what, expected: m.expected ?? null, actual: m.actual ?? null}}
169
+ }
170
+ return this.bad('execute', 'ok must be true or false', v)
171
+ }
172
+
173
+ /** Kills the process tree. taskkill reports a failure (no rights, a sandbox, not on PATH) by its status, not by an
174
+ * exception: then the direct child is killed. The pipes are always destroyed and the child unref'd, so a process
175
+ * that survives (a grandchild of the shell) can never hold the event loop of Stopbar open. */
176
+ kill() {
177
+ const ch = this.ch
178
+ if (!ch) return
179
+ if (ch.pid !== undefined && this.exited === null) {
180
+ let treeKilled = false
181
+ try {
182
+ if (process.platform === 'win32') {
183
+ const r = spawnSync('taskkill', ['/pid', String(ch.pid), '/T', '/F'], {stdio: 'ignore', windowsHide: true})
184
+ treeKilled = !r.error && r.status === 0
185
+ } else { process.kill(-ch.pid, 'SIGKILL'); treeKilled = true }
186
+ } catch { /* fall back to the direct child below */ }
187
+ if (!treeKilled) try { ch.kill('SIGKILL') } catch { /* gone */ }
188
+ }
189
+ for (const s of [ch.stdin, ch.stdout, ch.stderr]) try { s?.destroy() } catch { /* closed */ }
190
+ ch.unref()
191
+ }
192
+
193
+ /** Ends stdin (a well-behaved target exits on EOF); kills the process tree after `graceMs`. */
194
+ async close(graceMs = 2000) {
195
+ const ch = this.ch
196
+ if (!ch || this.exited !== null) return
197
+ await this.chain
198
+ if (this.exited !== null) return
199
+ const gone = new Promise ((ok) => ch.once('exit', () => ok()))
200
+ try { ch.stdin .end() } catch { /* already closed */ }
201
+ const timer = new Promise ((ok) => { const t = setTimeout(() => ok('late'), graceMs); t.unref?.() })
202
+ if (await Promise.race([gone.then(() => 'gone' ), timer]) === 'late') {
203
+ this.kill() // destroys the pipes and unrefs the child even when the kill itself fails
204
+ await Promise.race([gone, new Promise((ok) => { const t = setTimeout(ok, 1000); t.unref?.() })])
205
+ }
206
+ }
207
+ }
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.1.3'
9
+ export const VERSION = '1.2.0'
10
10
 
11
11
 
12
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stopbar",
3
- "version": "1.1.3",
3
+ "version": "1.2.0",
4
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",
@@ -16,11 +16,21 @@
16
16
  "bin": {
17
17
  "stopbar": "bin/stopbar.mjs"
18
18
  },
19
+ "exports": {
20
+ "./probe": {
21
+ "types": "./src/probe/sdk.ts",
22
+ "default": "./dist/probe/sdk.js"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
19
26
  "files": [
20
27
  "bin/",
21
- "dist/",
28
+ "dist/**/*.js",
29
+ "dist/build-info.json",
22
30
  "src/kernel.ts",
31
+ "src/probe/sdk.ts",
23
32
  "claude-hooks.example.json",
33
+ "skills/",
24
34
  "README.md",
25
35
  "SECURITY.md",
26
36
  "CHANGELOG.md",
@@ -39,6 +49,7 @@
39
49
  "verify:lean": "node scripts/build.ts && node scripts/verify-lean.ts",
40
50
  "probe": "node scripts/build.ts && node bin/stopbar.mjs probe",
41
51
  "bench": "node bench/hook-latency.ts",
52
+ "typecheck": "tsc --noEmit",
42
53
  "prepack": "node scripts/build.ts"
43
54
  },
44
55
  "keywords": [
@@ -56,5 +67,9 @@
56
67
  ],
57
68
  "dependencies": {
58
69
  "gdp-wired": "0.60.0"
70
+ },
71
+ "devDependencies": {
72
+ "@types/node": "24.19.4",
73
+ "typescript": "5.9.3"
59
74
  }
60
75
  }
@@ -0,0 +1,126 @@
1
+ ---
2
+ name: stopbar
3
+ description: Load this skill when you work in a repository that Stopbar GATE protects (a `.git/stopbar/` directory, Stopbar hooks, or a Stopbar block message), or when you write a multi-step `stopbar probe` target to the Zero-FP standard.
4
+ ---
5
+
6
+ # Stopbar
7
+
8
+ Stopbar is an execution gate for AI coding agents. Its hooks block a commit until the build and the full test suite
9
+ pass at the current tree, block unapproved test changes and block risky or outbound commands after a secret read.
10
+ The hooks check the command text. This skill tells you how to work with them and how to write probes that find only
11
+ real bugs.
12
+
13
+ `<cli>` below is the Stopbar command that the block hints show. The default is `npx --no-install stopbar`; a human can
14
+ set another one with `stopbar init --cli "<cmd>"`.
15
+
16
+ ## 1. Working under Stopbar GATE
17
+
18
+ ### Gate commands
19
+
20
+ - Run `buildCmd` and `fullTestCmd` exactly as configured: the same text, alone, in the foreground. Do not add `;`,
21
+ `&&`, `||`, `|`, `>`, `2>&1` or `tail`, and do not run them in the background. A changed or chained command is not
22
+ recorded as a gate.
23
+ - A gate that runs longer than 10 minutes: run `<cli> run build` or `<cli> run test`. This form can run in the
24
+ background. Stopbar records the real exit status when the process ends and discards it if the tree changed.
25
+ - Always use `<cli> run build|test` when the config has `requireRun: true` (`--require-run`) and when you are Codex
26
+ CLI (Codex reports no exit status to hooks).
27
+ - Run the build and the full tests again after each change to the tree. A gate counts only at the revision where it
28
+ passed.
29
+ - `<cli> status` is read-only. Use it to see why a commit is blocked. It also shows a change that no hook has counted
30
+ yet; the next hook counts it, and then you run the build and the full tests again.
31
+
32
+ ### Commits
33
+
34
+ - One commit is one command: `git commit -m "..."`, or a quoted heredoc:
35
+
36
+ ```sh
37
+ git commit -m "$(cat <<'EOF'
38
+ Fix the parser
39
+
40
+ Body text.
41
+ EOF
42
+ )"
43
+ ```
44
+
45
+ - Do not chain `git add` and `git commit`. Run them as two commands.
46
+
47
+ ### Respect a block
48
+
49
+ - A block is a decision, not an error to work around. Read the reason and fix the cause.
50
+ - Do not bypass a block with a script, a wrapper, a generated file, an alias, `git -c alias.*`, `--no-verify` or
51
+ another git client.
52
+ - Do not edit `.git/` (hooks, `.git/stopbar/`), the hook config of any agent (`.claude/`, `.cursor/`, `.codex/`,
53
+ `.gemini/`, `.agents/`) or the Stopbar package.
54
+
55
+ ### Human-only commands
56
+
57
+ `init`, `upgrade`, `approve-tests`, `approve-shell`, `resume` and `reset` belong to the human. Do not run them, do not
58
+ ask a tool or another agent to run them, and do not put them in a script. The hooks block them. `stopbar probe init`
59
+ (section 2) is not `init`: you can run it.
60
+
61
+ Stop and ask the human when one of these is true:
62
+
63
+ | State | Cause | What to report | Human command |
64
+ |---|---|---|---|
65
+ | `testsTainted` | you changed an existing test or test config | the changed test files and why | `stopbar approve-tests` |
66
+ | `secretTainted` | you read a secret file or token | the one risky or outbound call you need and why | `stopbar approve-shell` |
67
+ | `HALT` | retry limit or tool-call budget reached | the last failing gate and its error, in short | `stopbar resume --extra N` |
68
+
69
+ Write the report in a few lines, then wait. In `HALT`, only the tools in `config.safeTools` pass (default
70
+ `mcp__ccd_turn__*` and `mcp__ccd_session_mgmt__*`); use them to tell the human about the block.
71
+
72
+ ## 2. Writing Zero-FP stateful probes (`stopbar probe`)
73
+
74
+ A probe runs random multi-step sequences against the system under test (SUT) and compares each step with a model.
75
+ Zero-FP means that every failure is a real bug.
76
+
77
+ ### Start
78
+
79
+ ```sh
80
+ stopbar probe init --lang ts --name <module> # writes probes/<module>.probe.ts
81
+ stopbar probe init --lang py --name <module> # writes probes/<module>_probe.py
82
+ ```
83
+
84
+ - TS/JS: `defineModel` from `stopbar/probe` (`setup`, `actions` with `gen` and `run`, `invariants`, `mutants`). Run
85
+ with `stopbar probe --target probes/<module>.probe.ts`.
86
+ - Python, Go, Rust and other languages: a program that speaks NDJSON on stdin/stdout (`info`, `generate`,
87
+ `execute`). Run with `stopbar probe --cmd "<command>"`. stdout is for the protocol only; print logs to stderr.
88
+ Catch an exception of the SUT in `execute` and answer with a mismatch.
89
+ - Run only a prober that you wrote in this session. A prober file from outside the session (another agent, an earlier
90
+ session, a download) needs a human review before you run it (SECURITY.md section 4). A new prober that you wrote
91
+ needs a human review before its result counts as evidence in `stopbar attest`.
92
+
93
+ ### The 5 Zero-FP rules
94
+
95
+ 1. **Deterministic `gen`.** Draw arguments only from the seeded generator (`r` in TS, the seed in `generate`) and
96
+ return plain JSON data. The same seed gives the same run on every machine.
97
+ 2. **Independent oracle.** The model is a separate, simple reference (an array, a map, a reference formula) plus
98
+ invariants. Never compare the SUT with itself or with a copy of its own code.
99
+ 3. **No clock, network or global state.** Write files only in the scratch directory of the run (`dir` in
100
+ `execute`). Reset all state in `setup`. Do not assume a short start or answer time under CPU load: for a slow
101
+ `--cmd` target, set `--cmd-timeout` with a large margin.
102
+ 4. **At least 2 realistic mutants.** Each mutant is a small, real bug (a dropped bound check, an off-by-one). Run
103
+ `stopbar probe ... --check-mutants` and make it pass (exit 0, no survivor) before you increase `--runs`. A
104
+ surviving mutant shows a weak model or weak actions; fix the probe, not the mutant.
105
+ 5. **Shrink, then reproduce.** On a failure, use the shrunk sequence in `repro-<seed>.json` (in `--out`). Write a
106
+ minimal test that reproduces the bug (less than 25 lines) and look for a known issue or test before you report it.
107
+ Replay the file with `--regressions <dir>` after the fix.
108
+
109
+ ### Before you report a finding
110
+
111
+ - Make sure that the model, not the SUT, is correct for the failing step. A model error is a false positive: fix the
112
+ model.
113
+ - Run the reproduction twice with the same seed. A result that changes is a rule 1 or rule 3 error.
114
+
115
+ ### After the first finding
116
+
117
+ - Save `repro-<seed>.json`. Then add a switch to the generator that turns off the known bug category for a while, so
118
+ that the original passes and `--check-mutants` can run. Look for the next bug.
119
+
120
+ ### Evidence
121
+
122
+ - Run `stopbar probe` in a repository with Stopbar. Each run appends a `probe:result` entry to the event log (target,
123
+ sha256 of the target file, tree snapshot, runs, mutants). Do not pass `--no-record`. The only exception is an
124
+ explicit instruction from a human (for example, an audit that must not add entries to the log).
125
+ - The human or CI collects the evidence with `stopbar attest --format md` or `--format json`. The `Probe evidence`
126
+ section shows the latest result per target and whether the tree is still the one that was probed.