stopbar 1.1.3 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +184 -0
- package/README.md +225 -31
- package/SECURITY.md +129 -39
- package/bin/stopbar.mjs +0 -0
- package/dist/adapters/antigravity.js +6 -6
- package/dist/adapters/claude.js +1 -1
- package/dist/adapters/codex.js +7 -7
- package/dist/adapters/cursor.js +6 -6
- package/dist/adapters/gemini.js +7 -7
- package/dist/adapters/index.js +4 -3
- package/dist/adapters/types.js +7 -4
- package/dist/attest.js +28 -3
- package/dist/build-info.json +2 -2
- package/dist/classify.js +356 -29
- package/dist/cli.js +39 -7
- package/dist/commands.js +36 -13
- package/dist/config.js +7 -2
- package/dist/doctor.js +63 -28
- package/dist/hook.js +59 -32
- package/dist/integrations.js +50 -6
- package/dist/probe/index.js +261 -62
- package/dist/probe/init.js +217 -0
- package/dist/probe/sdk.js +242 -0
- package/dist/probe/stdio.js +219 -0
- package/dist/probe/wrapper.js +1 -1
- package/dist/store.js +1 -1
- package/dist/verify.js +34 -26
- package/package.json +17 -2
- package/skills/stopbar/SKILL.md +126 -0
- package/src/probe/sdk.ts +241 -0
package/dist/integrations.js
CHANGED
|
@@ -105,17 +105,56 @@ function antigravityFile(root , command ) {
|
|
|
105
105
|
return f
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
-
|
|
108
|
+
/** Where git runs the hooks of this repository (`git rev-parse --git-path hooks`). `customHooksPath`: the
|
|
109
|
+
* `core.hooksPath` value when it points outside the default <git-common-dir>/hooks (Husky, Lefthook, a shared or tracked
|
|
110
|
+
* hooks directory), else null. No core.hooksPath entry is no error; any other git config error fails closed. */
|
|
111
|
+
export function gitHooksDir(repo ) {
|
|
112
|
+
let configured = null
|
|
113
|
+
try { configured = git(repo.root, ['config', '--get', 'core.hooksPath']) || null } catch (e) {
|
|
114
|
+
if ((e ).status !== 1) throw new FailClosed(`git config --get core.hooksPath failed in ${repo.root}: ${(e ).message.split('\n')[0]}`)
|
|
115
|
+
}
|
|
109
116
|
const rel = git(repo.root, ['rev-parse', '--git-path', 'hooks'])
|
|
110
117
|
const dir = isAbsolute(rel) ? rel : resolve(repo.root, rel)
|
|
118
|
+
if (configured === null) return {dir, customHooksPath: null}
|
|
119
|
+
const common = git(repo.root, ['rev-parse', '--git-common-dir'])
|
|
120
|
+
const def = resolve(isAbsolute(common) ? common : resolve(repo.root, common), 'hooks')
|
|
121
|
+
const same = process.platform === 'win32' ? resolve(dir).toLowerCase() === def.toLowerCase() : resolve(dir) === def
|
|
122
|
+
return {dir, customHooksPath: same ? null : configured}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
const hookBin = (runtimeRoot ) => join(runtimeRoot, 'bin', 'stopbar.mjs').replace(/\\/g, '/')
|
|
127
|
+
const manualHooks = (hd , bin ) =>
|
|
128
|
+
`add \`node "${bin}" git-hook pre-commit\` to ${join(hd.dir, 'pre-commit')} and \`node "${bin}" git-hook pre-push\` to ${join(hd.dir, 'pre-push')}`
|
|
129
|
+
function customHooksRefusal(hd , runtimeRoot ) {
|
|
130
|
+
return new FailClosed(`core.hooksPath (${hd.customHooksPath}) points git hooks outside .git/hooks, to ${hd.dir}; not writing shared or tracked hooks there`,
|
|
131
|
+
`chain them by hand: ${manualHooks(hd, hookBin(runtimeRoot))}; or run again with --force-hooks to write them there (a foreign hook is kept as <name>.stopbar-backup)`)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A foreign pre-commit or pre-push hook: 'fail' (git named in --hooks), 'backup' (--force-hooks: kept as
|
|
135
|
+
* <name>.stopbar-backup, then replaced) or 'keep' (git added by default: the foreign hook stays, with a warning).
|
|
136
|
+
* A custom core.hooksPath (shared or tracked hooks) is written only with 'backup'; 'keep' writes nothing there and
|
|
137
|
+
* warns, 'fail' refuses. */
|
|
138
|
+
|
|
139
|
+
function gitHooks(repo , runtimeRoot , foreign , warn , hd = gitHooksDir(repo)) {
|
|
140
|
+
const {dir} = hd
|
|
141
|
+
const bin = hookBin(runtimeRoot)
|
|
142
|
+
if (hd.customHooksPath !== null && foreign !== 'backup') {
|
|
143
|
+
if (foreign === 'fail') throw customHooksRefusal(hd, runtimeRoot)
|
|
144
|
+
warn(`WARN: this repository uses a custom core.hooksPath (${hd.customHooksPath} -> ${dir}); Stopbar did not touch those shared or tracked hooks, so git commit and git push are not gated by Stopbar here. To chain them by hand, ${manualHooks(hd, bin)}; to write them there directly (a foreign hook is kept as <name>.stopbar-backup): stopbar upgrade --hooks git --force-hooks`)
|
|
145
|
+
return []
|
|
146
|
+
}
|
|
111
147
|
mkdirSync(dir, {recursive: true})
|
|
112
|
-
const bin = join(runtimeRoot, 'bin', 'stopbar.mjs').replace(/\\/g, '/')
|
|
113
148
|
const out = []
|
|
114
149
|
for (const name of ['pre-commit', 'pre-push']) {
|
|
115
150
|
const f = join(dir, name)
|
|
116
151
|
const body = `#!/bin/sh\n# Stopbar fallback gate, written by \`stopbar init --hooks git\`.\nexec node "${bin}" git-hook ${name}\n`
|
|
117
152
|
if (existsSync(f) && !readFileSync(f, 'utf8').includes('stopbar.mjs" git-hook')) {
|
|
118
|
-
if (
|
|
153
|
+
if (foreign === 'keep') {
|
|
154
|
+
warn(`WARN: ${f} exists and is not a Stopbar hook; kept it, so git ${name === 'pre-commit' ? 'commit' : 'push'} is not gated by Stopbar here. To replace it (the old hook is kept as ${name}.stopbar-backup): stopbar upgrade --hooks git --force-hooks`)
|
|
155
|
+
continue
|
|
156
|
+
}
|
|
157
|
+
if (foreign === 'fail') throw new FailClosed(`${f} exists and is not a Stopbar hook; not overwriting it`, 'remove it, chain it by hand, or run init again with --force-hooks (the old hook is kept as <name>.stopbar-backup)')
|
|
119
158
|
renameSync(f, `${f}.stopbar-backup`)
|
|
120
159
|
}
|
|
121
160
|
writeFileSync(f, body)
|
|
@@ -125,9 +164,14 @@ function gitHooks(repo , runtimeRoot , force ) {
|
|
|
125
164
|
return out
|
|
126
165
|
}
|
|
127
166
|
|
|
128
|
-
/** Installs every target; returns one line per written file.
|
|
129
|
-
|
|
167
|
+
/** Installs every target; returns one line per written file. `gitByDefault`: git was not named in --hooks but added by
|
|
168
|
+
* init, so a foreign git hook is kept with a warning (`warn`) instead of failing; --force-hooks still replaces it. */
|
|
169
|
+
export function installHooks(repo , targets , runtimeRoot , force , o = {}) {
|
|
130
170
|
const lines = []
|
|
171
|
+
const foreign = force ? 'backup' : o.gitByDefault ? 'keep' : 'fail'
|
|
172
|
+
const hd = targets.includes('git') ? gitHooksDir(repo) : null
|
|
173
|
+
// a refusal (explicit --hooks git into a custom core.hooksPath) comes before any client file is written
|
|
174
|
+
if (hd && foreign === 'fail' && hd.customHooksPath !== null) throw customHooksRefusal(hd, runtimeRoot)
|
|
131
175
|
for (const t of targets) {
|
|
132
176
|
if (t === 'claude') lines.push(`claude: ${claudeFile(repo.root, 'settings.local.json', hookCommand(runtimeRoot))}`)
|
|
133
177
|
else if (t === 'claude-project') lines.push(`claude: ${claudeFile(repo.root, 'settings.json', hookCommand(runtimeRoot))}`)
|
|
@@ -135,7 +179,7 @@ export function installHooks(repo , targets , runtimeRoot ,
|
|
|
135
179
|
else if (t === 'codex') lines.push(`codex: ${codexFile(repo.root, hookCommand(runtimeRoot, 'codex'))}`)
|
|
136
180
|
else if (t === 'gemini') lines.push(`gemini: ${geminiFile(repo.root, hookCommand(runtimeRoot, 'gemini'))}`)
|
|
137
181
|
else if (t === 'antigravity') lines.push(`antigravity: ${antigravityFile(repo.root, hookCommand(runtimeRoot, 'antigravity'))}`)
|
|
138
|
-
else if (t === 'git') for (const f of gitHooks(repo, runtimeRoot,
|
|
182
|
+
else if (t === 'git') for (const f of gitHooks(repo, runtimeRoot, foreign, o.warn ?? (() => {}), hd ?? undefined)) lines.push(`git: ${f}`)
|
|
139
183
|
}
|
|
140
184
|
return lines
|
|
141
185
|
}
|
package/dist/probe/index.js
CHANGED
|
@@ -2,36 +2,105 @@
|
|
|
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
|
-
//
|
|
6
|
-
// `stopbar probe --target
|
|
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
|
-
|
|
24
|
-
|
|
25
|
-
export const TARGETS = {
|
|
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'
|
|
23
|
+
|
|
24
|
+
export const TARGETS = {
|
|
26
25
|
wrapper: async () => (await import('./wrapper.js')).wrapperTarget,
|
|
27
26
|
}
|
|
28
27
|
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
const sha = (b ) => createHash('sha256').update(b).digest('hex')
|
|
29
|
+
|
|
30
|
+
function isTarget(v ) {
|
|
31
|
+
if (!v || typeof v !== 'object') return false
|
|
32
|
+
const x = v
|
|
33
|
+
return typeof x.name === 'string' && !!x.name && typeof x.description === 'string' &&
|
|
34
|
+
typeof x.generate === 'function' && typeof x.execute === 'function' &&
|
|
35
|
+
(x.mutants === undefined || (Array.isArray(x.mutants) && x.mutants.every((m ) => typeof m === 'string')))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What the runner drives: a ProbeTarget, or a --cmd target whose generate answers asynchronously and that must be closed. */
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
/** A name in TARGETS, else a .ts/.mts/.js/.mjs file (absolute, or relative to `cwd`, then to `repo`) that exports a
|
|
43
|
+
* ProbeTarget as `default` or as `target`. */
|
|
44
|
+
export async function loadTarget(spec , cwd = process.cwd(), repo ) {
|
|
45
|
+
if (Object.hasOwn(TARGETS, spec)) return {t: await TARGETS[spec](), spec, file: null, sha256: null}
|
|
46
|
+
const cands = isAbsolute(spec) ? [spec] : [resolve(cwd, spec), ...(repo ? [resolve(repo, spec)] : [])]
|
|
47
|
+
const file = cands.find((f) => existsSync(f))
|
|
48
|
+
if (!file) throw new ProbeError(`probe target ${JSON.stringify(spec)} is neither a known target (${Object.keys(TARGETS).join(', ')}) nor an existing file`)
|
|
49
|
+
if (!/\.(ts|mts|js|mjs)$/.test(file)) throw new ProbeError(`probe target ${file}: the file must end in .ts, .mts, .js or .mjs`)
|
|
50
|
+
let mod
|
|
51
|
+
try { mod = await import(pathToFileURL(file).href) } catch (e) {
|
|
52
|
+
throw new ProbeError(`probe target ${file} does not load: ${(e )?.message ?? e}`)
|
|
53
|
+
}
|
|
54
|
+
const t = isTarget(mod?.default) ? mod.default : isTarget(mod?.target) ? mod.target : null
|
|
55
|
+
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'`)
|
|
56
|
+
return {t, spec: file, file, sha256: sha(readFileSync(file))}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A --cmd target: asks the program for info (it is started now and again on demand after `close`). `targetFile`
|
|
60
|
+
* (absolute, or relative to `cwd`, then to `repo`) is hashed; else the first existing file in the command, else none. */
|
|
61
|
+
export async function loadCmd(cmd , o = {}) {
|
|
62
|
+
const cwd = o.cwd ?? process.cwd()
|
|
63
|
+
let file = null
|
|
64
|
+
if (o.targetFile !== undefined) {
|
|
65
|
+
const cands = isAbsolute(o.targetFile) ? [o.targetFile] : [resolve(cwd, o.targetFile), ...(o.repo ? [resolve(o.repo, o.targetFile)] : [])]
|
|
66
|
+
file = cands.find((f) => existsSync(f)) ?? null
|
|
67
|
+
if (!file) throw new ProbeError(`--target-file ${JSON.stringify(o.targetFile)} does not exist`)
|
|
68
|
+
} else file = commandFile(cmd, cwd)
|
|
69
|
+
const c = new CmdClient(cmd, {cwd, timeoutMs: o.timeoutMs})
|
|
70
|
+
let info
|
|
71
|
+
try { info = await c.info() } catch (e) { await c.close(); throw e }
|
|
72
|
+
const t = {
|
|
73
|
+
name: info.name, description: info.description, ...(info.mutants ? {mutants: info.mutants} : {}),
|
|
74
|
+
generate: (seed) => c.generate(seed),
|
|
75
|
+
execute: (run, dir, mutant) => c.execute(run, dir, mutant),
|
|
76
|
+
close: () => c.close(),
|
|
77
|
+
}
|
|
78
|
+
return {t, spec: info.name, file, sha256: file ? sha(readFileSync(file)) : null, cmd}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Every execute starts in an empty scratch directory. */
|
|
82
|
+
async function exec(t , run , dir , mutant ) {
|
|
83
|
+
rmSync(dir, {recursive: true, force: true, maxRetries: 5}); mkdirSync(dir, {recursive: true})
|
|
84
|
+
return mutant === undefined ? t.execute(run, dir) : t.execute(run, dir, mutant)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Delta debugging: the shortest sequence that still fails the same way (same `what`). Deterministic order.
|
|
88
|
+
* 0: cut after the failing step; 1: remove blocks of len/2, len/4, ... (>= 2), from the largest again after every
|
|
89
|
+
* success; 2: single deletions from the end, to a fixed point. */
|
|
90
|
+
export async function shrink (t , run , dir , what ) {
|
|
31
91
|
let cur = run
|
|
32
|
-
const fails = async (r ) => { const x = await t
|
|
33
|
-
const end = await t
|
|
92
|
+
const fails = async (r ) => { const x = await exec(t, r, dir); return !x.ok && x.mismatch.what === what }
|
|
93
|
+
const end = await exec(t, cur, dir)
|
|
34
94
|
if (!end.ok) cur = {...cur, actions: cur.actions.slice(0, end.mismatch.step + 1)}
|
|
95
|
+
phase1: while (cur.actions.length > 2) {
|
|
96
|
+
for (let size = Math.floor(cur.actions.length / 2); size >= 2; size = Math.floor(size / 2)) {
|
|
97
|
+
for (let at = 0; at < cur.actions.length; at += size) {
|
|
98
|
+
const cand = {...cur, actions: [...cur.actions.slice(0, at), ...cur.actions.slice(at + size)]}
|
|
99
|
+
if (cand.actions.length && await fails(cand)) { cur = cand; continue phase1 }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
break
|
|
103
|
+
}
|
|
35
104
|
for (let changed = true; changed;) {
|
|
36
105
|
changed = false
|
|
37
106
|
for (let i = cur.actions.length - 1; i >= 0; i--) {
|
|
@@ -42,78 +111,208 @@ export async function shrink (t , run , dir
|
|
|
42
111
|
return cur
|
|
43
112
|
}
|
|
44
113
|
|
|
45
|
-
|
|
114
|
+
|
|
46
115
|
|
|
47
|
-
/** Worker process: runs its share and prints one JSON line with the results.
|
|
116
|
+
/** Worker process: runs its share and prints one JSON line with the results (or {error} for a ProbeError). With
|
|
117
|
+
* `mutant` it runs the seeds in order against that mutant and stops at the first one that fails (no shrinking).
|
|
118
|
+
* A --cmd target is one process for the whole share, closed at the end. */
|
|
48
119
|
export async function worker(p ) {
|
|
49
|
-
|
|
120
|
+
let t = null
|
|
121
|
+
try {
|
|
122
|
+
t = (p.cmd !== undefined ? await loadCmd(p.cmd, {timeoutMs: p.timeoutMs}) : await loadTarget(p.target)).t
|
|
123
|
+
process.stdout.write(JSON.stringify(await share(t, p)) + '\n')
|
|
124
|
+
} catch (e) {
|
|
125
|
+
if (!(e instanceof ProbeError)) throw e
|
|
126
|
+
process.stdout.write(JSON.stringify({error: e.message}) + '\n')
|
|
127
|
+
} finally { await t?.close?.() }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function share(t , p ) {
|
|
50
131
|
const res = []
|
|
132
|
+
if (p.mutant !== undefined) {
|
|
133
|
+
let tried = 0
|
|
134
|
+
for (const seed of p.seeds) {
|
|
135
|
+
tried++
|
|
136
|
+
const dir = join(p.work, `mut-${process.pid}-${seed}`)
|
|
137
|
+
const x = await exec(t, await t.generate(seed), dir, p.mutant)
|
|
138
|
+
rmSync(dir, {recursive: true, force: true, maxRetries: 5})
|
|
139
|
+
if (!x.ok) { res.push({mutant: p.mutant, killed: true, seed, tried, mismatch: x.mismatch}); break }
|
|
140
|
+
}
|
|
141
|
+
if (!res.length) res.push({mutant: p.mutant, killed: false, tried})
|
|
142
|
+
return res
|
|
143
|
+
}
|
|
51
144
|
for (const f of p.regs) {
|
|
52
145
|
const run = JSON.parse(readFileSync(f, 'utf8')).run
|
|
53
146
|
const dir = join(p.work, `reg-${run.seed}-${process.pid}`)
|
|
54
|
-
|
|
147
|
+
const x = await exec(t, run, dir)
|
|
148
|
+
res.push({regression: f, seed: run.seed, ...x, ...(x.ok ? {} : {run})})
|
|
55
149
|
rmSync(dir, {recursive: true, force: true, maxRetries: 5})
|
|
56
150
|
}
|
|
57
151
|
for (const seed of p.seeds) {
|
|
58
|
-
const run = t.generate(seed)
|
|
152
|
+
const run = await t.generate(seed)
|
|
59
153
|
const dir = join(p.work, `run-${seed}`)
|
|
60
|
-
const x = await t
|
|
154
|
+
const x = await exec(t, run, dir)
|
|
61
155
|
if (!x.ok) {
|
|
62
156
|
const min = await shrink(t, run, dir, x.mismatch.what)
|
|
63
|
-
const again = await t
|
|
157
|
+
const again = await exec(t, min, dir)
|
|
64
158
|
res.push({seed, ...x, minimal: min, minimalMismatch: again.ok ? null : again.mismatch})
|
|
65
159
|
} else res.push({seed, ...x})
|
|
66
160
|
rmSync(dir, {recursive: true, force: true, maxRetries: 5})
|
|
67
161
|
}
|
|
68
|
-
|
|
162
|
+
return res
|
|
69
163
|
}
|
|
70
164
|
|
|
71
|
-
|
|
165
|
+
|
|
166
|
+
|
|
72
167
|
|
|
73
|
-
|
|
74
|
-
|
|
168
|
+
/** <git-dir>/stopbar/probe in a repository with Stopbar, else a temporary directory (a project without Stopbar gets
|
|
169
|
+
* no .git/stopbar from the prober). */
|
|
170
|
+
function defaultWork(dir ) {
|
|
171
|
+
try { const r = findRepo(dir); if (existsSync(r.stateDir)) return join(r.stateDir, 'probe') } catch { /* not a git repository */ }
|
|
172
|
+
return join(tmpdir(), `stopbar-probe-${process.pid}`)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** A worker gets its share in a file in `work` (`--worker-file <path>`): the seeds as one argv JSON overflow the command
|
|
176
|
+
* line (Windows ~32 KB, Linux 128 KB per argument) at large --runs or --mutant-runs. The file goes when the worker ends. */
|
|
177
|
+
let workerFiles = 0
|
|
178
|
+
/** One result line of a worker (see share): a run or a regression, or a mutant with `mutant` set. */
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
function spawnWorker (p ) {
|
|
183
|
+
return new Promise ((ok, bad) => {
|
|
184
|
+
const file = join(p.work, `worker-${process.pid}-${++workerFiles}.json`)
|
|
185
|
+
writeFileSync(file, JSON.stringify(p))
|
|
186
|
+
const ch = spawn(process.execPath, [join(PKG_ROOT, 'bin', 'stopbar.mjs'), 'probe', '--worker-file', file], {stdio: ['ignore', 'pipe', 'inherit']})
|
|
187
|
+
let s = ''
|
|
188
|
+
ch.stdout.on('data', (d) => { s += d })
|
|
189
|
+
ch.on('error', (e) => { rmSync(file, {force: true}); bad(e) })
|
|
190
|
+
ch.on('exit', (code) => {
|
|
191
|
+
rmSync(file, {force: true, maxRetries: 5})
|
|
192
|
+
let v
|
|
193
|
+
try { v = JSON.parse(s.trim().split('\n').pop() ) } catch { return bad(new Error(`probe worker exit ${code}: ${s.slice(0, 500)}`)) }
|
|
194
|
+
const error = v && typeof v === 'object' && !Array.isArray(v) ? (v ).error : undefined
|
|
195
|
+
if (typeof error === 'string') bad(new ProbeError(error))
|
|
196
|
+
else if (Array.isArray(v)) ok(v )
|
|
197
|
+
else bad(new Error(`probe worker exit ${code}: not a result list: ${s.slice(0, 500)}`))
|
|
198
|
+
})
|
|
199
|
+
})
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** At most `jobs` promises at a time; results in input order. */
|
|
203
|
+
async function pool (xs , jobs , f ) {
|
|
204
|
+
const out = new Array(xs.length)
|
|
205
|
+
let next = 0
|
|
206
|
+
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]) } }))
|
|
207
|
+
return out
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** A saved reproduction or regression: JSON with a run of actions (summary.json and other files are skipped). */
|
|
211
|
+
function isRegression(f ) {
|
|
212
|
+
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
213
|
}
|
|
76
214
|
|
|
77
215
|
export async function probe(o = {}) {
|
|
78
216
|
const log = o.log ?? ((s ) => process.stdout.write(s + '\n'))
|
|
79
|
-
const
|
|
80
|
-
if (
|
|
81
|
-
|
|
82
|
-
const
|
|
217
|
+
const repoDir = o.repo ?? process.cwd()
|
|
218
|
+
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')
|
|
219
|
+
if (o.targetFile !== undefined && o.cmd === undefined) throw new ProbeError('--target-file needs --cmd (a --target file is hashed anyway)')
|
|
220
|
+
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)
|
|
221
|
+
// the main process needs only info from a --cmd target: its process is not kept while the workers run
|
|
222
|
+
await R.t.close?.()
|
|
223
|
+
try { return await probeWith(R, o, log, repoDir) } finally { await R.t.close?.() }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function probeWith(R , o , log , repoDir ) {
|
|
227
|
+
const t = R.t
|
|
228
|
+
const mutantNames = t.mutants ?? []
|
|
229
|
+
if (o.checkMutants && !mutantNames.length) throw new ProbeError(`--check-mutants: target ${t.name} declares no mutants (add mutants: {...} to defineModel, or drop --check-mutants)`)
|
|
230
|
+
const runs = o.runs ?? 200, seed0 = o.seed ?? 1, mutantRuns = o.mutantRuns ?? 50
|
|
231
|
+
if (o.checkMutants && mutantRuns < 1) throw new ProbeError('--mutant-runs must be at least 1')
|
|
83
232
|
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
|
-
|
|
86
|
-
const
|
|
233
|
+
const work = o.work ?? defaultWork(repoDir), out = o.out ?? join(work, 'out')
|
|
234
|
+
// a file target replays only the regressions the user names; the wrapper also has Stopbar's own
|
|
235
|
+
const regDir = o.regressions ?? (R.file || R.cmd !== undefined ? null : join(PKG_ROOT, 'tests', 'regressions'))
|
|
236
|
+
const regs = regDir && existsSync(regDir) ? readdirSync(regDir).filter((f) => f.endsWith('.json')).sort().map((f) => join(regDir, f)).filter(isRegression) : []
|
|
87
237
|
const seeds = o.regressionsOnly ? [] : Array.from({length: runs}, (_, i) => seed0 + i)
|
|
88
238
|
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
|
-
|
|
91
|
-
|
|
239
|
+
for (const f of readdirSync(work)) if (/^(run|reg|mut|worker)-/.test(f)) rmSync(join(work, f), {recursive: true, force: true, maxRetries: 5})
|
|
240
|
+
// old reproductions go, unless they are the regressions of this run
|
|
241
|
+
if (!regDir || resolve(regDir) !== resolve(out)) for (const f of readdirSync(out)) if (/^repro-\d+\.json$/.test(f)) rmSync(join(out, f))
|
|
242
|
+
const targetPath = R.file ? relPath(repoDir, R.file) : t.name
|
|
243
|
+
const cmdField = R.cmd !== undefined ? {targetCmd: R.cmd} : {}
|
|
244
|
+
const cmdPart = R.cmd !== undefined ? {cmd: R.cmd, ...(o.cmdTimeoutMs !== undefined ? {timeoutMs: o.cmdTimeoutMs} : {})} : {}
|
|
245
|
+
log(`probe ${t.name}: ${t.description}; ${seeds.length} random runs + ${regs.length} regression(s), ${jobs} jobs${R.cmd !== undefined ? `\n command ${R.cmd}` : ''}` +
|
|
246
|
+
`${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
247
|
const t0 = Date.now()
|
|
93
|
-
const parts = Array.from({length: jobs}, () => ({target, seeds: [], regs: [], work}))
|
|
248
|
+
const parts = Array.from({length: jobs}, () => ({target: R.spec, ...cmdPart, seeds: [], regs: [], work}))
|
|
94
249
|
seeds.forEach((s, i) => parts[i % jobs].seeds.push(s))
|
|
95
250
|
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) =>
|
|
97
|
-
|
|
98
|
-
|
|
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()
|
|
102
|
-
const failed = results.filter((r) => !r.ok)
|
|
251
|
+
const results = (await Promise.all(parts.filter((p) => p.seeds.length || p.regs.length).map((p) => spawnWorker (p)))).flat()
|
|
252
|
+
.sort((a, b) => (a.regression ? 0 : 1) - (b.regression ? 0 : 1) || a.seed - b.seed)
|
|
253
|
+
const failed = results.filter((r) => !r.ok)
|
|
103
254
|
for (const f of failed) {
|
|
104
255
|
const file = join(out, `repro-${f.seed}.json`)
|
|
105
|
-
|
|
106
|
-
|
|
256
|
+
const run = f.minimal ?? f.run ?? await t.generate(f.seed)
|
|
257
|
+
writeFileSync(file, JSON.stringify({target: t.name, ...(R.file ? {targetPath} : {}), ...cmdField, found: new Date().toISOString(), mismatch: f.minimalMismatch ?? f.mismatch, run}, null, 1) + '\n')
|
|
258
|
+
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
259
|
}
|
|
108
|
-
const ok = results.filter((r)
|
|
260
|
+
const ok = results.filter((r) => r.ok && !r.regression)
|
|
109
261
|
const coverage = {}
|
|
110
|
-
for (const r of ok) for (const [k, v] of Object.entries(r.cov
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
262
|
+
for (const r of ok) for (const [k, v] of Object.entries(r.cov)) coverage[k] = (coverage[k] ?? 0) + v
|
|
263
|
+
|
|
264
|
+
// mutants: only on a passing original; each mutant in its own worker, seeds in order, the first failure kills it
|
|
265
|
+
let mutants = null
|
|
266
|
+
if (o.checkMutants && failed.length) log(`mutants: not checked, the original fails`)
|
|
267
|
+
else if (o.checkMutants) {
|
|
268
|
+
const mseeds = Array.from({length: mutantRuns}, (_, i) => seed0 + i)
|
|
269
|
+
const res = (await pool(mutantNames, jobs, (m) => spawnWorker ({target: R.spec, ...cmdPart, seeds: mseeds, regs: [], work, mutant: m}))).flat()
|
|
270
|
+
const details = res.map((r) => r.killed
|
|
271
|
+
? {name: r.mutant, status: 'KILLED', seed: r.seed, step: r.mismatch.step, what: r.mismatch.what, action: r.mismatch.action, runs: r.tried}
|
|
272
|
+
: {name: r.mutant, status: 'SURVIVED', runs: r.tried})
|
|
273
|
+
const survived = details.filter((d) => d.status === 'SURVIVED').map((d) => d.name )
|
|
274
|
+
mutants = {total: details.length, killed: details.length - survived.length, survived, runsPerMutant: mutantRuns, details}
|
|
275
|
+
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`)
|
|
276
|
+
log(`MUTANTS ${survived.length ? 'FAIL' : 'PASS'}: ${mutants.killed}/${mutants.total} killed${survived.length ? `; survived: ${survived.join(', ')}` : ''} (up to ${mutantRuns} runs each)`)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const passOk = failed.length === 0 && (!mutants || mutants.survived.length === 0)
|
|
280
|
+
const summary = {target: t.name, ...(R.file ? {targetPath} : {}), ...cmdField, targetSha256: R.sha256, ok: passOk, runs: seeds.length, regressions: regs.length,
|
|
281
|
+
passed: results.filter((r) => r.ok).length, failed: failed.length,
|
|
282
|
+
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}` : '-',
|
|
283
|
+
jobs, seconds: Math.round((Date.now() - t0) / 1000), coverage, ...(mutants ? {mutants} : {})}
|
|
284
|
+
const summaryFile = join(out, 'summary.json'), summaryText = JSON.stringify(summary, null, 1) + '\n'
|
|
285
|
+
writeFileSync(summaryFile, summaryText)
|
|
286
|
+
log(`PROBE ${passOk ? 'PASS' : 'FAIL'}: ${summary.passed}/${seeds.length + regs.length} sequences (${summary.runs} random, ${summary.regressions} regression), ` +
|
|
287
|
+
`${summary.steps} steps${summary.hookCalls ? `, ${summary.hookCalls} hook calls` : ''}, ${summary.seconds} s, ${jobs} jobs\n coverage ${JSON.stringify(coverage)}\n summary ${summaryFile}`)
|
|
288
|
+
for (const f of readdirSync(work)) if (/^(run|reg|mut|worker)-/.test(f)) rmSync(join(work, f), {recursive: true, force: true, maxRetries: 5})
|
|
289
|
+
|
|
290
|
+
const recorded = o.record === false ? null : record(repoDir, {target: t.name, targetPath, ...cmdField, targetSha256: R.sha256, runs: summary.runs, regressions: summary.regressions,
|
|
291
|
+
passed: summary.passed, failed: summary.failed, steps: summary.steps, ok: passOk, mutants: mutants ? {killed: mutants.killed, total: mutants.total, survived: mutants.survived} : null,
|
|
292
|
+
summarySha256: sha(summaryText)})
|
|
293
|
+
if (recorded) log(`recorded probe:result in ${recorded}`)
|
|
294
|
+
return {ok: passOk, summary, recorded}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const relPath = (repoDir , file ) => {
|
|
298
|
+
let root = repoDir
|
|
299
|
+
try { root = findRepo(repoDir).root } catch { /* not a git repository */ }
|
|
300
|
+
return relative(root, file).replace(/\\/g, '/') || file
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Appends `probe:result` to events.jsonl if `dir` is in a repository with a valid Stopbar config and state. No `req`:
|
|
304
|
+
* not a kernel step, state.json is not touched. Anything else (no git, no Stopbar, damaged files) records nothing. */
|
|
305
|
+
function record(dir , entry ) {
|
|
306
|
+
let repo
|
|
307
|
+
try { repo = findRepo(dir) } catch { return null }
|
|
308
|
+
const p = paths(repo)
|
|
309
|
+
if (!existsSync(p.config) || !existsSync(p.state)) return null
|
|
310
|
+
try {
|
|
311
|
+
return withLock(repo, () => {
|
|
312
|
+
readConfig(repo); readState(repo)
|
|
313
|
+
appendEvent(repo, {source: 'probe:result', target: entry.target, targetPath: entry.targetPath, targetSha256: entry.targetSha256, treeSnapshot: snapshot(repo).id,
|
|
314
|
+
...Object.fromEntries(Object.entries(entry).filter(([k]) => !['target', 'targetPath', 'targetSha256'].includes(k)))})
|
|
315
|
+
return p.events
|
|
316
|
+
})
|
|
317
|
+
} catch { return null }
|
|
119
318
|
}
|