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/cli.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Built from src/cli.ts by scripts/build.ts. Do not edit.
|
|
2
|
+
// stopbar CLI. Exit codes: hook 0 = allow, 2 = block or fail closed. Human commands: 0 = ok, 1 = refused, 2 = fail closed.
|
|
3
|
+
import {readFileSync} from 'node:fs'
|
|
4
|
+
import {VERSION} from './store.js'
|
|
5
|
+
|
|
6
|
+
const t0 = performance.now()
|
|
7
|
+
const argv = process.argv.slice(2)
|
|
8
|
+
const cmd = argv[0] ?? 'help'
|
|
9
|
+
|
|
10
|
+
const HELP = `stopbar ${VERSION}: proven gates for coding agents (Claude Code hooks)
|
|
11
|
+
|
|
12
|
+
stopbar init --build "<cmd>" --test "<cmd>" [--profile default|ts|python|strict] [--max-retries 3] [--cap 500]
|
|
13
|
+
[--cost 1] [--hooks claude,claude-project,cursor,codex,gemini,antigravity,git] [--no-pin] [--force] [--force-hooks] [--repo <dir>]
|
|
14
|
+
stopbar hook [--adapter auto|claude|cursor|codex|gemini|antigravity]
|
|
15
|
+
the agent hook (JSON on stdin); auto detects the client from the payload
|
|
16
|
+
stopbar git-hook pre-commit|pre-push fallback gate run by git (installed by init --hooks git)
|
|
17
|
+
stopbar run build|test runs the configured gate command and records its exit status
|
|
18
|
+
stopbar status [--json] gates, taint, budget, why a commit is blocked
|
|
19
|
+
stopbar approve-tests [--rev N] a human reviewed the changed tests/config up to revision N (default: current)
|
|
20
|
+
stopbar approve-shell a human allows ONE risky or outbound call after a secret was read
|
|
21
|
+
stopbar resume --extra N a human lifts a halt and adds N to the budget
|
|
22
|
+
stopbar reset a human starts a fresh kernel state (config and event log stay)
|
|
23
|
+
stopbar doctor [--json] environment, config, state, hooks and a dry run
|
|
24
|
+
|
|
25
|
+
Four pillars:
|
|
26
|
+
PROVE stopbar prove [--out f.json] [--lean f.lean] inductive proof of the kernel and the 10 mutants
|
|
27
|
+
(npm run verify:lean checks the Lean export with lake build in Docker)
|
|
28
|
+
PROBE stopbar probe [--target wrapper] [--runs 200] [--seed 1] [--jobs N] [--work dir] [--out dir]
|
|
29
|
+
stateful probing of the hooks against the proven kernel on real git repositories
|
|
30
|
+
GATE init, hook, status, approve-tests, approve-shell, resume, reset, doctor (above)
|
|
31
|
+
ATTEST stopbar attest [--format json|md] deterministic attestation: HEAD, tree, gates, human actions, log sha256
|
|
32
|
+
All commands take --repo <dir> (default: the current directory). 'verify' is an alias of 'prove'.`
|
|
33
|
+
|
|
34
|
+
function opts(a ) {
|
|
35
|
+
const get = (name ) => { const i = a.indexOf(`--${name}`); return i >= 0 && i + 1 < a.length ? a[i + 1] : undefined }
|
|
36
|
+
return {
|
|
37
|
+
get, has: (name ) => a.includes(`--${name}`),
|
|
38
|
+
int: (name , def ) => {
|
|
39
|
+
const raw = get(name); if (raw === undefined) return def
|
|
40
|
+
const n = Number(raw); if (!/^\d+$/.test(raw) || !Number.isSafeInteger(n)) throw new Error(`--${name} must be a non-negative integer`)
|
|
41
|
+
return n
|
|
42
|
+
},
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function main() {
|
|
47
|
+
if (cmd === 'hook') {
|
|
48
|
+
const {handle} = await import('./adapters/index.js')
|
|
49
|
+
const i = argv.indexOf('--adapter')
|
|
50
|
+
const which = i >= 0 ? argv[i + 1] ?? '' : 'auto'
|
|
51
|
+
let raw
|
|
52
|
+
try { raw = readFileSync(0, 'utf8') } catch (e) { return {code: 2, msg: `STOPBAR FAIL-CLOSED: cannot read stdin (${(e ).message})`} }
|
|
53
|
+
const r = handle(raw, which, t0)
|
|
54
|
+
if (r.stdout) process.stdout.write(r.stdout)
|
|
55
|
+
if (r.stderr) process.stderr.write(r.stderr)
|
|
56
|
+
return {code: r.code}
|
|
57
|
+
}
|
|
58
|
+
if (cmd === 'git-hook') return (await import('./githook.js')).gitHook(argv[1] ?? '', opts(argv.slice(2)))
|
|
59
|
+
if (cmd === 'run') return (await import('./run.js')).runGate(argv[1] ?? '', opts(argv.slice(2)))
|
|
60
|
+
if (cmd === 'help' || cmd === '--help' || cmd === '-h') return {code: 0, msg: HELP}
|
|
61
|
+
if (cmd === '--version' || cmd === 'version') return {code: 0, msg: VERSION}
|
|
62
|
+
const o = opts(argv.slice(1))
|
|
63
|
+
if (cmd === 'init') return (await import('./commands.js')).init(o)
|
|
64
|
+
if (['status', 'approve-tests', 'approve-shell', 'resume', 'reset'].includes(cmd)) return (await import('./commands.js')).human(cmd, o)
|
|
65
|
+
if (cmd === 'doctor') return (await import('./doctor.js')).doctor({repo: o.get('repo'), json: o.has('json')})
|
|
66
|
+
if (cmd === 'prove' || cmd === 'verify') {
|
|
67
|
+
const r = await (await import('./verify.js')).verify({out: o.get('out'), lean: o.get('lean')})
|
|
68
|
+
return {code: r.ok ? 0 : 1}
|
|
69
|
+
}
|
|
70
|
+
if (cmd === 'probe') {
|
|
71
|
+
const P = await import('./probe/index.js')
|
|
72
|
+
if (o.has('worker')) { await P.worker(JSON.parse(o.get('worker') )); return {code: 0} }
|
|
73
|
+
const num = (n ) => (o.get(n) === undefined ? undefined : o.int(n, 0))
|
|
74
|
+
const r = await P.probe({target: o.get('target'), runs: num('runs'), seed: num('seed'), jobs: num('jobs'), work: o.get('work'), out: o.get('out'),
|
|
75
|
+
regressions: o.get('regressions'), regressionsOnly: o.has('regressions-only')})
|
|
76
|
+
return {code: r.ok ? 0 : 1}
|
|
77
|
+
}
|
|
78
|
+
if (cmd === 'attest') return (await import('./attest.js')).attest({repo: o.get('repo'), format: o.get('format')})
|
|
79
|
+
return {code: 1, msg: `unknown command ${cmd}\n\n${HELP}`}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
let res
|
|
83
|
+
try { res = await main() } catch (e) {
|
|
84
|
+
const {failMsg} = await import('./hook.js')
|
|
85
|
+
res = {code: 2, msg: failMsg(e)}
|
|
86
|
+
}
|
|
87
|
+
if (res.msg) (res.code === 0 ? process.stdout : process.stderr).write(res.msg + '\n')
|
|
88
|
+
process.exitCode = res.code
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// Built from src/commands.ts by scripts/build.ts. Do not edit.
|
|
2
|
+
// Human commands: init, status, approve-tests, approve-shell, resume, reset. The agent cannot run them
|
|
3
|
+
// through its shell (classify.ts protectedCommand) and cannot edit their files (protectedPath).
|
|
4
|
+
import {cpSync, existsSync, mkdirSync, rmSync} from 'node:fs'
|
|
5
|
+
import {join} from 'node:path'
|
|
6
|
+
import {hasChain} from './classify.js'
|
|
7
|
+
import {CLAUDE_POST_MATCHER, claudeHooks, hookCommand, installHooks, parseTargets} from './integrations.js'
|
|
8
|
+
import { ConfigError, makeConfig, PROFILES} from './config.js'
|
|
9
|
+
import {decode, initKernel, kstep, MACHINE, } from './engine.js'
|
|
10
|
+
import {whyBlocked} from './hook.js'
|
|
11
|
+
import {PKG_ROOT} from './pkg.js'
|
|
12
|
+
import {findRepo, forgetSnapshots, markCounted, snapshot} from './repo.js'
|
|
13
|
+
import {appendEvent, paths, readConfig, readEvents, readState, VERSION, withLock, writeConfig, writeState} from './store.js'
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
export function fresh(r , c ) {
|
|
18
|
+
forgetSnapshots(r)
|
|
19
|
+
const params = {maxRetries: c.maxRetries, cap: c.cap}
|
|
20
|
+
const snap = snapshot(r)
|
|
21
|
+
markCounted(r)
|
|
22
|
+
return {version: 2, kernel: initKernel(params), snapshot: snap.id, params}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function humanStep(r , s , req , source ) {
|
|
26
|
+
s.kernel = kstep(s.params, s.kernel, req)
|
|
27
|
+
const after = decode(s.kernel)
|
|
28
|
+
appendEvent(r, {source, req, decision: after.decision, halted: after.halted, testsTainted: after.testsTainted,
|
|
29
|
+
shellToken: after.shellToken, treeRev: after.treeRev, spent: after.spent, capNow: after.capNow,
|
|
30
|
+
testFails: after.testFails, buildFails: after.buildFails})
|
|
31
|
+
return after
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ---------------------------------------------------------------- hooks config (Claude Code; other clients in integrations.ts)
|
|
35
|
+
export const HOOK_MATCHERS = {post: CLAUDE_POST_MATCHER}
|
|
36
|
+
export {hookCommand}
|
|
37
|
+
export const hooksConfig = (command ) => ({hooks: claudeHooks(command)})
|
|
38
|
+
/** Frozen copy of the runtime (bin/, dist/, package.json) in <git-dir>/stopbar/runtime. The hooks run this copy, so an
|
|
39
|
+
* agent that edits or rebuilds a Stopbar checkout cannot change the code that judges it. No node_modules needed. */
|
|
40
|
+
export function pinRuntime(r ) {
|
|
41
|
+
const dst = join(r.stateDir, 'runtime')
|
|
42
|
+
rmSync(dst, {recursive: true, force: true})
|
|
43
|
+
mkdirSync(dst, {recursive: true})
|
|
44
|
+
for (const n of ['bin', 'dist']) cpSync(join(PKG_ROOT, n), join(dst, n), {recursive: true})
|
|
45
|
+
for (const n of ['package.json', 'LICENSE']) if (existsSync(join(PKG_ROOT, n))) cpSync(join(PKG_ROOT, n), join(dst, n))
|
|
46
|
+
return dst
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ---------------------------------------------------------------- commands
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
export function init(o ) {
|
|
53
|
+
const repo = findRepo(o.get('repo') ?? process.cwd())
|
|
54
|
+
const buildCmd = o.get('build') ?? '', fullTestCmd = o.get('test') ?? ''
|
|
55
|
+
if (!buildCmd.trim() || !fullTestCmd.trim()) return {code: 1, msg: 'init needs --build "<cmd>" and --test "<cmd>"'}
|
|
56
|
+
for (const [k, v] of [['--build', buildCmd], ['--test', fullTestCmd]]) {
|
|
57
|
+
if (hasChain(v)) return {code: 1, msg: `${k} ${JSON.stringify(v)} has shell operators; put it in one script (e.g. an npm script) so its exit status is the gate`}
|
|
58
|
+
}
|
|
59
|
+
if (existsSync(paths(repo).config) && !o.has('force')) return {code: 1, msg: `already initialised (${paths(repo).config}); use --force to replace config and state`}
|
|
60
|
+
let cfg
|
|
61
|
+
try {
|
|
62
|
+
cfg = makeConfig({buildCmd, fullTestCmd, profile: o.get('profile'), maxRetries: o.int('max-retries', 3), cap: o.int('cap', 500), costPerCall: o.int('cost', 1)})
|
|
63
|
+
} catch (e) { if (e instanceof ConfigError) return {code: 1, msg: e.message}; throw e }
|
|
64
|
+
const hooksOpt = o.get('hooks')
|
|
65
|
+
const targets = hooksOpt === undefined ? [] : parseTargets(hooksOpt) // validated before anything is written
|
|
66
|
+
mkdirSync(repo.stateDir, {recursive: true})
|
|
67
|
+
return withLock(repo, () => {
|
|
68
|
+
writeConfig(repo, cfg)
|
|
69
|
+
writeState(repo, fresh(repo, cfg))
|
|
70
|
+
const pin = !o.has('no-pin')
|
|
71
|
+
const runtime = pin ? pinRuntime(repo) : PKG_ROOT
|
|
72
|
+
const command = hookCommand(runtime)
|
|
73
|
+
appendEvent(repo, {source: 'human:init', cfg, runtime, version: VERSION, kernel: MACHINE})
|
|
74
|
+
const lines = [`Stopbar ${VERSION} initialised in ${repo.stateDir}`, ` profile ${cfg.profile}; build: ${cfg.buildCmd}; full tests: ${cfg.fullTestCmd}`,
|
|
75
|
+
` hooks run: ${command}`]
|
|
76
|
+
if (targets.length) for (const l of installHooks(repo, targets, runtime, o.has('force-hooks'))) lines.push(` hooks written: ${l}`)
|
|
77
|
+
else lines.push(' add these hooks to .claude/settings.local.json (or run init again with --hooks claude,cursor,codex,gemini,antigravity,git):', JSON.stringify(hooksConfig(command), null, 2))
|
|
78
|
+
lines.push('Next: restart the agent in this repository and run `stopbar doctor`.')
|
|
79
|
+
return {code: 0, msg: lines.join('\n')}
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Why the secret gate is on: the first secret read since the last init or reset, from the event log. */
|
|
84
|
+
export function secretReason(repo ) {
|
|
85
|
+
const ev = readEvents(repo).events
|
|
86
|
+
let start = 0
|
|
87
|
+
ev.forEach((e, i) => { if (e.source === 'human:init' || e.source === 'human:reset') start = i + 1 })
|
|
88
|
+
const hit = ev.slice(start).find((e) => e.req?.op === 'READ_SECRET' && e.secretTainted === true)
|
|
89
|
+
if (!hit) return null
|
|
90
|
+
if (!hit.secret) return {text: `${hit.source} at rev ${hit.treeRev} (pattern not recorded)`, revision: hit.treeRev}
|
|
91
|
+
const {pattern, path, tool} = hit.secret
|
|
92
|
+
return {text: `matched ${pattern} (${path}) in ${tool} at rev ${hit.treeRev}`, pattern, path, tool, revision: hit.treeRev}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function statusText(repo , cfg , s ) {
|
|
96
|
+
const v = decode(s.kernel)
|
|
97
|
+
const yn = (b ) => (b ? 'yes' : 'no')
|
|
98
|
+
const ok = (rev ) => (rev === v.treeRev ? `ok at revision ${rev}` : 'not at the current revision')
|
|
99
|
+
const commit = v.halted ? 'blocked: session halted' : v.buildOkRev === v.treeRev && v.testsOkRev === v.treeRev && !v.testsTainted ? 'allowed' : `blocked: ${whyBlocked(v, cfg)}`
|
|
100
|
+
const torn = readEvents(repo).torn.length
|
|
101
|
+
return [
|
|
102
|
+
`Stopbar ${VERSION} repo ${repo.root}`,
|
|
103
|
+
`revision ${v.treeRev} (tree ${s.snapshot.slice(0, 12)})`,
|
|
104
|
+
`build ${ok(v.buildOkRev)} (${cfg.buildCmd})`,
|
|
105
|
+
`full tests ${ok(v.testsOkRev)} (${cfg.fullTestCmd})`,
|
|
106
|
+
`tainted ${yn(v.testsTainted)} secret read ${v.secretTainted ? `yes (${secretReason(repo)?.text ?? 'reason not in the event log'})` : 'no'} shell approval held ${yn(v.shellToken)}`,
|
|
107
|
+
`session ${v.halted ? 'HALTED' : 'running'} spent ${v.spent}/${v.capNow} test failures ${v.testFails}/${s.params.maxRetries} build failures ${v.buildFails}/${s.params.maxRetries}`,
|
|
108
|
+
`commit ${commit}`,
|
|
109
|
+
...(torn ? [`event log ${torn} torn line(s) kept as they are (see stopbar doctor)`] : []),
|
|
110
|
+
].join('\n')
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function human(cmd , o ) {
|
|
114
|
+
const repo = findRepo(o.get('repo') ?? process.cwd())
|
|
115
|
+
const cfg = readConfig(repo)
|
|
116
|
+
return withLock(repo, () => {
|
|
117
|
+
if (cmd === 'reset') {
|
|
118
|
+
writeState(repo, fresh(repo, cfg))
|
|
119
|
+
appendEvent(repo, {source: 'human:reset'})
|
|
120
|
+
return {code: 0, msg: 'Stopbar state reset: run the build and the full test suite again before a commit'}
|
|
121
|
+
}
|
|
122
|
+
const s = readState(repo)
|
|
123
|
+
if (cmd === 'status') {
|
|
124
|
+
return {code: 0, msg: o.has('json') ? JSON.stringify({version: VERSION, repo: repo.root, stateDir: repo.stateDir, config: cfg, snapshot: s.snapshot, params: s.params, kernel: decode(s.kernel),
|
|
125
|
+
secretRead: decode(s.kernel).secretTainted ? secretReason(repo) : null}, null, 1) : statusText(repo, cfg, s)}
|
|
126
|
+
}
|
|
127
|
+
let res
|
|
128
|
+
if (cmd === 'approve-tests') {
|
|
129
|
+
const cur = decode(s.kernel)
|
|
130
|
+
const rev = o.int('rev', cur.treeRev)
|
|
131
|
+
const after = humanStep(repo, s, {op: 'APPROVE_TESTS', approveRev: rev}, 'human:approve-tests')
|
|
132
|
+
res = after.decision === 'ALLOW' ? {code: 0, msg: `approved: test changes up to revision ${rev}; tainted=${after.testsTainted}`}
|
|
133
|
+
: {code: 1, msg: after.halted ? 'refused: the session is halted; run `stopbar resume` first' : `refused: revision ${rev} is not the current revision ${after.treeRev}`}
|
|
134
|
+
} else if (cmd === 'approve-shell') {
|
|
135
|
+
const after = humanStep(repo, s, {op: 'APPROVE_SHELL'}, 'human:approve-shell')
|
|
136
|
+
res = after.shellToken ? {code: 0, msg: 'approved: one risky or outbound call'} : {code: 1, msg: 'refused: the session is halted; run `stopbar resume` first'}
|
|
137
|
+
} else if (cmd === 'resume') {
|
|
138
|
+
const after = humanStep(repo, s, {op: 'RESUME', extra: o.int('extra', 0)}, 'human:resume')
|
|
139
|
+
res = {code: 0, msg: `resumed: budget ${after.spent}/${after.capNow}, failure counters reset`}
|
|
140
|
+
} else return {code: 1, msg: `unknown command ${cmd}`}
|
|
141
|
+
writeState(repo, s)
|
|
142
|
+
return res
|
|
143
|
+
})
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export const profiles = () => Object.keys(PROFILES)
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Built from src/config.ts by scripts/build.ts. Do not edit.
|
|
2
|
+
// config.json: gate commands, limits and path patterns. Lives in <git-dir>/stopbar/, out of the agent's reach.
|
|
3
|
+
import {globToRegExp} from './glob.js'
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
const TEST_COMMON = ['**/tests/**', '**/test/**', '**/__tests__/**']
|
|
20
|
+
const TEST_JS = ['**/*.test.*', '**/*.spec.*', '**/e2e/**']
|
|
21
|
+
const TEST_PY = ['**/test_*.py', '**/*_test.py']
|
|
22
|
+
const TEST_OTHER = ['**/*_test.go', '**/*_test.rs', '**/*Test.java', '**/*Tests.cs']
|
|
23
|
+
|
|
24
|
+
const CFG_COMMON = ['.gitignore', '.gitattributes', '.github/workflows/**', '.gitlab-ci.yml', '.pre-commit-config.yaml', 'Makefile']
|
|
25
|
+
const CFG_JS = ['package.json', 'tsconfig*.json', '.eslint*', 'eslint.config.*', 'vitest.config.*', 'vitest.workspace.*',
|
|
26
|
+
'jest.config.*', 'playwright.config.*', '.mocharc*', 'ava.config.*', 'biome.json', '.c8rc*', '.nycrc*']
|
|
27
|
+
const CFG_PY = ['pyproject.toml', 'pytest.ini', 'conftest.py', 'tox.ini', 'setup.cfg', 'noxfile.py', '.coveragerc',
|
|
28
|
+
'mypy.ini', '.mypy.ini', 'ruff.toml', '.ruff.toml']
|
|
29
|
+
const CFG_OTHER = ['Cargo.toml', 'go.mod']
|
|
30
|
+
|
|
31
|
+
const SECRETS = ['.env*', '*.pem', '*.key', '*.p12', '*.pfx', 'id_rsa*', 'id_ed25519*', 'id_ecdsa*', '**/secrets/**',
|
|
32
|
+
'**/.ssh/**', '*.kdbx', 'age-identity*', 'auth.json', 'credentials*.json', 'clerk-tokens.json', '.npmrc', '.pypirc', '.netrc']
|
|
33
|
+
|
|
34
|
+
/** Presets for `stopbar init --profile`. config.json keeps the expanded lists, so a team tunes them without code changes. */
|
|
35
|
+
export const PROFILES = {
|
|
36
|
+
default: {tests: [...TEST_COMMON, ...TEST_JS, ...TEST_PY, ...TEST_OTHER], testConfig: [...CFG_COMMON, ...CFG_JS, ...CFG_PY, ...CFG_OTHER], secrets: SECRETS},
|
|
37
|
+
ts: {tests: [...TEST_COMMON, ...TEST_JS], testConfig: [...CFG_COMMON, ...CFG_JS], secrets: SECRETS},
|
|
38
|
+
python: {tests: [...TEST_COMMON, ...TEST_PY], testConfig: [...CFG_COMMON, ...CFG_PY], secrets: SECRETS},
|
|
39
|
+
// strict: Python service with a quality script, a uv lock file and container-based checks; more config is suspicious
|
|
40
|
+
strict: {
|
|
41
|
+
tests: [...TEST_COMMON, ...TEST_PY],
|
|
42
|
+
testConfig: [...CFG_COMMON, ...CFG_PY, 'quality.sh', '**/quality*.sh', 'scripts/quality*', 'uv.lock', 'Dockerfile*', 'docker-compose*.yml', 'hypothesis*.ini'],
|
|
43
|
+
secrets: [...SECRETS, '*.age', 'secrets.*'],
|
|
44
|
+
},
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const DEFAULTS = {maxRetries: 3, cap: 500, costPerCall: 1}
|
|
48
|
+
// local UI tools of Claude Desktop (task list and turn summary): no network, no files
|
|
49
|
+
export const DEFAULT_SAFE_TOOLS = ['mcp__ccd_turn__*']
|
|
50
|
+
|
|
51
|
+
export class ConfigError extends Error {}
|
|
52
|
+
|
|
53
|
+
function isNat(x ) { return typeof x === 'number' && Number.isSafeInteger(x) && x >= 0 }
|
|
54
|
+
|
|
55
|
+
/** Validates a parsed config.json. Throws ConfigError with a precise reason. */
|
|
56
|
+
export function validateConfig(c ) {
|
|
57
|
+
if (!c || typeof c !== 'object' || Array.isArray(c)) throw new ConfigError('config.json must hold a JSON object')
|
|
58
|
+
const o = c
|
|
59
|
+
if (o.version !== 1) throw new ConfigError(`config.version must be 1, got ${JSON.stringify(o.version)}`)
|
|
60
|
+
for (const k of ['buildCmd', 'fullTestCmd'] ) {
|
|
61
|
+
if (typeof o[k] !== 'string' || !(o[k] ).trim()) throw new ConfigError(`config.${k} must be a non-empty string`)
|
|
62
|
+
}
|
|
63
|
+
for (const k of ['maxRetries', 'cap', 'costPerCall'] ) {
|
|
64
|
+
if (!isNat(o[k])) throw new ConfigError(`config.${k} must be a safe non-negative integer`)
|
|
65
|
+
}
|
|
66
|
+
if ((o.maxRetries ) < 1 || (o.cap ) < 1) throw new ConfigError('config.maxRetries and config.cap must be >= 1')
|
|
67
|
+
const p = o.paths
|
|
68
|
+
if (!p || typeof p !== 'object') throw new ConfigError('config.paths must be an object with tests, testConfig and secrets')
|
|
69
|
+
for (const k of ['tests', 'testConfig', 'secrets'] ) {
|
|
70
|
+
const list = p[k]
|
|
71
|
+
if (!Array.isArray(list) || !list.every((x) => typeof x === 'string' && x.length > 0)) throw new ConfigError(`config.paths.${k} must be a list of glob strings`)
|
|
72
|
+
for (const g of list ) {
|
|
73
|
+
try { globToRegExp(g) } catch (e) { throw new ConfigError(`config.paths.${k}: ${(e ).message}`) }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (typeof o.profile !== 'string') throw new ConfigError('config.profile must be a string')
|
|
77
|
+
if (o.safeTools !== undefined) {
|
|
78
|
+
if (!Array.isArray(o.safeTools) || !o.safeTools.every((x) => typeof x === 'string' && x.length > 0)) throw new ConfigError('config.safeTools must be a list of glob strings')
|
|
79
|
+
for (const g of o.safeTools ) {
|
|
80
|
+
try { globToRegExp(g) } catch (e) { throw new ConfigError(`config.safeTools: ${(e ).message}`) }
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return o
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function makeConfig(a ) {
|
|
87
|
+
const profile = a.profile ?? 'default'
|
|
88
|
+
const paths = PROFILES[profile]
|
|
89
|
+
if (!paths) throw new ConfigError(`unknown profile ${JSON.stringify(profile)}; known: ${Object.keys(PROFILES).join(', ')}`)
|
|
90
|
+
return validateConfig({
|
|
91
|
+
version: 1, profile, buildCmd: a.buildCmd.trim(), fullTestCmd: a.fullTestCmd.trim(),
|
|
92
|
+
maxRetries: a.maxRetries ?? DEFAULTS.maxRetries, cap: a.cap ?? DEFAULTS.cap, costPerCall: a.costPerCall ?? DEFAULTS.costPerCall,
|
|
93
|
+
paths: {tests: [...paths.tests], testConfig: [...paths.testConfig], secrets: [...paths.secrets]},
|
|
94
|
+
safeTools: [...DEFAULT_SAFE_TOOLS],
|
|
95
|
+
})
|
|
96
|
+
}
|
package/dist/doctor.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// Built from src/doctor.ts by scripts/build.ts. Do not edit.
|
|
2
|
+
// `stopbar doctor`: environment, configuration, state, hooks, and a dry run of the real hook pipeline on a scratch repo.
|
|
3
|
+
import {execFileSync} from 'node:child_process'
|
|
4
|
+
import {createHash} from 'node:crypto'
|
|
5
|
+
import {existsSync, mkdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs'
|
|
6
|
+
import {isAbsolute, join} from 'node:path'
|
|
7
|
+
import {hasChain} from './classify.js'
|
|
8
|
+
import {fresh, HOOK_MATCHERS} from './commands.js'
|
|
9
|
+
import {DEFAULT_SAFE_TOOLS, makeConfig} from './config.js'
|
|
10
|
+
import {decode, MACHINE} from './engine.js'
|
|
11
|
+
import {runHook} from './hook.js'
|
|
12
|
+
import {PKG_ROOT} from './pkg.js'
|
|
13
|
+
import {FailClosed, findRepo, } from './repo.js'
|
|
14
|
+
import {paths, readConfig, readEvents, readState, VERSION, writeConfig, writeState} from './store.js'
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
const sha = (f ) => createHash('sha256').update(readFileSync(f)).digest('hex')
|
|
18
|
+
|
|
19
|
+
function hooksIn(file ) {
|
|
20
|
+
if (!existsSync(file)) return null
|
|
21
|
+
try { return JSON.parse(readFileSync(file, 'utf8')).hooks ?? {} } catch { return {__invalid: []} }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function checkHooks(root , add ) {
|
|
25
|
+
const files = ['settings.json', 'settings.local.json'].map((n) => join(root, '.claude', n))
|
|
26
|
+
const merged = {}
|
|
27
|
+
for (const f of files) {
|
|
28
|
+
const h = hooksIn(f)
|
|
29
|
+
if (!h) continue
|
|
30
|
+
if ('__invalid' in h) { add('FAIL', 'hooks', `${f} is not valid JSON: Claude Code will not load the hooks`); continue }
|
|
31
|
+
for (const [ev, entries] of Object.entries(h)) {
|
|
32
|
+
for (const e of Array.isArray(entries) ? entries : []) {
|
|
33
|
+
for (const x of Array.isArray(e?.hooks) ? e.hooks : []) {
|
|
34
|
+
if (typeof x?.command === 'string' && /stopbar(\.mjs)?"?\s+hook\b/.test(x.command)) (merged[ev] ??= []).push({matcher: e.matcher, command: x.command, file: f})
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const covers = (m , tools ) => m === undefined || m === '*' || m === '' || tools.every((t) => new RegExp(`^(?:${m})$`).test(t))
|
|
40
|
+
const need = [['PreToolUse', ['Bash', 'Edit', 'Write', 'Read', 'WebFetch']], ['PostToolUse', HOOK_MATCHERS.post.split('|')],
|
|
41
|
+
['PostToolUseFailure', ['Bash', 'PowerShell']], ['Stop', []]]
|
|
42
|
+
for (const [ev, tools] of need) {
|
|
43
|
+
const hs = merged[ev] ?? []
|
|
44
|
+
if (!hs.length) { add('FAIL', `hook ${ev}`, `no Stopbar hook in ${files.join(' or ')}`); continue }
|
|
45
|
+
if (!hs.some((h) => covers(h.matcher, tools))) { add('FAIL', `hook ${ev}`, `matcher ${JSON.stringify(hs[0].matcher)} misses some of ${tools.join(', ')}`); continue }
|
|
46
|
+
const script = /node\s+"?([^"]+?stopbar\.mjs)"?\s+hook/.exec(hs[0].command)?.[1]
|
|
47
|
+
if (script && !existsSync(script)) { add('FAIL', `hook ${ev}`, `script not found: ${script}`); continue }
|
|
48
|
+
add('OK', `hook ${ev}`, `${hs[0].command} (${hs[0].file.replace(/\\/g, '/').split('/').slice(-2).join('/')})`)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const STOPBAR = /stopbar(\.mjs)?"?\s+(hook|git-hook)\b/
|
|
53
|
+
const scriptOf = (cmd ) => /node\s+"?([^"]+?stopbar\.mjs)"?\s+(?:git-)?hook/.exec(cmd)?.[1]
|
|
54
|
+
function readJsonOrInvalid(f ) {
|
|
55
|
+
if (!existsSync(f)) return null
|
|
56
|
+
try { return JSON.parse(readFileSync(f, 'utf8')) } catch { return 'invalid' }
|
|
57
|
+
}
|
|
58
|
+
/** Commands of Stopbar hooks per event, from any nesting of {command} objects under each event. */
|
|
59
|
+
function stopbarCommands(events ) {
|
|
60
|
+
const out = {}
|
|
61
|
+
const walk = (ev , x ) => {
|
|
62
|
+
if (Array.isArray(x)) { for (const y of x) walk(ev, y); return }
|
|
63
|
+
if (!x || typeof x !== 'object') return
|
|
64
|
+
const o = x
|
|
65
|
+
if (typeof o.command === 'string' && STOPBAR.test(o.command)) (out[ev] ??= []).push(o.command)
|
|
66
|
+
if (o.hooks) walk(ev, o.hooks)
|
|
67
|
+
}
|
|
68
|
+
for (const [ev, v] of Object.entries(events ?? {})) walk(ev, v)
|
|
69
|
+
return out
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Other clients and the git fallback. Returns how many have Stopbar hooks. */
|
|
73
|
+
function checkOtherClients(repo , add ) {
|
|
74
|
+
let found = 0
|
|
75
|
+
const clients = [
|
|
76
|
+
['cursor', join(repo.root, '.cursor', 'hooks.json'), (j) => j.hooks, ['preToolUse', 'postToolUse', 'postToolUseFailure', 'stop']],
|
|
77
|
+
['codex', join(repo.root, '.codex', 'hooks.json'), (j) => j.hooks, ['PreToolUse', 'PostToolUse', 'Stop']],
|
|
78
|
+
['gemini', join(repo.root, '.gemini', 'settings.json'), (j) => j.hooks, ['BeforeTool', 'AfterTool', 'AfterAgent']],
|
|
79
|
+
['antigravity', join(repo.root, '.agents', 'hooks.json'), (j) => Object.assign({}, ...Object.values(j).filter((v) => v && typeof v === 'object' && (v ).enabled !== false)), ['PreToolUse', 'PostToolUse', 'Stop']],
|
|
80
|
+
]
|
|
81
|
+
for (const [name, f, events, need] of clients) {
|
|
82
|
+
const j = readJsonOrInvalid(f)
|
|
83
|
+
if (j === null) continue
|
|
84
|
+
if (j === 'invalid') { add('FAIL', `hooks ${name}`, `${f} is not valid JSON`); found++; continue }
|
|
85
|
+
const cmds = stopbarCommands(events(j))
|
|
86
|
+
if (!Object.keys(cmds).length) continue
|
|
87
|
+
found++
|
|
88
|
+
const missing = need.filter((e) => !cmds[e]?.length)
|
|
89
|
+
const script = scriptOf(Object.values(cmds)[0][0])
|
|
90
|
+
if (missing.length) add('FAIL', `hooks ${name}`, `${f}: no Stopbar hook for ${missing.join(', ')}`)
|
|
91
|
+
else if (script && !existsSync(script)) add('FAIL', `hooks ${name}`, `script not found: ${script}`)
|
|
92
|
+
else if (name === 'cursor' && JSON.stringify(j.hooks).includes('"failClosed":false')) add('WARN', `hooks ${name}`, `${f}: failClosed is false, so a crash of the hook lets the action run`)
|
|
93
|
+
else add('OK', `hooks ${name}`, `${need.join(', ')} (${f.replace(/\\/g, '/').split('/').slice(-2).join('/')})`)
|
|
94
|
+
}
|
|
95
|
+
let dir = join(repo.gitDir, 'hooks')
|
|
96
|
+
try { const rel = execFileSync('git', ['rev-parse', '--git-path', 'hooks'], {cwd: repo.root, encoding: 'utf8'}).trim(); dir = isAbsolute(rel) ? rel : join(repo.root, rel) } catch { /* default */ }
|
|
97
|
+
const gh = ['pre-commit', 'pre-push'].filter((n) => existsSync(join(dir, n)) && readFileSync(join(dir, n), 'utf8').includes('stopbar.mjs" git-hook'))
|
|
98
|
+
if (gh.length) { found++; add(gh.length === 2 ? 'OK' : 'WARN', 'hooks git', `${gh.join(', ')} in ${dir}${gh.length === 2 ? '' : ' (one of pre-commit, pre-push is missing)'}`) }
|
|
99
|
+
return found
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The real hook pipeline (in process) on a scratch repository inside <git-dir>/stopbar/doctor-run. */
|
|
103
|
+
function dryRun(base , add ) {
|
|
104
|
+
const dir = join(base, 'doctor-run')
|
|
105
|
+
rmSync(dir, {recursive: true, force: true})
|
|
106
|
+
mkdirSync(join(dir, 'src'), {recursive: true}); mkdirSync(join(dir, 'tests'), {recursive: true})
|
|
107
|
+
const g = (...a ) => execFileSync('git', ['-c', 'user.name=stopbar-doctor', '-c', 'user.email=doctor@stopbar.invalid', '-c', 'commit.gpgsign=false', ...a], {cwd: dir, stdio: 'ignore'})
|
|
108
|
+
try {
|
|
109
|
+
writeFileSync(join(dir, 'src', 'a.mjs'), 'export const a = 1\n')
|
|
110
|
+
writeFileSync(join(dir, 'tests', 'a.test.mjs'), 'export {}\n')
|
|
111
|
+
g('init', '-q'); g('add', '-A'); g('commit', '-q', '-m', 'base')
|
|
112
|
+
const repo = findRepo(dir)
|
|
113
|
+
const cfg = makeConfig({buildCmd: 'node build.mjs', fullTestCmd: 'node --test'})
|
|
114
|
+
writeConfig(repo, cfg); writeState(repo, fresh(repo, cfg))
|
|
115
|
+
const hook = (ev , tool , ti , extra = {}) => runHook(JSON.stringify({hook_event_name: ev, tool_name: tool, tool_input: ti, cwd: dir, ...extra}))
|
|
116
|
+
const steps = [
|
|
117
|
+
['edit code is allowed', () => { const p = hook('PreToolUse', 'Write', {file_path: join(dir, 'src', 'a.mjs')}).code === 0; writeFileSync(join(dir, 'src', 'a.mjs'), 'export const a = 2\n'); return p && hook('PostToolUse', 'Write', {file_path: join(dir, 'src', 'a.mjs')}).code === 0 }],
|
|
118
|
+
['commit without build and tests is blocked (exit 2)', () => hook('PreToolUse', 'Bash', {command: 'git commit -m "x"'}).code === 2],
|
|
119
|
+
['passing build and full suite are recorded', () => hook('PostToolUse', 'Bash', {command: 'node build.mjs'}, {tool_response: {stdout: '', stderr: '', interrupted: false}}).code === 0 &&
|
|
120
|
+
hook('PostToolUse', 'Bash', {command: 'node --test'}, {tool_response: {stdout: '', stderr: '', interrupted: false}}).code === 0],
|
|
121
|
+
["safe heredoc commit git commit -m \"$(cat <<'EOF' ...)\" is allowed", () => hook('PreToolUse', 'Bash', {command: "git commit -m \"$(cat <<'EOF'\nFix a\n\nReviewed-by: Jane Doe <jane@example.invalid>\nEOF\n)\""}).code === 0],
|
|
122
|
+
['command substitution in a commit is blocked', () => hook('PreToolUse', 'Bash', {command: 'git commit -m "$(rm -rf /)"'}).code === 2],
|
|
123
|
+
['editing an existing test taints the session', () => { writeFileSync(join(dir, 'tests', 'a.test.mjs'), 'export {} // weakened\n'); return hook('PostToolUse', 'Edit', {file_path: join(dir, 'tests', 'a.test.mjs')}).code === 2 && decode(readState(repo).kernel).testsTainted === true }],
|
|
124
|
+
['writing .claude/settings.local.json is blocked', () => hook('PreToolUse', 'Write', {file_path: join(dir, '.claude', 'settings.local.json')}).code === 2],
|
|
125
|
+
['writing .git/hooks/pre-commit is blocked', () => hook('PreToolUse', 'Write', {file_path: join(dir, '.git', 'hooks', 'pre-commit')}).code === 2],
|
|
126
|
+
['a damaged state.json fails closed (exit 2)', () => { writeFileSync(paths(repo).state, '{"version": 2, "kern'); const r = hook('PreToolUse', 'Read', {file_path: join(dir, 'src', 'a.mjs')}); return r.code === 2 && /FAIL-CLOSED/.test(r.msg ?? '') }],
|
|
127
|
+
]
|
|
128
|
+
for (const [name, f] of steps) {
|
|
129
|
+
let ok = false
|
|
130
|
+
try { ok = f() } catch { ok = false }
|
|
131
|
+
add(ok ? 'OK' : 'FAIL', 'dry run', name)
|
|
132
|
+
}
|
|
133
|
+
} finally {
|
|
134
|
+
rmSync(dir, {recursive: true, force: true})
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function doctor(o ) {
|
|
139
|
+
const checks = []
|
|
140
|
+
const add = (status , name , detail ) => { checks.push({status, name, detail}) }
|
|
141
|
+
const [maj, min] = process.versions.node.split('.').map(Number)
|
|
142
|
+
add(maj > 22 || (maj === 22 && min >= 18) ? 'OK' : 'FAIL', 'node', `v${process.versions.node} (needs >= 22.18)`)
|
|
143
|
+
try { add('OK', 'git', execFileSync('git', ['--version'], {encoding: 'utf8'}).trim()) } catch { add('FAIL', 'git', 'git not found on PATH') }
|
|
144
|
+
add(MACHINE.name === 'stopbar_kernel_none' ? 'OK' : 'FAIL', 'kernel', `${MACHINE.name}, kernel.ts sha256 ${MACHINE.kernelSha256.slice(0, 16)}, machine sha256 ${MACHINE.machineSha256.slice(0, 16)}`)
|
|
145
|
+
if (existsSync(join(PKG_ROOT, 'node_modules', 'gdp-wired')) && existsSync(join(PKG_ROOT, 'dist', 'kernel.js'))) {
|
|
146
|
+
try {
|
|
147
|
+
const {checkGenerated} = await import('./verify.js')
|
|
148
|
+
const g = await checkGenerated(500)
|
|
149
|
+
add(g.ok ? 'OK' : 'FAIL', 'kernel link', `compileJs(kernel.ts) == dist/kernel.gen.js: ${g.sameMachine}; kernel.ts hash: ${g.sameSource}; ${(g.differential ).steps} steps vs interpreter, ${(g.differential ).mismatches} mismatches`)
|
|
150
|
+
} catch (e) { add('WARN', 'kernel link', `not checked: ${(e ).message}`) }
|
|
151
|
+
} else add('WARN', 'kernel link', 'gdp-wired not installed next to this copy (pinned runtime): run `stopbar prove` in the package')
|
|
152
|
+
|
|
153
|
+
let repo = null
|
|
154
|
+
try { repo = findRepo(o.repo ?? process.cwd()); add('OK', 'repository', `${repo.root} (state in ${repo.stateDir})`) } catch (e) { add('FAIL', 'repository', (e ).message) }
|
|
155
|
+
if (repo) {
|
|
156
|
+
let cfgOk = false
|
|
157
|
+
try {
|
|
158
|
+
const cfg = readConfig(repo); cfgOk = true
|
|
159
|
+
add('OK', 'config.json', `profile ${cfg.profile}; build \`${cfg.buildCmd}\`; full tests \`${cfg.fullTestCmd}\`; maxRetries ${cfg.maxRetries}; cap ${cfg.cap}; ` +
|
|
160
|
+
`${cfg.paths.tests.length}/${cfg.paths.testConfig.length}/${cfg.paths.secrets.length} test/config/secret patterns; safeTools ${JSON.stringify(cfg.safeTools ?? DEFAULT_SAFE_TOOLS)}`)
|
|
161
|
+
for (const [k, v] of [['buildCmd', cfg.buildCmd], ['fullTestCmd', cfg.fullTestCmd]]) if (hasChain(v)) add('FAIL', 'config.json', `${k} has shell operators: it can never pass as a gate`)
|
|
162
|
+
try {
|
|
163
|
+
const s = readState(repo), v = decode(s.kernel)
|
|
164
|
+
add(v.halted ? 'WARN' : 'OK', 'state.json', `revision ${v.treeRev}; ${v.halted ? 'HALTED' : 'running'}; spent ${v.spent}/${v.capNow}; tainted ${v.testsTainted}`)
|
|
165
|
+
if (s.params.maxRetries !== cfg.maxRetries || s.params.cap !== cfg.cap) add('WARN', 'state.json', `state params ${JSON.stringify(s.params)} differ from config; a human runs \`stopbar reset\` to apply the config`)
|
|
166
|
+
} catch (e) { add('FAIL', 'state.json', e instanceof FailClosed ? `${e.message}. Fix: ${e.fix}` : String(e)) }
|
|
167
|
+
} catch (e) { add('FAIL', 'config.json', e instanceof FailClosed ? `${e.message}. Fix: ${e.fix}` : String(e)) }
|
|
168
|
+
const ev = readEvents(repo)
|
|
169
|
+
add(ev.torn.length ? 'WARN' : 'OK', 'events.jsonl', `${ev.events.length} entries${ev.torn.length ? `; ${ev.torn.length} torn line(s) (crash mid-write) at line ${ev.torn.map((t) => t.line).join(', ')}: kept, later entries are intact` : ''}`)
|
|
170
|
+
const rt = join(repo.stateDir, 'runtime', 'dist', 'kernel.gen.js')
|
|
171
|
+
if (existsSync(rt)) {
|
|
172
|
+
const same = existsSync(join(PKG_ROOT, 'dist', 'kernel.gen.js')) && sha(rt) === sha(join(PKG_ROOT, 'dist', 'kernel.gen.js'))
|
|
173
|
+
add(same ? 'OK' : 'WARN', 'pinned runtime', `${join(repo.stateDir, 'runtime')}${same ? ' (same kernel as this package)' : ' differs from this package: a human runs `stopbar init --force ...` to re-pin'}`)
|
|
174
|
+
} else if (cfgOk) add('WARN', 'pinned runtime', 'none: hooks run an unpinned copy (init --no-pin)')
|
|
175
|
+
const others = checkOtherClients(repo, add)
|
|
176
|
+
const claudeHas = ['settings.json', 'settings.local.json'].some((n) => { const h = hooksIn(join(repo .root, '.claude', n)); return h !== null && Object.keys(stopbarCommands(h)).length > 0 })
|
|
177
|
+
if (claudeHas || others === 0) checkHooks(repo.root, add) // without any client hooks, report the Claude Code ones as missing (v1.0 output)
|
|
178
|
+
try { dryRun(repo.stateDir, add) } catch (e) { add('FAIL', 'dry run', String(e)) }
|
|
179
|
+
}
|
|
180
|
+
const fails = checks.filter((c) => c.status === 'FAIL').length, warns = checks.filter((c) => c.status === 'WARN').length
|
|
181
|
+
const msg = o.json ? JSON.stringify({version: VERSION, ok: fails === 0, fails, warns, checks}, null, 1)
|
|
182
|
+
: [`stopbar doctor (Stopbar ${VERSION})`, ...checks.map((c) => `[${c.status.padEnd(4)}] ${c.name.padEnd(18)} ${c.detail}`),
|
|
183
|
+
`RESULT: ${fails ? `FAIL (${fails} problem(s), ${warns} warning(s))` : `OK (${warns} warning(s))`}`].join('\n')
|
|
184
|
+
return {code: fails ? 1 : 0, msg}
|
|
185
|
+
}
|
package/dist/engine.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Built from src/engine.ts by scripts/build.ts. Do not edit.
|
|
2
|
+
// One step of the proven rule. The step function is generated by gdp-wired's compileJs from src/kernel.ts at build
|
|
3
|
+
// time (dist/kernel.gen.js): the same machine the prover checked, without loading the prover in a hook.
|
|
4
|
+
// `stopbar verify` and the test suite regenerate it and compare it byte for byte, and replay random runs
|
|
5
|
+
// against gdp-wired's interpreter. There is no hand-written copy of step() anywhere.
|
|
6
|
+
import * as G from './kernel.gen.js'
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
const DEF = {op: 'EDIT_CODE', cost: 0, passed: false, fullSuite: false, suspicious: false, risky: false, treeChanged: false, approveRev: 0, extra: 0}
|
|
15
|
+
|
|
16
|
+
export const MACHINE = {name: G.MACHINE_NAME, kernelSha256: G.KERNEL_SOURCE_SHA256, machineSha256: G.MACHINE_SHA256}
|
|
17
|
+
if (G.MACHINE_NAME !== 'stopbar_kernel_none') throw new Error(`kernel.gen.js holds ${G.MACHINE_NAME}, not the unmutated kernel`)
|
|
18
|
+
|
|
19
|
+
export function encodeInput(r ) {
|
|
20
|
+
const req = {...DEF, ...r}
|
|
21
|
+
const out = {}
|
|
22
|
+
for (const f of G.CODEC.inputs) {
|
|
23
|
+
const v = req[f.name]
|
|
24
|
+
if (f.kind === 'oneOf') {
|
|
25
|
+
const i = f.values .indexOf(v )
|
|
26
|
+
if (i < 0) throw new Error(`unknown ${f.name} ${JSON.stringify(v)}`)
|
|
27
|
+
out[f.name] = i
|
|
28
|
+
} else if (f.kind === 'bool') out[f.name] = v ? 1 : 0
|
|
29
|
+
else {
|
|
30
|
+
if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0) throw new Error(`${f.name} must be a safe non-negative integer, got ${v}`)
|
|
31
|
+
out[f.name] = v
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return out
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function decode(st ) {
|
|
38
|
+
const out = {}
|
|
39
|
+
for (const f of G.CODEC.state) {
|
|
40
|
+
const v = st.scalars[f.name]
|
|
41
|
+
out[f.name] = f.kind === 'bool' ? v === 1 : f.kind === 'oneOf' ? f.values [v] : v
|
|
42
|
+
}
|
|
43
|
+
return out
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function initKernel(p ) { return G.init(p) }
|
|
47
|
+
|
|
48
|
+
/** Pure step. Throws on an input outside the rule's assumptions (fail closed). */
|
|
49
|
+
export function kstep(p , st , r ) {
|
|
50
|
+
return G.step(p, G.fork(st), encodeInput(r))
|
|
51
|
+
}
|
package/dist/githook.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Built from src/githook.ts by scripts/build.ts. Do not edit.
|
|
2
|
+
// `stopbar git-hook pre-commit|pre-push`: the fallback gate for tools without their own hook system. Git runs it from
|
|
3
|
+
// .git/hooks; it goes through the same path as an agent's `git commit` / `git push` (the generated kernel step): the
|
|
4
|
+
// working tree is synced, then COMMIT must be allowed (passing build and full suite at this revision, no unapproved
|
|
5
|
+
// test changes); a push is also a risky outbound call, paused after a secret read without a human approval.
|
|
6
|
+
// Exit 0 lets git go on, exit 1 aborts the commit or push (git's convention).
|
|
7
|
+
import {runEvent} from './hook.js'
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
export function gitHook(which , o ) {
|
|
12
|
+
if (which !== 'pre-commit' && which !== 'pre-push') return {code: 1, msg: 'usage: stopbar git-hook pre-commit|pre-push'}
|
|
13
|
+
const out = runEvent({hook_event_name: 'PreToolUse', cwd: o.get('repo') ?? process.cwd(), tool_name: 'Bash',
|
|
14
|
+
tool_input: {command: which === 'pre-commit' ? 'git commit' : 'git push'}, stopbar: {adapter: 'git', rawKeys: [], event: which}})
|
|
15
|
+
if (out.code === 0) return {code: 0}
|
|
16
|
+
return {code: 1, msg: `stopbar ${which}: ${out.msg ?? 'blocked'}`}
|
|
17
|
+
}
|