stopbar 0.0.0-stage → 1.1.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 +47 -0
- package/LICENSE +21 -0
- package/README.md +208 -2
- package/SECURITY.md +139 -0
- package/bin/stopbar.mjs +6 -0
- package/claude-hooks.example.json +27 -0
- package/dist/adapters/antigravity.js +45 -0
- package/dist/adapters/claude.js +19 -0
- package/dist/adapters/codex.js +48 -0
- package/dist/adapters/cursor.js +63 -0
- package/dist/adapters/gemini.js +47 -0
- package/dist/adapters/index.js +45 -0
- package/dist/adapters/types.js +103 -0
- package/dist/attest.js +97 -0
- package/dist/build-info.json +6 -0
- package/dist/classify.js +212 -0
- package/dist/cli.js +88 -0
- package/dist/commands.js +146 -0
- package/dist/config.js +96 -0
- package/dist/doctor.js +185 -0
- package/dist/engine.js +51 -0
- package/dist/githook.js +17 -0
- package/dist/glob.js +68 -0
- package/dist/hook.js +236 -0
- package/dist/integrations.js +141 -0
- package/dist/kernel.gen.js +63 -0
- package/dist/kernel.js +162 -0
- package/dist/pkg.js +13 -0
- package/dist/probe/index.js +119 -0
- package/dist/probe/wrapper.js +311 -0
- package/dist/repo.js +177 -0
- package/dist/run.js +28 -0
- package/dist/store.js +144 -0
- package/dist/verify.js +154 -0
- package/package.json +58 -4
- package/src/kernel.ts +161 -0
package/dist/repo.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Built from src/repo.ts by scripts/build.ts. Do not edit.
|
|
2
|
+
// Repository discovery without spawning git, the git runner, and the content hash of the working tree.
|
|
3
|
+
import {execFileSync} from 'node:child_process'
|
|
4
|
+
import {createHash} from 'node:crypto'
|
|
5
|
+
import {copyFileSync, existsSync, readFileSync, rmSync, statSync} from 'node:fs'
|
|
6
|
+
import {dirname, isAbsolute, join, resolve} from 'node:path'
|
|
7
|
+
|
|
8
|
+
export class FailClosed extends Error {
|
|
9
|
+
fix
|
|
10
|
+
constructor(message , fix = '') { super(message); this.fix = fix }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
/** Walks up from `cwd` to the first directory with `.git` (a directory, or a file `gitdir: ...` for worktrees and
|
|
16
|
+
* submodules). Pure file system: no git process in PreToolUse. */
|
|
17
|
+
export function findRepo(cwd ) {
|
|
18
|
+
// Git Bash style /c/x on Windows means C:/x
|
|
19
|
+
if (process.platform === 'win32') cwd = cwd.replace(/^\/([a-zA-Z])(\/|$)/, '$1:/')
|
|
20
|
+
let dir = resolve(cwd)
|
|
21
|
+
for (;;) {
|
|
22
|
+
const dotGit = join(dir, '.git')
|
|
23
|
+
let st
|
|
24
|
+
try { st = statSync(dotGit) } catch { st = undefined }
|
|
25
|
+
if (st?.isDirectory()) return {root: dir, gitDir: dotGit, stateDir: join(dotGit, 'stopbar')}
|
|
26
|
+
if (st?.isFile()) {
|
|
27
|
+
const m = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotGit, 'utf8'))
|
|
28
|
+
if (!m) throw new FailClosed(`${dotGit} is not a valid gitdir file`)
|
|
29
|
+
const gd = isAbsolute(m[1]) ? m[1] : resolve(dir, m[1])
|
|
30
|
+
return {root: dir, gitDir: gd, stateDir: join(gd, 'stopbar')}
|
|
31
|
+
}
|
|
32
|
+
const up = dirname(dir)
|
|
33
|
+
if (up === dir) throw new FailClosed(`not inside a git repository: ${cwd}`, 'run Claude Code inside a git repository, or run `git init` and `stopbar init`')
|
|
34
|
+
dir = up
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export let gitCalls = 0
|
|
39
|
+
export function git(cwd , args , env , input ) {
|
|
40
|
+
gitCalls++
|
|
41
|
+
return execFileSync('git', args, {
|
|
42
|
+
cwd, encoding: 'utf8', input, maxBuffer: 256 << 20, windowsHide: true,
|
|
43
|
+
env: env ? {...process.env, ...env} : process.env, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
|
|
44
|
+
}).replace(/\r?\n$/, '')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function headTree(root ) {
|
|
48
|
+
try { return git(root, ['rev-parse', '-q', '--verify', 'HEAD^{tree}']) } catch { return null }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ---------------------------------------------------------------- working-tree snapshot
|
|
52
|
+
// A private index in the state dir, refreshed by one `git add -A` (it re-hashes only files whose stat data changed, sees
|
|
53
|
+
// edits, deletions and untracked non-ignored files, and ignores the user's staging area). The snapshot id is a sha256 over
|
|
54
|
+
// the index entries (mode, object id, path): equal ids = equal tree content. Comparing and diffing happen here, by reading
|
|
55
|
+
// the index file, so a hook needs one git process instead of three (on Windows each costs 50-70 ms).
|
|
56
|
+
// path -> "<mode> <oid>"
|
|
57
|
+
|
|
58
|
+
const GIT_FLAGS = ['-c', 'core.splitIndex=false', '-c', 'index.sparse=false', '-c', 'index.version=2', '-c', 'core.fsmonitor=false']
|
|
59
|
+
const idx = (r ) => ({live: join(r.stateDir, 'snapshot.index'), counted: join(r.stateDir, 'snapshot.counted.index')})
|
|
60
|
+
|
|
61
|
+
/** Parses a git index file (versions 2, 3, 4; SHA-1 or SHA-256 object ids). Throws on anything it does not understand,
|
|
62
|
+
* including a checksum mismatch, so a damaged or unusual index is rebuilt instead of misread. */
|
|
63
|
+
export function parseIndex(buf ) {
|
|
64
|
+
if (buf.length < 12 || buf.toString('latin1', 0, 4) !== 'DIRC') throw new Error('not a git index')
|
|
65
|
+
const version = buf.readUInt32BE(4), count = buf.readUInt32BE(8)
|
|
66
|
+
if (version < 2 || version > 4) throw new Error(`index version ${version}`)
|
|
67
|
+
let hashLen = 0
|
|
68
|
+
for (const [len, algo] of [[20, 'sha1'], [32, 'sha256']] ) {
|
|
69
|
+
if (buf.length > 12 + len && createHash(algo).update(buf.subarray(0, buf.length - len)).digest().equals(buf.subarray(buf.length - len))) { hashLen = len; break }
|
|
70
|
+
}
|
|
71
|
+
if (!hashLen) throw new Error('index checksum mismatch')
|
|
72
|
+
const out = new Map()
|
|
73
|
+
let pos = 12, prev = ''
|
|
74
|
+
for (let i = 0; i < count; i++) {
|
|
75
|
+
const start = pos
|
|
76
|
+
const mode = buf.readUInt32BE(pos + 24)
|
|
77
|
+
const oid = buf.toString('hex', pos + 40, pos + 40 + hashLen)
|
|
78
|
+
const flags = buf.readUInt16BE(pos + 40 + hashLen)
|
|
79
|
+
pos += 40 + hashLen + 2
|
|
80
|
+
if (flags & 0x4000) { if (version < 3) throw new Error('extended flag in index v2'); pos += 2 }
|
|
81
|
+
if ((flags >> 12) & 3) throw new Error('unmerged entry in the private index')
|
|
82
|
+
let path
|
|
83
|
+
if (version === 4) {
|
|
84
|
+
let n = 0, b
|
|
85
|
+
do { b = buf[pos++]; n = (n << 7) | (b & 0x7f); if (b & 0x80) n++ } while (b & 0x80)
|
|
86
|
+
const end = buf.indexOf(0, pos)
|
|
87
|
+
if (end < 0 || n > Buffer.byteLength(prev)) throw new Error('bad v4 path')
|
|
88
|
+
const pb = Buffer.from(prev)
|
|
89
|
+
path = Buffer.concat([pb.subarray(0, pb.length - n), buf.subarray(pos, end)]).toString('utf8')
|
|
90
|
+
pos = end + 1
|
|
91
|
+
} else {
|
|
92
|
+
const end = buf.indexOf(0, pos)
|
|
93
|
+
if (end < 0) throw new Error('bad path')
|
|
94
|
+
path = buf.toString('utf8', pos, end)
|
|
95
|
+
pos = start + ((end - start + 8) & ~7)
|
|
96
|
+
}
|
|
97
|
+
if (pos > buf.length - hashLen) throw new Error('index truncated')
|
|
98
|
+
out.set(path, `${mode.toString(8)} ${oid}`)
|
|
99
|
+
prev = path
|
|
100
|
+
}
|
|
101
|
+
return out
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function digest(e ) {
|
|
105
|
+
const h = createHash('sha256')
|
|
106
|
+
for (const [p, v] of e) h.update(`${v} ${p}\0`)
|
|
107
|
+
return h.digest('hex')
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Refreshes the private index and returns the snapshot. One git process (two the first time). */
|
|
111
|
+
export function snapshot(r ) {
|
|
112
|
+
const {live} = idx(r)
|
|
113
|
+
const env = {GIT_INDEX_FILE: live}
|
|
114
|
+
const fill = () => {
|
|
115
|
+
if (!existsSync(live)) {
|
|
116
|
+
try { git(r.root, [...GIT_FLAGS, 'read-tree', 'HEAD'], env) } catch { git(r.root, [...GIT_FLAGS, 'read-tree', '--empty'], env) }
|
|
117
|
+
}
|
|
118
|
+
git(r.root, [...GIT_FLAGS, 'add', '-A'], env)
|
|
119
|
+
const entries = parseIndex(readFileSync(live))
|
|
120
|
+
return {id: digest(entries), entries}
|
|
121
|
+
}
|
|
122
|
+
try { return fill() } catch {
|
|
123
|
+
// damaged or unusual private index (torn write, other version): rebuild it once, then fail closed
|
|
124
|
+
rmSync(live, {force: true})
|
|
125
|
+
return fill()
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The entries of the last snapshot the kernel counted, if the saved copy still matches its id. */
|
|
130
|
+
export function countedEntries(r , id ) {
|
|
131
|
+
try {
|
|
132
|
+
const e = parseIndex(readFileSync(idx(r).counted))
|
|
133
|
+
return digest(e) === id ? e : null
|
|
134
|
+
} catch { return null }
|
|
135
|
+
}
|
|
136
|
+
export function markCounted(r ) { copyFileSync(idx(r).live, idx(r).counted) }
|
|
137
|
+
export function forgetSnapshots(r ) { for (const f of Object.values(idx(r))) rmSync(f, {force: true}) }
|
|
138
|
+
|
|
139
|
+
export function diffEntries(a , b ) {
|
|
140
|
+
const out = []
|
|
141
|
+
for (const [p, v] of b) { const old = a.get(p); if (old === undefined) out.push({status: 'A', path: p}); else if (old !== v) out.push({status: 'M', path: p}) }
|
|
142
|
+
for (const p of a.keys()) if (!b.has(p)) out.push({status: 'D', path: p})
|
|
143
|
+
return out.sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : 0))
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Fallback diff when the counted copy is gone: the current snapshot against HEAD (one git process). */
|
|
147
|
+
export function changesSinceHead(r , now ) {
|
|
148
|
+
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) }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Does the current private index differ from HEAD? (one git process; no HEAD = differs unless empty) */
|
|
160
|
+
export function differsFromHead(r , now ) {
|
|
161
|
+
try {
|
|
162
|
+
git(r.root, ['diff-index', '--cached', '--quiet', 'HEAD', '--'], {GIT_INDEX_FILE: idx(r).live})
|
|
163
|
+
return false
|
|
164
|
+
} catch (e) {
|
|
165
|
+
if ((e ).status === 1) return true
|
|
166
|
+
return now.size > 0 || headTree(r.root) !== null
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Which of `paths` exist in HEAD (one git process, only when test files changed). */
|
|
171
|
+
export function inHead(root , paths ) {
|
|
172
|
+
if (!paths.length) return new Set()
|
|
173
|
+
try {
|
|
174
|
+
const out = git(root, ['--literal-pathspecs', '-c', 'core.quotepath=false', 'ls-tree', '-r', '-z', '--name-only', '--full-tree', 'HEAD', '--', ...paths])
|
|
175
|
+
return new Set(out.split('\0').filter(Boolean))
|
|
176
|
+
} catch { return new Set() }
|
|
177
|
+
}
|
package/dist/run.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Built from src/run.ts by scripts/build.ts. Do not edit.
|
|
2
|
+
// `stopbar run build|test`: runs the configured gate command itself and records its real exit status in the kernel.
|
|
3
|
+
// For agents without hooks (with the git fallback) this is how a build or full test run counts. The working tree is
|
|
4
|
+
// synced before the run; the result is recorded at that revision and a change made during the run is counted after it,
|
|
5
|
+
// so a run never passes a revision it did not see.
|
|
6
|
+
import {spawnSync} from 'node:child_process'
|
|
7
|
+
import {runEvent} from './hook.js'
|
|
8
|
+
import {findRepo} from './repo.js'
|
|
9
|
+
import {readConfig} from './store.js'
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
export function runGate(which , o ) {
|
|
14
|
+
if (which !== 'build' && which !== 'test') return {code: 1, msg: 'usage: stopbar run build|test'}
|
|
15
|
+
const cwd = o.get('repo') ?? process.cwd()
|
|
16
|
+
const repo = findRepo(cwd)
|
|
17
|
+
const cfg = readConfig(repo)
|
|
18
|
+
const command = which === 'build' ? cfg.buildCmd : cfg.fullTestCmd
|
|
19
|
+
const meta = (event ) => ({adapter: 'run', rawKeys: [], event})
|
|
20
|
+
const before = runEvent({hook_event_name: 'PostToolUse', cwd: repo.root, tool_name: 'Bash', tool_input: {command: ':'}, tool_response: {exitCode: 0}, stopbar: meta('sync')})
|
|
21
|
+
if (before.code !== 0 && /FAIL-CLOSED|halted/.test(before.msg ?? '')) return {code: 2, msg: before.msg}
|
|
22
|
+
const r = spawnSync(command, {cwd: repo.root, shell: true, stdio: 'inherit'})
|
|
23
|
+
const exit = r.status ?? 1
|
|
24
|
+
const after = runEvent({hook_event_name: exit === 0 ? 'PostToolUse' : 'PostToolUseFailure', cwd: repo.root, tool_name: 'Bash', tool_input: {command},
|
|
25
|
+
tool_response: {exitCode: exit}, stopbar: meta(which)})
|
|
26
|
+
const msg = `stopbar run ${which}: \`${command}\` exited ${exit}; recorded as ${exit === 0 ? 'a pass' : 'a failure'}${after.msg ? `\n${after.msg}` : ''}`
|
|
27
|
+
return {code: exit === 0 && after.code === 0 ? 0 : exit || 2, msg}
|
|
28
|
+
}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Built from src/store.ts by scripts/build.ts. Do not edit.
|
|
2
|
+
// State, config and event log in <git-dir>/stopbar/. Lock for concurrent hooks. Damaged files fail closed.
|
|
3
|
+
import {closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync, writeSync} from 'node:fs'
|
|
4
|
+
import {join} from 'node:path'
|
|
5
|
+
import { ConfigError, validateConfig} from './config.js'
|
|
6
|
+
import {CODEC} from './kernel.gen.js'
|
|
7
|
+
import {FailClosed, } from './repo.js'
|
|
8
|
+
|
|
9
|
+
export const VERSION = '1.1.0'
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
const files = (r ) => ({
|
|
14
|
+
config: join(r.stateDir, 'config.json'), state: join(r.stateDir, 'state.json'),
|
|
15
|
+
events: join(r.stateDir, 'events.jsonl'), lock: join(r.stateDir, 'lock'),
|
|
16
|
+
})
|
|
17
|
+
export const paths = files
|
|
18
|
+
|
|
19
|
+
// ---------------------------------------------------------------- lock
|
|
20
|
+
const sleep = (ms ) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
|
|
21
|
+
function alive(pid ) {
|
|
22
|
+
try { process.kill(pid, 0); return true } catch (e) { return (e ).code === 'EPERM' }
|
|
23
|
+
}
|
|
24
|
+
/** Exclusive lock file with the owner's pid. A lock whose owner died, or older than 60 s, is stale and taken over. */
|
|
25
|
+
export function withLock (r , f , waitMs = 20000) {
|
|
26
|
+
const lock = files(r).lock
|
|
27
|
+
mkdirSync(r.stateDir, {recursive: true})
|
|
28
|
+
const until = Date.now() + waitMs
|
|
29
|
+
for (;;) {
|
|
30
|
+
try {
|
|
31
|
+
const fd = openSync(lock, 'wx')
|
|
32
|
+
writeSync(fd, String(process.pid)); closeSync(fd)
|
|
33
|
+
break
|
|
34
|
+
} catch (e) {
|
|
35
|
+
if ((e ).code !== 'EEXIST') throw e
|
|
36
|
+
let stale = false
|
|
37
|
+
try {
|
|
38
|
+
const pid = Number(readFileSync(lock, 'utf8'))
|
|
39
|
+
const age = Date.now() - statSync(lock).mtimeMs
|
|
40
|
+
stale = (Number.isSafeInteger(pid) && pid > 0 && !alive(pid)) || age > 60000
|
|
41
|
+
} catch { /* lock vanished between calls */ }
|
|
42
|
+
if (stale) { rmSync(lock, {force: true}); continue }
|
|
43
|
+
if (Date.now() > until) throw new FailClosed(`lock ${lock} busy for ${waitMs / 1000} s`, 'another Stopbar hook is running; if none is, delete the lock file')
|
|
44
|
+
sleep(5)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
try { return f() } finally { rmSync(lock, {force: true}) }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ---------------------------------------------------------------- config
|
|
51
|
+
export function readConfig(r ) {
|
|
52
|
+
const f = files(r).config
|
|
53
|
+
if (!existsSync(f)) throw new FailClosed(`Stopbar is not initialised in ${r.root} (no ${f})`, 'a human runs: stopbar init --build "<cmd>" --test "<cmd>"')
|
|
54
|
+
const raw = readFileSync(f, 'utf8')
|
|
55
|
+
if (!raw.trim()) throw new FailClosed(`config.json is empty: ${f}`, 'a human runs `stopbar init --force --build "<cmd>" --test "<cmd>"` to write it again')
|
|
56
|
+
let parsed
|
|
57
|
+
try { parsed = JSON.parse(raw) } catch (e) {
|
|
58
|
+
throw new FailClosed(`config.json is not valid JSON (${(e ).message}): ${f}`, 'a human fixes the file or runs `stopbar init --force --build "<cmd>" --test "<cmd>"`')
|
|
59
|
+
}
|
|
60
|
+
try { return validateConfig(parsed) } catch (e) {
|
|
61
|
+
if (e instanceof ConfigError) throw new FailClosed(`config.json is invalid: ${e.message}: ${f}`, 'a human fixes the field or runs `stopbar init --force ...`')
|
|
62
|
+
throw e
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
export function writeConfig(r , c ) {
|
|
66
|
+
mkdirSync(r.stateDir, {recursive: true})
|
|
67
|
+
atomicWrite(files(r).config, JSON.stringify(c, null, 2) + '\n')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ---------------------------------------------------------------- state
|
|
71
|
+
function atomicWrite(f , data ) {
|
|
72
|
+
const tmp = `${f}.${process.pid}.tmp`
|
|
73
|
+
writeFileSync(tmp, data)
|
|
74
|
+
for (let i = 0; ; i++) {
|
|
75
|
+
try { renameSync(tmp, f); return } catch (e) {
|
|
76
|
+
// Windows: a reader (antivirus, indexer) may hold the target for a moment
|
|
77
|
+
if (i >= 20 || !['EPERM', 'EACCES', 'EBUSY'].includes((e ).code ?? '')) { rmSync(tmp, {force: true}); throw e }
|
|
78
|
+
sleep(10)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const isNat = (x ) => typeof x === 'number' && Number.isSafeInteger(x) && x >= 0
|
|
84
|
+
export function validateState(s ) {
|
|
85
|
+
const bad = (why ) => { throw new Error(why) }
|
|
86
|
+
if (!s || typeof s !== 'object') bad('not an object')
|
|
87
|
+
const o = s
|
|
88
|
+
if (o.version !== 2) bad(`version must be 2, got ${JSON.stringify(o.version)}`)
|
|
89
|
+
if (typeof o.snapshot !== 'string' || !/^[0-9a-f]{40,64}$/.test(o.snapshot)) bad('snapshot must be a git tree id')
|
|
90
|
+
if (!o.params || !isNat(o.params.maxRetries) || !isNat(o.params.cap) || o.params.maxRetries < 1 || o.params.cap < 1) bad('params.maxRetries and params.cap must be integers >= 1')
|
|
91
|
+
const k = o.kernel
|
|
92
|
+
if (!k || typeof k !== 'object' || !k.scalars || typeof k.scalars !== 'object' || !k.maps || typeof k.maps !== 'object') bad('kernel must hold scalars and maps')
|
|
93
|
+
const names = CODEC.state.map((f) => f.name)
|
|
94
|
+
for (const name of Object.keys(k.scalars)) if (!names.includes(name)) bad(`unknown kernel field ${name}`)
|
|
95
|
+
for (const f of CODEC.state) {
|
|
96
|
+
const v = k.scalars[f.name]
|
|
97
|
+
if (!isNat(v)) bad(`kernel field ${f.name} must be a natural number`)
|
|
98
|
+
if (f.kind === 'bool' && v > 1) bad(`kernel field ${f.name} must be 0 or 1`)
|
|
99
|
+
if (f.kind === 'oneOf' && v >= f.values .length) bad(`kernel field ${f.name} out of range`)
|
|
100
|
+
}
|
|
101
|
+
return o
|
|
102
|
+
}
|
|
103
|
+
export function readState(r ) {
|
|
104
|
+
const f = files(r).state
|
|
105
|
+
const fix = 'a human runs `stopbar reset` (fresh kernel state; the event log is kept) and re-runs the build and the full test suite'
|
|
106
|
+
if (!existsSync(f)) throw new FailClosed(`state.json is missing: ${f}`, fix)
|
|
107
|
+
const raw = readFileSync(f, 'utf8')
|
|
108
|
+
if (!raw.trim()) throw new FailClosed(`state.json is empty: ${f}`, fix)
|
|
109
|
+
let parsed
|
|
110
|
+
try { parsed = JSON.parse(raw) } catch (e) { throw new FailClosed(`state.json is not valid JSON (${(e ).message}): ${f}`, fix) }
|
|
111
|
+
try { return validateState(parsed) } catch (e) { throw new FailClosed(`state.json is invalid: ${(e ).message}: ${f}`, fix) }
|
|
112
|
+
}
|
|
113
|
+
export function writeState(r , s ) { atomicWrite(files(r).state, JSON.stringify(s)) }
|
|
114
|
+
|
|
115
|
+
// ---------------------------------------------------------------- event log
|
|
116
|
+
/** Appends one JSON line. If the last line was torn (a crash mid-write left no final newline), a newline goes first,
|
|
117
|
+
* so the torn fragment stays a line of its own and the new entry is never glued onto it. Call under the lock. */
|
|
118
|
+
export function appendEvent(r , entry ) {
|
|
119
|
+
const f = files(r).events
|
|
120
|
+
const line = JSON.stringify({ts: new Date().toISOString(), ...entry}) + '\n'
|
|
121
|
+
const fd = openSync(f, 'a+')
|
|
122
|
+
try {
|
|
123
|
+
const size = fstatSync(fd).size
|
|
124
|
+
let lead = ''
|
|
125
|
+
if (size > 0) {
|
|
126
|
+
const b = Buffer.alloc(1)
|
|
127
|
+
readSync(fd, b, 0, 1, size - 1)
|
|
128
|
+
if (b[0] !== 0x0a) lead = '\n'
|
|
129
|
+
}
|
|
130
|
+
writeSync(fd, lead + line)
|
|
131
|
+
} finally { closeSync(fd) }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
export function readEvents(r ) {
|
|
136
|
+
const f = files(r).events
|
|
137
|
+
if (!existsSync(f)) return {events: [], torn: []}
|
|
138
|
+
const out = {events: [], torn: []}
|
|
139
|
+
readFileSync(f, 'utf8').split('\n').forEach((l, i) => {
|
|
140
|
+
if (!l) return
|
|
141
|
+
try { out.events.push(JSON.parse(l)) } catch { out.torn.push({line: i + 1, text: l.slice(0, 120)}) }
|
|
142
|
+
})
|
|
143
|
+
return out
|
|
144
|
+
}
|
package/dist/verify.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// Built from src/verify.ts by scripts/build.ts. Do not edit.
|
|
2
|
+
// `stopbar prove` (alias `verify`): the inductive proof of src/kernel.ts, the 10 mutants (each must fall with a counterexample run),
|
|
3
|
+
// and the link between the proven rule and the step function the hooks run (dist/kernel.gen.js).
|
|
4
|
+
// Loads gdp-wired (the prover); hooks never do.
|
|
5
|
+
import {createHash} from 'node:crypto'
|
|
6
|
+
import {existsSync, readFileSync, writeFileSync} from 'node:fs'
|
|
7
|
+
import {join} from 'node:path'
|
|
8
|
+
import {pathToFileURL} from 'node:url'
|
|
9
|
+
import * as G from './kernel.gen.js'
|
|
10
|
+
import {PKG_ROOT} from './pkg.js'
|
|
11
|
+
|
|
12
|
+
const OPS = ['EDIT_CODE', 'EDIT_TEST', 'RUN_BUILD', 'RUN_TESTS', 'READ_SECRET', 'SHELL', 'APPROVE_TESTS', 'APPROVE_SHELL', 'RESUME', 'COMMIT']
|
|
13
|
+
const sha = (s ) => createHash('sha256').update(s).digest('hex')
|
|
14
|
+
|
|
15
|
+
/** Random requests inside the rule's assumption (human actions cost nothing). */
|
|
16
|
+
export function randomRequest(rnd ) {
|
|
17
|
+
const op = OPS[Math.floor(rnd() * OPS.length)]
|
|
18
|
+
const human = op === 'APPROVE_TESTS' || op === 'APPROVE_SHELL' || op === 'RESUME'
|
|
19
|
+
const b = () => rnd() < 0.5
|
|
20
|
+
return {op, cost: human ? 0 : Math.floor(rnd() * 4), passed: b(), fullSuite: b(), suspicious: b(), risky: b(), treeChanged: b(),
|
|
21
|
+
approveRev: Math.floor(rnd() * 6), extra: Math.floor(rnd() * 5)}
|
|
22
|
+
}
|
|
23
|
+
export function lcg(seed ) { let x = seed >>> 0 || 1; return () => { x = (Math.imul(x, 1103515245) + 12345) >>> 0; return x / 2 ** 32 } }
|
|
24
|
+
|
|
25
|
+
export async function loadKernel() {
|
|
26
|
+
const k = await import(pathToFileURL(join(PKG_ROOT, 'dist', 'kernel.js')).href)
|
|
27
|
+
const gw = await import('gdp-wired')
|
|
28
|
+
const machine = await import('gdp-wired/machine')
|
|
29
|
+
return {k, gw, machine}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The generated step function is the compileJs output of the unmutated kernel, and it agrees with the interpreter. */
|
|
33
|
+
export async function checkGenerated(steps = 3000) {
|
|
34
|
+
const {k, machine} = await loadKernel()
|
|
35
|
+
const R = k.kernel('none')
|
|
36
|
+
const js = machine.compileJs(R.machine)
|
|
37
|
+
const src = join(PKG_ROOT, 'src', 'kernel.ts')
|
|
38
|
+
const kernelSha = existsSync(src) ? sha(readFileSync(src)) : null
|
|
39
|
+
const res = {
|
|
40
|
+
machineName: G.MACHINE_NAME, machineSha256: G.MACHINE_SHA256, regeneratedSha256: sha(js),
|
|
41
|
+
sameMachine: sha(js) === G.MACHINE_SHA256 && G.MACHINE_NAME === R.machine.name,
|
|
42
|
+
kernelSourceSha256: G.KERNEL_SOURCE_SHA256, kernelSourceNow: kernelSha, sameSource: kernelSha === null ? null : kernelSha === G.KERNEL_SOURCE_SHA256,
|
|
43
|
+
}
|
|
44
|
+
// differential replay: interpreter of the proven rule vs the generated step, state compared after every step
|
|
45
|
+
const IT = R.interpreter()
|
|
46
|
+
let mismatches = 0, done = 0, refused = 0
|
|
47
|
+
const rnd = lcg(20261126)
|
|
48
|
+
for (let run = 0; done < steps; run++) {
|
|
49
|
+
const params = {maxRetries: 1 + Math.floor(rnd() * 3), cap: 1 + Math.floor(rnd() * 12)}
|
|
50
|
+
const P = R.encodeParams(params)
|
|
51
|
+
let a = IT.init(P), b = G.init(params)
|
|
52
|
+
for (let i = 0; i < 25 && done < steps; i++, done++) {
|
|
53
|
+
const req = randomRequest(rnd)
|
|
54
|
+
const enc = R.encodeInput(req, params)
|
|
55
|
+
let ea = null, eb = null
|
|
56
|
+
try { a = IT.step(P, a, enc) } catch (e) { ea = e }
|
|
57
|
+
try { b = G.step(params, G.fork(b), enc) } catch (e) { eb = e }
|
|
58
|
+
if (ea || eb) { refused++; if (!ea !== !eb) mismatches++; break }
|
|
59
|
+
if (JSON.stringify(a.scalars) !== JSON.stringify(b.scalars)) { mismatches++; break }
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
res.differential = {steps: done, refused, mismatches}
|
|
63
|
+
res.ok = res.sameMachine === true && res.sameSource !== false && mismatches === 0
|
|
64
|
+
return res
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// A concrete counterexample run for each mutant (each one found by the prover). verify
|
|
68
|
+
// replays it on the mutant, where a law must fail, and on the original kernel, where every law must hold. The kill is
|
|
69
|
+
// then deterministic, also when the prover's own search returns only an inductive witness within its time budget.
|
|
70
|
+
const REQ0 = {op: 'EDIT_CODE', cost: 0, passed: false, fullSuite: false, suspicious: false, risky: false, treeChanged: false, approveRev: 0, extra: 0}
|
|
71
|
+
export const KNOWN_RUNS = {
|
|
72
|
+
M1a: {params: {maxRetries: 2, cap: 100}, trace: [{op: 'RUN_TESTS', passed: true, fullSuite: true}, {op: 'RUN_BUILD', passed: true}, {op: 'SHELL', treeChanged: true}, {op: 'COMMIT'}]},
|
|
73
|
+
M1b: {params: {maxRetries: 2, cap: 100}, trace: [{op: 'RUN_TESTS'}, {op: 'RUN_TESTS', passed: true}, {op: 'RUN_TESTS'}]},
|
|
74
|
+
M2: {params: {maxRetries: 2, cap: 100}, trace: [{op: 'EDIT_TEST', suspicious: true}, {op: 'RUN_TESTS', passed: true, fullSuite: true}]},
|
|
75
|
+
M3: {params: {maxRetries: 2, cap: 100}, trace: [{op: 'READ_SECRET'}, {op: 'EDIT_CODE'}]},
|
|
76
|
+
M3b: {params: {maxRetries: 2, cap: 100}, trace: [{op: 'READ_SECRET'}, {op: 'SHELL', risky: true}]},
|
|
77
|
+
M4: {params: {maxRetries: 2, cap: 100}, trace: [{op: 'RUN_TESTS', fullSuite: true}, {op: 'RUN_BUILD', passed: true}, {op: 'RUN_TESTS', fullSuite: true}]},
|
|
78
|
+
M4b: {params: {maxRetries: 2, cap: 100}, trace: [{op: 'RUN_TESTS'}, {op: 'RUN_TESTS', passed: true}, {op: 'RUN_TESTS'}]},
|
|
79
|
+
M5: {params: {maxRetries: 2, cap: 3}, trace: [{op: 'RUN_BUILD', cost: 3, passed: true}, {op: 'APPROVE_SHELL'}]},
|
|
80
|
+
M6: {params: {maxRetries: 1, cap: 1}, trace: [{op: 'SHELL', suspicious: true, treeChanged: true}, {op: 'RUN_TESTS', passed: true, fullSuite: true}, {op: 'APPROVE_TESTS', approveRev: 0}, {op: 'RUN_BUILD', passed: true}, {op: 'COMMIT'}]},
|
|
81
|
+
M7: {params: {maxRetries: 2, cap: 3}, trace: [{op: 'RUN_BUILD', cost: 3, passed: true}, {op: 'APPROVE_SHELL'}]},
|
|
82
|
+
}
|
|
83
|
+
const show = (q ) => {
|
|
84
|
+
const flags = Object.entries(q).filter(([k, x]) => k !== 'op' && x).map(([k, x]) => `${k}=${x}`)
|
|
85
|
+
return flags.length ? `${q.op}(${flags.join(',')})` : String(q.op)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function verify(o = {}) {
|
|
89
|
+
const log = o.log ?? ((s ) => process.stdout.write(s + '\n'))
|
|
90
|
+
const {k, gw} = await loadKernel()
|
|
91
|
+
const {kernel, laws, lemmas, MUTANTS} = k
|
|
92
|
+
const OPT = {search: {ms: 60000}}
|
|
93
|
+
const out = {gdpWired: '0.60.0', node: process.version, platform: `${process.platform} ${process.arch}`}
|
|
94
|
+
|
|
95
|
+
log('1. generated step function vs the proven rule')
|
|
96
|
+
out.generated = await checkGenerated()
|
|
97
|
+
log(` machine ${out.generated.machineName}: same compileJs output=${out.generated.sameMachine}, kernel.ts hash matches=${out.generated.sameSource}, ` +
|
|
98
|
+
`differential ${out.generated.differential.steps} steps, mismatches=${out.generated.differential.mismatches}`)
|
|
99
|
+
|
|
100
|
+
log('2. inductive proof of the original kernel (laws + lemmas I1-I5)')
|
|
101
|
+
{
|
|
102
|
+
const r = kernel('none'), {laws: L, stepLaws: S} = laws(r)
|
|
103
|
+
const t = Date.now()
|
|
104
|
+
const v = gw.proveSteps(r, [...L, ...lemmas(r)], S, OPT)
|
|
105
|
+
out.original = {proven: v.proven, checked: v.checked, stuck: v.stuck, goal: v.goal, why: v.why, ms: Date.now() - t,
|
|
106
|
+
laws: [...L, ...lemmas(r)].map((l ) => l.name), stepLaws: S.map((l ) => l.name)}
|
|
107
|
+
log(` proven=${v.proven} checked=${v.checked} ${Date.now() - t} ms${v.goal ? ' goal=' + v.goal : ''}`)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
log('3. mutants: each must fall with a counterexample run')
|
|
111
|
+
out.mutants = {}
|
|
112
|
+
for (const m of MUTANTS.filter((x ) => x !== 'none')) {
|
|
113
|
+
const r = kernel(m), {laws: L, stepLaws: S} = laws(r)
|
|
114
|
+
const t = Date.now()
|
|
115
|
+
const v = gw.proveSteps(r, L, S, OPT)
|
|
116
|
+
const failed = [...L, ...S].find((l ) => v.goal?.startsWith(l.name))
|
|
117
|
+
let minimized = false
|
|
118
|
+
if (v.run && failed) { try { v.run = gw.minimizeRun(r, failed, v.run); minimized = true } catch { /* keep the unminimised run */ } }
|
|
119
|
+
const trace = (v.run?.trace ?? []).map((q ) => {
|
|
120
|
+
const op = typeof q.op === 'number' ? OPS[q.op] : q.op
|
|
121
|
+
const flags = Object.entries(q).filter(([kk, x]) => kk !== 'op' && x).map(([kk, x]) => `${kk}=${x}`)
|
|
122
|
+
return flags.length ? `${op}(${flags.join(',')})` : op
|
|
123
|
+
})
|
|
124
|
+
// deterministic replay of the known counterexample: a law fails on the mutant and every law holds on the original
|
|
125
|
+
const known = KNOWN_RUNS[m]
|
|
126
|
+
const r0 = kernel('none'), l0 = laws(r0)
|
|
127
|
+
const enc = (rule ) => known.trace.map((q) => rule.encodeInput({...REQ0, ...q}, known.params))
|
|
128
|
+
const onMutant = gw.replayRefutation(r, L, S, r.encodeParams(known.params), enc(r), 1000)
|
|
129
|
+
const onOriginal = gw.replayRefutation(r0, l0.laws, l0.stepLaws, r0.encodeParams(known.params), enc(r0), 1000)
|
|
130
|
+
const killed = v.proven === false && onMutant === true && onOriginal === false
|
|
131
|
+
out.mutants[m] = {killed, proven: v.proven, goal: v.goal, ms: Date.now() - t, minimized, proverRun: v.run ? {params: v.run.params, trace} : null,
|
|
132
|
+
proverWitness: v.run ? undefined : v.witness, counterexample: {params: known.params, trace: known.trace.map(show), breaksMutant: onMutant, breaksOriginal: onOriginal}}
|
|
133
|
+
log(` ${m.padEnd(4)} ${killed ? 'KILLED' : 'SURVIVED'} by ${v.goal ?? '-'} (${Date.now() - t} ms)` +
|
|
134
|
+
`\n counterexample ${known.trace.map(show).join(' -> ')} ${JSON.stringify(known.params)}: breaks the mutant=${onMutant}, breaks the original=${onOriginal}` +
|
|
135
|
+
(trace.length ? `\n prover run (minimized=${minimized}): ${trace.join(' -> ')}` : '\n prover: inductive witness only (no run within the search budget)'))
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (o.lean) {
|
|
139
|
+
const {toLean} = await import('gdp-wired/lean')
|
|
140
|
+
const r = kernel('none'), {laws: L, stepLaws: S} = laws(r)
|
|
141
|
+
const lean = toLean([{id: 'stopbar_kernel', machine: r.machine, laws: [...L, ...lemmas(r)], stepLaws: S}], {title: 'Stopbar kernel (gdp-wired 0.60.0)'})
|
|
142
|
+
writeFileSync(o.lean, lean)
|
|
143
|
+
out.lean = {file: o.lean, lines: lean.split('\n').length, theorems: (lean.match(/^\s*theorem\s/gm) ?? []).length, sorry: (lean.match(/\bsorry\b/g) ?? []).length, leanChecked: false}
|
|
144
|
+
log(`4. Lean export ${o.lean}: ${out.lean.lines} lines, ${out.lean.theorems} theorems, ${out.lean.sorry} sorry (not checked by Lean here)`)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const killed = Object.values(out.mutants).filter((x ) => x.killed).length
|
|
148
|
+
const total = Object.keys(out.mutants).length
|
|
149
|
+
out.ok = out.generated.ok && out.original.proven === true && out.original.checked === true && killed === total && total === 10
|
|
150
|
+
out.summary = `original proven=${out.original.proven} checked=${out.original.checked}; mutants killed ${killed}/${total}; generated step ok=${out.generated.ok}`
|
|
151
|
+
log(`RESULT: ${out.ok ? 'PASS' : 'FAIL'}: ${out.summary}`)
|
|
152
|
+
if (o.out) writeFileSync(o.out, JSON.stringify(out, null, 1) + '\n')
|
|
153
|
+
return out
|
|
154
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stopbar",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
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
|
+
"author": "Paweł Olszewski <kontakt@polszewski.com>",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/polszewski-pl/stopbar.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/polszewski-pl/stopbar#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/polszewski-pl/stopbar/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"bin": {
|
|
17
|
+
"stopbar": "bin/stopbar.mjs"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"bin/",
|
|
21
|
+
"dist/",
|
|
22
|
+
"src/kernel.ts",
|
|
23
|
+
"claude-hooks.example.json",
|
|
24
|
+
"README.md",
|
|
25
|
+
"SECURITY.md",
|
|
26
|
+
"CHANGELOG.md",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
],
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=22.18"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "node scripts/build.ts",
|
|
34
|
+
"test": "node scripts/build.ts && node tests/run-all.ts",
|
|
35
|
+
"test:fuzz": "node tests/stateful-wrapper.ts",
|
|
36
|
+
"test:e2e": "node tests/e2e.ts",
|
|
37
|
+
"prove": "node scripts/build.ts && node bin/stopbar.mjs prove",
|
|
38
|
+
"verify": "node scripts/build.ts && node bin/stopbar.mjs prove",
|
|
39
|
+
"verify:lean": "node scripts/build.ts && node scripts/verify-lean.ts",
|
|
40
|
+
"probe": "node scripts/build.ts && node bin/stopbar.mjs probe",
|
|
41
|
+
"bench": "node bench/hook-latency.ts",
|
|
42
|
+
"prepack": "node scripts/build.ts"
|
|
43
|
+
},
|
|
44
|
+
"keywords": [
|
|
45
|
+
"claude-code",
|
|
46
|
+
"cursor",
|
|
47
|
+
"codex",
|
|
48
|
+
"gemini-cli",
|
|
49
|
+
"antigravity",
|
|
50
|
+
"ai-agents",
|
|
51
|
+
"hooks",
|
|
52
|
+
"coding-agent",
|
|
53
|
+
"guardrails",
|
|
54
|
+
"formal-verification",
|
|
55
|
+
"git"
|
|
56
|
+
],
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"gdp-wired": "0.60.0"
|
|
59
|
+
}
|
|
60
|
+
}
|