stopbar 1.2.1 → 1.2.2

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.
@@ -212,6 +212,6 @@ export function initProbe(o = {}) {
212
212
  .replaceAll('__NAME__', name).replace('__RUN__', command)
213
213
  mkdirSync(dir, {recursive: true})
214
214
  writeFileSync(file, text)
215
- const needs = lang === 'ts' ? `\n (needs stopbar in the project, so that 'stopbar/probe' resolves: npm install --save-dev stopbar)` : ''
215
+ const needs = lang === 'ts' ? `\n (\`stopbar probe\` resolves 'stopbar/probe' itself; an editor or tsc needs stopbar in the project: npm install --save-dev stopbar)` : ''
216
216
  return {file, lang, command, message: `wrote ${file}\nrun it:\n ${command}${needs}`}
217
217
  }
package/dist/repo.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import {execFileSync} from 'node:child_process'
4
4
  import {createHash} from 'node:crypto'
5
5
  import {copyFileSync, existsSync, readFileSync, rmSync, statSync} from 'node:fs'
6
+ import {homedir} from 'node:os'
6
7
  import {dirname, isAbsolute, join, resolve} from 'node:path'
7
8
 
8
9
  export class FailClosed extends Error {
@@ -35,6 +36,67 @@ export function findRepo(cwd ) {
35
36
  }
36
37
  }
37
38
 
39
+ // ---------------------------------------------------------------- core.hooksPath without a git process
40
+ /** The git common dir: `<gitDir>/commondir` (a worktree) names it, relative to gitDir; else gitDir itself. */
41
+ function commonDirOf(r ) {
42
+ try {
43
+ const rel = readFileSync(join(r.gitDir, 'commondir'), 'utf8').trim()
44
+ if (rel) return isAbsolute(rel) ? rel : resolve(r.gitDir, rel)
45
+ } catch { /* no commondir: not a linked worktree */ }
46
+ return r.gitDir
47
+ }
48
+
49
+ /** The value of one line `key = value` of a git config file: quotes removed, the escapes \" \\ \t \n \b read, an
50
+ * inline comment (# or ; outside quotes) dropped, spaces around the value trimmed. A key with no `=` is boolean true. */
51
+ function configLineValue(rest ) {
52
+ let out = '', q = false, pend = ''
53
+ for (let i = 0; i < rest.length; i++) {
54
+ const c = rest[i]
55
+ if (c === '\\' && i + 1 < rest.length) { const n = rest[++i]; out += pend + ({t: '\t', n: '\n', b: '\b'}[n] ?? n); pend = ''; continue }
56
+ if (c === '"') { q = !q; out += pend; pend = ''; continue }
57
+ if (!q && (c === '#' || c === ';')) break
58
+ if (!q && (c === ' ' || c === '\t')) { if (out) pend += c; continue }
59
+ out += pend + c; pend = ''
60
+ }
61
+ return out
62
+ }
63
+
64
+ /** The last `[core] hooksPath` value of a git config file, or undefined. Section and key names are case-insensitive;
65
+ * `[core "x"]` is another section. Include files are not followed (a known limit, SECURITY.md). */
66
+ export function configHooksPath(text ) {
67
+ let inCore = false, val
68
+ for (let line of text.split(/\r?\n/)) {
69
+ line = line.trim()
70
+ const sec = /^\[\s*([A-Za-z0-9.-]+)(\s+"(?:[^"\\]|\\.)*")?\s*\]\s*/.exec(line)
71
+ if (sec) { inCore = sec[1].toLowerCase() === 'core' && !sec[2]; line = line.slice(sec[0].length) }
72
+ if (!inCore || !line || line.startsWith('#') || line.startsWith(';')) continue
73
+ const kv = /^([A-Za-z][A-Za-z0-9-]*)\s*(?:=(.*))?$/.exec(line)
74
+ if (kv && kv[1].toLowerCase() === 'hookspath') val = kv[2] === undefined ? 'true' : configLineValue(kv[2])
75
+ }
76
+ return val
77
+ }
78
+
79
+
80
+ /** `core.hooksPath` read from the files: `<common-dir>/config`, then `<gitDir>/config.worktree` (wins when set). A
81
+ * relative value is relative to the working tree root (as git runs the hooks), `~/` is the home directory. Null when
82
+ * unset, empty, or when it names the default <common-dir>/hooks. Pure file system: no git process in PreToolUse. */
83
+ export function readHooksPath(r ) {
84
+ const common = commonDirOf(r)
85
+ let raw
86
+ for (const f of [join(common, 'config'), join(r.gitDir, 'config.worktree')]) {
87
+ let text
88
+ try { text = readFileSync(f, 'utf8') } catch { continue }
89
+ const v = configHooksPath(text)
90
+ if (v !== undefined) raw = v
91
+ }
92
+ if (!raw) return null
93
+ const expanded = raw === '~' || raw.startsWith('~/') ? join(homedir(), raw.slice(1)) : raw
94
+ const dir = isAbsolute(expanded) ? resolve(expanded) : resolve(r.root, expanded)
95
+ const def = resolve(common, 'hooks')
96
+ const same = process.platform === 'win32' ? dir.toLowerCase() === def.toLowerCase() : dir === def
97
+ return same ? null : {raw, dir}
98
+ }
99
+
38
100
  export let gitCalls = 0
