stopbar 0.0.0-stage → 1.0.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/dist/kernel.js ADDED
@@ -0,0 +1,162 @@
1
+ // Built from src/kernel.ts by scripts/build.ts. Do not edit.
2
+ // Stopbar kernel: the decision rule of the hooks, deterministic, in the gdp-wired 0.60.0 DSL.
3
+ //
4
+ // An action is one request with an `op` field. The wrapper supplies the classes deterministically:
5
+ // suspicious - EDIT_TEST / SHELL that changes the tree: a change of an existing test or of test config
6
+ // risky - SHELL: risky or outbound (true) or safe and local (false)
7
+ // treeChanged - SHELL: the wrapper sees a different git tree hash after the call (e.g. `sed -i`)
8
+ // approveRev - APPROVE_TESTS: the tree revision whose accumulated test changes a human reviewed
9
+ //
10
+ // The g* fields are ghost variables: the SPECIFICATION keeps them, not the implementation. Mutants change only the
11
+ // implementation, so the laws over g* do not repeat the COMMIT condition (no tautology).
12
+ import {bool, max, nat, no, oneOf, rule, when, yes} from 'gdp-wired'
13
+
14
+ // APPROVE_TESTS and APPROVE_SHELL are a full no-op in the halted state (step law L4.4, mutant M7).
15
+ export const MUTANTS = ['none', 'M1a', 'M1b', 'M2', 'M3', 'M3b', 'M4', 'M4b', 'M5', 'M6', 'M7']
16
+
17
+
18
+ const OPS = ['EDIT_CODE', 'EDIT_TEST', 'RUN_BUILD', 'RUN_TESTS', 'READ_SECRET', 'SHELL',
19
+ 'APPROVE_TESTS', 'APPROVE_SHELL', 'RESUME', 'COMMIT']
20
+
21
+ export function kernel(m = 'none') {
22
+ return rule(`stopbar_kernel_${m}`)
23
+ .params({maxRetries: nat, cap: nat})
24
+ .pre(({maxRetries, cap}) => maxRetries.atLeast(1).and(cap.atLeast(1)))
25
+ .inputs({op: oneOf(...OPS), cost: nat, passed: bool, fullSuite: bool, suspicious: bool, risky: bool,
26
+ treeChanged: bool, approveRev: nat, extra: nat})
27
+ // human actions cost nothing (only agent actions count against the budget)
28
+ .assume(({op, cost}) => op.is('APPROVE_TESTS').or(op.is('APPROVE_SHELL'), op.is('RESUME')).implies(cost.eq(0)))
29
+ .state({
30
+ // implementation
31
+ treeRev: 1, buildOkRev: 0, testsOkRev: 0,
32
+ testsTainted: bool.from(false), secretTainted: bool.from(false), shellToken: bool.from(false),
33
+ buildFails: 0, testFails: 0, spent: 0, capNow: ({cap}) => cap,
34
+ halted: bool.from(false), decision: oneOf('ALLOW', 'BLOCK', 'PAUSE').from('ALLOW'), commitExecuted: bool.from(false),
35
+ // ghost (specification)
36
+ gRev: 1, gBuildOk: bool.from(false), gTestsOk: bool.from(false), gMaxSusp: 0, gMaxAppr: 0,
37
+ gBuildFails: 0, gTestFails: 0,
38
+ })
39
+ .step((e) => {
40
+ const {op, cost, passed, fullSuite, suspicious, risky, treeChanged, approveRev, extra, maxRetries} = e
41
+ const human = op.is('APPROVE_TESTS').or(op.is('APPROVE_SHELL'), op.is('RESUME'))
42
+ const agent = human.not()
43
+ const overBudget = agent.and(e.capNow.atMost(e.spent.plus(cost)))
44
+ const exec = agent.and(e.halted.not(), overBudget.not())
45
+
46
+ // --- specification: what changes the tree and what is a gate run (never mutated)
47
+ const specTreeEdit = exec.and(op.is('EDIT_CODE').or(op.is('EDIT_TEST'), op.is('SHELL').and(treeChanged)))
48
+ const specSuspEdit = exec.and(op.is('EDIT_TEST').or(op.is('SHELL').and(treeChanged)), suspicious)
49
+ const build = exec.and(op.is('RUN_BUILD'))
50
+ const tests = exec.and(op.is('RUN_TESTS'))
51
+ const specFullPass = tests.and(passed, fullSuite)
52
+
53
+ // --- implementation (the mutants act here)
54
+ const treeEdit = m === 'M1a' ? exec.and(op.is('EDIT_CODE').or(op.is('EDIT_TEST'))) : specTreeEdit
55
+ const fullPass = m === 'M1b' ? tests.and(passed) : specFullPass
56
+ const testFail = tests.and(passed.not())
57
+ const buildPass = build.and(passed)
58
+ const buildFail = build.and(passed.not())
59
+ const awake = e.halted.not() // human approvals act only outside the halted state
60
+ const approveT = m === 'M6' ? op.is('APPROVE_TESTS').and(awake) : op.is('APPROVE_TESTS').and(approveRev.eq(e.treeRev), awake)
61
+ const grantShell = m === 'M7' ? op.is('APPROVE_SHELL') : op.is('APPROVE_SHELL').and(awake) // M7: token also when halted
62
+ const riskyShell = exec.and(op.is('SHELL'), risky)
63
+ const needPause = m === 'M3b' ? no : riskyShell.and(e.secretTainted, e.shellToken.not())
64
+ const commitOk = exec.and(op.is('COMMIT'), e.buildOkRev.eq(e.treeRev), e.testsOkRev.eq(e.treeRev), e.testsTainted.not())
65
+
66
+ const testReset = m === 'M4' ? fullPass.or(buildPass) : m === 'M4b' ? fullPass.or(tests.and(passed)) : fullPass
67
+ const testFailsNext = when(op.is('RESUME'), 0, when(testReset, 0, when(testFail, e.testFails.plus(1), e.testFails)))
68
+ const buildFailsNext = when(op.is('RESUME'), 0, when(buildPass, 0, when(buildFail, e.buildFails.plus(1), e.buildFails)))
69
+ const loopHalt = testFail.and(maxRetries.atMost(testFailsNext)).or(buildFail.and(maxRetries.atMost(buildFailsNext)))
70
+ const haltedNext = when(op.is('RESUME'), no, e.halted.or(overBudget, loopHalt))
71
+
72
+ const taintClear = m === 'M2' ? approveT.or(fullPass) : approveT
73
+ const secretNext = m === 'M3' ? when(exec.and(op.is('EDIT_CODE')), no, e.secretTainted.or(exec.and(op.is('READ_SECRET'))))
74
+ : e.secretTainted.or(exec.and(op.is('READ_SECRET')))
75
+ const approveVisible = m === 'M5' ? no : e.halted // M5: a test approval lifts PAUSE in the halted state
76
+
77
+ const ALLOW = e.decision.of('ALLOW'), BLOCK = e.decision.of('BLOCK'), PAUSE = e.decision.of('PAUSE')
78
+ const decision = when(op.is('RESUME'), ALLOW,
79
+ when(approveVisible, PAUSE,
80
+ when(op.is('APPROVE_TESTS'), when(approveT, ALLOW, BLOCK),
81
+ when(op.is('APPROVE_SHELL'), ALLOW,
82
+ when(overBudget.or(loopHalt, specSuspEdit, needPause), PAUSE,
83
+ when(op.is('COMMIT'), when(commitOk, ALLOW, BLOCK), ALLOW))))))
84
+
85
+ return {
86
+ treeRev: when(treeEdit, e.treeRev.plus(1), e.treeRev),
87
+ buildOkRev: when(buildPass, e.treeRev, when(buildFail, 0, e.buildOkRev)),
88
+ testsOkRev: when(fullPass, e.treeRev, when(testFail, 0, e.testsOkRev)),
89
+ testsTainted: when(specSuspEdit, yes, when(taintClear, no, e.testsTainted)),
90
+ secretTainted: secretNext,
91
+ shellToken: when(grantShell, yes, when(riskyShell.and(e.secretTainted), no, e.shellToken)),
92
+ buildFails: buildFailsNext,
93
+ testFails: testFailsNext,
94
+ spent: when(agent.and(e.halted.not()), e.spent.plus(cost), e.spent),
95
+ capNow: when(op.is('RESUME'), e.capNow.plus(extra), e.capNow),
96
+ halted: haltedNext,
97
+ decision,
98
+ commitExecuted: commitOk,
99
+ // ghost
100
+ gRev: when(specTreeEdit, e.gRev.plus(1), e.gRev),
101
+ gBuildOk: when(specTreeEdit, no, when(build, passed, e.gBuildOk)),
102
+ gTestsOk: when(specTreeEdit, no, when(specFullPass, yes, when(tests.and(passed.not()), no, e.gTestsOk))),
103
+ gMaxSusp: when(specSuspEdit, max(e.gMaxSusp, e.gRev.plus(1)), e.gMaxSusp),
104
+ gMaxAppr: when(op.is('APPROVE_TESTS').and(approveRev.atMost(e.gRev), e.halted.not()), max(e.gMaxAppr, approveRev), e.gMaxAppr),
105
+ gBuildFails: when(op.is('RESUME'), 0, when(build.and(passed), 0, when(build.and(passed.not()), e.gBuildFails.plus(1), e.gBuildFails))),
106
+ gTestFails: when(op.is('RESUME'), 0, when(specFullPass, 0, when(tests.and(passed.not()), e.gTestFails.plus(1), e.gTestFails))),
107
+ }
108
+ })
109
+ }
110
+
111
+
112
+
113
+ // Inductive lemmas: the simulation relation between the implementation and the ghosts. They add no requirement;
114
+ // they strengthen the induction (the prover does not find them on its own).
115
+ export function lemmas(r ) {
116
+ return [
117
+ r.law('I1 tree revision starts at 1 and the ghost follows it', ({treeRev, gRev}) => treeRev.atLeast(1).and(gRev.eq(treeRev))),
118
+ r.law('I2 a build verified at the current revision means the spec saw a passing build since the last tree change',
119
+ ({buildOkRev, treeRev, gBuildOk}) => buildOkRev.atMost(treeRev).and(buildOkRev.eq(treeRev).implies(gBuildOk))),
120
+ r.law('I3 a suite verified at the current revision means the spec saw a full passing suite since the last tree change',
121
+ ({testsOkRev, treeRev, gTestsOk}) => testsOkRev.atMost(treeRev).and(testsOkRev.eq(treeRev).implies(gTestsOk))),
122
+ r.law('I4 suspicious edits never exceed the current revision; clean tests mean they are all approved',
123
+ ({gMaxSusp, gMaxAppr, gRev, testsTainted}) => gMaxSusp.atMost(gRev).and(gMaxAppr.atMost(gRev), testsTainted.not().implies(gMaxSusp.atMost(gMaxAppr)))),
124
+ r.law('I5 failure counters equal their ghosts', ({testFails, gTestFails, buildFails, gBuildFails}) =>
125
+ testFails.eq(gTestFails).and(buildFails.eq(gBuildFails))),
126
+ ]
127
+ }
128
+
129
+ export function laws(r ) {
130
+ return {
131
+ laws: [
132
+ r.law('L1 commit only after build ok and full suite ok since last tree change',
133
+ ({commitExecuted, gBuildOk, gTestsOk}) => commitExecuted.implies(gBuildOk.and(gTestsOk))),
134
+ r.law('L2.1 commit only when every suspicious test edit is covered by a human approval',
135
+ ({commitExecuted, gMaxSusp, gMaxAppr}) => commitExecuted.implies(gMaxSusp.atMost(gMaxAppr))),
136
+ r.law('L4.3a maxRetries consecutive failed test runs without a full pass halt the session',
137
+ ({gTestFails, maxRetries, halted}) => maxRetries.atMost(gTestFails).implies(halted)),
138
+ r.law('L4.3b maxRetries consecutive failed builds halt the session',
139
+ ({gBuildFails, maxRetries, halted}) => maxRetries.atMost(gBuildFails).implies(halted)),
140
+ ],
141
+ stepLaws: [
142
+ r.stepLaw('L2.2 taint survives every action except a human test approval (RUN_TESTS full pass included)',
143
+ (b, a) => b.testsTainted.and(b.op.is('APPROVE_TESTS').not()).implies(a.testsTainted)),
144
+ r.stepLaw('L3.1 secretTainted is monotone',
145
+ (b, a) => b.secretTainted.implies(a.secretTainted)),
146
+ r.stepLaw('L3.2 exfiltration gate: risky shell after a secret read pauses unless a one-time human approval is held',
147
+ (b, a) => b.secretTainted.and(b.op.is('SHELL'), b.risky, b.shellToken.not()).implies(a.decision.is('PAUSE'))),
148
+ r.stepLaw('L3.3 the one-time shell approval is used up by the risky call it allows',
149
+ (b, a) => b.secretTainted.and(b.op.is('SHELL'), b.risky, b.halted.not(), b.spent.plus(b.cost).lt(b.capNow)).implies(a.shellToken.not())),
150
+ r.stepLaw('L4.1 halted: only RESUME unblocks; no ALLOW/BLOCK, no commit',
151
+ (b, a) => b.halted.and(b.op.is('RESUME').not()).implies(a.halted.and(a.decision.is('PAUSE'), a.commitExecuted.not()))),
152
+ r.stepLaw('L4.4 halted: no action but RESUME changes the key state fields',
153
+ (b, a) => b.halted.and(b.op.is('RESUME').not()).implies(
154
+ a.testsTainted.iff(b.testsTainted).and(a.shellToken.iff(b.shellToken), a.treeRev.eq(b.treeRev),
155
+ a.buildOkRev.eq(b.buildOkRev), a.testsOkRev.eq(b.testsOkRev), a.buildFails.eq(b.buildFails),
156
+ a.testFails.eq(b.testFails), a.spent.eq(b.spent), a.capNow.eq(b.capNow)))),
157
+ r.stepLaw('L4.2 reaching the budget cap halts at once',
158
+ (b, a) => b.op.is('APPROVE_TESTS').or(b.op.is('APPROVE_SHELL'), b.op.is('RESUME')).not()
159
+ .and(b.capNow.atMost(b.spent.plus(b.cost))).implies(a.halted)),
160
+ ],
161
+ }
162
+ }
package/dist/pkg.js ADDED
@@ -0,0 +1,13 @@
1
+ // Built from src/pkg.ts by scripts/build.ts. Do not edit.
2
+ // Where the running Stopbar lives. Its code is protected from agent edits (see classify.ts protectedPath).
3
+ import {existsSync} from 'node:fs'
4
+ import {dirname, join, resolve} from 'node:path'
5
+ import {fileURLToPath} from 'node:url'
6
+
7
+ /** Package root: the directory with bin/, dist/ and package.json (dist/pkg.js -> ..). */
8
+ export const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
9
+
10
+ export function codeDirs() {
11
+ const names = ['bin', 'dist', 'src', 'scripts', 'node_modules', 'package.json', 'package-lock.json']
12
+ return names.map((n) => join(PKG_ROOT, n)).filter((p) => existsSync(p))
13
+ }
@@ -0,0 +1,119 @@
1
+ // Built from src/probe/index.ts by scripts/build.ts. Do not edit.
2
+ // PROBE: stateful probing with a reference model. A target generates runs (a seed and a list of actions, pure data),
3
+ // executes them against the real thing and compares every step with its model. The runner spreads seeds over worker
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>`.
7
+ import {spawn} from 'node:child_process'
8
+ import {existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs'
9
+ import {availableParallelism, tmpdir} from 'node:os'
10
+ import {join} from 'node:path'
11
+ 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 = {
26
+ wrapper: async () => (await import('./wrapper.js')).wrapperTarget,
27
+ }
28
+
29
+ /** Delta debugging by single deletions: the shortest sequence that still fails the same way. */
30
+ export async function shrink (t , run , dir , what ) {
31
+ 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)
34
+ if (!end.ok) cur = {...cur, actions: cur.actions.slice(0, end.mismatch.step + 1)}
35
+ for (let changed = true; changed;) {
36
+ changed = false
37
+ for (let i = cur.actions.length - 1; i >= 0; i--) {
38
+ const cand = {...cur, actions: cur.actions.filter((_, j) => j !== i)}
39
+ if (cand.actions.length && await fails(cand)) { cur = cand; changed = true }
40
+ }
41
+ }
42
+ return cur
43
+ }
44
+
45
+
46
+
47
+ /** Worker process: runs its share and prints one JSON line with the results. */
48
+ export async function worker(p ) {
49
+ const t = await TARGETS[p.target]()
50
+ const res = []
51
+ for (const f of p.regs) {
52
+ const run = JSON.parse(readFileSync(f, 'utf8')).run
53
+ const dir = join(p.work, `reg-${run.seed}-${process.pid}`)
54
+ res.push({regression: f, seed: run.seed, ...(await t.execute(run, dir))})
55
+ rmSync(dir, {recursive: true, force: true, maxRetries: 5})
56
+ }
57
+ for (const seed of p.seeds) {
58
+ const run = t.generate(seed)
59
+ const dir = join(p.work, `run-${seed}`)
60
+ const x = await t.execute(run, dir)
61
+ if (!x.ok) {
62
+ const min = await shrink(t, run, dir, x.mismatch.what)
63
+ const again = await t.execute(min, dir)
64
+ res.push({seed, ...x, minimal: min, minimalMismatch: again.ok ? null : again.mismatch})
65
+ } else res.push({seed, ...x})
66
+ rmSync(dir, {recursive: true, force: true, maxRetries: 5})
67
+ }
68
+ process.stdout.write(JSON.stringify(res) + '\n')
69
+ }
70
+
71
+
72
+
73
+ function defaultWork() {
74
+ try { return join(findRepo(process.cwd()).gitDir, 'stopbar', 'probe') } catch { return join(tmpdir(), `stopbar-probe-${process.pid}`) }
75
+ }
76
+
77
+ export async function probe(o = {}) {
78
+ 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
83
+ 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)) : []
87
+ const seeds = o.regressionsOnly ? [] : Array.from({length: runs}, (_, i) => seed0 + i)
88
+ 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`)
92
+ const t0 = Date.now()
93
+ const parts = Array.from({length: jobs}, () => ({target, seeds: [], regs: [], work}))
94
+ seeds.forEach((s, i) => parts[i % jobs].seeds.push(s))
95
+ 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()
102
+ const failed = results.filter((r) => !r.ok)
103
+ for (const f of failed) {
104
+ 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}`)
107
+ }
108
+ const ok = results.filter((r) => r.ok && !r.regression)
109
+ const coverage = {}
110
+ 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}
119
+ }
@@ -0,0 +1,311 @@
1
+ // Built from src/probe/wrapper.ts by scripts/build.ts. Do not edit.
2
+ // PROBE target "wrapper": the stateful self-fuzzer of the Stopbar hooks. Random sequences of 20-30 steps run on the
3
+ // REAL wrapper (runHook and the human commands, in process) against a REAL git repository with real files:
4
+ // PreToolUse, PostToolUse, PostToolUseFailure, Stop, approve-tests, approve-shell, resume, edits of code, tests and
5
+ // config, human edits, deletions, a lost snapshot copy, torn events.jsonl lines and a damaged state.json.
6
+ // After every step the result is compared with a reference model: gdp-wired's interpreter of the proven kernel (not
7
+ // the generated step the wrapper runs), driven by an independent description of what each tool call means (file roles
8
+ // are known by construction, no glob code). Compared: exit code, every kernel field, kernel steps in events.jsonl.
9
+ import {execFileSync} from 'node:child_process'
10
+ import {appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs'
11
+ import {dirname, join} from 'node:path'
12
+ import * as C from '../commands.js'
13
+ import {runHook} from '../hook.js'
14
+
15
+
16
+ // ---------------------------------------------------------------- actions (pure data, generated from a seed)
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+ 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
+
43
+ const CODE = ['src/c0.mjs', 'src/c1.mjs', 'src/c2.mjs']
44
+ const TESTS = ['tests/t0.test.mjs', 'tests/t1.test.mjs']
45
+ const CONFIG = 'pytest.ini'
46
+
47
+ function genRun(seed ) {
48
+ const r = rng(seed), pick = (xs ) => xs[Math.floor(r() * xs.length)]
49
+ const n = 20 + Math.floor(r() * 11)
50
+ let k = 0
51
+ const content = () => (r() < 0.08 ? 'same\n' : `// ${seed}-${k++}-${Math.floor(r() * 1e6)}\n`)
52
+ const anyFile = () => pick([...CODE, ...TESTS, `tests/n${Math.floor(r() * 3)}.test.mjs`, `src/n${Math.floor(r() * 3)}.mjs`, CONFIG])
53
+ const actions = []
54
+ const W = [
55
+ [14, () => ({t: 'edit', tool: pick(['Write', 'Edit'] ), file: pick([...CODE, ...CODE, `src/n${Math.floor(r() * 3)}.mjs`]), content: content()})],
56
+ [6, () => ({t: 'edit', tool: pick(['Write', 'Edit'] ), file: pick([...TESTS, `tests/n${Math.floor(r() * 3)}.test.mjs`, CONFIG]), content: content()})],
57
+ [4, () => ({t: 'shellEdit', file: anyFile(), content: content()})],
58
+ [2, () => ({t: 'shellDelete', file: anyFile()})],
59
+ [2, () => ({t: 'humanEdit', file: anyFile(), content: content()})],
60
+ [10, () => ({t: 'build', outcome: pick(['pass', 'pass', 'pass', 'fail', 'interrupt', 'interrupted'] )})],
61
+ [10, () => ({t: 'fulltest', outcome: pick(['pass', 'pass', 'pass', 'fail', 'fail', 'interrupt', 'interrupted'] )})],
62
+ [3, () => ({t: 'partial', pass: r() < 0.6})],
63
+ [5, () => ({t: 'shell', cmd: pick(['ls -la', 'curl --version', 'cat .env', 'git status'] )})],
64
+ [4, () => ({t: 'read', file: pick(['.env', 'src/c0.mjs', 'secrets/key.txt', 'README.md'])})],
65
+ [2, () => ({t: 'web'})],
66
+ [9, () => ({t: 'commit', heredoc: r() < 0.5, msg: `fuzz ${seed} ${k++}`})],
67
+ [2, () => ({t: 'chained', cmd: pick(['node --test; echo $?', 'node build.mjs | tail -3', 'git add -A && git commit -q -m x', 'git commit -m "$(id)"', "git commit -m \"$(cat <<EOF\nx\nEOF\n)\""])})],
68
+ [3, () => pick([
69
+ {t: 'protected', tool: 'Write', input: {file_path: '.git/stopbar/state.json'}},
70
+ {t: 'protected', tool: 'Edit', input: {file_path: '.claude/settings.local.json'}},
71
+ {t: 'protected', tool: 'Write', input: {file_path: '.git/hooks/pre-commit'}},
72
+ {t: 'protected', tool: 'Bash', input: {command: 'rm -f .git/stopbar/config.json'}},
73
+ {t: 'protected', tool: 'Bash', input: {command: 'git config core.hooksPath x'}},
74
+ {t: 'protected', tool: 'Bash', input: {command: 'npx stopbar approve-tests'}},
75
+ ] )],
76
+ [3, () => ({t: 'stop', active: r() < 0.2})],
77
+ [3, () => ({t: 'approveTests', stale: r() < 0.3 ? 1 + Math.floor(r() * 2) : 0})],
78
+ [2, () => ({t: 'approveShell'})],
79
+ [2, () => ({t: 'resume', extra: Math.floor(r() * 12)})],
80
+ [2, () => ({t: 'tornLog'})],
81
+ [1, () => ({t: 'loseCounted'})],
82
+ [1, () => ({t: 'corruptState', how: pick(['empty', 'truncated', 'garbage'] )})],
83
+ ]
84
+ const total = W.reduce((s, [w]) => s + w, 0)
85
+ while (actions.length < n) {
86
+ // the honest path as one macro: green build, green full suite, commit (sometimes after an approval)
87
+ if (r() < 0.12) {
88
+ if (r() < 0.3) actions.push({t: 'approveTests', stale: 0})
89
+ actions.push({t: 'build', outcome: 'pass'}, {t: 'fulltest', outcome: 'pass'}, {t: 'commit', heredoc: r() < 0.5, msg: `honest ${seed} ${k++}`})
90
+ continue
91
+ }
92
+ let x = r() * total
93
+ for (const [w, f] of W) { if ((x -= w) < 0) { actions.push(f()); break } }
94
+ }
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)}
96
+ }
97
+
98
+ // ---------------------------------------------------------------- execution against the real wrapper + the model
99
+
100
+ async function execute(run , dir ) {
101
+ // the model needs the prover package (gdp-wired); the hooks under test never load it
102
+ const {kernel} = await import('../kernel.js')
103
+ const R = kernel('none'), IT = R.interpreter()
104
+ const {maxRetries, cap, cost} = run.params
105
+ const P = R.encodeParams({maxRetries, cap})
106
+
107
+ rmSync(dir, {recursive: true, force: true, maxRetries: 5})
108
+ mkdirSync(join(dir, 'src'), {recursive: true}); mkdirSync(join(dir, 'tests'), {recursive: true})
109
+ const g = (...a ) => execFileSync('git', ['-c', 'user.name=fuzz', '-c', 'user.email=f@x.invalid', '-c', 'commit.gpgsign=false', '-c', 'core.autocrlf=false', ...a], {cwd: dir, stdio: 'ignore'})
110
+ const work = new Map ()
111
+ const put = (f , c ) => { mkdirSync(dirname(join(dir, f)), {recursive: true}); writeFileSync(join(dir, f), c); work.set(f, c) }
112
+ for (const f of [...CODE, ...TESTS]) put(f, `// base ${f}\n`)
113
+ put(CONFIG, '[pytest]\n'); put('README.md', '# fuzz\n')
114
+ writeFileSync(join(dir, '.gitignore'), '.env\nsecrets/\n'); work.set('.gitignore', '.env\nsecrets/\n')
115
+ writeFileSync(join(dir, '.env'), 'X=1\n')
116
+ g('init', '-q'); g('config', 'core.autocrlf', 'false'); g('add', '-A'); g('commit', '-qm', 'base')
117
+ 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': ''}))
119
+ if (ini.code !== 0) throw new Error(`init failed: ${ini.msg}`)
120
+
121
+ // ---- model
122
+ let st = IT.init(P)
123
+ let modelSteps = 0
124
+ let head = new Map(work), counted = new Map(work), countedCopy = true
125
+ const view = () => R.decode(st)
126
+ const kstep = (req ) => {
127
+ st = IT.step(P, st, R.encodeInput({op: 'EDIT_CODE', cost: 0, passed: false, fullSuite: false, suspicious: false, risky: false, treeChanged: false, approveRev: 0, extra: 0, ...req}, {maxRetries, cap}))
128
+ modelSteps++
129
+ return view()
130
+ }
131
+ const same = (a , b ) => a.size === b.size && [...a].every(([k, v]) => b.get(k) === v)
132
+ const isTest = (f ) => f.startsWith('tests/')
133
+ const mSync = (c ) => {
134
+ if (same(work, counted)) return null
135
+ const base = countedCopy ? counted : head
136
+ const changed = [...new Set([...base.keys(), ...work.keys()])].filter((f) => base.get(f) !== work.get(f))
137
+ if (!changed.length) {
138
+ // the counted copy was lost and the tree equals HEAD: the wrapper still sees a new snapshot id with no changes
139
+ }
140
+ 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)))
142
+ const before = view().treeRev
143
+ const after = kstep({op: anyTest ? 'EDIT_TEST' : 'EDIT_CODE', suspicious, cost: c})
144
+ if (after.treeRev > before) { counted = new Map(work); countedCopy = true }
145
+ return {suspicious}
146
+ }
147
+
148
+ // ---- real wrapper
149
+ let hooks = 0
150
+ const hook = (ev , tool , input , extra = {}) => { hooks++; return runHook(JSON.stringify({session_id: 'fuzz', hook_event_name: ev, tool_name: tool, tool_input: input, cwd: dir, ...extra})).code }
151
+ const okResp = {tool_response: {stdout: '', stderr: '', interrupted: false, isImage: false, noOutputExpected: false}}
152
+ const sd = join(dir, '.git', 'stopbar')
153
+ const readKernel = () => JSON.parse(readFileSync(join(sd, 'state.json'), 'utf8')).kernel.scalars
154
+ const loggedSteps = () => readFileSync(join(sd, 'events.jsonl'), 'utf8').split('\n').filter((l) => { try { return !!JSON.parse(l).req } catch { return false } }).length
155
+ const initSteps = loggedSteps()
156
+
157
+ const cov = {}
158
+ const inc = (k ) => { cov[k] = (cov[k] ?? 0) + 1 }
159
+ for (let i = 0; i < run.actions.length; i++) {
160
+ const a = run.actions[i]
161
+ const v0 = view()
162
+ const halted = () => view().halted
163
+ let expCode = 0, gotCode = 0
164
+ const expectPre = () => (halted() ? 2 : 0)
165
+ // PostToolUse: PAUSE when a suspicious change was counted or the session is halted
166
+ const postCode = (cls ) => (cls?.suspicious || halted() ? 2 : 0)
167
+ switch (a.t) {
168
+ case 'edit': {
169
+ const input = {file_path: join(dir, a.file), content: a.content}
170
+ expCode = expectPre(); gotCode = hook('PreToolUse', a.tool, input)
171
+ if (gotCode !== 0 || expCode !== 0) break
172
+ put(a.file, a.content)
173
+ expCode = postCode(mSync(cost))
174
+ gotCode = hook('PostToolUse', a.tool, input, {tool_response: {filePath: input.file_path, success: true}})
175
+ break
176
+ }
177
+ case 'shellEdit': case 'shellDelete': {
178
+ const command = a.t === 'shellEdit' ? `node -e "require('fs').writeFileSync('${a.file}', 'x')"` : `rm -f ${a.file}`
179
+ expCode = expectPre()
180
+ if (!halted()) { const v = kstep({op: 'SHELL', risky: false, cost}); if (v.decision === 'PAUSE') expCode = 2 }
181
+ gotCode = hook('PreToolUse', 'Bash', {command})
182
+ if (gotCode !== 0 || expCode !== 0) break
183
+ if (a.t === 'shellEdit') put(a.file, a.content)
184
+ else { rmSync(join(dir, a.file), {force: true}); work.delete(a.file) }
185
+ expCode = postCode(mSync(0))
186
+ gotCode = hook('PostToolUse', 'Bash', {command}, okResp)
187
+ break
188
+ }
189
+ case 'humanEdit': put(a.file, a.content); break
190
+ case 'build': case 'fulltest': {
191
+ const command = a.t === 'build' ? 'node build.mjs' : 'node --test'
192
+ expCode = expectPre(); gotCode = hook('PreToolUse', 'Bash', {command})
193
+ if (gotCode !== 0 || expCode !== 0) break
194
+ const op = a.t === 'build' ? 'RUN_BUILD' : 'RUN_TESTS'
195
+ if (a.outcome !== 'interrupt') kstep({op, passed: a.outcome === 'pass', fullSuite: a.t === 'fulltest', cost})
196
+ expCode = postCode(mSync(0))
197
+ gotCode = a.outcome === 'pass' ? hook('PostToolUse', 'Bash', {command}, okResp)
198
+ : a.outcome === 'interrupted' ? hook('PostToolUse', 'Bash', {command}, {tool_response: {...okResp.tool_response, interrupted: true}})
199
+ : hook('PostToolUseFailure', 'Bash', {command}, {error: a.outcome === 'interrupt' ? 'Interrupted by user' : 'Command failed with exit code 1', is_interrupt: a.outcome === 'interrupt'})
200
+ break
201
+ }
202
+ case 'partial': {
203
+ const command = 'node --test tests/t0.test.mjs'
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
+ kstep({op: 'RUN_TESTS', passed: a.pass, fullSuite: false})
209
+ expCode = postCode(mSync(0))
210
+ gotCode = a.pass ? hook('PostToolUse', 'Bash', {command}, okResp) : hook('PostToolUseFailure', 'Bash', {command}, {error: 'exit 1', is_interrupt: false})
211
+ break
212
+ }
213
+ case 'shell': {
214
+ expCode = expectPre()
215
+ if (!halted()) {
216
+ if (a.cmd === 'cat .env') kstep({op: 'READ_SECRET'})
217
+ const v = kstep({op: 'SHELL', risky: a.cmd === 'curl --version', cost})
218
+ if (v.decision === 'PAUSE') expCode = 2
219
+ }
220
+ gotCode = hook('PreToolUse', 'Bash', {command: a.cmd})
221
+ if (gotCode !== 0 || expCode !== 0) break
222
+ expCode = postCode(mSync(0))
223
+ gotCode = hook('PostToolUse', 'Bash', {command: a.cmd}, okResp)
224
+ break
225
+ }
226
+ case 'read': {
227
+ expCode = expectPre()
228
+ if (!halted() && (a.file === '.env' || a.file.startsWith('secrets/'))) kstep({op: 'READ_SECRET', cost})
229
+ gotCode = hook('PreToolUse', 'Read', {file_path: join(dir, a.file)})
230
+ break
231
+ }
232
+ case 'web': {
233
+ expCode = expectPre()
234
+ if (!halted()) { const v = kstep({op: 'SHELL', risky: true, cost}); if (v.decision === 'PAUSE') expCode = 2 }
235
+ gotCode = hook('PreToolUse', 'WebFetch', {url: 'https://example.invalid', prompt: 'x'})
236
+ break
237
+ }
238
+ case 'commit': {
239
+ const command = a.heredoc ? `git commit -q -m "$(cat <<'EOF'\n${a.msg}\n\nReviewed-by: Jane Doe <jane@example.invalid>\nEOF\n)"` : `git commit -q -m "${a.msg}"`
240
+ expCode = expectPre()
241
+ if (!halted()) { mSync(0); const v = kstep({op: 'COMMIT', cost}); expCode = v.decision === 'ALLOW' ? 0 : 2 }
242
+ gotCode = hook('PreToolUse', 'Bash', {command})
243
+ if (gotCode !== 0 || expCode !== 0) break
244
+ g('add', '-A'); try { g('commit', '-q', '--allow-empty', '-m', a.msg) } catch { /* nothing */ }
245
+ head = new Map(work)
246
+ expCode = postCode(mSync(0))
247
+ gotCode = hook('PostToolUse', 'Bash', {command}, okResp)
248
+ break
249
+ }
250
+ case 'chained': expCode = 2; gotCode = hook('PreToolUse', 'Bash', {command: a.cmd}); break
251
+ case 'protected': expCode = 2; gotCode = hook('PreToolUse', a.tool, a.tool === 'Bash' ? a.input : {file_path: join(dir, a.input.file_path)}); break
252
+ case 'stop': {
253
+ if (a.active) { expCode = 0; gotCode = hook('Stop', '', {}, {stop_hook_active: true}); break }
254
+ mSync(0)
255
+ if (same(work, head)) expCode = 0
256
+ else expCode = kstep({op: 'COMMIT'}).decision === 'ALLOW' ? 0 : 2
257
+ gotCode = hook('Stop', '', {})
258
+ break
259
+ }
260
+ case 'approveTests': {
261
+ const rev = Math.max(0, view().treeRev - a.stale)
262
+ expCode = kstep({op: 'APPROVE_TESTS', approveRev: rev}).decision === 'ALLOW' ? 0 : 1
263
+ gotCode = C.human('approve-tests', opts({repo: dir, rev: String(rev)})).code
264
+ break
265
+ }
266
+ case 'approveShell': expCode = kstep({op: 'APPROVE_SHELL'}).shellToken ? 0 : 1; gotCode = C.human('approve-shell', opts({repo: dir})).code; break
267
+ case 'resume': kstep({op: 'RESUME', extra: a.extra}); expCode = 0; gotCode = C.human('resume', opts({repo: dir, extra: String(a.extra)})).code; break
268
+ case 'tornLog': appendFileSync(join(sd, 'events.jsonl'), `{"ts":"x","source":"pre:Bash","req":{"op":"SHE`); break
269
+ case 'loseCounted': rmSync(join(sd, 'snapshot.counted.index'), {force: true}); countedCopy = false; break
270
+ case 'corruptState': {
271
+ // a crash or a stray write damages state.json: every hook fails closed and changes nothing, then a human resets
272
+ const good = readFileSync(join(sd, 'state.json'), 'utf8')
273
+ writeFileSync(join(sd, 'state.json'), a.how === 'empty' ? '' : a.how === 'truncated' ? good.slice(0, Math.floor(good.length / 2)) : '{"version": 2, "kernel": 7}')
274
+ const logBefore = readFileSync(join(sd, 'events.jsonl'), 'utf8')
275
+ expCode = 2; gotCode = hook('PreToolUse', 'Read', {file_path: join(dir, 'src', 'c0.mjs')})
276
+ if (gotCode !== 2) break
277
+ gotCode = hook('Stop', '', {})
278
+ if (gotCode !== 2) break
279
+ if (readFileSync(join(sd, 'events.jsonl'), 'utf8') !== logBefore) { gotCode = -1; break } // fail closed writes nothing
280
+ st = IT.init(P); counted = new Map(work); countedCopy = true
281
+ expCode = 0; gotCode = C.human('reset', opts({repo: dir})).code
282
+ break
283
+ }
284
+ }
285
+ if (gotCode !== expCode) return {ok: false, mismatch: {step: i, action: a, what: 'exit code', expected: expCode, actual: gotCode}}
286
+ const v1 = view()
287
+ if (a.t === 'commit') inc(expCode === 0 ? 'commitAllowed' : v0.halted ? 'commitPausedHalted' : 'commitBlocked')
288
+ if (a.t === 'stop' && !a.active) inc(expCode === 0 ? 'stopAllowed' : 'stopBlocked')
289
+ if (!v0.halted && v1.halted) inc('halts')
290
+ if (!v0.testsTainted && v1.testsTainted) inc('taints')
291
+ if (v0.testsTainted && !v1.testsTainted) inc('taintCleared')
292
+ if (a.t === 'approveShell' && expCode === 0) inc('shellApproved')
293
+ if (expCode === 2 && v0.secretTainted && (a.t === 'shell' || a.t === 'web') && !v0.halted) inc('exfilPaused')
294
+ if (a.t === 'protected') inc('protectedBlocked')
295
+ if (a.t === 'loseCounted' || a.t === 'tornLog' || a.t === 'corruptState') inc(a.t)
296
+ if (expCode === 2) inc('exit2')
297
+ const real = readKernel()
298
+ if (JSON.stringify(real) !== JSON.stringify(st.scalars)) return {ok: false, mismatch: {step: i, action: a, what: 'kernel state', expected: st.scalars, actual: real}}
299
+ const logged = loggedSteps() - initSteps
300
+ if (logged !== modelSteps) return {ok: false, mismatch: {step: i, action: a, what: 'kernel steps in events.jsonl', expected: modelSteps, actual: logged}}
301
+ }
302
+ return {ok: true, steps: run.actions.length, hooks, cov}
303
+ }
304
+
305
+
306
+ export const wrapperTarget = {
307
+ name: 'wrapper',
308
+ description: 'Stopbar hooks and human commands vs the gdp-wired interpreter of the proven kernel, on a real git repository',
309
+ generate: genRun,
310
+ execute,
311
+ }