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.
- package/CHANGELOG.md +180 -0
- package/README.md +165 -29
- package/SECURITY.md +115 -13
- package/dist/attest.js +28 -3
- package/dist/build-info.json +2 -2
- package/dist/classify.js +201 -25
- package/dist/cli.js +44 -8
- package/dist/commands.js +96 -22
- package/dist/config.js +7 -2
- package/dist/doctor.js +19 -9
- package/dist/hook.js +73 -36
- package/dist/integrations.js +14 -5
- package/dist/probe/index.js +247 -57
- package/dist/probe/init.js +217 -0
- package/dist/probe/sdk.js +242 -0
- package/dist/probe/stdio.js +207 -0
- package/dist/probe/wrapper.js +36 -7
- package/dist/repo.js +37 -11
- package/dist/store.js +1 -1
- package/package.json +17 -2
- package/skills/stopbar/SKILL.md +126 -0
- package/src/probe/sdk.ts +241 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stopbar",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "A formally proven execution gate for AI coding agents: hooks for Claude Code, Cursor, Codex CLI, Gemini CLI and Antigravity CLI, plus git hooks. No commit without a passing build and full test suite, no silent test weakening, no exfiltration after a secret read.",
|
|
5
5
|
"author": "Paweł Olszewski <kontakt@polszewski.com>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -16,11 +16,21 @@
|
|
|
16
16
|
"bin": {
|
|
17
17
|
"stopbar": "bin/stopbar.mjs"
|
|
18
18
|
},
|
|
19
|
+
"exports": {
|
|
20
|
+
"./probe": {
|
|
21
|
+
"types": "./src/probe/sdk.ts",
|
|
22
|
+
"default": "./dist/probe/sdk.js"
|
|
23
|
+
},
|
|
24
|
+
"./package.json": "./package.json"
|
|
25
|
+
},
|
|
19
26
|
"files": [
|
|
20
27
|
"bin/",
|
|
21
|
-
"dist
|
|
28
|
+
"dist/**/*.js",
|
|
29
|
+
"dist/build-info.json",
|
|
22
30
|
"src/kernel.ts",
|
|
31
|
+
"src/probe/sdk.ts",
|
|
23
32
|
"claude-hooks.example.json",
|
|
33
|
+
"skills/",
|
|
24
34
|
"README.md",
|
|
25
35
|
"SECURITY.md",
|
|
26
36
|
"CHANGELOG.md",
|
|
@@ -39,6 +49,7 @@
|
|
|
39
49
|
"verify:lean": "node scripts/build.ts && node scripts/verify-lean.ts",
|
|
40
50
|
"probe": "node scripts/build.ts && node bin/stopbar.mjs probe",
|
|
41
51
|
"bench": "node bench/hook-latency.ts",
|
|
52
|
+
"typecheck": "tsc --noEmit",
|
|
42
53
|
"prepack": "node scripts/build.ts"
|
|
43
54
|
},
|
|
44
55
|
"keywords": [
|
|
@@ -56,5 +67,9 @@
|
|
|
56
67
|
],
|
|
57
68
|
"dependencies": {
|
|
58
69
|
"gdp-wired": "0.60.0"
|
|
70
|
+
},
|
|
71
|
+
"devDependencies": {
|
|
72
|
+
"@types/node": "24.19.4",
|
|
73
|
+
"typescript": "5.9.3"
|
|
59
74
|
}
|
|
60
75
|
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: stopbar
|
|
3
|
+
description: Load this skill when you work in a repository that Stopbar GATE protects (a `.git/stopbar/` directory, Stopbar hooks, or a Stopbar block message), or when you write a multi-step `stopbar probe` target to the Zero-FP standard.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Stopbar
|
|
7
|
+
|
|
8
|
+
Stopbar is an execution gate for AI coding agents. Its hooks block a commit until the build and the full test suite
|
|
9
|
+
pass at the current tree, block unapproved test changes and block risky or outbound commands after a secret read.
|
|
10
|
+
The hooks check the command text. This skill tells you how to work with them and how to write probes that find only
|
|
11
|
+
real bugs.
|
|
12
|
+
|
|
13
|
+
`<cli>` below is the Stopbar command that the block hints show. The default is `npx --no-install stopbar`; a human can
|
|
14
|
+
set another one with `stopbar init --cli "<cmd>"`.
|
|
15
|
+
|
|
16
|
+
## 1. Working under Stopbar GATE
|
|
17
|
+
|
|
18
|
+
### Gate commands
|
|
19
|
+
|
|
20
|
+
- Run `buildCmd` and `fullTestCmd` exactly as configured: the same text, alone, in the foreground. Do not add `;`,
|
|
21
|
+
`&&`, `||`, `|`, `>`, `2>&1` or `tail`, and do not run them in the background. A changed or chained command is not
|
|
22
|
+
recorded as a gate.
|
|
23
|
+
- A gate that runs longer than 10 minutes: run `<cli> run build` or `<cli> run test`. This form can run in the
|
|
24
|
+
background. Stopbar records the real exit status when the process ends and discards it if the tree changed.
|
|
25
|
+
- Always use `<cli> run build|test` when the config has `requireRun: true` (`--require-run`) and when you are Codex
|
|
26
|
+
CLI (Codex reports no exit status to hooks).
|
|
27
|
+
- Run the build and the full tests again after each change to the tree. A gate counts only at the revision where it
|
|
28
|
+
passed.
|
|
29
|
+
- `<cli> status` is read-only. Use it to see why a commit is blocked. It also shows a change that no hook has counted
|
|
30
|
+
yet; the next hook counts it, and then you run the build and the full tests again.
|
|
31
|
+
|
|
32
|
+
### Commits
|
|
33
|
+
|
|
34
|
+
- One commit is one command: `git commit -m "..."`, or a quoted heredoc:
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
git commit -m "$(cat <<'EOF'
|
|
38
|
+
Fix the parser
|
|
39
|
+
|
|
40
|
+
Body text.
|
|
41
|
+
EOF
|
|
42
|
+
)"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
- Do not chain `git add` and `git commit`. Run them as two commands.
|
|
46
|
+
|
|
47
|
+
### Respect a block
|
|
48
|
+
|
|
49
|
+
- A block is a decision, not an error to work around. Read the reason and fix the cause.
|
|
50
|
+
- Do not bypass a block with a script, a wrapper, a generated file, an alias, `git -c alias.*`, `--no-verify` or
|
|
51
|
+
another git client.
|
|
52
|
+
- Do not edit `.git/` (hooks, `.git/stopbar/`), the hook config of any agent (`.claude/`, `.cursor/`, `.codex/`,
|
|
53
|
+
`.gemini/`, `.agents/`) or the Stopbar package.
|
|
54
|
+
|
|
55
|
+
### Human-only commands
|
|
56
|
+
|
|
57
|
+
`init`, `upgrade`, `approve-tests`, `approve-shell`, `resume` and `reset` belong to the human. Do not run them, do not
|
|
58
|
+
ask a tool or another agent to run them, and do not put them in a script. The hooks block them. `stopbar probe init`
|
|
59
|
+
(section 2) is not `init`: you can run it.
|
|
60
|
+
|
|
61
|
+
Stop and ask the human when one of these is true:
|
|
62
|
+
|
|
63
|
+
| State | Cause | What to report | Human command |
|
|
64
|
+
|---|---|---|---|
|
|
65
|
+
| `testsTainted` | you changed an existing test or test config | the changed test files and why | `stopbar approve-tests` |
|
|
66
|
+
| `secretTainted` | you read a secret file or token | the one risky or outbound call you need and why | `stopbar approve-shell` |
|
|
67
|
+
| `HALT` | retry limit or tool-call budget reached | the last failing gate and its error, in short | `stopbar resume --extra N` |
|
|
68
|
+
|
|
69
|
+
Write the report in a few lines, then wait. In `HALT`, only the tools in `config.safeTools` pass (default
|
|
70
|
+
`mcp__ccd_turn__*` and `mcp__ccd_session_mgmt__*`); use them to tell the human about the block.
|
|
71
|
+
|
|
72
|
+
## 2. Writing Zero-FP stateful probes (`stopbar probe`)
|
|
73
|
+
|
|
74
|
+
A probe runs random multi-step sequences against the system under test (SUT) and compares each step with a model.
|
|
75
|
+
Zero-FP means that every failure is a real bug.
|
|
76
|
+
|
|
77
|
+
### Start
|
|
78
|
+
|
|
79
|
+
```sh
|
|
80
|
+
stopbar probe init --lang ts --name <module> # writes probes/<module>.probe.ts
|
|
81
|
+
stopbar probe init --lang py --name <module> # writes probes/<module>_probe.py
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
- TS/JS: `defineModel` from `stopbar/probe` (`setup`, `actions` with `gen` and `run`, `invariants`, `mutants`). Run
|
|
85
|
+
with `stopbar probe --target probes/<module>.probe.ts`.
|
|
86
|
+
- Python, Go, Rust and other languages: a program that speaks NDJSON on stdin/stdout (`info`, `generate`,
|
|
87
|
+
`execute`). Run with `stopbar probe --cmd "<command>"`. stdout is for the protocol only; print logs to stderr.
|
|
88
|
+
Catch an exception of the SUT in `execute` and answer with a mismatch.
|
|
89
|
+
- Run only a prober that you wrote in this session. A prober file from outside the session (another agent, an earlier
|
|
90
|
+
session, a download) needs a human review before you run it (SECURITY.md section 4). A new prober that you wrote
|
|
91
|
+
needs a human review before its result counts as evidence in `stopbar attest`.
|
|
92
|
+
|
|
93
|
+
### The 5 Zero-FP rules
|
|
94
|
+
|
|
95
|
+
1. **Deterministic `gen`.** Draw arguments only from the seeded generator (`r` in TS, the seed in `generate`) and
|
|
96
|
+
return plain JSON data. The same seed gives the same run on every machine.
|
|
97
|
+
2. **Independent oracle.** The model is a separate, simple reference (an array, a map, a reference formula) plus
|
|
98
|
+
invariants. Never compare the SUT with itself or with a copy of its own code.
|
|
99
|
+
3. **No clock, network or global state.** Write files only in the scratch directory of the run (`dir` in
|
|
100
|
+
`execute`). Reset all state in `setup`. Do not assume a short start or answer time under CPU load: for a slow
|
|
101
|
+
`--cmd` target, set `--cmd-timeout` with a large margin.
|
|
102
|
+
4. **At least 2 realistic mutants.** Each mutant is a small, real bug (a dropped bound check, an off-by-one). Run
|
|
103
|
+
`stopbar probe ... --check-mutants` and make it pass (exit 0, no survivor) before you increase `--runs`. A
|
|
104
|
+
surviving mutant shows a weak model or weak actions; fix the probe, not the mutant.
|
|
105
|
+
5. **Shrink, then reproduce.** On a failure, use the shrunk sequence in `repro-<seed>.json` (in `--out`). Write a
|
|
106
|
+
minimal test that reproduces the bug (less than 25 lines) and look for a known issue or test before you report it.
|
|
107
|
+
Replay the file with `--regressions <dir>` after the fix.
|
|
108
|
+
|
|
109
|
+
### Before you report a finding
|
|
110
|
+
|
|
111
|
+
- Make sure that the model, not the SUT, is correct for the failing step. A model error is a false positive: fix the
|
|
112
|
+
model.
|
|
113
|
+
- Run the reproduction twice with the same seed. A result that changes is a rule 1 or rule 3 error.
|
|
114
|
+
|
|
115
|
+
### After the first finding
|
|
116
|
+
|
|
117
|
+
- Save `repro-<seed>.json`. Then add a switch to the generator that turns off the known bug category for a while, so
|
|
118
|
+
that the original passes and `--check-mutants` can run. Look for the next bug.
|
|
119
|
+
|
|
120
|
+
### Evidence
|
|
121
|
+
|
|
122
|
+
- Run `stopbar probe` in a repository with Stopbar. Each run appends a `probe:result` entry to the event log (target,
|
|
123
|
+
sha256 of the target file, tree snapshot, runs, mutants). Do not pass `--no-record`. The only exception is an
|
|
124
|
+
explicit instruction from a human (for example, an audit that must not add entries to the log).
|
|
125
|
+
- The human or CI collects the evidence with `stopbar attest --format md` or `--format json`. The `Probe evidence`
|
|
126
|
+
section shows the latest result per target and whether the tree is still the one that was probed.
|
package/src/probe/sdk.ts
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
// stopbar/probe: the SDK for PROBE targets of any TS/JS project. A target describes a model as a list of actions
|
|
2
|
+
// (each with a generator of pure JSON data and a run that drives the real thing and checks it), invariants that hold
|
|
3
|
+
// after every step, and optional mutants (a damaged system under test) that the prober must catch.
|
|
4
|
+
// `stopbar probe --target <file>` loads the file (default export or export `target`) and runs it as any other target.
|
|
5
|
+
// This module has no imports besides node:util, so its source ships as the type declaration of `stopbar/probe`.
|
|
6
|
+
import {isDeepStrictEqual} from 'node:util'
|
|
7
|
+
|
|
8
|
+
// ---------------------------------------------------------------- the target contract (shared with the runner)
|
|
9
|
+
export type Mismatch = {step: number; action: unknown; what: string; expected: unknown; actual: unknown}
|
|
10
|
+
export type Outcome = {ok: true; steps: number; hooks?: number; cov: Record<string, number>} | {ok: false; mismatch: Mismatch}
|
|
11
|
+
export type ProbeRun = {seed: number; actions: unknown[]}
|
|
12
|
+
export interface ProbeTarget<R extends ProbeRun> {
|
|
13
|
+
name: string
|
|
14
|
+
description: string
|
|
15
|
+
/** Names of the mutants `execute` accepts as its third argument (for `stopbar probe --check-mutants`). */
|
|
16
|
+
mutants?: string[]
|
|
17
|
+
generate(seed: number): R
|
|
18
|
+
/** Runs `run` in the empty scratch directory `dir` (against `mutant` if given); never throws for a mismatch, returns it. */
|
|
19
|
+
execute(run: R, dir: string, mutant?: string): Promise<Outcome>
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// ---------------------------------------------------------------- deterministic random numbers
|
|
23
|
+
export interface Rng {
|
|
24
|
+
/** A number in [0, 1). */
|
|
25
|
+
next(): number
|
|
26
|
+
/** An integer in [min, max], both included. */
|
|
27
|
+
int(min: number, max: number): number
|
|
28
|
+
/** true with probability p (default 0.5). */
|
|
29
|
+
bool(p?: number): boolean
|
|
30
|
+
pick<T>(xs: readonly T[]): T
|
|
31
|
+
/** A value chosen by weight (default weight 1). */
|
|
32
|
+
weighted<T>(xs: readonly {weight?: number; value: T}[]): T
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** xorshift32 on 32-bit integer arithmetic only: the same seed gives the same numbers on every platform. */
|
|
36
|
+
export function createRng(seed: number): Rng {
|
|
37
|
+
if (!Number.isFinite(seed)) throw new TypeError(`createRng: seed must be a finite number, got ${seed}`)
|
|
38
|
+
let x = Math.imul(Math.trunc(seed) | 0, 0x9e3779b1) >>> 0 || 7
|
|
39
|
+
const next = () => { x ^= x << 13; x >>>= 0; x ^= x >>> 17; x ^= x << 5; x >>>= 0; return x / 2 ** 32 }
|
|
40
|
+
const int = (min: number, max: number) => {
|
|
41
|
+
if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || max < min) throw new RangeError(`rng.int: need integers min <= max, got ${min}, ${max}`)
|
|
42
|
+
return min + Math.floor(next() * (max - min + 1))
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
next, int,
|
|
46
|
+
bool: (p = 0.5) => next() < p,
|
|
47
|
+
pick: <T>(xs: readonly T[]): T => {
|
|
48
|
+
if (!xs.length) throw new RangeError('rng.pick: empty list')
|
|
49
|
+
return xs[Math.floor(next() * xs.length)]
|
|
50
|
+
},
|
|
51
|
+
weighted: <T>(xs: readonly {weight?: number; value: T}[]): T => {
|
|
52
|
+
const w = xs.map((e) => e.weight ?? 1)
|
|
53
|
+
if (w.some((v) => !Number.isFinite(v) || v < 0)) throw new RangeError('rng.weighted: weights must be finite numbers >= 0')
|
|
54
|
+
const total = w.reduce((s, v) => s + v, 0)
|
|
55
|
+
if (!(total > 0)) throw new RangeError('rng.weighted: no value with a weight > 0')
|
|
56
|
+
let r = next() * total
|
|
57
|
+
for (let i = 0; i < xs.length; i++) { if (w[i] > 0 && r < w[i]) return xs[i].value; r -= w[i] }
|
|
58
|
+
for (let i = xs.length - 1; ; i--) if (w[i] > 0) return xs[i].value // rounding at the upper end
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---------------------------------------------------------------- checks
|
|
64
|
+
/** Thrown by a failed check; `execute` turns it into `{ok: false, mismatch}` with the step and the action. */
|
|
65
|
+
export class MismatchError extends Error {
|
|
66
|
+
what: string
|
|
67
|
+
expected: unknown
|
|
68
|
+
actual: unknown
|
|
69
|
+
constructor(what: string, expected: unknown, actual: unknown) {
|
|
70
|
+
super(`${what}: expected ${show(expected)}, actual ${show(actual)}`)
|
|
71
|
+
this.name = 'MismatchError'
|
|
72
|
+
this.what = what; this.expected = expected; this.actual = actual
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface Check {
|
|
77
|
+
/** Fails when `cond` is falsy. `actual` and `expected` (optional) go into the report. */
|
|
78
|
+
ok(what: string, cond: unknown, actual?: unknown, expected?: unknown): void
|
|
79
|
+
/** Fails unless `actual` and `expected` are deeply and strictly equal (node:util isDeepStrictEqual). */
|
|
80
|
+
eq(what: string, actual: unknown, expected: unknown): void
|
|
81
|
+
fail(what: string, expected: unknown, actual: unknown): never
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const check: Check = {
|
|
85
|
+
ok(what, cond, ...rest: unknown[]) {
|
|
86
|
+
if (!cond) throw new MismatchError(what, rest.length >= 2 ? rest[1] : 'truthy', rest.length >= 1 ? rest[0] : cond)
|
|
87
|
+
},
|
|
88
|
+
eq(what, actual, expected) { if (!isDeepStrictEqual(actual, expected)) throw new MismatchError(what, expected, actual) },
|
|
89
|
+
fail(what, expected, actual): never { throw new MismatchError(what, expected, actual) },
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function show(v: unknown): string {
|
|
93
|
+
try { return JSON.stringify(v, jsonSafe) ?? String(v) } catch { return String(v) }
|
|
94
|
+
}
|
|
95
|
+
function jsonSafe(_k: string, v: unknown) {
|
|
96
|
+
if (typeof v === 'bigint') return `${v}n`
|
|
97
|
+
if (v instanceof Map) return {Map: [...v.entries()]}
|
|
98
|
+
if (v instanceof Set) return {Set: [...v.values()]}
|
|
99
|
+
if (typeof v === 'function' || typeof v === 'symbol') return String(v)
|
|
100
|
+
return v
|
|
101
|
+
}
|
|
102
|
+
/** Values of a mismatch travel as JSON between processes: make them plain data (BigInt, Map, Set, cycles). */
|
|
103
|
+
function plain(v: unknown): unknown {
|
|
104
|
+
if (v === undefined) return undefined
|
|
105
|
+
try { const s = JSON.stringify(v, jsonSafe); return s === undefined ? String(v) : JSON.parse(s) } catch { return String(v) }
|
|
106
|
+
}
|
|
107
|
+
function errorText(e: unknown): string {
|
|
108
|
+
if (e instanceof Error) return `${e.name}: ${e.message}`
|
|
109
|
+
return `thrown ${show(e)}`
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ---------------------------------------------------------------- defineModel
|
|
113
|
+
type Ctx = {seed: number; dir: string; mutant?: string}
|
|
114
|
+
type Awaitable<T> = T | Promise<T>
|
|
115
|
+
export type ActionSpec<S> = {
|
|
116
|
+
name: string
|
|
117
|
+
/** Relative frequency (default 1). */
|
|
118
|
+
weight?: number
|
|
119
|
+
/** Arguments of one step: pure data that survives JSON (saved in reproductions and regressions). */
|
|
120
|
+
gen(r: Rng): unknown
|
|
121
|
+
run(state: S, args: any, check: Check): Awaitable<void>
|
|
122
|
+
}
|
|
123
|
+
export type Invariant<S> = ((state: S, check: Check) => Awaitable<void>) | {name: string; check(state: S, check: Check): Awaitable<void>}
|
|
124
|
+
export type MutantSpec<S> = ((ctx: {seed: number; dir: string}) => Awaitable<S>) | {description?: string; setup(ctx: {seed: number; dir: string}): Awaitable<S>}
|
|
125
|
+
export type ModelSpec<S> = {
|
|
126
|
+
name: string
|
|
127
|
+
description: string
|
|
128
|
+
/** Steps per generated run (defaults 15 and 40). */
|
|
129
|
+
minSteps?: number
|
|
130
|
+
maxSteps?: number
|
|
131
|
+
setup(ctx: Ctx): Awaitable<S>
|
|
132
|
+
/** Called in `finally` after every run whose setup returned, also after a failure. */
|
|
133
|
+
teardown?(state: S, ctx: Ctx): Awaitable<void>
|
|
134
|
+
actions: ActionSpec<S>[]
|
|
135
|
+
/** Checked after setup (step -1) and after every step. */
|
|
136
|
+
invariants?: Invariant<S>[]
|
|
137
|
+
/** Each mutant replaces `setup` with a damaged system under test; the prober must find a mismatch on it. */
|
|
138
|
+
mutants?: Record<string, MutantSpec<S>>
|
|
139
|
+
}
|
|
140
|
+
export type ModelStep = {t: string; args?: unknown}
|
|
141
|
+
export type ModelRun = {seed: number; actions: ModelStep[]}
|
|
142
|
+
|
|
143
|
+
const NAT = (n: unknown) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0
|
|
144
|
+
|
|
145
|
+
export function defineModel<S>(spec: ModelSpec<S>): ProbeTarget<ModelRun> & {mutants: string[]} {
|
|
146
|
+
const bad = (why: string): never => { throw new TypeError(`defineModel(${JSON.stringify(spec?.name)}): ${why}`) }
|
|
147
|
+
if (!spec || typeof spec !== 'object') bad('spec must be an object')
|
|
148
|
+
if (typeof spec.name !== 'string' || !spec.name) bad('name must be a non-empty string')
|
|
149
|
+
if (typeof spec.description !== 'string') bad('description must be a string')
|
|
150
|
+
if (typeof spec.setup !== 'function') bad('setup must be a function')
|
|
151
|
+
if (spec.teardown !== undefined && typeof spec.teardown !== 'function') bad('teardown must be a function')
|
|
152
|
+
if (!Array.isArray(spec.actions) || !spec.actions.length) bad('actions must be a non-empty array')
|
|
153
|
+
const byName = new Map<string, ActionSpec<S>>()
|
|
154
|
+
for (const a of spec.actions) {
|
|
155
|
+
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)')
|
|
156
|
+
if (byName.has(a.name)) bad(`action ${JSON.stringify(a.name)} is defined twice`)
|
|
157
|
+
if (a.weight !== undefined && !(Number.isFinite(a.weight) && a.weight >= 0)) bad(`action ${a.name}: weight must be a number >= 0`)
|
|
158
|
+
byName.set(a.name, a)
|
|
159
|
+
}
|
|
160
|
+
if (!spec.actions.some((a) => (a.weight ?? 1) > 0)) bad('at least one action needs a weight > 0')
|
|
161
|
+
const minSteps = spec.minSteps ?? 15, maxSteps = spec.maxSteps ?? 40
|
|
162
|
+
if (!NAT(minSteps) || !NAT(maxSteps) || minSteps > maxSteps) bad('minSteps and maxSteps must be integers with 0 <= minSteps <= maxSteps')
|
|
163
|
+
const invariants = (spec.invariants ?? []).map((inv, i) => {
|
|
164
|
+
if (typeof inv === 'function') return {name: '', check: inv}
|
|
165
|
+
if (inv && typeof inv.check === 'function' && typeof inv.name === 'string') return inv
|
|
166
|
+
return bad(`invariant ${i} must be a function or {name, check}`)
|
|
167
|
+
})
|
|
168
|
+
const mutants = new Map<string, (ctx: {seed: number; dir: string}) => Awaitable<S>>()
|
|
169
|
+
for (const [name, m] of Object.entries(spec.mutants ?? {})) {
|
|
170
|
+
if (typeof m === 'function') mutants.set(name, m)
|
|
171
|
+
else if (m && typeof m.setup === 'function') mutants.set(name, (ctx) => m.setup(ctx))
|
|
172
|
+
else bad(`mutant ${name} must be a setup function or {setup}`)
|
|
173
|
+
}
|
|
174
|
+
const weighted = spec.actions.map((a) => ({weight: a.weight ?? 1, value: a}))
|
|
175
|
+
|
|
176
|
+
return {
|
|
177
|
+
name: spec.name,
|
|
178
|
+
description: spec.description,
|
|
179
|
+
mutants: [...mutants.keys()],
|
|
180
|
+
generate(seed: number): ModelRun {
|
|
181
|
+
const r = createRng(seed)
|
|
182
|
+
const n = r.int(minSteps, maxSteps)
|
|
183
|
+
const actions: ModelStep[] = []
|
|
184
|
+
for (let i = 0; i < n; i++) {
|
|
185
|
+
const a = r.weighted(weighted)
|
|
186
|
+
const args = a.gen(r)
|
|
187
|
+
// the run in memory must equal its JSON copy (a saved reproduction replays exactly what was found)
|
|
188
|
+
actions.push(args === undefined ? {t: a.name} : {t: a.name, args: JSON.parse(JSON.stringify(args))})
|
|
189
|
+
}
|
|
190
|
+
return {seed, actions}
|
|
191
|
+
},
|
|
192
|
+
async execute(run: ModelRun, dir: string, mutant?: string): Promise<Outcome> {
|
|
193
|
+
const ctx: Ctx = mutant === undefined ? {seed: run.seed, dir} : {seed: run.seed, dir, mutant}
|
|
194
|
+
const cov: Record<string, number> = {}
|
|
195
|
+
let step = -1, action: unknown = null, state: S | undefined, ready = false
|
|
196
|
+
const mismatch = (e: unknown, prefix = ''): Outcome => e instanceof MismatchError
|
|
197
|
+
? {ok: false, mismatch: {step, action, what: prefix + e.what, expected: plain(e.expected), actual: plain(e.actual)}}
|
|
198
|
+
: {ok: false, mismatch: {step, action, what: prefix ? `${prefix}exception` : 'exception', expected: 'no error', actual: errorText(e)}}
|
|
199
|
+
const checkAll = async () => {
|
|
200
|
+
for (const inv of invariants) {
|
|
201
|
+
try { await inv.check(state as S, check) } catch (e) { throw new Tagged(e, inv.name ? `invariant ${inv.name}: ` : '') }
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
let out: Outcome
|
|
205
|
+
try {
|
|
206
|
+
let setup: (c: any) => Awaitable<S> = spec.setup
|
|
207
|
+
if (mutant !== undefined) {
|
|
208
|
+
const m = mutants.get(mutant)
|
|
209
|
+
if (!m) throw new MismatchError('unknown mutant', [...mutants.keys()], mutant)
|
|
210
|
+
setup = m
|
|
211
|
+
}
|
|
212
|
+
state = await setup(mutant === undefined ? ctx : {seed: run.seed, dir})
|
|
213
|
+
ready = true
|
|
214
|
+
await checkAll()
|
|
215
|
+
for (let i = 0; i < run.actions.length; i++) {
|
|
216
|
+
step = i; action = run.actions[i]
|
|
217
|
+
const a = run.actions[i] as ModelStep
|
|
218
|
+
const def = a && typeof a === 'object' ? byName.get(a.t) : undefined
|
|
219
|
+
if (!def) throw new MismatchError('unknown action', [...byName.keys()], a)
|
|
220
|
+
cov[def.name] = (cov[def.name] ?? 0) + 1
|
|
221
|
+
await def.run(state as S, a.args, check)
|
|
222
|
+
await checkAll()
|
|
223
|
+
}
|
|
224
|
+
out = {ok: true, steps: run.actions.length, cov}
|
|
225
|
+
} catch (e) {
|
|
226
|
+
out = e instanceof Tagged ? mismatch(e.cause, e.prefix) : mismatch(e)
|
|
227
|
+
}
|
|
228
|
+
if (ready && spec.teardown) {
|
|
229
|
+
try { await spec.teardown(state as S, ctx) } catch (e) { if (out.ok) out = mismatch(e, 'teardown: ') }
|
|
230
|
+
}
|
|
231
|
+
return out
|
|
232
|
+
},
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** An error from an invariant, with the invariant's name for the report. */
|
|
237
|
+
class Tagged {
|
|
238
|
+
cause: unknown
|
|
239
|
+
prefix: string
|
|
240
|
+
constructor(cause: unknown, prefix: string) { this.cause = cause; this.prefix = prefix }
|
|
241
|
+
}
|