39
101
  export function git(cwd , args , env , input ) {
40
102
  gitCalls++
package/dist/run.js CHANGED
@@ -11,6 +11,17 @@ import {readConfig, readState} from './store.js'
11
11
 
12
12
 
13
13
 
14
+ /** The environment of the gate command. On Windows `shell: true` starts cmd.exe; a PWD=C:/... inherited from Git Bash
15
+ * would reach a bash inside the gate, where `PATH="$PWD/node_modules/.bin:$PATH"` breaks at the colon of `C:` (exit
16
+ * 127). Without PWD
17
+ * that shell sets it from its own working directory. Other platforms: the environment as it is. */
18
+ export function gateEnv(env , platform = process.platform) {
19
+ if (platform !== 'win32') return env
20
+ const out = {}
21
+ for (const [k, v] of Object.entries(env)) if (k.toUpperCase() !== 'PWD') out[k] = v
22
+ return out
23
+ }
24
+
14
25
  export function runGate(which , o ) {
15
26
  if (which !== 'build' && which !== 'test') return {code: 1, msg: 'usage: stopbar run build|test'}
16
27
  const cwd = o.get('repo') ?? process.cwd()
@@ -22,7 +33,7 @@ export function runGate(which , o ) {
22
33
  if (before.code !== 0 && /FAIL-CLOSED|halted/.test(before.msg ?? '')) return {code: 2, msg: before.msg}
23
34
  const s0 = readState(repo)
24
35
  const expectedSnapshot = s0.snapshot, expectedRev = decode(s0.kernel).treeRev
25
- const r = spawnSync(command, {cwd: repo.root, shell: true, stdio: 'inherit'})
36
+ const r = spawnSync(command, {cwd: repo.root, shell: true, stdio: 'inherit', env: gateEnv(process.env)})
26
37
  const exit = r.status ?? 1
27
38
  const after = runEvent({hook_event_name: exit === 0 ? 'PostToolUse' : 'PostToolUseFailure', cwd: repo.root, tool_name: 'Bash', tool_input: {command},
28
39
  tool_response: {exitCode: exit}, stopbar: {...meta(which), expectedSnapshot, expectedRev}})
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.2.1'
9
+ export const VERSION = '1.2.2'
10
10
 
11
11
 
12
12
 
@@ -131,14 +131,16 @@ export function appendEvent(r , entry ) {
131
131
  } finally { closeSync(fd) }
132
132
  }
133
133
 
134
-
134
+ /** One parsed line of events.jsonl: the fields read by status, doctor and attest are typed; the rest stay unknown. */
135
+
136
+
135
137
  export function readEvents(r ) {
136
138
  const f = files(r).events
137
139
  if (!existsSync(f)) return {events: [], torn: []}
138
140
  const out = {events: [], torn: []}
139
141
  readFileSync(f, 'utf8').split('\n').forEach((l, i) => {
140
142
  if (!l) return
141
- try { out.events.push(JSON.parse(l)) } catch { out.torn.push({line: i + 1, text: l.slice(0, 120)}) }
143
+ try { const e = JSON.parse(l); out.events.push(e && typeof e === 'object' && !Array.isArray(e) ? e : {value: e}) } catch { out.torn.push({line: i + 1, text: l.slice(0, 120)}) }
142
144
  })
143
145
  return out
144
146
  }
package/docs/probe.md ADDED
@@ -0,0 +1,94 @@
1
+ # PROBE for your project
2
+
3
+ PROBE is the test tool of the Stopbar package: stateful probing of your own code against a model, with mutants that
4
+ must be caught. Back to the [README](../README.md).
5
+
6
+ `stopbar probe --target <file>` runs a model of any TS/JS code. The file exports (as `default` or as `target`) a
7
+ target; `defineModel` from `stopbar/probe` builds one from a list of actions:
8
+
9
+ ```ts
10
+ import {defineModel} from 'stopbar/probe'
11
+
12
+ export default defineModel<{q: BoundedQueue<number>; model: number[]}>({
13
+ name: 'bounded-queue', description: 'FIFO queue with capacity 4 vs an array model',
14
+ setup: () => ({q: new BoundedQueue<number>(4), model: []}),
15
+ actions: [
16
+ {name: 'push', weight: 3, gen: (r) => ({x: r.int(0, 99)}), run: (s, {x}, check) => {
17
+ const accepted = s.model.length < 4
18
+ check.eq('push result', s.q.push(x), accepted)
19
+ if (accepted) s.model.push(x)
20
+ }},
21
+ {name: 'shift', gen: () => null, run: (s, _a, check) => check.eq('shift result', s.q.shift(), s.model.shift())},
22
+ ],
23
+ invariants: [{name: 'size', check: (s, check) => check.eq('size', s.q.size, s.model.length)}],
24
+ mutants: {M1_dropCap: () => ({q: new BoundedQueue<number>(4, {checkCap: false}), model: []})},
25
+ })
26
+ ```
27
+
28
+ - `gen(r)` returns pure JSON data for one step. `r` is a deterministic generator (`createRng`: xorshift32, the same
29
+ numbers on Windows and Linux). A run is `{seed, actions: [{t: name, args}]}` with `minSteps`..`maxSteps` steps
30
+ (default 15..40).
31
+ - `run(state, args, check)` drives the real code and compares it with the model: `check.eq` (deep strict equality),
32
+ `check.ok`, `check.fail`. A failed check, and any exception from the code under test, is a mismatch with the step and
33
+ the action, not a crash. Invariants run after `setup` (step -1) and after every step. `teardown` runs after every run
34
+ whose `setup` returned, also after a failure.
35
+ - A failure is shrunk (cut after the failing step, then removal of blocks of half, a quarter, ... of the run, then of
36
+ single steps) and written to `repro-<seed>.json` in `--out`. `--regressions <dir>` replays such files on every run.
37
+ A file target replays only the regressions you name.
38
+ - `--check-mutants`: each mutant replaces `setup` with a damaged system under test. The original must pass, and every
39
+ mutant must fail within `--mutant-runs` seeds (default 50). Exit 0 only then. A survivor is named in the output and
40
+ in `summary.json` (`mutants.survived`). A target without mutants is refused.
41
+ - In a repository with Stopbar, every run appends a `probe:result` entry to `events.jsonl` (target, sha256 of the
42
+ target file, tree snapshot, runs, steps, mutants, sha256 of `summary.json`). It is not a kernel step and does not
43
+ change `state.json`. `stopbar attest` shows the latest entry per target and whether the tree is still the one that
44
+ was probed. `--no-record` skips the entry. Outside a Stopbar repository nothing is recorded.
45
+
46
+ A complete example with two mutants: [`examples/bounded-queue.probe.ts`](../examples/bounded-queue.probe.ts)
47
+ (`stopbar probe --target examples/bounded-queue.probe.ts --check-mutants`). TypeScript files need Node's type
48
+ stripping (Node 22.18 or later): only erasable syntax, no `enum` and no constructor parameter properties.
49
+
50
+ `import {defineModel} from 'stopbar/probe'` resolves to the SDK of the Stopbar that runs `stopbar probe`, also when
51
+ the project has no `stopbar` in its `node_modules` (a global install, `npx`, a copy elsewhere): since 1.2.2 the probe
52
+ runner registers a module resolve hook (`registerHooks` from `node:module`) for that one specifier, in the runner and in
53
+ every worker. An editor or `tsc` still needs `stopbar` in the project for the types (`npm install --save-dev stopbar`).
54
+
55
+ ## Any language: `--cmd`
56
+
57
+ `stopbar probe --cmd "<command>"` probes a program in any language (Python, Go, Rust, ...). Each worker (`--jobs`)
58
+ starts the command once, in a shell, in the current directory, and keeps it for all its runs, so the start-up cost
59
+ is paid once per worker and not once per seed. Stopbar sends one JSON object per line on stdin and reads one answer
60
+ per line on stdout (NDJSON):
61
+
62
+ | Request | Answer |
63
+ |---|---|
64
+ | `{"op":"info"}` | `{"name":"<string>","description":"<string>","mutants":["M1",...]}` (`mutants` is optional) |
65
+ | `{"op":"generate","seed":123}` | `{"seed":123,"actions":[...]}`: pure JSON data, the same for the same seed |
66
+ | `{"op":"execute","run":{"seed":123,"actions":[...]},"dir":"<scratch dir>","mutant":"M1"}` | `{"ok":true,"steps":N,"cov":{"push":3}}` or `{"ok":false,"mismatch":{"step":2,"action":{...},"what":"...","expected":...,"actual":...}}` |
67
+
68
+ - `mutant` is sent only with `--check-mutants`. `dir` is an empty scratch directory for each execution.
69
+ - Any answer can be `{"error":"<text>"}`. stdout is for the protocol only: print logs to stderr.
70
+ - An exception of the code under test is a finding: catch it in `execute` and answer with a mismatch (the
71
+ templates do this). A process that exits, closes stdout, prints a line that is not JSON or gives no answer within
72
+ `--cmd-timeout` ms (default 300000) stops the probe with exit 1 and the end of its stderr. When the probe ends,
73
+ Stopbar closes stdin; a process that does not exit within 2 s is killed.
74
+ - Shrinking, `--regressions` / `--regressions-only`, `--check-mutants`, `summary.json`, `repro-<seed>.json`,
75
+ `probe:result` and `attest` work as for `--target <file>`. `target` in a reproduction is the `name` from `info`;
76
+ `targetCmd` is the command. A `--cmd` target replays only the regressions in `--regressions <dir>`.
77
+ - `targetSha256` is the sha256 of `--target-file <path>`, else of the first word after the interpreter that is an
78
+ existing file (`python examples/bounded_queue_probe.py` hashes that file), else `null`.
79
+
80
+ [`examples/bounded_queue_probe.py`](../examples/bounded_queue_probe.py) is the same queue model in Python, with the
81
+ standard library only:
82
+
83
+ ```sh
84
+ stopbar probe --cmd "python examples/bounded_queue_probe.py" --runs 200 --check-mutants
85
+ ```
86
+
87
+ ## A starter target: `stopbar probe init`
88
+
89
+ `stopbar probe init --lang ts` writes `probes/sample.probe.ts` (`defineModel`), and `--lang py` writes
90
+ `probes/sample_probe.py` (the NDJSON protocol, standard library only: `json`, `random`, `sys`). Both hold the same
91
+ model with 2 actions, 1 invariant, 2 mutants and the rules for zero false positives, and `--check-mutants` passes on
92
+ them as written. The command prints the line that runs the file. `--name` takes letters, digits, `-` and `_` only;
93
+ `--out` (default `probes`) is relative to `--repo`, else to the current directory; an existing file stays unless you
94
+ pass `--force`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stopbar",
3
- "version": "1.2.1",
3
+ "version": "1.2.2",
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",
@@ -31,6 +31,7 @@
31
31
  "src/probe/sdk.ts",
32
32
  "claude-hooks.example.json",
33
33
  "skills/",
34
+ "docs/probe.md",
34
35
  "README.md",
35
36
  "SECURITY.md",
36
37
  "CHANGELOG.md",
@@ -50,7 +50,8 @@ set another one with `stopbar init --cli "<cmd>"`.
50
50
  - Do not bypass a block with a script, a wrapper, a generated file, an alias, `git -c alias.*`, `--no-verify` or
51
51
  another git client.
52
52
  - Do not edit `.git/` (hooks, `.git/stopbar/`), the hook config of any agent (`.claude/`, `.cursor/`, `.codex/`,
53
- `.gemini/`, `.agents/`) or the Stopbar package.
53
+ `.gemini/`, `.agents/`), the git hook managers (`.husky/`, `lefthook*.yml`, `.lefthook/`, a custom
54
+ `core.hooksPath`) or the Stopbar package. A change to a hook there is for a human.
54
55
 
55
56
  ### Human-only commands
56
57