stopbar 1.1.2 → 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.
@@ -2,36 +2,103 @@
2
2
  // PROBE: stateful probing with a reference model. A target generates runs (a seed and a list of actions, pure data),
3
3
  // executes them against the real thing and compares every step with its model. The runner spreads seeds over worker
4
4
  // processes, replays saved regressions, shrinks a failing run to a minimal one and writes it as JSON.
5
- // v1.0 has one target, "wrapper" (the Stopbar hooks themselves). New targets register in TARGETS; the CLI stays
6
- // `stopbar probe --target <name>`.
5
+ // Targets: "wrapper" (the Stopbar hooks themselves, in TARGETS), a file of any TS/JS project
6
+ // (`stopbar probe --target path/to/x.probe.ts`, usually written with defineModel from `stopbar/probe`) or a program in
7
+ // any language that speaks NDJSON on stdin/stdout (`stopbar probe --cmd "python x_probe.py"`, see stdio.ts).
8
+ // With --check-mutants every mutant the target declares must be caught; a result is recorded in events.jsonl.
7
9
  import {spawn} from 'node:child_process'
10
+ import {createHash} from 'node:crypto'
8
11
  import {existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs'
9
12
  import {availableParallelism, tmpdir} from 'node:os'
10
- import {join} from 'node:path'
13
+ import {isAbsolute, join, relative, resolve} from 'node:path'
14
+ import {pathToFileURL} from 'node:url'
11
15
  import {PKG_ROOT} from '../pkg.js'
12
- import {findRepo} from '../repo.js'
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
16
+ import {findRepo, snapshot} from '../repo.js'
17
+ import {appendEvent, paths, readConfig, readState, withLock} from '../store.js'
18
+
19
+ import {CmdClient, commandFile, ProbeError} from './stdio.js'
20
+
21
+
22
+ export {ProbeError} from './stdio.js'
24
23
 
25
24
  export const TARGETS = {
26
25
  wrapper: async () => (await import('./wrapper.js')).wrapperTarget,
27
26
  }
28
27
 
29
- /** Delta debugging by single deletions: the shortest sequence that still fails the same way. */
30
- export async function shrink (t , run , dir , what ) {
28
+ const sha = (b ) => createHash('sha256').update(b).digest('hex')
29
+
30
+ function isTarget(x ) {
31
+ return !!x && typeof x === 'object' && typeof x.name === 'string' && !!x.name && typeof x.description === 'string' &&
32
+ typeof x.generate === 'function' && typeof x.execute === 'function' &&
33
+ (x.mutants === undefined || (Array.isArray(x.mutants) && x.mutants.every((m ) => typeof m === 'string')))
34
+ }
35
+
36
+ /** What the runner drives: a ProbeTarget, or a --cmd target whose generate answers asynchronously and that must be closed. */
37
+
38
+
39
+
40
+ /** A name in TARGETS, else a .ts/.mts/.js/.mjs file (absolute, or relative to `cwd`, then to `repo`) that exports a
41
+ * ProbeTarget as `default` or as `target`. */
42
+ export async function loadTarget(spec , cwd = process.cwd(), repo ) {
43
+ if (Object.hasOwn(TARGETS, spec)) return {t: await TARGETS[spec](), spec, file: null, sha256: null}
44
+ const cands = isAbsolute(spec) ? [spec] : [resolve(cwd, spec), ...(repo ? [resolve(repo, spec)] : [])]
45
+ const file = cands.find((f) => existsSync(f))
46
+ if (!file) throw new ProbeError(`probe target ${JSON.stringify(spec)} is neither a known target (${Object.keys(TARGETS).join(', ')}) nor an existing file`)
47
+ 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) {
50
+ throw new ProbeError(`probe target ${file} does not load: ${(e )?.message ?? e}`)
51
+ }
52
+ const t = isTarget(mod?.default) ? mod.default : isTarget(mod?.target) ? mod.target : null
53
+ if (!t) throw new ProbeError(`probe target ${file} has no valid export: export default (or export const target) an object with name, description, generate(seed) and execute(run, dir), e.g. defineModel({...}) from 'stopbar/probe'`)
54
+ return {t, spec: file, file, sha256: sha(readFileSync(file))}
55
+ }
56
+
57
+ /** A --cmd target: asks the program for info (it is started now and again on demand after `close`). `targetFile`
58
+ * (absolute, or relative to `cwd`, then to `repo`) is hashed; else the first existing file in the command, else none. */
59
+ export async function loadCmd(cmd , o = {}) {
60
+ const cwd = o.cwd ?? process.cwd()
61
+ let file = null
62
+ if (o.targetFile !== undefined) {
63
+ const cands = isAbsolute(o.targetFile) ? [o.targetFile] : [resolve(cwd, o.targetFile), ...(o.repo ? [resolve(o.repo, o.targetFile)] : [])]
64
+ file = cands.find((f) => existsSync(f)) ?? null
65
+ if (!file) throw new ProbeError(`--target-file ${JSON.stringify(o.targetFile)} does not exist`)
66
+ } else file = commandFile(cmd, cwd)
67
+ const c = new CmdClient(cmd, {cwd, timeoutMs: o.timeoutMs})
68
+ let info
69
+ try { info = await c.info() } catch (e) { await c.close(); throw e }
70
+ const t = {
71
+ name: info.name, description: info.description, ...(info.mutants ? {mutants: info.mutants} : {}),
72
+ generate: (seed) => c.generate(seed),
73
+ execute: (run, dir, mutant) => c.execute(run, dir, mutant),
74
+ close: () => c.close(),
75
+ }
76
+ return {t, spec: info.name, file, sha256: file ? sha(readFileSync(file)) : null, cmd}
77
+ }
78
+
79
+ /** Every execute starts in an empty scratch directory. */
80
+ async function exec(t , run , dir , mutant ) {
81
+ rmSync(dir, {recursive: true, force: true, maxRetries: 5}); mkdirSync(dir, {recursive: true})
82
+ return mutant === undefined ? t.execute(run, dir) : t.execute(run, dir, mutant)
83
+ }
84
+
85
+ /** Delta debugging: the shortest sequence that still fails the same way (same `what`). Deterministic order.
86
+ * 0: cut after the failing step; 1: remove blocks of len/2, len/4, ... (>= 2), from the largest again after every
87
+ * success; 2: single deletions from the end, to a fixed point. */
88
+ export async function shrink (t , run , dir , what ) {
31
89
  let cur = run
32
- const fails = async (r ) => { const x = await t.execute(r, dir); return !x.ok && x.mismatch.what === what }
33
- const end = await t.execute(cur, dir)
90
+ const fails = async (r ) => { const x = await exec(t, r, dir); return !x.ok && x.mismatch.what === what }
91
+ const end = await exec(t, cur, dir)
34
92
  if (!end.ok) cur = {...cur, actions: cur.actions.slice(0, end.mismatch.step + 1)}
93
+ phase1: while (cur.actions.length > 2) {
94
+ for (let size = Math.floor(cur.actions.length / 2); size >= 2; size = Math.floor(size / 2)) {
95
+ for (let at = 0; at < cur.actions.length; at += size) {
96
+ const cand = {...cur, actions: [...cur.actions.slice(0, at), ...cur.actions.slice(at + size)]}
97
+ if (cand.actions.length && await fails(cand)) { cur = cand; continue phase1 }
98
+ }
99
+ }
100
+ break
101
+ }
35
102
  for (let changed = true; changed;) {
36
103
  changed = false
37
104
  for (let i = cur.actions.length - 1; i >= 0; i--) {
@@ -42,78 +109,201 @@ export async function shrink (t , run , dir
42
109
  return cur
43
110
  }
44
111
 
45
-
112
+
46
113
 
47
- /** Worker process: runs its share and prints one JSON line with the results. */
114
+ /** Worker process: runs its share and prints one JSON line with the results (or {error} for a ProbeError). With
115
+ * `mutant` it runs the seeds in order against that mutant and stops at the first one that fails (no shrinking).
116
+ * A --cmd target is one process for the whole share, closed at the end. */
48
117
  export async function worker(p ) {
49
- const t = await TARGETS[p.target]()
118
+ let t = null
119
+ try {
120
+ t = (p.cmd !== undefined ? await loadCmd(p.cmd, {timeoutMs: p.timeoutMs}) : await loadTarget(p.target)).t
121
+ process.stdout.write(JSON.stringify(await share(t, p)) + '\n')
122
+ } catch (e) {
123
+ if (!(e instanceof ProbeError)) throw e
124
+ process.stdout.write(JSON.stringify({error: e.message}) + '\n')
125
+ } finally { await t?.close?.() }
126
+ }
127
+
128
+ async function share(t , p ) {
50
129
  const res = []
130
+ if (p.mutant !== undefined) {
131
+ let tried = 0
132
+ for (const seed of p.seeds) {
133
+ tried++
134
+ const dir = join(p.work, `mut-${process.pid}-${seed}`)
135
+ const x = await exec(t, await t.generate(seed), dir, p.mutant)
136
+ rmSync(dir, {recursive: true, force: true, maxRetries: 5})
137
+ if (!x.ok) { res.push({mutant: p.mutant, killed: true, seed, tried, mismatch: x.mismatch}); break }
138
+ }
139
+ if (!res.length) res.push({mutant: p.mutant, killed: false, tried})
140
+ return res
141
+ }
51
142
  for (const f of p.regs) {
52
143
  const run = JSON.parse(readFileSync(f, 'utf8')).run
53
144
  const dir = join(p.work, `reg-${run.seed}-${process.pid}`)
54
- res.push({regression: f, seed: run.seed, ...(await t.execute(run, dir))})
145
+ const x = await exec(t, run, dir)
146
+ res.push({regression: f, seed: run.seed, ...x, ...(x.ok ? {} : {run})})
55
147
  rmSync(dir, {recursive: true, force: true, maxRetries: 5})
56
148
  }
57
149
  for (const seed of p.seeds) {
58
- const run = t.generate(seed)
150
+ const run = await t.generate(seed)
59
151
  const dir = join(p.work, `run-${seed}`)
60
- const x = await t.execute(run, dir)
152
+ const x = await exec(t, run, dir)
61
153
  if (!x.ok) {
62
154
  const min = await shrink(t, run, dir, x.mismatch.what)
63
- const again = await t.execute(min, dir)
155
+ const again = await exec(t, min, dir)
64
156
  res.push({seed, ...x, minimal: min, minimalMismatch: again.ok ? null : again.mismatch})
65
157
  } else res.push({seed, ...x})
66
158
  rmSync(dir, {recursive: true, force: true, maxRetries: 5})
67
159
  }
68
- process.stdout.write(JSON.stringify(res) + '\n')
160
+ return res
69
161
  }
70
162
 
71
-
163
+
164
+
72
165
 
73
- function defaultWork() {
74
- try { return join(findRepo(process.cwd()).gitDir, 'stopbar', 'probe') } catch { return join(tmpdir(), `stopbar-probe-${process.pid}`) }
166
+ /** <git-dir>/stopbar/probe in a repository with Stopbar, else a temporary directory (a project without Stopbar gets
167
+ * no .git/stopbar from the prober). */
168
+ function defaultWork(dir ) {
169
+ try { const r = findRepo(dir); if (existsSync(r.stateDir)) return join(r.stateDir, 'probe') } catch { /* not a git repository */ }
170
+ return join(tmpdir(), `stopbar-probe-${process.pid}`)
171
+ }
172
+
173
+ /** A worker gets its share in a file in `work` (`--worker-file <path>`): the seeds as one argv JSON overflow the command
174
+ * line (Windows ~32 KB, Linux 128 KB per argument) at large --runs or --mutant-runs. The file goes when the worker ends. */
175
+ let workerFiles = 0
176
+ function spawnWorker(p ) {
177
+ return new Promise ((ok, bad) => {
178
+ const file = join(p.work, `worker-${process.pid}-${++workerFiles}.json`)
179
+ writeFileSync(file, JSON.stringify(p))
180
+ const ch = spawn(process.execPath, [join(PKG_ROOT, 'bin', 'stopbar.mjs'), 'probe', '--worker-file', file], {stdio: ['ignore', 'pipe', 'inherit']})
181
+ let s = ''
182
+ ch.stdout.on('data', (d) => { s += d })
183
+ ch.on('error', (e) => { rmSync(file, {force: true}); bad(e) })
184
+ ch.on('exit', (code) => {
185
+ rmSync(file, {force: true, maxRetries: 5})
186
+ let v
187
+ 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)
189
+ })
190
+ })
191
+ }
192
+
193
+ /** At most `jobs` promises at a time; results in input order. */
194
+ async function pool (xs , jobs , f ) {
195
+ const out = new Array(xs.length)
196
+ let next = 0
197
+ await Promise.all(Array.from({length: Math.min(jobs, xs.length)}, async () => { while (next < xs.length) { const i = next++; out[i] = await f(xs[i]) } }))
198
+ return out
199
+ }
200
+
201
+ /** A saved reproduction or regression: JSON with a run of actions (summary.json and other files are skipped). */
202
+ function isRegression(f ) {
203
+ try { const j = JSON.parse(readFileSync(f, 'utf8')); return !!j?.run && Array.isArray(j.run.actions) && typeof j.run.seed === 'number' } catch { return false }
75
204
  }
76
205
 
77
206
  export async function probe(o = {}) {
78
207
  const log = o.log ?? ((s ) => process.stdout.write(s + '\n'))
79
- const target = o.target ?? 'wrapper'
80
- if (!TARGETS[target]) throw new Error(`unknown probe target ${JSON.stringify(target)}; known: ${Object.keys(TARGETS).join(', ')}`)
81
- const t = await TARGETS[target]()
82
- const runs = o.runs ?? 200, seed0 = o.seed ?? 1
208
+ const repoDir = o.repo ?? process.cwd()
209
+ if (o.cmd !== undefined && o.target !== undefined) throw new ProbeError('--target and --cmd exclude each other: give a file or name with --target, or a command with --cmd')
210
+ if (o.targetFile !== undefined && o.cmd === undefined) throw new ProbeError('--target-file needs --cmd (a --target file is hashed anyway)')
211
+ const R = o.cmd !== undefined ? await loadCmd(o.cmd, {repo: o.repo, targetFile: o.targetFile, timeoutMs: o.cmdTimeoutMs}) : await loadTarget(o.target ?? 'wrapper', process.cwd(), o.repo)
212
+ // the main process needs only info from a --cmd target: its process is not kept while the workers run
213
+ await R.t.close?.()
214
+ try { return await probeWith(R, o, log, repoDir) } finally { await R.t.close?.() }
215
+ }
216
+
217
+ async function probeWith(R , o , log , repoDir ) {
218
+ const t = R.t
219
+ const mutantNames = t.mutants ?? []
220
+ if (o.checkMutants && !mutantNames.length) throw new ProbeError(`--check-mutants: target ${t.name} declares no mutants (add mutants: {...} to defineModel, or drop --check-mutants)`)
221
+ const runs = o.runs ?? 200, seed0 = o.seed ?? 1, mutantRuns = o.mutantRuns ?? 50
222
+ if (o.checkMutants && mutantRuns < 1) throw new ProbeError('--mutant-runs must be at least 1')
83
223
  const jobs = Math.max(1, o.jobs ?? Math.min(16, Math.max(1, availableParallelism() - 2)))
84
- const work = o.work ?? defaultWork(), out = o.out ?? join(work, 'out')
85
- const regDir = o.regressions ?? join(PKG_ROOT, 'tests', 'regressions')
86
- const regs = existsSync(regDir) ? readdirSync(regDir).filter((f) => f.endsWith('.json')).map((f) => join(regDir, f)) : []
224
+ const work = o.work ?? defaultWork(repoDir), out = o.out ?? join(work, 'out')
225
+ // a file target replays only the regressions the user names; the wrapper also has Stopbar's own
226
+ const regDir = o.regressions ?? (R.file || R.cmd !== undefined ? null : join(PKG_ROOT, 'tests', 'regressions'))
227
+ const regs = regDir && existsSync(regDir) ? readdirSync(regDir).filter((f) => f.endsWith('.json')).sort().map((f) => join(regDir, f)).filter(isRegression) : []
87
228
  const seeds = o.regressionsOnly ? [] : Array.from({length: runs}, (_, i) => seed0 + i)
88
229
  mkdirSync(work, {recursive: true}); mkdirSync(out, {recursive: true})
89
- for (const f of readdirSync(work)) if (/^(run|reg)-/.test(f)) rmSync(join(work, f), {recursive: true, force: true, maxRetries: 5})
90
- for (const f of readdirSync(out)) if (/^repro-\d+\.json$/.test(f)) rmSync(join(out, f))
91
- log(`probe ${target}: ${t.description}; ${seeds.length} random runs + ${regs.length} regression(s), ${jobs} jobs`)
230
+ for (const f of readdirSync(work)) if (/^(run|reg|mut|worker)-/.test(f)) rmSync(join(work, f), {recursive: true, force: true, maxRetries: 5})
231
+ // old reproductions go, unless they are the regressions of this run
232
+ if (!regDir || resolve(regDir) !== resolve(out)) for (const f of readdirSync(out)) if (/^repro-\d+\.json$/.test(f)) rmSync(join(out, f))
233
+ const targetPath = R.file ? relPath(repoDir, R.file) : t.name
234
+ const cmdField = R.cmd !== undefined ? {targetCmd: R.cmd} : {}
235
+ const cmdPart = R.cmd !== undefined ? {cmd: R.cmd, ...(o.cmdTimeoutMs !== undefined ? {timeoutMs: o.cmdTimeoutMs} : {})} : {}
236
+ log(`probe ${t.name}: ${t.description}; ${seeds.length} random runs + ${regs.length} regression(s), ${jobs} jobs${R.cmd !== undefined ? `\n command ${R.cmd}` : ''}` +
237
+ `${R.sha256 ? `\n target ${R.file} sha256 ${R.sha256}` : R.cmd !== undefined ? '\n target sha256 none (no file found in the command; name one with --target-file)' : ''}`)
92
238
  const t0 = Date.now()
93
- const parts = Array.from({length: jobs}, () => ({target, seeds: [], regs: [], work}))
239
+ const parts = Array.from({length: jobs}, () => ({target: R.spec, ...cmdPart, seeds: [], regs: [], work}))
94
240
  seeds.forEach((s, i) => parts[i % jobs].seeds.push(s))
95
241
  regs.forEach((f, i) => parts[i % jobs].regs.push(f))
96
- const results = (await Promise.all(parts.filter((p) => p.seeds.length || p.regs.length).map((p) => new Promise ((ok, bad) => {
97
- const ch = spawn(process.execPath, [join(PKG_ROOT, 'bin', 'stopbar.mjs'), 'probe', '--worker', JSON.stringify(p)], {stdio: ['ignore', 'pipe', 'inherit']})
98
- let s = ''
99
- ch.stdout.on('data', (d) => { s += d })
100
- ch.on('exit', (code) => { try { ok(JSON.parse(s.trim().split('\n').pop() )) } catch { bad(new Error(`probe worker exit ${code}: ${s.slice(0, 500)}`)) } })
101
- })))).flat()
242
+ const results = (await Promise.all(parts.filter((p) => p.seeds.length || p.regs.length).map(spawnWorker))).flat()
243
+ .sort((a, b) => (a.regression ? 0 : 1) - (b.regression ? 0 : 1) || a.seed - b.seed)
102
244
  const failed = results.filter((r) => !r.ok)
103
245
  for (const f of failed) {
104
246
  const file = join(out, `repro-${f.seed}.json`)
105
- writeFileSync(file, JSON.stringify({target, found: new Date().toISOString(), mismatch: f.minimalMismatch ?? f.mismatch, run: f.minimal ?? t.generate(f.seed)}, null, 1) + '\n')
106
- 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 minimal reproduction (${(f.minimal?.actions ?? []).length} steps): ${file}`)
247
+ const run = f.minimal ?? f.run ?? await t.generate(f.seed)
248
+ 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
+ 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}`)
107
250
  }
108
251
  const ok = results.filter((r) => r.ok && !r.regression)
109
252
  const coverage = {}
110
253
  for (const r of ok) for (const [k, v] of Object.entries(r.cov )) coverage[k] = (coverage[k] ?? 0) + v
111
- const summary = {target, runs: seeds.length, regressions: regs.length, passed: results.filter((r) => r.ok).length, failed: failed.length,
112
- steps: ok.reduce((s, r) => s + r.steps, 0), hookCalls: ok.reduce((s, r) => s + r.hooks, 0), seeds: seeds.length ? `${seed0}..${seed0 + seeds.length - 1}` : '-',
113
- jobs, seconds: Math.round((Date.now() - t0) / 1000), coverage}
114
- writeFileSync(join(out, 'summary.json'), JSON.stringify(summary, null, 1) + '\n')
115
- log(`PROBE ${failed.length ? 'FAIL' : 'PASS'}: ${summary.passed}/${seeds.length + regs.length} sequences (${summary.runs} random, ${summary.regressions} regression), ` +
116
- `${summary.steps} steps, ${summary.hookCalls} hook calls, ${summary.seconds} s, ${jobs} jobs\n coverage ${JSON.stringify(coverage)}`)
117
- for (const f of readdirSync(work)) if (/^(run|reg)-/.test(f)) rmSync(join(work, f), {recursive: true, force: true, maxRetries: 5})
118
- return {ok: failed.length === 0, summary}
254
+
255
+ // mutants: only on a passing original; each mutant in its own worker, seeds in order, the first failure kills it
256
+ let mutants = null
257
+ if (o.checkMutants && failed.length) log(`mutants: not checked, the original fails`)
258
+ else if (o.checkMutants) {
259
+ 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()
261
+ const details = res.map((r) => r.killed
262
+ ? {name: r.mutant, status: 'KILLED', seed: r.seed, step: r.mismatch.step, what: r.mismatch.what, action: r.mismatch.action, runs: r.tried}
263
+ : {name: r.mutant, status: 'SURVIVED', runs: r.tried})
264
+ const survived = details.filter((d) => d.status === 'SURVIVED').map((d) => d.name )
265
+ mutants = {total: details.length, killed: details.length - survived.length, survived, runsPerMutant: mutantRuns, details}
266
+ for (const d of details) log(d.status === 'KILLED' ? ` mutant ${d.name}: KILLED at seed ${d.seed}, step ${d.step}: ${d.what} ${JSON.stringify(d.action)}` : ` mutant ${d.name}: SURVIVED ${d.runs} runs`)
267
+ log(`MUTANTS ${survived.length ? 'FAIL' : 'PASS'}: ${mutants.killed}/${mutants.total} killed${survived.length ? `; survived: ${survived.join(', ')}` : ''} (up to ${mutantRuns} runs each)`)
268
+ }
269
+
270
+ const passOk = failed.length === 0 && (!mutants || mutants.survived.length === 0)
271
+ const summary = {target: t.name, ...(R.file ? {targetPath} : {}), ...cmdField, targetSha256: R.sha256, ok: passOk, runs: seeds.length, regressions: regs.length,
272
+ passed: results.filter((r) => r.ok).length, failed: failed.length,
273
+ steps: ok.reduce((s, r) => s + r.steps, 0), hookCalls: ok.reduce((s, r) => s + (r.hooks ?? 0), 0), seeds: seeds.length ? `${seed0}..${seed0 + seeds.length - 1}` : '-',
274
+ jobs, seconds: Math.round((Date.now() - t0) / 1000), coverage, ...(mutants ? {mutants} : {})}
275
+ const summaryFile = join(out, 'summary.json'), summaryText = JSON.stringify(summary, null, 1) + '\n'
276
+ writeFileSync(summaryFile, summaryText)
277
+ log(`PROBE ${passOk ? 'PASS' : 'FAIL'}: ${summary.passed}/${seeds.length + regs.length} sequences (${summary.runs} random, ${summary.regressions} regression), ` +
278
+ `${summary.steps} steps${summary.hookCalls ? `, ${summary.hookCalls} hook calls` : ''}, ${summary.seconds} s, ${jobs} jobs\n coverage ${JSON.stringify(coverage)}\n summary ${summaryFile}`)
279
+ for (const f of readdirSync(work)) if (/^(run|reg|mut|worker)-/.test(f)) rmSync(join(work, f), {recursive: true, force: true, maxRetries: 5})
280
+
281
+ const recorded = o.record === false ? null : record(repoDir, {target: t.name, targetPath, ...cmdField, targetSha256: R.sha256, runs: summary.runs, regressions: summary.regressions,
282
+ passed: summary.passed, failed: summary.failed, steps: summary.steps, ok: passOk, mutants: mutants ? {killed: mutants.killed, total: mutants.total, survived: mutants.survived} : null,
283
+ summarySha256: sha(summaryText)})
284
+ if (recorded) log(`recorded probe:result in ${recorded}`)
285
+ return {ok: passOk, summary, recorded}
286
+ }
287
+
288
+ const relPath = (repoDir , file ) => {
289
+ let root = repoDir
290
+ try { root = findRepo(repoDir).root } catch { /* not a git repository */ }
291
+ return relative(root, file).replace(/\\/g, '/') || file
292
+ }
293
+
294
+ /** Appends `probe:result` to events.jsonl if `dir` is in a repository with a valid Stopbar config and state. No `req`:
295
+ * not a kernel step, state.json is not touched. Anything else (no git, no Stopbar, damaged files) records nothing. */
296
+ function record(dir , entry ) {
297
+ let repo
298
+ try { repo = findRepo(dir) } catch { return null }
299
+ const p = paths(repo)
300
+ if (!existsSync(p.config) || !existsSync(p.state)) return null
301
+ try {
302
+ return withLock(repo, () => {
303
+ readConfig(repo); readState(repo)
304
+ appendEvent(repo, {source: 'probe:result', target: entry.target, targetPath: entry.targetPath, targetSha256: entry.targetSha256, treeSnapshot: snapshot(repo).id,
305
+ ...Object.fromEntries(Object.entries(entry).filter(([k]) => !['target', 'targetPath', 'targetSha256'].includes(k)))})
306
+ return p.events
307
+ })
308
+ } catch { return null }
119
309
  }
@@ -0,0 +1,217 @@
1
+ // Built from src/probe/init.ts by scripts/build.ts. Do not edit.
2
+ // stopbar probe init: writes a starter PROBE target, in TypeScript (defineModel from 'stopbar/probe') or in Python
3
+ // (the NDJSON protocol of --cmd, standard library only). Both hold the same model with 2 actions, 1 invariant and
4
+ // 2 mutants, so `--check-mutants` passes on the template as written.
5
+ import {existsSync, mkdirSync, writeFileSync} from 'node:fs'
6
+ import {isAbsolute, join, relative, resolve} from 'node:path'
7
+ import {ProbeError} from './stdio.js'
8
+
9
+
10
+
11
+
12
+ const NAME = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/
13
+
14
+ const ZERO_FP = String.raw`Zero false positives: a failure must always be a real bug.
15
+ 1. gen draws its arguments only from the seeded random numbers and returns plain JSON data:
16
+ the same seed gives the same run on every machine.
17
+ 2. The model is the oracle: compare the system with the model, never with itself.
18
+ 3. No clock, network or shared global state; files only under the scratch directory of the run.
19
+ 4. A mutant is a small, real bug; --check-mutants passes only when the prober catches every one.`
20
+
21
+ const TS = String.raw`// PROBE target __NAME__, written by 'stopbar probe init'. Run it:
22
+ // __RUN__
23
+ // Replace UniqueList with an import of your own code, keep the model (a plain array) and add actions.
24
+ __ZERO_FP__
25
+ import {defineModel} from 'stopbar/probe'
26
+
27
+ type Bug = '' | 'dupes' | 'noRemove'
28
+
29
+ /** The system under test: a list of numbers without duplicates. */
30
+ class UniqueList {
31
+ items: number[] = []
32
+ bug: Bug
33
+ constructor(bug: Bug = '') { this.bug = bug }
34
+ /** Adds x unless it is already there; true if it was added. */
35
+ add(x: number): boolean {
36
+ if (this.bug !== 'dupes' && this.items.includes(x)) return false
37
+ this.items.push(x)
38
+ return true
39
+ }
40
+ /** Removes x; true if it was there. */
41
+ remove(x: number): boolean {
42
+ const i = this.items.indexOf(x)
43
+ if (i < 0) return false
44
+ if (this.bug !== 'noRemove') this.items.splice(i, 1)
45
+ return true
46
+ }
47
+ }
48
+
49
+ type State = {list: UniqueList; model: number[]}
50
+ const fresh = (bug: Bug = ''): State => ({list: new UniqueList(bug), model: []})
51
+
52
+ export default defineModel<State>({
53
+ name: '__NAME__',
54
+ description: 'a list without duplicates vs an array model',
55
+ minSteps: 10,
56
+ maxSteps: 30,
57
+ setup: () => fresh(),
58
+ actions: [
59
+ {
60
+ name: 'add', weight: 2,
61
+ gen: (r) => r.int(0, 9),
62
+ run: (s, x: number, check) => {
63
+ const expected = !s.model.includes(x)
64
+ check.eq('add result', s.list.add(x), expected)
65
+ if (expected) s.model.push(x)
66
+ },
67
+ },
68
+ {
69
+ name: 'remove',
70
+ gen: (r) => r.int(0, 9),
71
+ run: (s, x: number, check) => {
72
+ const i = s.model.indexOf(x)
73
+ check.eq('remove result', s.list.remove(x), i >= 0)
74
+ if (i >= 0) s.model.splice(i, 1)
75
+ },
76
+ },
77
+ ],
78
+ invariants: [{name: 'contents', check: (s, check) => check.eq('contents', s.list.items, s.model)}],
79
+ mutants: {
80
+ M1_allowDuplicates: {description: 'add accepts a value that is already there', setup: () => fresh('dupes')},
81
+ M2_removeKeeps: {description: 'remove reports success but keeps the value', setup: () => fresh('noRemove')},
82
+ },
83
+ })
84
+ `
85
+
86
+ const PY = String.raw`#!/usr/bin/env python3
87
+ # PROBE target __NAME__, written by 'stopbar probe init'. Run it:
88
+ # __RUN__
89
+ # It speaks NDJSON on stdin/stdout, one JSON object per line: info, generate, execute (stdout is for the protocol
90
+ # only; print logs to stderr). Standard library only. Replace UniqueList with an import of your own code, keep the
91
+ # model (a plain list) and add actions.
92
+ __ZERO_FP__
93
+ import json
94
+ import random
95
+ import sys
96
+
97
+ NAME = "__NAME__"
98
+ BUGS = {None: "", "M1_allowDuplicates": "dupes", "M2_removeKeeps": "noRemove"}
99
+
100
+
101
+ class UniqueList:
102
+ """The system under test: a list of numbers without duplicates."""
103
+
104
+ def __init__(self, bug=""):
105
+ self.items, self.bug = [], bug
106
+
107
+ def add(self, x):
108
+ if self.bug != "dupes" and x in self.items:
109
+ return False
110
+ self.items.append(x)
111
+ return True
112
+
113
+ def remove(self, x):
114
+ if x not in self.items:
115
+ return False
116
+ if self.bug != "noRemove":
117
+ self.items.remove(x)
118
+ return True
119
+
120
+
121
+ class Mismatch(Exception):
122
+ def __init__(self, what, expected, actual):
123
+ super().__init__(what)
124
+ self.what, self.expected, self.actual = what, expected, actual
125
+
126
+
127
+ def eq(what, actual, expected):
128
+ if actual != expected:
129
+ raise Mismatch(what, expected, actual)
130
+
131
+
132
+ def generate(seed):
133
+ r = random.Random(seed)
134
+ names = r.choices(["add", "remove"], weights=[2, 1], k=r.randint(10, 30))
135
+ return {"seed": seed, "actions": [{"t": t, "args": r.randint(0, 9)} for t in names]}
136
+
137
+
138
+ def execute(run, mutant=None):
139
+ step, action, cov = -1, None, {}
140
+ try:
141
+ if mutant not in BUGS:
142
+ raise Mismatch("unknown mutant", [m for m in BUGS if m], mutant)
143
+ lst, model = UniqueList(BUGS[mutant]), []
144
+ eq("invariant contents: contents", lst.items, model)
145
+ for step, action in enumerate(run["actions"]):
146
+ t, x = action.get("t"), action.get("args")
147
+ if t == "add":
148
+ expected = x not in model
149
+ eq("add result", lst.add(x), expected)
150
+ if expected:
151
+ model.append(x)
152
+ elif t == "remove":
153
+ there = x in model
154
+ eq("remove result", lst.remove(x), there)
155
+ if there:
156
+ model.remove(x)
157
+ else:
158
+ raise Mismatch("unknown action", ["add", "remove"], action)
159
+ cov[t] = cov.get(t, 0) + 1
160
+ eq("invariant contents: contents", lst.items, model)
161
+ except Mismatch as m:
162
+ return {"ok": False, "mismatch": {"step": step, "action": action, "what": m.what, "expected": m.expected, "actual": m.actual}}
163
+ except Exception as e: # a crash of the code under test is a finding, not a protocol error
164
+ return {"ok": False, "mismatch": {"step": step, "action": action, "what": "exception", "expected": "no error", "actual": "%s: %s" % (type(e).__name__, e)}}
165
+ return {"ok": True, "steps": len(run["actions"]), "cov": cov}
166
+
167
+
168
+ def main():
169
+ for line in iter(sys.stdin.readline, ""):
170
+ if not line.strip():
171
+ continue
172
+ req = json.loads(line)
173
+ op = req.get("op")
174
+ if op == "info":
175
+ res = {"name": NAME, "description": "a list without duplicates vs a list model", "mutants": [m for m in BUGS if m]}
176
+ elif op == "generate":
177
+ res = generate(req["seed"])
178
+ elif op == "execute":
179
+ res = execute(req["run"], req.get("mutant"))
180
+ else:
181
+ res = {"error": "unknown op %r" % op}
182
+ sys.stdout.write(json.dumps(res) + "\n")
183
+ sys.stdout.flush()
184
+
185
+
186
+ if __name__ == "__main__":
187
+ main()
188
+ `
189
+
190
+ /** A path for the printed command: relative to `cwd` when inside it, with forward slashes. */
191
+ function shown(file , cwd ) {
192
+ const r = relative(cwd, file)
193
+ return (r && !r.startsWith('..') && !isAbsolute(r) ? r : file).replace(/\\/g, '/')
194
+ }
195
+
196
+ export function initProbe(o = {}) {
197
+ const lang = o.lang ?? 'ts'
198
+ if (lang !== 'ts' && lang !== 'py') throw new ProbeError(`probe init: --lang must be ts or py, got ${JSON.stringify(lang)}`)
199
+ const name = o.name ?? 'sample'
200
+ if (!NAME.test(name)) throw new ProbeError(`probe init: --name ${JSON.stringify(name)} must start with a letter and hold only letters, digits, - and _ (at most 64), no path`)
201
+ const cwd = o.cwd ?? process.cwd()
202
+ const base = o.repo ? resolve(cwd, o.repo) : cwd
203
+ const dir = resolve(base, o.out ?? 'probes')
204
+ const file = join(dir, lang === 'ts' ? `${name}.probe.ts` : `${name}_probe.py`)
205
+ if (existsSync(file) && !o.force) throw new ProbeError(`probe init: ${file} exists; pass --force to overwrite it`)
206
+ const py = process.platform === 'win32' ? 'python' : 'python3'
207
+ const command = lang === 'ts'
208
+ ? `stopbar probe --target ${shown(file, cwd)} --check-mutants`
209
+ : `stopbar probe --cmd "${py} ${shown(file, cwd)}" --check-mutants`
210
+ const text = (lang === 'ts' ? TS : PY)
211
+ .replace('__ZERO_FP__', ZERO_FP.split('\n').map((l) => (lang === 'ts' ? '// ' : '# ') + l).join('\n'))
212
+ .replaceAll('__NAME__', name).replace('__RUN__', command)
213
+ mkdirSync(dir, {recursive: true})
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)` : ''
216
+ return {file, lang, command, message: `wrote ${file}\nrun it:\n ${command}${needs}`}
217
+ }