stopbar 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,34 +9,49 @@
9
9
  import {spawn} from 'node:child_process'
10
10
  import {createHash} from 'node:crypto'
11
11
  import {existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs'
12
+ import {registerHooks} from 'node:module'
12
13
  import {availableParallelism, tmpdir} from 'node:os'
13
14
  import {isAbsolute, join, relative, resolve} from 'node:path'
14
15
  import {pathToFileURL} from 'node:url'
15
16
  import {PKG_ROOT} from '../pkg.js'
16
17
  import {findRepo, snapshot} from '../repo.js'
17
18
  import {appendEvent, paths, readConfig, readState, withLock} from '../store.js'
18
-
19
+
19
20
  import {CmdClient, commandFile, ProbeError} from './stdio.js'
20
21
 
21
22
 
22
23
  export {ProbeError} from './stdio.js'
23
24
 
24
- export const TARGETS = {
25
+ export const TARGETS = {
25
26
  wrapper: async () => (await import('./wrapper.js')).wrapperTarget,
26
27
  }
27
28
 
28
29
  const sha = (b ) => createHash('sha256').update(b).digest('hex')
29
30
 
30
- function isTarget(x ) {
31
- return !!x && typeof x === 'object' && typeof x.name === 'string' && !!x.name && typeof x.description === 'string' &&
31
+ function isTarget(v ) {
32
+ if (!v || typeof v !== 'object') return false
33
+ const x = v
34
+ return typeof x.name === 'string' && !!x.name && typeof x.description === 'string' &&
32
35
  typeof x.generate === 'function' && typeof x.execute === 'function' &&
33
36
  (x.mutants === undefined || (Array.isArray(x.mutants) && x.mutants.every((m ) => typeof m === 'string')))
34
37
  }
35
38
 
36
39
  /** What the runner drives: a ProbeTarget, or a --cmd target whose generate answers asynchronously and that must be closed. */
37
-
40
+
38
41
 
39
42
 
43
+ let probeHook = false
44
+ /** `import ... from 'stopbar/probe'` in a target file resolves to this package's SDK, also where no node_modules on the
45
+ * way from the file has stopbar (a global install, a copy outside the project). Every other specifier resolves as
46
+ * Node resolves it. Synchronous module hooks (node:module registerHooks, Node >= 22.15), registered once per process
47
+ * (the runner and each worker). */
48
+ function resolveStopbarProbe() {
49
+ if (probeHook) return
50
+ probeHook = true
51
+ const sdk = pathToFileURL(join(PKG_ROOT, 'dist', 'probe', 'sdk.js')).href
52
+ registerHooks({resolve: (specifier, context, nextResolve) => (specifier === 'stopbar/probe' ? {url: sdk, shortCircuit: true} : nextResolve(specifier, context))})
53
+ }
54
+
40
55
  /** A name in TARGETS, else a .ts/.mts/.js/.mjs file (absolute, or relative to `cwd`, then to `repo`) that exports a
41
56
  * ProbeTarget as `default` or as `target`. */
42
57
  export async function loadTarget(spec , cwd = process.cwd(), repo ) {
@@ -45,8 +60,9 @@ export async function loadTarget(spec , cwd = process.cwd(), repo
45
60
  const file = cands.find((f) => existsSync(f))
46
61
  if (!file) throw new ProbeError(`probe target ${JSON.stringify(spec)} is neither a known target (${Object.keys(TARGETS).join(', ')}) nor an existing file`)
47
62
  if (!/\.(ts|mts|js|mjs)$/.test(file)) throw new ProbeError(`probe target ${file}: the file must end in .ts, .mts, .js or .mjs`)
48
- let mod
49
- try { mod = await import(pathToFileURL(file).href) } catch (e) {
63
+ resolveStopbarProbe()
64
+ let mod
65
+ try { mod = await import(pathToFileURL(file).href) } catch (e) {
50
66
  throw new ProbeError(`probe target ${file} does not load: ${(e )?.message ?? e}`)
51
67
  }
52
68
  const t = isTarget(mod?.default) ? mod.default : isTarget(mod?.target) ? mod.target : null
@@ -173,8 +189,12 @@ function defaultWork(dir ) {
173
189
  /** A worker gets its share in a file in `work` (`--worker-file <path>`): the seeds as one argv JSON overflow the command
174
190
  * line (Windows ~32 KB, Linux 128 KB per argument) at large --runs or --mutant-runs. The file goes when the worker ends. */
175
191
  let workerFiles = 0
176
- function spawnWorker(p ) {
177
- return new Promise ((ok, bad) => {
192
+ /** One result line of a worker (see share): a run or a regression, or a mutant with `mutant` set. */
193
+
194
+
195
+
196
+ function spawnWorker (p ) {
197
+ return new Promise ((ok, bad) => {
178
198
  const file = join(p.work, `worker-${process.pid}-${++workerFiles}.json`)
179
199
  writeFileSync(file, JSON.stringify(p))
180
200
  const ch = spawn(process.execPath, [join(PKG_ROOT, 'bin', 'stopbar.mjs'), 'probe', '--worker-file', file], {stdio: ['ignore', 'pipe', 'inherit']})
@@ -183,9 +203,12 @@ function spawnWorker(p ) {
183
203
  ch.on('error', (e) => { rmSync(file, {force: true}); bad(e) })
184
204
  ch.on('exit', (code) => {
185
205
  rmSync(file, {force: true, maxRetries: 5})
186
- let v
206
+ let v
187
207
  try { v = JSON.parse(s.trim().split('\n').pop() ) } catch { return bad(new Error(`probe worker exit ${code}: ${s.slice(0, 500)}`)) }
188
- if (v && !Array.isArray(v) && typeof v.error === 'string') bad(new ProbeError(v.error)); else ok(v)
208
+ const error = v && typeof v === 'object' && !Array.isArray(v) ? (v ).error : undefined
209
+ if (typeof error === 'string') bad(new ProbeError(error))
210
+ else if (Array.isArray(v)) ok(v )
211
+ else bad(new Error(`probe worker exit ${code}: not a result list: ${s.slice(0, 500)}`))
189
212
  })
190
213
  })
191
214
  }
@@ -239,25 +262,25 @@ async function probeWith(R , o , log ,
239
262
  const parts = Array.from({length: jobs}, () => ({target: R.spec, ...cmdPart, seeds: [], regs: [], work}))
240
263
  seeds.forEach((s, i) => parts[i % jobs].seeds.push(s))
241
264
  regs.forEach((f, i) => parts[i % jobs].regs.push(f))
242
- const results = (await Promise.all(parts.filter((p) => p.seeds.length || p.regs.length).map(spawnWorker))).flat()
265
+ const results = (await Promise.all(parts.filter((p) => p.seeds.length || p.regs.length).map((p) => spawnWorker (p)))).flat()
243
266
  .sort((a, b) => (a.regression ? 0 : 1) - (b.regression ? 0 : 1) || a.seed - b.seed)
244
- const failed = results.filter((r) => !r.ok)
267
+ const failed = results.filter((r) => !r.ok)
245
268
  for (const f of failed) {
246
269
  const file = join(out, `repro-${f.seed}.json`)
247
270
  const run = f.minimal ?? f.run ?? await t.generate(f.seed)
248
271
  writeFileSync(file, JSON.stringify({target: t.name, ...(R.file ? {targetPath} : {}), ...cmdField, found: new Date().toISOString(), mismatch: f.minimalMismatch ?? f.mismatch, run}, null, 1) + '\n')
249
272
  log(`FAIL seed ${f.seed}${f.regression ? ' (regression ' + f.regression + ')' : ''}: ${f.mismatch.what} at step ${f.mismatch.step} ${JSON.stringify(f.mismatch.action)}\n expected ${JSON.stringify(f.mismatch.expected)}\n actual ${JSON.stringify(f.mismatch.actual)}\n ${f.minimal ? 'minimal ' : ''}reproduction (${run.actions.length} steps): ${file}`)
250
273
  }
251
- const ok = results.filter((r) => r.ok && !r.regression)
274
+ const ok = results.filter((r) => r.ok && !r.regression)
252
275
  const coverage = {}
253
- for (const r of ok) for (const [k, v] of Object.entries(r.cov )) coverage[k] = (coverage[k] ?? 0) + v
276
+ for (const r of ok) for (const [k, v] of Object.entries(r.cov)) coverage[k] = (coverage[k] ?? 0) + v
254
277
 
255
278
  // mutants: only on a passing original; each mutant in its own worker, seeds in order, the first failure kills it
256
279
  let mutants = null
257
280
  if (o.checkMutants && failed.length) log(`mutants: not checked, the original fails`)
258
281
  else if (o.checkMutants) {
259
282
  const mseeds = Array.from({length: mutantRuns}, (_, i) => seed0 + i)
260
- const res = (await pool(mutantNames, jobs, (m) => spawnWorker({target: R.spec, ...cmdPart, seeds: mseeds, regs: [], work, mutant: m}))).flat()
283
+ const res = (await pool(mutantNames, jobs, (m) => spawnWorker ({target: R.spec, ...cmdPart, seeds: mseeds, regs: [], work, mutant: m}))).flat()
261
284
  const details = res.map((r) => r.killed
262
285
  ? {name: r.mutant, status: 'KILLED', seed: r.seed, step: r.mismatch.step, what: r.mismatch.what, action: r.mismatch.action, runs: r.tried}
263
286
  : {name: r.mutant, status: 'SURVIVED', runs: r.tried})
@@ -212,6 +212,6 @@ export function initProbe(o = {}) {
212
212
  .replaceAll('__NAME__', name).replace('__RUN__', command)
213
213
  mkdirSync(dir, {recursive: true})
214
214
  writeFileSync(file, text)
215
- const needs = lang === 'ts' ? `\n (needs stopbar in the project, so that 'stopbar/probe' resolves: npm install --save-dev stopbar)` : ''
215
+ const needs = lang === 'ts' ? `\n (\`stopbar probe\` resolves 'stopbar/probe' itself; an editor or tsc needs stopbar in the project: npm install --save-dev stopbar)` : ''
216
216
  return {file, lang, command, message: `wrote ${file}\nrun it:\n ${command}${needs}`}
217
217
  }
package/dist/probe/sdk.js CHANGED
@@ -119,7 +119,7 @@ function errorText(e ) {
119
119
 
120
120
 
121
121
 
122
-
122
+
123
123
 
124
124
 
125
125
 
@@ -45,8 +45,9 @@ export function commandFile(cmd , cwd = process.cwd()) {
45
45
  return null
46
46
  }
47
47
 
48
- const NAT = (n ) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0
49
- const isObj = (x ) => !!x && typeof x === 'object' && !Array.isArray(x)
48
+ const NAT = (n ) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0
49
+ const INT = (n ) => typeof n === 'number' && Number.isSafeInteger(n)
50
+ const isObj = (x ) => !!x && typeof x === 'object' && !Array.isArray(x)
50
51
 
51
52
  /** One long-lived process of a --cmd target. Requests go one at a time; `close` ends stdin and kills it if needed. */
52
53
  export class CmdClient {
@@ -55,6 +56,7 @@ export class CmdClient {
55
56
  buf = ''
56
57
  err = ''
57
58
  exited = null
59
+ killed = false // set by kill(): its 'exit' may never arrive (the child is unref'd)
58
60
  waiting = null
59
61
  chain = Promise.resolve()
60
62
  cwd
@@ -77,8 +79,8 @@ export class CmdClient {
77
79
  }
78
80
 
79
81
  start() {
80
- if (this.ch && this.exited === null) return this.ch
81
- this.buf = ''; this.err = ''; this.exited = null
82
+ if (this.ch && this.exited === null && !this.killed) return this.ch
83
+ this.buf = ''; this.err = ''; this.exited = null; this.killed = false
82
84
  // a shell, so the command line works as typed (python, py -3, npx tsx, a script with a #!)
83
85
  const ch = spawn(this.cmd, {cwd: this.cwd, shell: true, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32'})
84
86
  this.ch = ch
@@ -128,7 +130,7 @@ export class CmdClient {
128
130
  return p
129
131
  }
130
132
 
131
- async ask(msg ) {
133
+ async ask(msg ) {
132
134
  const v = await this.request(msg)
133
135
  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
136
  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)}`)
@@ -160,11 +162,11 @@ export class CmdClient {
160
162
  if (!NAT(v.steps)) this.bad('execute', 'steps must be an integer >= 0', v)
161
163
  const cov = v.cov ?? {}
162
164
  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}
165
+ return {ok: true, steps: v.steps, cov: cov }
164
166
  }
165
167
  if (v.ok === false) {
166
168
  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)
169
+ if (!isObj(m) || !INT(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
170
  return {ok: false, mismatch: {step: m.step, action: m.action ?? null, what: m.what, expected: m.expected ?? null, actual: m.actual ?? null}}
169
171
  }
170
172
  return this.bad('execute', 'ok must be true or false', v)
@@ -176,6 +178,7 @@ export class CmdClient {
176
178
  kill() {
177
179
  const ch = this.ch
178
180
  if (!ch) return
181
+ this.killed = true
179
182
  if (ch.pid !== undefined && this.exited === null) {
180
183
  let treeKilled = false
181
184
  try {
@@ -190,18 +193,27 @@ export class CmdClient {
190
193
  ch.unref()
191
194
  }
192
195
 
193
- /** Ends stdin (a well-behaved target exits on EOF); kills the process tree after `graceMs`. */
196
+ /** Ends stdin (a well-behaved target exits on EOF); kills the process tree after `graceMs`. Returns at once for a
197
+ * process that has exited or was killed. The timers here hold the event loop and are cleared when the wait ends: an
198
+ * unref'd timer racing an 'exit' that never comes would let Node end with the caller's error unthrown (exit 0 from
199
+ * the CLI, exit 13 from `await probe()`). */
194
200
  async close(graceMs = 2000) {
195
201
  const ch = this.ch
196
- if (!ch || this.exited !== null) return
202
+ const done = () => this.killed || this.exited !== null || ch .exitCode !== null || ch .signalCode !== null
203
+ if (!ch || done()) return
197
204
  await this.chain
198
- if (this.exited !== null) return
205
+ if (done()) return
199
206
  const gone = new Promise ((ok) => ch.once('exit', () => ok()))
200
207
  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') {
208
+ if (await settle(gone, graceMs) === 'late') {
203
209
  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?.() })])
210
+ await settle(gone, 1000)
205
211
  }
206
212
  }
207
213
  }
214
+
215
+ /** 'gone' when `p` settles first, else 'late' after `ms`; the timer is cleared either way. */
216
+ async function settle(p , ms ) {
217
+ let t
218
+ try { return await Promise.race([p.then(() => 'gone' ), new Promise ((ok) => { t = setTimeout(() => ok('late'), ms) })]) } finally { clearTimeout(t) }
219
+ }
@@ -131,7 +131,7 @@ async function execute(run , dir ) {
131
131
  let st = IT.init(P)
132
132
  let modelSteps = 0
133
133
  let head = new Map(work), counted = new Map(work), countedCopy = true
134
- const view = () => R.decode(st)
134
+ const view = () => R.decode(st)
135
135
  const kstep = (req ) => {
136
136
  st = IT.step(P, st, R.encodeInput({op: 'EDIT_CODE', cost: 0, passed: false, fullSuite: false, suspicious: false, risky: false, treeChanged: false, approveRev: 0, extra: 0, ...req}, {maxRetries, cap}))
137
137
  modelSteps++
package/dist/repo.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import {execFileSync} from 'node:child_process'
4
4
  import {createHash} from 'node:crypto'
5
5
  import {copyFileSync, existsSync, readFileSync, rmSync, statSync} from 'node:fs'
6
+ import {homedir} from 'node:os'
6
7
  import {dirname, isAbsolute, join, resolve} from 'node:path'
7
8
 
8
9
  export class FailClosed extends Error {
@@ -35,6 +36,67 @@ export function findRepo(cwd ) {
35
36
  }
36
37
  }
37
38
 
39
+ // ---------------------------------------------------------------- core.hooksPath without a git process
40
+ /** The git common dir: `<gitDir>/commondir` (a worktree) names it, relative to gitDir; else gitDir itself. */
41
+ function commonDirOf(r ) {
42
+ try {
43
+ const rel = readFileSync(join(r.gitDir, 'commondir'), 'utf8').trim()
44
+ if (rel) return isAbsolute(rel) ? rel : resolve(r.gitDir, rel)
45
+ } catch { /* no commondir: not a linked worktree */ }
46
+ return r.gitDir
47
+ }
48
+
49
+ /** The value of one line `key = value` of a git config file: quotes removed, the escapes \" \\ \t \n \b read, an
50
+ * inline comment (# or ; outside quotes) dropped, spaces around the value trimmed. A key with no `=` is boolean true. */
51
+ function configLineValue(rest ) {
52
+ let out = '', q = false, pend = ''
53
+ for (let i = 0; i < rest.length; i++) {
54
+ const c = rest[i]
55
+ if (c === '\\' && i + 1 < rest.length) { const n = rest[++i]; out += pend + ({t: '\t', n: '\n', b: '\b'}[n] ?? n); pend = ''; continue }
56
+ if (c === '"') { q = !q; out += pend; pend = ''; continue }
57
+ if (!q && (c === '#' || c === ';')) break
58
+ if (!q && (c === ' ' || c === '\t')) { if (out) pend += c; continue }
59
+ out += pend + c; pend = ''
60
+ }
61
+ return out
62
+ }
63
+
64
+ /** The last `[core] hooksPath` value of a git config file, or undefined. Section and key names are case-insensitive;
65
+ * `[core "x"]` is another section. Include files are not followed (a known limit, SECURITY.md). */
66
+ export function configHooksPath(text ) {
67
+ let inCore = false, val
68
+ for (let line of text.split(/\r?\n/)) {
69
+ line = line.trim()
70
+ const sec = /^\[\s*([A-Za-z0-9.-]+)(\s+"(?:[^"\\]|\\.)*")?\s*\]\s*/.exec(line)
71
+ if (sec) { inCore = sec[1].toLowerCase() === 'core' && !sec[2]; line = line.slice(sec[0].length) }
72
+ if (!inCore || !line || line.startsWith('#') || line.startsWith(';')) continue
73
+ const kv = /^([A-Za-z][A-Za-z0-9-]*)\s*(?:=(.*))?$/.exec(line)
74
+ if (kv && kv[1].toLowerCase() === 'hookspath') val = kv[2] === undefined ? 'true' : configLineValue(kv[2])
75
+ }
76
+ return val
77
+ }
78
+
79
+
80
+ /** `core.hooksPath` read from the files: `<common-dir>/config`, then `<gitDir>/config.worktree` (wins when set). A
81
+ * relative value is relative to the working tree root (as git runs the hooks), `~/` is the home directory. Null when
82
+ * unset, empty, or when it names the default <common-dir>/hooks. Pure file system: no git process in PreToolUse. */
83
+ export function readHooksPath(r ) {
84
+ const common = commonDirOf(r)
85
+ let raw
86
+ for (const f of [join(common, 'config'), join(r.gitDir, 'config.worktree')]) {
87
+ let text
88
+ try { text = readFileSync(f, 'utf8') } catch { continue }
89
+ const v = configHooksPath(text)
90
+ if (v !== undefined) raw = v
91
+ }
92
+ if (!raw) return null
93
+ const expanded = raw === '~' || raw.startsWith('~/') ? join(homedir(), raw.slice(1)) : raw
94
+ const dir = isAbsolute(expanded) ? resolve(expanded) : resolve(r.root, expanded)
95
+ const def = resolve(common, 'hooks')
96
+ const same = process.platform === 'win32' ? dir.toLowerCase() === def.toLowerCase() : dir === def
97
+ return same ? null : {raw, dir}
98
+ }
99
+
38
100
  export let gitCalls = 0
39
101
  export function git(cwd , args , env , input ) {
40
102
  gitCalls++
package/dist/run.js CHANGED
@@ -11,6 +11,17 @@ import {readConfig, readState} from './store.js'
11
11
 
12
12
 
13
13
 
14
+ /** The environment of the gate command. On Windows `shell: true` starts cmd.exe; a PWD=C:/... inherited from Git Bash
15
+ * would reach a bash inside the gate, where `PATH="$PWD/node_modules/.bin:$PATH"` breaks at the colon of `C:` (exit
16
+ * 127). Without PWD
17
+ * that shell sets it from its own working directory. Other platforms: the environment as it is. */
18
+ export function gateEnv(env , platform = process.platform) {
19
+ if (platform !== 'win32') return env
20
+ const out = {}
21
+ for (const [k, v] of Object.entries(env)) if (k.toUpperCase() !== 'PWD') out[k] = v
22
+ return out
23
+ }
24
+
14
25
  export function runGate(which , o ) {
15
26
  if (which !== 'build' && which !== 'test') return {code: 1, msg: 'usage: stopbar run build|test'}
16
27
  const cwd = o.get('repo') ?? process.cwd()
@@ -22,7 +33,7 @@ export function runGate(which , o ) {
22
33
  if (before.code !== 0 && /FAIL-CLOSED|halted/.test(before.msg ?? '')) return {code: 2, msg: before.msg}
23
34
  const s0 = readState(repo)
24
35
  const expectedSnapshot = s0.snapshot, expectedRev = decode(s0.kernel).treeRev
25
- const r = spawnSync(command, {cwd: repo.root, shell: true, stdio: 'inherit'})
36
+ const r = spawnSync(command, {cwd: repo.root, shell: true, stdio: 'inherit', env: gateEnv(process.env)})
26
37
  const exit = r.status ?? 1
27
38
  const after = runEvent({hook_event_name: exit === 0 ? 'PostToolUse' : 'PostToolUseFailure', cwd: repo.root, tool_name: 'Bash', tool_input: {command},
28
39
  tool_response: {exitCode: exit}, stopbar: {...meta(which), expectedSnapshot, expectedRev}})
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.2.0'
9
+ export const VERSION = '1.2.2'
10
10
 
11
11
 
12
12
 
@@ -131,14 +131,16 @@ export function appendEvent(r , entry ) {
131
131
  } finally { closeSync(fd) }
132
132
  }
133
133
 
134
-
134
+ /** One parsed line of events.jsonl: the fields read by status, doctor and attest are typed; the rest stay unknown. */
135
+
136
+
135
137
  export function readEvents(r ) {
136
138
  const f = files(r).events
137
139
  if (!existsSync(f)) return {events: [], torn: []}
138
140
  const out = {events: [], torn: []}
139
141
  readFileSync(f, 'utf8').split('\n').forEach((l, i) => {
140
142
  if (!l) return
141
- try { out.events.push(JSON.parse(l)) } catch { out.torn.push({line: i + 1, text: l.slice(0, 120)}) }
143
+ try { const e = JSON.parse(l); out.events.push(e && typeof e === 'object' && !Array.isArray(e) ? e : {value: e}) } catch { out.torn.push({line: i + 1, text: l.slice(0, 120)}) }
142
144
  })
143
145
  return out
144
146
  }
package/dist/verify.js CHANGED
@@ -29,14 +29,20 @@ export async function loadKernel() {
29
29
  return {k, gw, machine}
30
30
  }
31
31
 
32
+
33
+
34
+
35
+
36
+
37
+
32
38
  /** The generated step function is the compileJs output of the unmutated kernel, and it agrees with the interpreter. */
33
- export async function checkGenerated(steps = 3000) {
39
+ export async function checkGenerated(steps = 3000) {
34
40
  const {k, machine} = await loadKernel()
35
41
  const R = k.kernel('none')
36
42
  const js = machine.compileJs(R.machine)
37
43
  const src = join(PKG_ROOT, 'src', 'kernel.ts')
38
44
  const kernelSha = existsSync(src) ? sha(readFileSync(src)) : null
39
- const res = {
45
+ const head = {
40
46
  machineName: G.MACHINE_NAME, machineSha256: G.MACHINE_SHA256, regeneratedSha256: sha(js),
41
47
  sameMachine: sha(js) === G.MACHINE_SHA256 && G.MACHINE_NAME === R.machine.name,
42
48
  kernelSourceSha256: G.KERNEL_SOURCE_SHA256, kernelSourceNow: kernelSha, sameSource: kernelSha === null ? null : kernelSha === G.KERNEL_SOURCE_SHA256,
@@ -48,7 +54,7 @@ export async function checkGenerated(steps = 3000) {
48
54
  for (let run = 0; done < steps; run++) {
49
55
  const params = {maxRetries: 1 + Math.floor(rnd() * 3), cap: 1 + Math.floor(rnd() * 12)}
50
56
  const P = R.encodeParams(params)
51
- let a = IT.init(P), b = G.init(params)
57
+ let a = IT.init(P), b = G.init(params)
52
58
  for (let i = 0; i < 25 && done < steps; i++, done++) {
53
59
  const req = randomRequest(rnd)
54
60
  const enc = R.encodeInput(req, params)
@@ -59,9 +65,7 @@ export async function checkGenerated(steps = 3000) {
59
65
  if (JSON.stringify(a.scalars) !== JSON.stringify(b.scalars)) { mismatches++; break }
60
66
  }
61
67
  }
62
- res.differential = {steps: done, refused, mismatches}
63
- res.ok = res.sameMachine === true && res.sameSource !== false && mismatches === 0
64
- return res
68
+ return {...head, differential: {steps: done, refused, mismatches}, ok: head.sameMachine && head.sameSource !== false && mismatches === 0}
65
69
  }
66
70
 
67
71
  // A concrete counterexample run for each mutant (each one found by the prover). verify
@@ -80,6 +84,7 @@ export const KNOWN_RUNS
80
84
  M6: {params: {maxRetries: 1, cap: 1}, trace: [{op: 'SHELL', suspicious: true, treeChanged: true}, {op: 'RUN_TESTS', passed: true, fullSuite: true}, {op: 'APPROVE_TESTS', approveRev: 0}, {op: 'RUN_BUILD', passed: true}, {op: 'COMMIT'}]},
81
85
  M7: {params: {maxRetries: 2, cap: 3}, trace: [{op: 'RUN_BUILD', cost: 3, passed: true}, {op: 'APPROVE_SHELL'}]},
82
86
  }
87
+
83
88
  const show = (q ) => {
84
89
  const flags = Object.entries(q).filter(([k, x]) => k !== 'op' && x).map(([k, x]) => `${k}=${x}`)
85
90
  return flags.length ? `${q.op}(${flags.join(',')})` : String(q.op)
@@ -90,64 +95,67 @@ export async function verify(o
90
95
  const {k, gw} = await loadKernel()
91
96
  const {kernel, laws, lemmas, MUTANTS} = k
92
97
  const OPT = {search: {ms: 60000}}
93
- const out = {gdpWired: '0.60.0', node: process.version, platform: `${process.platform} ${process.arch}`}
98
+ const head = {gdpWired: '0.60.0', node: process.version, platform: `${process.platform} ${process.arch}`}
94
99
 
95
100
  log('1. generated step function vs the proven rule')
96
- out.generated = await checkGenerated()
97
- log(` machine ${out.generated.machineName}: same compileJs output=${out.generated.sameMachine}, kernel.ts hash matches=${out.generated.sameSource}, ` +
98
- `differential ${out.generated.differential.steps} steps, mismatches=${out.generated.differential.mismatches}`)
101
+ const generated = await checkGenerated()
102
+ log(` machine ${generated.machineName}: same compileJs output=${generated.sameMachine}, kernel.ts hash matches=${generated.sameSource}, ` +
103
+ `differential ${generated.differential.steps} steps, mismatches=${generated.differential.mismatches}`)
99
104
 
100
105
  log('2. inductive proof of the original kernel (laws + lemmas I1-I5)')
106
+ let original
101
107
  {
102
108
  const r = kernel('none'), {laws: L, stepLaws: S} = laws(r)
103
109
  const t = Date.now()
104
110
  const v = gw.proveSteps(r, [...L, ...lemmas(r)], S, OPT)
105
- out.original = {proven: v.proven, checked: v.checked, stuck: v.stuck, goal: v.goal, why: v.why, ms: Date.now() - t,
106
- laws: [...L, ...lemmas(r)].map((l ) => l.name), stepLaws: S.map((l ) => l.name)}
111
+ original = {proven: v.proven, checked: v.checked, stuck: v.stuck, goal: v.goal, why: v.why, ms: Date.now() - t,
112
+ laws: [...L, ...lemmas(r)].map((l ) => l.name), stepLaws: S.map((l ) => l.name)}
107
113
  log(` proven=${v.proven} checked=${v.checked} ${Date.now() - t} ms${v.goal ? ' goal=' + v.goal : ''}`)
108
114
  }
109
115
 
110
116
  log('3. mutants: each must fall with a counterexample run')
111
- out.mutants = {}
117
+ const mutants = {}
112
118
  for (const m of MUTANTS.filter((x ) => x !== 'none')) {
113
119
  const r = kernel(m), {laws: L, stepLaws: S} = laws(r)
114
120
  const t = Date.now()
115
121
  const v = gw.proveSteps(r, L, S, OPT)
116
- const failed = [...L, ...S].find((l ) => v.goal?.startsWith(l.name))
122
+ const failed = [...L, ...S].find((l ) => v.goal?.startsWith(l.name))
117
123
  let minimized = false
118
124
  if (v.run && failed) { try { v.run = gw.minimizeRun(r, failed, v.run); minimized = true } catch { /* keep the unminimised run */ } }
119
- const trace = (v.run?.trace ?? []).map((q ) => {
120
- const op = typeof q.op === 'number' ? OPS[q.op] : q.op
125
+ const trace = (v.run?.trace ?? []).map((q ) => {
126
+ const op = typeof q.op === 'number' ? OPS[q.op] : String(q.op)
121
127
  const flags = Object.entries(q).filter(([kk, x]) => kk !== 'op' && x).map(([kk, x]) => `${kk}=${x}`)
122
128
  return flags.length ? `${op}(${flags.join(',')})` : op
123
129
  })
124
130
  // deterministic replay of the known counterexample: a law fails on the mutant and every law holds on the original
125
131
  const known = KNOWN_RUNS[m]
126
132
  const r0 = kernel('none'), l0 = laws(r0)
127
- const enc = (rule ) => known.trace.map((q) => rule.encodeInput({...REQ0, ...q}, known.params))
133
+ const enc = (rule ) => known.trace.map((q) => rule.encodeInput({...REQ0, ...q}, known.params))
128
134
  const onMutant = gw.replayRefutation(r, L, S, r.encodeParams(known.params), enc(r), 1000)
129
135
  const onOriginal = gw.replayRefutation(r0, l0.laws, l0.stepLaws, r0.encodeParams(known.params), enc(r0), 1000)
130
136
  const killed = v.proven === false && onMutant === true && onOriginal === false
131
- out.mutants[m] = {killed, proven: v.proven, goal: v.goal, ms: Date.now() - t, minimized, proverRun: v.run ? {params: v.run.params, trace} : null,
137
+ mutants[m] = {killed, proven: v.proven, goal: v.goal, ms: Date.now() - t, minimized, proverRun: v.run ? {params: v.run.params, trace} : null,
132
138
  proverWitness: v.run ? undefined : v.witness, counterexample: {params: known.params, trace: known.trace.map(show), breaksMutant: onMutant, breaksOriginal: onOriginal}}
133
139
  log(` ${m.padEnd(4)} ${killed ? 'KILLED' : 'SURVIVED'} by ${v.goal ?? '-'} (${Date.now() - t} ms)` +
134
140
  `\n counterexample ${known.trace.map(show).join(' -> ')} ${JSON.stringify(known.params)}: breaks the mutant=${onMutant}, breaks the original=${onOriginal}` +
135
141
  (trace.length ? `\n prover run (minimized=${minimized}): ${trace.join(' -> ')}` : '\n prover: inductive witness only (no run within the search budget)'))
136
142
  }
137
143
 
144
+ let lean
138
145
  if (o.lean) {
139
146
  const {toLean} = await import('gdp-wired/lean')
140
147
  const r = kernel('none'), {laws: L, stepLaws: S} = laws(r)
141
- const lean = toLean([{id: 'stopbar_kernel', machine: r.machine, laws: [...L, ...lemmas(r)], stepLaws: S}], {title: 'Stopbar kernel (gdp-wired 0.60.0)'})
142
- writeFileSync(o.lean, lean)
143
- out.lean = {file: o.lean, lines: lean.split('\n').length, theorems: (lean.match(/^\s*theorem\s/gm) ?? []).length, sorry: (lean.match(/\bsorry\b/g) ?? []).length, leanChecked: false}
144
- log(`4. Lean export ${o.lean}: ${out.lean.lines} lines, ${out.lean.theorems} theorems, ${out.lean.sorry} sorry (not checked by Lean here)`)
148
+ const text = toLean([{id: 'stopbar_kernel', machine: r.machine, laws: [...L, ...lemmas(r)], stepLaws: S}], {title: 'Stopbar kernel (gdp-wired 0.60.0)'})
149
+ writeFileSync(o.lean, text)
150
+ lean = {file: o.lean, lines: text.split('\n').length, theorems: (text.match(/^\s*theorem\s/gm) ?? []).length, sorry: (text.match(/\bsorry\b/g) ?? []).length, leanChecked: false}
151
+ log(`4. Lean export ${o.lean}: ${lean.lines} lines, ${lean.theorems} theorems, ${lean.sorry} sorry (not checked by Lean here)`)
145
152
  }
146
153
 
147
- const killed = Object.values(out.mutants).filter((x ) => x.killed).length
148
- const total = Object.keys(out.mutants).length
149
- out.ok = out.generated.ok && out.original.proven === true && out.original.checked === true && killed === total && total === 10
150
- out.summary = `original proven=${out.original.proven} checked=${out.original.checked}; mutants killed ${killed}/${total}; generated step ok=${out.generated.ok}`
154
+ const killed = Object.values(mutants).filter((x) => x.killed).length
155
+ const total = Object.keys(mutants).length
156
+ const ok = generated.ok && original.proven === true && original.checked === true && killed === total && total === 10
157
+ const summary = `original proven=${original.proven} checked=${original.checked}; mutants killed ${killed}/${total}; generated step ok=${generated.ok}`
158
+ const out = {...head, generated, original, mutants, ...(lean ? {lean} : {}), ok, summary}
151
159
  log(`RESULT: ${out.ok ? 'PASS' : 'FAIL'}: ${out.summary}`)
152
160
  if (o.out) writeFileSync(o.out, JSON.stringify(out, null, 1) + '\n')
153
161
  return out
package/docs/probe.md ADDED
@@ -0,0 +1,94 @@
1
+ # PROBE for your project
2
+
3
+ PROBE is the test tool of the Stopbar package: stateful probing of your own code against a model, with mutants that
4
+ must be caught. Back to the [README](../README.md).
5
+
6
+ `stopbar probe --target <file>` runs a model of any TS/JS code. The file exports (as `default` or as `target`) a
7
+ target; `defineModel` from `stopbar/probe` builds one from a list of actions:
8
+
9
+ ```ts
10
+ import {defineModel} from 'stopbar/probe'
11
+
12
+ export default defineModel<{q: BoundedQueue<number>; model: number[]}>({
13
+ name: 'bounded-queue', description: 'FIFO queue with capacity 4 vs an array model',
14
+ setup: () => ({q: new BoundedQueue<number>(4), model: []}),
15
+ actions: [
16
+ {name: 'push', weight: 3, gen: (r) => ({x: r.int(0, 99)}), run: (s, {x}, check) => {
17
+ const accepted = s.model.length < 4
18
+ check.eq('push result', s.q.push(x), accepted)
19
+ if (accepted) s.model.push(x)
20
+ }},
21
+ {name: 'shift', gen: () => null, run: (s, _a, check) => check.eq('shift result', s.q.shift(), s.model.shift())},
22
+ ],
23
+ invariants: [{name: 'size', check: (s, check) => check.eq('size', s.q.size, s.model.length)}],
24
+ mutants: {M1_dropCap: () => ({q: new BoundedQueue<number>(4, {checkCap: false}), model: []})},
25
+ })
26
+ ```
27
+
28
+ - `gen(r)` returns pure JSON data for one step. `r` is a deterministic generator (`createRng`: xorshift32, the same
29
+ numbers on Windows and Linux). A run is `{seed, actions: [{t: name, args}]}` with `minSteps`..`maxSteps` steps
30
+ (default 15..40).
31
+ - `run(state, args, check)` drives the real code and compares it with the model: `check.eq` (deep strict equality),
32
+ `check.ok`, `check.fail`. A failed check, and any exception from the code under test, is a mismatch with the step and
33
+ the action, not a crash. Invariants run after `setup` (step -1) and after every step. `teardown` runs after every run
34
+ whose `setup` returned, also after a failure.
35
+ - A failure is shrunk (cut after the failing step, then removal of blocks of half, a quarter, ... of the run, then of
36
+ single steps) and written to `repro-<seed>.json` in `--out`. `--regressions <dir>` replays such files on every run.
37
+ A file target replays only the regressions you name.
38
+ - `--check-mutants`: each mutant replaces `setup` with a damaged system under test. The original must pass, and every
39
+ mutant must fail within `--mutant-runs` seeds (default 50). Exit 0 only then. A survivor is named in the output and
40
+ in `summary.json` (`mutants.survived`). A target without mutants is refused.
41
+ - In a repository with Stopbar, every run appends a `probe:result` entry to `events.jsonl` (target, sha256 of the
42
+ target file, tree snapshot, runs, steps, mutants, sha256 of `summary.json`). It is not a kernel step and does not
43
+ change `state.json`. `stopbar attest` shows the latest entry per target and whether the tree is still the one that
44
+ was probed. `--no-record` skips the entry. Outside a Stopbar repository nothing is recorded.
45
+
46
+ A complete example with two mutants: [`examples/bounded-queue.probe.ts`](../examples/bounded-queue.probe.ts)
47
+ (`stopbar probe --target examples/bounded-queue.probe.ts --check-mutants`). TypeScript files need Node's type
48
+ stripping (Node 22.18 or later): only erasable syntax, no `enum` and no constructor parameter properties.
49
+
50
+ `import {defineModel} from 'stopbar/probe'` resolves to the SDK of the Stopbar that runs `stopbar probe`, also when
51
+ the project has no `stopbar` in its `node_modules` (a global install, `npx`, a copy elsewhere): since 1.2.2 the probe
52
+ runner registers a module resolve hook (`registerHooks` from `node:module`) for that one specifier, in the runner and in
53
+ every worker. An editor or `tsc` still needs `stopbar` in the project for the types (`npm install --save-dev stopbar`).
54
+
55
+ ## Any language: `--cmd`
56
+
57
+ `stopbar probe --cmd "<command>"` probes a program in any language (Python, Go, Rust, ...). Each worker (`--jobs`)
58
+ starts the command once, in a shell, in the current directory, and keeps it for all its runs, so the start-up cost
59
+ is paid once per worker and not once per seed. Stopbar sends one JSON object per line on stdin and reads one answer
60
+ per line on stdout (NDJSON):
61
+
62
+ | Request | Answer |
63
+ |---|---|
64
+ | `{"op":"info"}` | `{"name":"<string>","description":"<string>","mutants":["M1",...]}` (`mutants` is optional) |
65
+ | `{"op":"generate","seed":123}` | `{"seed":123,"actions":[...]}`: pure JSON data, the same for the same seed |
66
+ | `{"op":"execute","run":{"seed":123,"actions":[...]},"dir":"<scratch dir>","mutant":"M1"}` | `{"ok":true,"steps":N,"cov":{"push":3}}` or `{"ok":false,"mismatch":{"step":2,"action":{...},"what":"...","expected":...,"actual":...}}` |
67
+
68
+ - `mutant` is sent only with `--check-mutants`. `dir` is an empty scratch directory for each execution.
69
+ - Any answer can be `{"error":"<text>"}`. stdout is for the protocol only: print logs to stderr.
70
+ - An exception of the code under test is a finding: catch it in `execute` and answer with a mismatch (the
71
+ templates do this). A process that exits, closes stdout, prints a line that is not JSON or gives no answer within
72
+ `--cmd-timeout` ms (default 300000) stops the probe with exit 1 and the end of its stderr. When the probe ends,
73
+ Stopbar closes stdin; a process that does not exit within 2 s is killed.
74
+ - Shrinking, `--regressions` / `--regressions-only`, `--check-mutants`, `summary.json`, `repro-<seed>.json`,
75
+ `probe:result` and `attest` work as for `--target <file>`. `target` in a reproduction is the `name` from `info`;
76
+ `targetCmd` is the command. A `--cmd` target replays only the regressions in `--regressions <dir>`.
77
+ - `targetSha256` is the sha256 of `--target-file <path>`, else of the first word after the interpreter that is an
78
+ existing file (`python examples/bounded_queue_probe.py` hashes that file), else `null`.
79
+
80
+ [`examples/bounded_queue_probe.py`](../examples/bounded_queue_probe.py) is the same queue model in Python, with the
81
+ standard library only:
82
+
83
+ ```sh
84
+ stopbar probe --cmd "python examples/bounded_queue_probe.py" --runs 200 --check-mutants
85
+ ```
86
+
87
+ ## A starter target: `stopbar probe init`
88
+
89
+ `stopbar probe init --lang ts` writes `probes/sample.probe.ts` (`defineModel`), and `--lang py` writes
90
+ `probes/sample_probe.py` (the NDJSON protocol, standard library only: `json`, `random`, `sys`). Both hold the same
91
+ model with 2 actions, 1 invariant, 2 mutants and the rules for zero false positives, and `--check-mutants` passes on
92
+ them as written. The command prints the line that runs the file. `--name` takes letters, digits, `-` and `_` only;
93
+ `--out` (default `probes`) is relative to `--repo`, else to the current directory; an existing file stays unless you
94
+ pass `--force`.