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.
@@ -0,0 +1,242 @@
1
+ // Built from src/probe/sdk.ts by scripts/build.ts. Do not edit.
2
+ // stopbar/probe: the SDK for PROBE targets of any TS/JS project. A target describes a model as a list of actions
3
+ // (each with a generator of pure JSON data and a run that drives the real thing and checks it), invariants that hold
4
+ // after every step, and optional mutants (a damaged system under test) that the prober must catch.
5
+ // `stopbar probe --target <file>` loads the file (default export or export `target`) and runs it as any other target.
6
+ // This module has no imports besides node:util, so its source ships as the type declaration of `stopbar/probe`.
7
+ import {isDeepStrictEqual} from 'node:util'
8
+
9
+ // ---------------------------------------------------------------- the target contract (shared with the runner)
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+ // ---------------------------------------------------------------- deterministic random numbers
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+ /** xorshift32 on 32-bit integer arithmetic only: the same seed gives the same numbers on every platform. */
37
+ export function createRng(seed ) {
38
+ if (!Number.isFinite(seed)) throw new TypeError(`createRng: seed must be a finite number, got ${seed}`)
39
+ let x = Math.imul(Math.trunc(seed) | 0, 0x9e3779b1) >>> 0 || 7
40
+ const next = () => { x ^= x << 13; x >>>= 0; x ^= x >>> 17; x ^= x << 5; x >>>= 0; return x / 2 ** 32 }
41
+ const int = (min , max ) => {
42
+ if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || max < min) throw new RangeError(`rng.int: need integers min <= max, got ${min}, ${max}`)
43
+ return min + Math.floor(next() * (max - min + 1))
44
+ }
45
+ return {
46
+ next, int,
47
+ bool: (p = 0.5) => next() < p,
48
+ pick: (xs ) => {
49
+ if (!xs.length) throw new RangeError('rng.pick: empty list')
50
+ return xs[Math.floor(next() * xs.length)]
51
+ },
52
+ weighted: (xs ) => {
53
+ const w = xs.map((e) => e.weight ?? 1)
54
+ if (w.some((v) => !Number.isFinite(v) || v < 0)) throw new RangeError('rng.weighted: weights must be finite numbers >= 0')
55
+ const total = w.reduce((s, v) => s + v, 0)
56
+ if (!(total > 0)) throw new RangeError('rng.weighted: no value with a weight > 0')
57
+ let r = next() * total
58
+ for (let i = 0; i < xs.length; i++) { if (w[i] > 0 && r < w[i]) return xs[i].value; r -= w[i] }
59
+ for (let i = xs.length - 1; ; i--) if (w[i] > 0) return xs[i].value // rounding at the upper end
60
+ },
61
+ }
62
+ }
63
+
64
+ // ---------------------------------------------------------------- checks
65
+ /** Thrown by a failed check; `execute` turns it into `{ok: false, mismatch}` with the step and the action. */
66
+ export class MismatchError extends Error {
67
+ what
68
+ expected
69
+ actual
70
+ constructor(what , expected , actual ) {
71
+ super(`${what}: expected ${show(expected)}, actual ${show(actual)}`)
72
+ this.name = 'MismatchError'
73
+ this.what = what; this.expected = expected; this.actual = actual
74
+ }
75
+ }
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+ export const check = {
86
+ ok(what, cond, ...rest ) {
87
+ if (!cond) throw new MismatchError(what, rest.length >= 2 ? rest[1] : 'truthy', rest.length >= 1 ? rest[0] : cond)
88
+ },
89
+ eq(what, actual, expected) { if (!isDeepStrictEqual(actual, expected)) throw new MismatchError(what, expected, actual) },
90
+ fail(what, expected, actual) { throw new MismatchError(what, expected, actual) },
91
+ }
92
+
93
+ function show(v ) {
94
+ try { return JSON.stringify(v, jsonSafe) ?? String(v) } catch { return String(v) }
95
+ }
96
+ function jsonSafe(_k , v ) {
97
+ if (typeof v === 'bigint') return `${v}n`
98
+ if (v instanceof Map) return {Map: [...v.entries()]}
99
+ if (v instanceof Set) return {Set: [...v.values()]}
100
+ if (typeof v === 'function' || typeof v === 'symbol') return String(v)
101
+ return v
102
+ }
103
+ /** Values of a mismatch travel as JSON between processes: make them plain data (BigInt, Map, Set, cycles). */
104
+ function plain(v ) {
105
+ if (v === undefined) return undefined
106
+ try { const s = JSON.stringify(v, jsonSafe); return s === undefined ? String(v) : JSON.parse(s) } catch { return String(v) }
107
+ }
108
+ function errorText(e ) {
109
+ if (e instanceof Error) return `${e.name}: ${e.message}`
110
+ return `thrown ${show(e)}`
111
+ }
112
+
113
+ // ---------------------------------------------------------------- defineModel
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+ const NAT = (n ) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0
145
+
146
+ export function defineModel (spec ) {
147
+ const bad = (why ) => { throw new TypeError(`defineModel(${JSON.stringify(spec?.name)}): ${why}`) }
148
+ if (!spec || typeof spec !== 'object') bad('spec must be an object')
149
+ if (typeof spec.name !== 'string' || !spec.name) bad('name must be a non-empty string')
150
+ if (typeof spec.description !== 'string') bad('description must be a string')
151
+ if (typeof spec.setup !== 'function') bad('setup must be a function')
152
+ if (spec.teardown !== undefined && typeof spec.teardown !== 'function') bad('teardown must be a function')
153
+ if (!Array.isArray(spec.actions) || !spec.actions.length) bad('actions must be a non-empty array')
154
+ const byName = new Map ()
155
+ for (const a of spec.actions) {
156
+ if (!a || typeof a.name !== 'string' || !a.name || typeof a.gen !== 'function' || typeof a.run !== 'function') bad('every action needs a name, gen(r) and run(state, args, check)')
157
+ if (byName.has(a.name)) bad(`action ${JSON.stringify(a.name)} is defined twice`)
158
+ if (a.weight !== undefined && !(Number.isFinite(a.weight) && a.weight >= 0)) bad(`action ${a.name}: weight must be a number >= 0`)
159
+ byName.set(a.name, a)
160
+ }
161
+ if (!spec.actions.some((a) => (a.weight ?? 1) > 0)) bad('at least one action needs a weight > 0')
162
+ const minSteps = spec.minSteps ?? 15, maxSteps = spec.maxSteps ?? 40
163
+ if (!NAT(minSteps) || !NAT(maxSteps) || minSteps > maxSteps) bad('minSteps and maxSteps must be integers with 0 <= minSteps <= maxSteps')
164
+ const invariants = (spec.invariants ?? []).map((inv, i) => {
165
+ if (typeof inv === 'function') return {name: '', check: inv}
166
+ if (inv && typeof inv.check === 'function' && typeof inv.name === 'string') return inv
167
+ return bad(`invariant ${i} must be a function or {name, check}`)
168
+ })
169
+ const mutants = new Map ()
170
+ for (const [name, m] of Object.entries(spec.mutants ?? {})) {
171
+ if (typeof m === 'function') mutants.set(name, m)
172
+ else if (m && typeof m.setup === 'function') mutants.set(name, (ctx) => m.setup(ctx))
173
+ else bad(`mutant ${name} must be a setup function or {setup}`)
174
+ }
175
+ const weighted = spec.actions.map((a) => ({weight: a.weight ?? 1, value: a}))
176
+
177
+ return {
178
+ name: spec.name,
179
+ description: spec.description,
180
+ mutants: [...mutants.keys()],
181
+ generate(seed ) {
182
+ const r = createRng(seed)
183
+ const n = r.int(minSteps, maxSteps)
184
+ const actions = []
185
+ for (let i = 0; i < n; i++) {
186
+ const a = r.weighted(weighted)
187
+ const args = a.gen(r)
188
+ // the run in memory must equal its JSON copy (a saved reproduction replays exactly what was found)
189
+ actions.push(args === undefined ? {t: a.name} : {t: a.name, args: JSON.parse(JSON.stringify(args))})
190
+ }
191
+ return {seed, actions}
192
+ },
193
+ async execute(run , dir , mutant ) {
194
+ const ctx = mutant === undefined ? {seed: run.seed, dir} : {seed: run.seed, dir, mutant}
195
+ const cov = {}
196
+ let step = -1, action = null, state , ready = false
197
+ const mismatch = (e , prefix = '') => e instanceof MismatchError
198
+ ? {ok: false, mismatch: {step, action, what: prefix + e.what, expected: plain(e.expected), actual: plain(e.actual)}}
199
+ : {ok: false, mismatch: {step, action, what: prefix ? `${prefix}exception` : 'exception', expected: 'no error', actual: errorText(e)}}
200
+ const checkAll = async () => {
201
+ for (const inv of invariants) {
202
+ try { await inv.check(state , check) } catch (e) { throw new Tagged(e, inv.name ? `invariant ${inv.name}: ` : '') }
203
+ }
204
+ }
205
+ let out
206
+ try {
207
+ let setup = spec.setup
208
+ if (mutant !== undefined) {
209
+ const m = mutants.get(mutant)
210
+ if (!m) throw new MismatchError('unknown mutant', [...mutants.keys()], mutant)
211
+ setup = m
212
+ }
213
+ state = await setup(mutant === undefined ? ctx : {seed: run.seed, dir})
214
+ ready = true
215
+ await checkAll()
216
+ for (let i = 0; i < run.actions.length; i++) {
217
+ step = i; action = run.actions[i]
218
+ const a = run.actions[i]
219
+ const def = a && typeof a === 'object' ? byName.get(a.t) : undefined
220
+ if (!def) throw new MismatchError('unknown action', [...byName.keys()], a)
221
+ cov[def.name] = (cov[def.name] ?? 0) + 1
222
+ await def.run(state , a.args, check)
223
+ await checkAll()
224
+ }
225
+ out = {ok: true, steps: run.actions.length, cov}
226
+ } catch (e) {
227
+ out = e instanceof Tagged ? mismatch(e.cause, e.prefix) : mismatch(e)
228
+ }
229
+ if (ready && spec.teardown) {
230
+ try { await spec.teardown(state , ctx) } catch (e) { if (out.ok) out = mismatch(e, 'teardown: ') }
231
+ }
232
+ return out
233
+ },
234
+ }
235
+ }
236
+
237
+ /** An error from an invariant, with the invariant's name for the report. */
238
+ class Tagged {
239
+ cause
240
+ prefix
241
+ constructor(cause , prefix ) { this.cause = cause; this.prefix = prefix }
242
+ }
@@ -0,0 +1,207 @@
1
+ // Built from src/probe/stdio.ts by scripts/build.ts. Do not edit.
2
+ // PROBE targets in any language: `stopbar probe --cmd "<command>"` starts the command once per worker and speaks
3
+ // line-delimited JSON (NDJSON) with it on stdin/stdout, one request and one answer per line, in order:
4
+ // {"op":"info"} -> {"name":"...","description":"...","mutants":["M1",...]}
5
+ // {"op":"generate","seed":123} -> {"seed":123,"actions":[...]}
6
+ // {"op":"execute","run":{...},"dir":"...","mutant":"M1"} -> an Outcome ({"ok":true,"steps":N,"cov":{...}} or
7
+ // {"ok":false,"mismatch":{"step","action","what","expected","actual"}})
8
+ // Any answer may be {"error":"..."} instead. stdout carries only the protocol; the program logs to stderr. A process
9
+ // that exits, closes stdout, answers with something that is not JSON or does not answer within the timeout is an
10
+ // error (ProbeError with the end of its stderr), never a hung worker.
11
+ import {spawn, spawnSync, } from 'node:child_process'
12
+ import {existsSync, statSync} from 'node:fs'
13
+ import {resolve} from 'node:path'
14
+
15
+
16
+ /** A refusal of the user's input (unknown file, bad export, no mutants, a broken --cmd): the CLI exits 1 with it. */
17
+ export class ProbeError extends Error {}
18
+
19
+
20
+
21
+
22
+ /** Splits a command line into words: whitespace separates, '...' and "..." group (no escapes inside '...'). */
23
+ export function splitCommand(cmd ) {
24
+ const out = []
25
+ let cur = '', inWord = false, q = null
26
+ for (let i = 0; i < cmd.length; i++) {
27
+ const c = cmd[i]
28
+ if (q) {
29
+ if (c === q) q = null
30
+ else if (q === '"' && c === '\\' && (cmd[i + 1] === '"' || cmd[i + 1] === '\\')) cur += cmd[++i]
31
+ else cur += c
32
+ } else if (c === '"' || c === "'") { q = c; inWord = true } else if (/\s/.test(c)) { if (inWord) out.push(cur); cur = ''; inWord = false } else { cur += c; inWord = true }
33
+ }
34
+ if (inWord) out.push(cur)
35
+ return out
36
+ }
37
+
38
+ /** The file a command runs: the first word after the interpreter that names an existing file (relative to `cwd`). */
39
+ export function commandFile(cmd , cwd = process.cwd()) {
40
+ for (const w of splitCommand(cmd).slice(1)) {
41
+ if (w.startsWith('-')) continue
42
+ const f = resolve(cwd, w)
43
+ try { if (existsSync(f) && statSync(f).isFile()) return f } catch { /* not a file */ }
44
+ }
45
+ return null
46
+ }
47
+
48
+ const NAT = (n ) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0
49
+ const isObj = (x ) => !!x && typeof x === 'object' && !Array.isArray(x)
50
+
51
+ /** One long-lived process of a --cmd target. Requests go one at a time; `close` ends stdin and kills it if needed. */
52
+ export class CmdClient {
53
+ cmd
54
+ ch = null
55
+ buf = ''
56
+ err = ''
57
+ exited = null
58
+ waiting = null
59
+ chain = Promise.resolve()
60
+ cwd
61
+ timeoutMs
62
+
63
+ constructor(cmd , o = {}) {
64
+ if (!cmd.trim()) throw new ProbeError('--cmd needs a command, e.g. --cmd "python my_probe.py"')
65
+ this.cmd = cmd; this.cwd = o.cwd ?? process.cwd(); this.timeoutMs = o.timeoutMs ?? 300_000
66
+ }
67
+
68
+ stderrTail() {
69
+ const t = this.err.trim()
70
+ return t ? `; stderr: ${t.length > 600 ? '...' + t.slice(-600) : t}` : '; stderr: (empty)'
71
+ }
72
+
73
+ fail(why ) {
74
+ const w = this.waiting
75
+ this.waiting = null
76
+ if (w) { if (w.timer) clearTimeout(w.timer); w.bad(new ProbeError(`probe command ${JSON.stringify(this.cmd)} ${why} (waiting for the answer to ${w.op})${this.stderrTail()}`)) }
77
+ }
78
+
79
+ start() {
80
+ if (this.ch && this.exited === null) return this.ch
81
+ this.buf = ''; this.err = ''; this.exited = null
82
+ // a shell, so the command line works as typed (python, py -3, npx tsx, a script with a #!)
83
+ const ch = spawn(this.cmd, {cwd: this.cwd, shell: true, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32'})
84
+ this.ch = ch
85
+ ch.stdout .setEncoding('utf8'); ch.stderr .setEncoding('utf8')
86
+ const live = () => this.ch === ch // handlers of an earlier process of this client do nothing
87
+ ch.stderr .on('data', (d ) => { if (live()) this.err = (this.err + d).slice(-4000) })
88
+ ch.stdout .on('data', (d ) => {
89
+ if (!live()) return
90
+ this.buf += d
91
+ for (let i = this.buf.indexOf('\n'); i >= 0; i = this.buf.indexOf('\n')) {
92
+ const line = this.buf.slice(0, i).trim()
93
+ this.buf = this.buf.slice(i + 1)
94
+ if (!line) continue
95
+ const w = this.waiting
96
+ if (!w) { this.err += `\n[stopbar] unexpected line on stdout: ${line.slice(0, 200)}`; continue }
97
+ let v
98
+ try { v = JSON.parse(line) } catch {
99
+ this.fail(`printed a line that is not JSON: ${JSON.stringify(line.slice(0, 200))} (stdout is for the protocol only; log to stderr)`)
100
+ this.kill(); return
101
+ }
102
+ this.waiting = null
103
+ if (w.timer) clearTimeout(w.timer)
104
+ w.ok(v)
105
+ }
106
+ })
107
+ const gone = () => { if (live() && this.waiting) this.fail(this.exited ? `${this.exited} before answering` : 'closed stdout') }
108
+ // stdout may end before 'exit' arrives: wait a moment so the error names the exit code
109
+ ch.stdout .on('end', () => setTimeout(gone, 100))
110
+ ch.stdin .on('error', () => { /* EPIPE after an exit: reported below */ })
111
+ ch.on('error', (e) => { if (!live()) return; this.exited = `failed to start: ${e.message}`; this.fail(this.exited) })
112
+ ch.on('exit', (code, sig) => { if (live()) this.exited = `exited with ${sig ? `signal ${sig}` : `code ${code}`}` })
113
+ ch.on('close', gone)
114
+ return ch
115
+ }
116
+
117
+ /** Sends one request and waits for its answer line (requests are queued, one at a time). */
118
+ request(msg ) {
119
+ const go = () => new Promise ((ok, bad) => {
120
+ const ch = this.start()
121
+ const op = String(msg.op)
122
+ this.waiting = {op, ok, bad}
123
+ if (this.timeoutMs > 0) this.waiting.timer = setTimeout(() => { this.fail(`did not answer within ${this.timeoutMs} ms`); this.kill() }, this.timeoutMs)
124
+ try { ch.stdin .write(JSON.stringify(msg) + '\n') } catch (e) { this.fail(`does not read stdin: ${(e ).message}`) }
125
+ })
126
+ const p = this.chain.then(go, go)
127
+ this.chain = p.catch(() => undefined)
128
+ return p
129
+ }
130
+
131
+ async ask(msg ) {
132
+ const v = await this.request(msg)
133
+ if (isObj(v) && typeof v.error === 'string') throw new ProbeError(`probe command ${JSON.stringify(this.cmd)} answered ${msg.op} with an error: ${v.error}${this.stderrTail()}`)
134
+ if (!isObj(v)) throw new ProbeError(`probe command ${JSON.stringify(this.cmd)}: the answer to ${msg.op} is not a JSON object: ${JSON.stringify(v)?.slice(0, 200)}`)
135
+ return v
136
+ }
137
+
138
+ bad(op , why , v ) {
139
+ throw new ProbeError(`probe command ${JSON.stringify(this.cmd)}: bad answer to ${op}: ${why}; got ${JSON.stringify(v)?.slice(0, 300)}`)
140
+ }
141
+
142
+ async info() {
143
+ const v = await this.ask({op: 'info'})
144
+ if (typeof v.name !== 'string' || !v.name) this.bad('info', 'name must be a non-empty string', v)
145
+ if (typeof v.description !== 'string') this.bad('info', 'description must be a string', v)
146
+ if (v.mutants !== undefined && v.mutants !== null && !(Array.isArray(v.mutants) && v.mutants.every((m ) => typeof m === 'string' && m))) this.bad('info', 'mutants must be a list of names', v)
147
+ return {name: v.name, description: v.description, ...(Array.isArray(v.mutants) ? {mutants: v.mutants} : {})}
148
+ }
149
+
150
+ async generate(seed ) {
151
+ const v = await this.ask({op: 'generate', seed})
152
+ if (v.seed !== seed) this.bad('generate', `seed must be ${seed}`, v)
153
+ if (!Array.isArray(v.actions)) this.bad('generate', 'actions must be a list', v)
154
+ return {...v, seed, actions: v.actions}
155
+ }
156
+
157
+ async execute(run , dir , mutant ) {
158
+ const v = await this.ask({op: 'execute', run, dir, ...(mutant === undefined ? {} : {mutant})})
159
+ if (v.ok === true) {
160
+ if (!NAT(v.steps)) this.bad('execute', 'steps must be an integer >= 0', v)
161
+ const cov = v.cov ?? {}
162
+ if (!isObj(cov) || !Object.values(cov).every(NAT)) this.bad('execute', 'cov must map names to integers >= 0', v)
163
+ return {ok: true, steps: v.steps, cov}
164
+ }
165
+ if (v.ok === false) {
166
+ const m = v.mismatch
167
+ if (!isObj(m) || !Number.isSafeInteger(m.step) || m.step < -1 || typeof m.what !== 'string' || !m.what) this.bad('execute', 'mismatch needs step (integer >= -1) and what (non-empty string)', v)
168
+ return {ok: false, mismatch: {step: m.step, action: m.action ?? null, what: m.what, expected: m.expected ?? null, actual: m.actual ?? null}}
169
+ }
170
+ return this.bad('execute', 'ok must be true or false', v)
171
+ }
172
+
173
+ /** Kills the process tree. taskkill reports a failure (no rights, a sandbox, not on PATH) by its status, not by an
174
+ * exception: then the direct child is killed. The pipes are always destroyed and the child unref'd, so a process
175
+ * that survives (a grandchild of the shell) can never hold the event loop of Stopbar open. */
176
+ kill() {
177
+ const ch = this.ch
178
+ if (!ch) return
179
+ if (ch.pid !== undefined && this.exited === null) {
180
+ let treeKilled = false
181
+ try {
182
+ if (process.platform === 'win32') {
183
+ const r = spawnSync('taskkill', ['/pid', String(ch.pid), '/T', '/F'], {stdio: 'ignore', windowsHide: true})
184
+ treeKilled = !r.error && r.status === 0
185
+ } else { process.kill(-ch.pid, 'SIGKILL'); treeKilled = true }
186
+ } catch { /* fall back to the direct child below */ }
187
+ if (!treeKilled) try { ch.kill('SIGKILL') } catch { /* gone */ }
188
+ }
189
+ for (const s of [ch.stdin, ch.stdout, ch.stderr]) try { s?.destroy() } catch { /* closed */ }
190
+ ch.unref()
191
+ }
192
+
193
+ /** Ends stdin (a well-behaved target exits on EOF); kills the process tree after `graceMs`. */
194
+ async close(graceMs = 2000) {
195
+ const ch = this.ch
196
+ if (!ch || this.exited !== null) return
197
+ await this.chain
198
+ if (this.exited !== null) return
199
+ const gone = new Promise ((ok) => ch.once('exit', () => ok()))
200
+ try { ch.stdin .end() } catch { /* already closed */ }
201
+ const timer = new Promise ((ok) => { const t = setTimeout(() => ok('late'), graceMs); t.unref?.() })
202
+ if (await Promise.race([gone.then(() => 'gone' ), timer]) === 'late') {
203
+ this.kill() // destroys the pipes and unrefs the child even when the kill itself fails
204
+ await Promise.race([gone, new Promise((ok) => { const t = setTimeout(ok, 1000); t.unref?.() })])
205
+ }
206
+ }
207
+ }
@@ -18,6 +18,7 @@ import {runHook} from '../hook.js'
18
18
 
19
19
 
20
20
 
21
+
21
22
 
22
23
 
23
24
 
@@ -36,7 +37,9 @@ import {runHook} from '../hook.js'
36
37
 
37
38
 
38
39
 
39
-
40
+ // baseRef: init --base-ref on a branch at the base commit that never moves (HEAD moves with every commit); saved runs
41
+ // without the field run without a base ref, as before 1.1.3
42
+
40
43
 
41
44
  function rng(seed ) { let x = (seed * 2654435761) >>> 0 || 7; return () => { x ^= x << 13; x >>>= 0; x ^= x >>> 17; x ^= x << 5; x >>>= 0; return x / 2 ** 32 } }
42
45
 
@@ -56,6 +59,7 @@ function genRun(seed ) {
56
59
  [6, () => ({t: 'edit', tool: pick(['Write', 'Edit'] ), file: pick([...TESTS, `tests/n${Math.floor(r() * 3)}.test.mjs`, CONFIG]), content: content()})],
57
60
  [4, () => ({t: 'shellEdit', file: anyFile(), content: content()})],
58
61
  [2, () => ({t: 'shellDelete', file: anyFile()})],
62
+ [3, () => ({t: 'restore', file: r() < 0.7 ? pick([...TESTS, CONFIG]) : anyFile()})],
59
63
  [2, () => ({t: 'humanEdit', file: anyFile(), content: content()})],
60
64
  [10, () => ({t: 'build', outcome: pick(['pass', 'pass', 'pass', 'fail', 'interrupt', 'interrupted', 'bgPre', 'bgPost'] )})],
61
65
  [10, () => ({t: 'fulltest', outcome: pick(['pass', 'pass', 'pass', 'fail', 'fail', 'interrupt', 'interrupted', 'bgPre', 'bgPost'] )})],
@@ -92,7 +96,8 @@ function genRun(seed ) {
92
96
  let x = r() * total
93
97
  for (const [w, f] of W) { if ((x -= w) < 0) { actions.push(f()); break } }
94
98
  }
95
- return {seed, params: {maxRetries: 1 + Math.floor(r() * 3), cap: 10 + Math.floor(r() * 60), cost: Math.floor(r() * 3)}, actions: actions.slice(0, 30)}
99
+ // baseRef from the seed's parity, not from r(): the action sequence of a seed stays what it was before 1.1.3
100
+ return {seed, params: {maxRetries: 1 + Math.floor(r() * 3), cap: 10 + Math.floor(r() * 60), cost: Math.floor(r() * 3), baseRef: seed % 2 === 1}, actions: actions.slice(0, 30)}
96
101
  }
97
102
 
98
103
  // ---------------------------------------------------------------- execution against the real wrapper + the model
@@ -101,7 +106,7 @@ async function execute(run , dir ) {
101
106
  // the model needs the prover package (gdp-wired); the hooks under test never load it
102
107
  const {kernel} = await import('../kernel.js')
103
108
  const R = kernel('none'), IT = R.interpreter()
104
- const {maxRetries, cap, cost} = run.params
109
+ const {maxRetries, cap, cost} = run.params, useBase = run.params.baseRef === true
105
110
  const P = R.encodeParams({maxRetries, cap})
106
111
 
107
112
  rmSync(dir, {recursive: true, force: true, maxRetries: 5})
@@ -114,10 +119,14 @@ async function execute(run , dir ) {
114
119
  writeFileSync(join(dir, '.gitignore'), '.env\nsecrets/\n'); work.set('.gitignore', '.env\nsecrets/\n')
115
120
  writeFileSync(join(dir, '.env'), 'X=1\n')
116
121
  g('init', '-q'); g('config', 'core.autocrlf', 'false'); g('add', '-A'); g('commit', '-qm', 'base')
122
+ g('branch', 'probe-base') // the base commit; the base ref of runs with params.baseRef
117
123
  const opts = (o ) => ({get: (k ) => o[k], has: (k ) => k in o, int: (k , d ) => (k in o ? Number(o[k]) : d)})
118
- const ini = C.init(opts({repo: dir, build: 'node build.mjs', test: 'node --test', 'max-retries': String(maxRetries), cap: String(cap), cost: String(cost), 'no-pin': ''}))
124
+ const ini = C.init(opts({repo: dir, build: 'node build.mjs', test: 'node --test', 'max-retries': String(maxRetries), cap: String(cap), cost: String(cost), 'no-pin': '', ...(useBase ? {'base-ref': 'probe-base'} : {})}))
119
125
  if (ini.code !== 0) throw new Error(`init failed: ${ini.msg}`)
120
126
 
127
+ const cov = {}
128
+ const inc = (k ) => { cov[k] = (cov[k] ?? 0) + 1 }
129
+
121
130
  // ---- model
122
131
  let st = IT.init(P)
123
132
  let modelSteps = 0
@@ -130,6 +139,11 @@ async function execute(run , dir ) {
130
139
  }
131
140
  const same = (a , b ) => a.size === b.size && [...a].every(([k, v]) => b.get(k) === v)
132
141
  const isTest = (f ) => f.startsWith('tests/')
142
+ const isCfg = (f ) => f === CONFIG || f === '.gitignore'
143
+ const baseTree = new Map(work) // the tree of the base ref (it never moves in a run)
144
+ // with a base ref: suspicious = test config whose content differs from the base ref, or a test of the base ref whose
145
+ // content differs from it (changed or deleted); a file equal to the base ref is not (checkout, rebase, cherry-pick)
146
+ const differsFromRef = (f , ref ) => (isCfg(f) || (isTest(f) && ref.has(f))) && work.get(f) !== ref.get(f)
133
147
  const mSync = (c ) => {
134
148
  if (same(work, counted)) return null
135
149
  const base = countedCopy ? counted : head
@@ -138,7 +152,8 @@ async function execute(run , dir ) {
138
152
  // the counted copy was lost and the tree equals HEAD: the wrapper still sees a new snapshot id with no changes
139
153
  }
140
154
  const anyTest = changed.some((f) => isTest(f) || f === CONFIG || f === '.gitignore')
141
- const suspicious = changed.some((f) => f === CONFIG || f === '.gitignore' || (isTest(f) && head.has(f)))
155
+ const suspicious = useBase ? changed.some((f) => differsFromRef(f, baseTree)) : changed.some((f) => isCfg(f) || (isTest(f) && head.has(f)))
156
+ if (useBase && changed.some((f) => (isCfg(f) || (isTest(f) && baseTree.has(f))) && !differsFromRef(f, baseTree))) inc('sameAsBaseRef')
142
157
  const before = view().treeRev
143
158
  const after = kstep({op: anyTest ? 'EDIT_TEST' : 'EDIT_CODE', suspicious, cost: c})
144
159
  if (after.treeRev > before) { counted = new Map(work); countedCopy = true }
@@ -154,8 +169,6 @@ async function execute(run , dir ) {
154
169
  const loggedSteps = () => readFileSync(join(sd, 'events.jsonl'), 'utf8').split('\n').filter((l) => { try { return !!JSON.parse(l).req } catch { return false } }).length
155
170
  const initSteps = loggedSteps()
156
171
 
157
- const cov = {}
158
- const inc = (k ) => { cov[k] = (cov[k] ?? 0) + 1 }
159
172
  for (let i = 0; i < run.actions.length; i++) {
160
173
  const a = run.actions[i]
161
174
  const v0 = view()
@@ -186,6 +199,19 @@ async function execute(run , dir ) {
186
199
  gotCode = hook('PostToolUse', 'Bash', {command}, okResp)
187
200
  break
188
201
  }
202
+ case 'restore': {
203
+ const command = `git checkout -q probe-base -- ${a.file}`
204
+ expCode = expectPre()
205
+ if (!halted()) { const v = kstep({op: 'SHELL', risky: false, cost}); if (v.decision === 'PAUSE') expCode = 2 }
206
+ gotCode = hook('PreToolUse', 'Bash', {command})
207
+ if (gotCode !== 0 || expCode !== 0) break
208
+ const was = baseTree.get(a.file)
209
+ if (was !== undefined) put(a.file, was)
210
+ else { rmSync(join(dir, a.file), {force: true}); work.delete(a.file) }
211
+ expCode = postCode(mSync(0))
212
+ gotCode = hook('PostToolUse', 'Bash', {command}, okResp)
213
+ break
214
+ }
189
215
  case 'humanEdit': put(a.file, a.content); break
190
216
  case 'build': case 'fulltest': {
191
217
  const command = a.t === 'build' ? 'node build.mjs' : 'node --test'
@@ -289,6 +315,9 @@ async function execute(run , dir ) {
289
315
  if (gotCode !== 2) break
290
316
  if (readFileSync(join(sd, 'events.jsonl'), 'utf8') !== logBefore) { gotCode = -1; break } // fail closed writes nothing
291
317
  st = IT.init(P); counted = new Map(work); countedCopy = true
318
+ // reset on a dirty tree: test or test-config changes against the base ref (else HEAD) keep the session tainted
319
+ const ref = useBase ? baseTree : head
320
+ if ([...new Set([...ref.keys(), ...work.keys()])].some((f) => differsFromRef(f, ref))) { kstep({op: 'EDIT_TEST', suspicious: true, cost: 0}); inc('resetDirtyTests') }
292
321
  expCode = 0; gotCode = C.human('reset', opts({repo: dir})).code
293
322
  break
294
323
  }
package/dist/repo.js CHANGED
@@ -143,19 +143,45 @@ export function diffEntries(a , b )
143
143
  return out.sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : 0))
144
144
  }
145
145
 
146
- /** Fallback diff when the counted copy is gone: the current snapshot against HEAD (one git process). */
147
- export function changesSinceHead(r , now ) {
146
+ const refFailed = (ref ) => new FailClosed(`baseRef ${JSON.stringify(ref)} could not be resolved in git`,
147
+ 'a human restores the ref or runs `stopbar init --force ... --base-ref <ref>`')
148
+
149
+ /** `git ls-tree -r` of `ref` as entries (path -> "<mode> <oid>", leading zeros of the mode dropped as in the index).
150
+ * `paths` limits the listing (literal pathspecs); null lists the whole tree. One git process.
151
+ * A ref that does not resolve: HEAD (no commit yet) = empty tree; any other ref fails closed. */
152
+ function lsTree(root , ref , paths ) {
153
+ const out = new Map()
154
+ let raw
148
155
  try {
149
- const out = git(r.root, ['-c', 'core.quotepath=false', 'ls-tree', '-r', '-z', '--full-tree', 'HEAD'])
150
- const head = new Map()
151
- for (const rec of out.split('\0')) {
152
- const m = /^(\d+) \w+ ([0-9a-f]+)\t(.*)$/s.exec(rec)
153
- if (m) head.set(m[3], `${m[1].replace(/^0+/, '')} ${m[2]}`)
154
- }
155
- return diffEntries(head, now)
156
- } catch { return diffEntries(new Map(), now) }
156
+ raw = git(root, ['--literal-pathspecs', '-c', 'core.quotepath=false', 'ls-tree', '-r', '-z', '--full-tree', ref, ...(paths ? ['--', ...paths] : [])])
157
+ } catch {
158
+ if (ref === 'HEAD') return out
159
+ throw refFailed(ref)
160
+ }
161
+ for (const rec of raw.split('\0')) {
162
+ const m = /^(\d+) \w+ ([0-9a-f]+)\t(.*)$/s.exec(rec)
163
+ if (m) out.set(m[3], `${m[1].replace(/^0+/, '')} ${m[2]}`)
164
+ }
165
+ return out
157
166
  }
158
167
 
168
+ /** The entries of `paths` in `ref` (path -> "<mode> <oid>"; a path missing from the map is not in `ref`).
169
+ * One git process, called only when test files or test config changed. Non-HEAD ref that does not resolve: FailClosed. */
170
+ export function refEntries(root , ref , paths ) {
171
+ return paths.length ? lsTree(root, ref, paths) : new Map()
172
+ }
173
+
174
+ /** The blob id of an entry "<mode> <oid>" (the mode is ignored: on Windows the file mode is not reliable). */
175
+ export const oidOf = (v ) => v?.split(' ')[1]
176
+
177
+ /** The current snapshot against `ref` (one git process). Non-HEAD ref that does not resolve: FailClosed. */
178
+ export function changesSinceRef(r , ref , now ) {
179
+ return diffEntries(lsTree(r.root, ref, null), now)
180
+ }
181
+
182
+ /** Fallback diff when the counted copy is gone: the current snapshot against HEAD (one git process). */
183
+ export const changesSinceHead = (r , now ) => changesSinceRef(r, 'HEAD', now)
184
+
159
185
  /** Does the current private index differ from HEAD? (one git process; no HEAD = differs unless empty) */
160
186
  export function differsFromHead(r , now ) {
161
187
  try {
@@ -181,7 +207,7 @@ export function inRef(root , ref , paths ) {
181
207
  return new Set(out.split('\0').filter(Boolean))
182
208
  } catch {
183
209
  if (ref === 'HEAD') return new Set()
184
- throw new FailClosed(`baseRef ${JSON.stringify(ref)} could not be resolved in git`, 'a human restores the ref or runs `stopbar init --force ... --base-ref <ref>`')
210
+ throw refFailed(ref)
185
211
  }
186
212
  }
187
213
 
package/dist/store.js CHANGED
@@ -6,7 +6,7 @@ import { ConfigError, validateConfig} from './config.js'
6
6
  import {CODEC} from './kernel.gen.js'
7
7
  import {FailClosed, } from './repo.js'
8
8
 
9
- export const VERSION = '1.1.2'
9
+ export const VERSION = '1.2.0'
10
10
 
11
11
 
12
12