stopbar 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,183 @@
1
+ // Built from src/classify.ts by scripts/build.ts. Do not edit.
2
+ // Deterministic classification rules of the wrapper: file paths and the text of a shell command. No AST.
3
+ // Everything here is enforced by the wrapper, not by the proof (see SECURITY.md).
4
+
5
+ import {matchAny, matchAnySuffix} from './glob.js'
6
+
7
+ const norm = (p ) => p.replace(/\\/g, '/')
8
+
9
+ export const isTestPath = (p , paths ) => matchAny(norm(p), paths.tests)
10
+ export const isTestConfigPath = (p , paths ) => matchAny(norm(p), paths.testConfig)
11
+ /** Secret by file name. Absolute paths match too (a pattern may match any suffix of the path). */
12
+ export const isSecretPath = (p , paths ) => matchAnySuffix(norm(p), paths.secrets)
13
+
14
+ // ---------------------------------------------------------------- safe heredoc commit
15
+ // The one form of command substitution the wrapper lets through, the way Claude Code writes commit messages:
16
+ // git commit [args] -m "$(cat <<'EOF'
17
+ // ...message...
18
+ // EOF
19
+ // )"
20
+ // The delimiter is in single quotes, so bash expands nothing in the body: no variables, no $(...), no backticks.
21
+ // The prefix before -m must be a plain git commit without operators; nothing may follow `)"`.
22
+ // Only spaces and tabs between tokens: a newline is a command separator in bash.
23
+ const HEREDOC_RE = /^([^\n]*?)[ \t]+-m[ \t]+"\$\(cat[ \t]*<<[ \t]*'([A-Za-z_][A-Za-z0-9_]*)'\n((?:[^\n]*\n)*?)\2\n\)"[ \t]*\n?$/
24
+
25
+
26
+
27
+ export function parseSafeHeredocCommit(cmd ) {
28
+ if (cmd.includes('\r') || cmd.includes('\0')) return null
29
+ const m = HEREDOC_RE.exec(cmd.replace(/^\s+/, ''))
30
+ if (!m) return null
31
+ const [, prefix, delimiter, message] = m
32
+ if (scanPlain(prefix).chain) return null
33
+ if (!COMMIT_ONLY_RE.test(prefix.trim())) return null
34
+ // the body may not contain the delimiter line (the lazy match already guarantees this; checked again for clarity)
35
+ if (message.split('\n').some((l) => l === delimiter)) return null
36
+ return {prefix: prefix.trim(), message: message.replace(/\n$/, ''), delimiter}
37
+ }
38
+
39
+ /** Shell scan as bash sees it: operators and redirections count only outside quotes. Inside '...' everything is literal.
40
+ * Inside "..." the escapes \" \\ \$ \` work, but $(...) and `...` still run, so they are a chain.
41
+ * An unterminated quote is a chain (fail closed). Outside quotes \x is a literal x. */
42
+ function scanPlain(cmd ) {
43
+ let q = ''
44
+ for (let i = 0; i < cmd.length; i++) {
45
+ const c = cmd[i], n = cmd[i + 1]
46
+ if (q === "'") { if (c === "'") q = ''; continue }
47
+ if (q === '"') {
48
+ if (c === '\\') { i++; continue }
49
+ if (c === '"') { q = ''; continue }
50
+ if (c === '`' || (c === '$' && n === '(')) return {chain: true, reason: 'command substitution inside double quotes'}
51
+ continue
52
+ }
53
+ if (c === '\\') { i++; continue }
54
+ if (c === "'" || c === '"') { q = c; continue }
55
+ if (c === '`' || (c === '$' && n === '(')) return {chain: true, reason: 'command substitution'}
56
+ if ('&|;<>\r\n'.includes(c)) return {chain: true, reason: `operator ${JSON.stringify(c)} outside quotes`}
57
+ }
58
+ return q ? {chain: true, reason: 'unterminated quote'} : {chain: false}
59
+ }
60
+
61
+ export function scanShell(cmd ) {
62
+ if (parseSafeHeredocCommit(cmd)) return {chain: false, heredoc: true}
63
+ return scanPlain(cmd)
64
+ }
65
+ export const hasChain = (cmd ) => scanShell(cmd).chain
66
+
67
+ // ---------------------------------------------------------------- risky / outbound shell
68
+ const NET_TOOLS = /\b(curl|wget|nc|ncat|netcat|socat|ssh|scp|sftp|rsync|ftp|tftp|telnet)\b/i
69
+ const PS_NET = /Invoke-WebRequest|Invoke-RestMethod|\biwr\b|\birm\b|Start-BitsTransfer|Net\.WebClient|System\.Net\.|Net\.Sockets/i
70
+ const INLINE_CODE = /\b(node|deno|bun)\s+(-e|--eval|-p|--print)\b|\bpython[0-9.]*\s+(-I\s+)?(-X\s+\S+\s+)?-c\b|\bperl\s+-e\b|\bruby\s+-e\b/i
71
+ const NET_WORDS = /https?:|fetch\(|\bnet\b|socket|urllib|requests|http\.client|dns|XMLHttpRequest|WebSocket/i
72
+ const OBFUSCATION = /base64\s+(-d|--decode)|FromBase64String|\beval\b|\biex\b|Invoke-Expression|-EncodedCommand|\bsh\s+-c\b|\bbash\s+-c\b/i
73
+ const PUBLISH = /\b(npm|pnpm|yarn)\s+publish\b|\btwine\s+upload\b|\bgit\s+(clone|fetch|pull|remote|ls-remote)\b|\bgh\s+(api|gist|release|pr|issue)\b/i
74
+
75
+ /** RISKY_OR_OUTBOUND: network tool, inline code with network words, obfuscation or publication. */
76
+ export function isRiskyShell(cmd ) {
77
+ return NET_TOOLS.test(cmd) || PS_NET.test(cmd) || (INLINE_CODE.test(cmd) && NET_WORDS.test(cmd)) ||
78
+ OBFUSCATION.test(cmd) || PUBLISH.test(cmd)
79
+ }
80
+
81
+ // ---------------------------------------------------------------- git commands
82
+ // git global options before the subcommand: -c k=v, -C dir, --git-dir=..., --work-tree ..., --no-pager, -p (values may be quoted)
83
+ const GIT_GLOBALS = String.raw`(?:\s+(?:-[cC]\s*(?:"[^"]*"|'[^']*'|\S+)|--(?:git-dir|work-tree|namespace|exec-path|config-env)(?:=|\s+)(?:"[^"]*"|'[^']*'|\S+)|--[\w-]+|-[A-Za-z]))*`
84
+ const gitSub = (sub , flags = 'i') => new RegExp(String.raw`\bgit(?:\.exe)?${GIT_GLOBALS}\s+(?:${sub})\b`, flags)
85
+ const COMMIT_RE = gitSub('commit|push'), PUSH_RE = gitSub('push'), CONFIG_RE = gitSub('config')
86
+ const COMMIT_ONLY_RE = new RegExp(String.raw`^git(?:\.exe)?${GIT_GLOBALS}\s+commit\b`, 'i')
87
+ const CONFIG_READ = /\s(--get|--get-all|--get-regexp|--list|-l|--show-origin|--show-scope|get|list)(\s|=|$)/i
88
+
89
+ /** Text a commit/push decision is made on: for a safe heredoc commit only the prefix (the message is data). */
90
+ const commandPart = (cmd ) => parseSafeHeredocCommit(cmd)?.prefix ?? cmd
91
+ export const isCommitCmd = (cmd ) => COMMIT_RE.test(commandPart(cmd))
92
+ export const isPushCmd = (cmd ) => PUSH_RE.test(commandPart(cmd))
93
+ export const isGitConfigWrite = (cmd ) => CONFIG_RE.test(cmd) && !CONFIG_READ.test(cmd)
94
+
95
+ // A runner counts only as a command word: `cat pytest.ini` or `vim jest.config.js` is not a test run (fuzzer find, seed 12).
96
+ const END = String.raw`(?![\w.\-/\\])`
97
+ const TEST_RUNNER = new RegExp([
98
+ String.raw`\bnode(?:\s+\S+)*?\s+--test${END}`,
99
+ String.raw`\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test(?![\w.\-/\\])`,
100
+ String.raw`(?:^|[\s;&|(])(?:npx\s+|pnpm\s+exec\s+|yarn\s+|uv\s+run\s+)?(?:vitest|jest|mocha|ava|py\.test|pytest|tox|nox)${END}`,
101
+ String.raw`\bplaywright\s+test${END}`,
102
+ String.raw`\bpython[0-9.]*(?:\s+\S+)*?\s+-m\s+(?:pytest|unittest)${END}`,
103
+ String.raw`\bgo\s+test${END}`, String.raw`\bcargo\s+test${END}`,
104
+ ].join('|'), 'i')
105
+ export const looksLikeTests = (cmd ) => TEST_RUNNER.test(cmd)
106
+
107
+ /** Secret paths named in a command (e.g. `cat .env`, `type secrets\\db.txt`). */
108
+ export function mentionsSecret(cmd , paths ) {
109
+ return cmd.split(/[\s'"=(),;|&<>@:]+/).filter(Boolean).some((tok) => isSecretPath(tok, paths))
110
+ }
111
+
112
+
113
+
114
+
115
+
116
+
117
+
118
+ /** Exact match of gate commands: no chain operators, no extra arguments. `shell` is 'bash' or 'powershell'. */
119
+ export function classifyBash(cmd , cfg , shell = 'bash') {
120
+ const c = cmd.trim()
121
+ const scan = shell === 'bash' ? scanShell(c) : scanPlain(c)
122
+ if (COMMIT_RE.test(scan.heredoc ? commandPart(c) : c)) {
123
+ if (scan.chain) return {kind: 'commit-chained', reason: scan.reason ?? 'chain'}
124
+ return {kind: 'commit', heredoc: !!scan.heredoc, push: isPushCmd(c)}
125
+ }
126
+ // a gate command with operators (`node --test; echo $?`, `|| true`, `| tail`) hides its exit status: blocked in PreToolUse
127
+ if (scan.chain) {
128
+ for (const g of [cfg.fullTestCmd.trim(), cfg.buildCmd.trim()]) if (g && c.includes(g)) return {kind: 'gate-chained', gate: g, reason: scan.reason ?? 'chain'}
129
+ } else {
130
+ if (c === cfg.buildCmd.trim()) return {kind: 'build'}
131
+ if (c === cfg.fullTestCmd.trim()) return {kind: 'fulltest'}
132
+ }
133
+ return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: mentionsSecret(c, cfg.paths)}
134
+ }
135
+
136
+ /** Kind of a tree change from a list of (status, path) and a test for "the path exists in HEAD". */
137
+ export function classifyTreeChange(changes , inHead , paths ) {
138
+ let anyTest = false, suspicious = false
139
+ const why = []
140
+ for (const {status, path} of changes) {
141
+ if (isTestConfigPath(path, paths)) { anyTest = true; suspicious = true; why.push(`config ${status} ${path}`); continue }
142
+ if (isTestPath(path, paths)) {
143
+ anyTest = true
144
+ if (inHead(path)) { suspicious = true; why.push(`existing test ${status} ${path}`) } else why.push(`new test ${status} ${path}`)
145
+ }
146
+ }
147
+ return {op: anyTest ? 'EDIT_TEST' : 'EDIT_CODE' , suspicious, why}
148
+ }
149
+
150
+ // ---------------------------------------------------------------- self-protection
151
+ // Unconditional BLOCK in PreToolUse, outside the kernel. Paths are compared normalised: '/' separators, lower case.
152
+
153
+
154
+ const lc = (p ) => norm(p).toLowerCase().replace(/\/+$/, '')
155
+ const under = (a , dir ) => a === dir || a.startsWith(dir + '/')
156
+
157
+ /** File path written by an Edit/Write tool. Returns the reason for a block, or null. */
158
+ export function protectedPath(abs , root , pr ) {
159
+ const a = lc(abs), r = lc(root)
160
+ // inside the repository the .git test runs on the relative path; outside it on the whole path (other repositories)
161
+ const tail = under(a, r) ? a.slice(r.length) : a
162
+ if (/(^|\/)\.git(\/|$)/.test(tail) || under(a, lc(pr.gitDir)) || under(a, lc(pr.stateDir))) return 'git metadata (.git/**, Stopbar state, git hooks, git config)'
163
+ if (/(^|\/)\.claude\/[^/]*settings[^/]*\.json$/.test(a)) return 'Claude Code settings (.claude/settings*.json) hold the Stopbar hooks'
164
+ for (const d of pr.codeDirs) if (under(a, lc(d))) return `Stopbar code (${d})`
165
+ return null
166
+ }
167
+
168
+ const SEG = (name ) => new RegExp(String.raw`(^|[^a-z0-9_.\-])${name.replace(/\./g, '\\.')}([^a-z0-9_\-]|$)`, 'i')
169
+ const DOT_GIT = SEG('.git'), DOT_CLAUDE = SEG('.claude')
170
+ const HUMAN_ONLY = /\b(approve-tests|approve-shell)\b|\bSTOPBAR_[A-Z_]+/i
171
+ const STOPBAR_ADMIN = /stopbar[^\n]*\b(init|resume|reset|doctor\s+--fix)\b/i
172
+
173
+ /** Shell command text. Returns the reason for a block, or null. Text matching only: see SECURITY.md. */
174
+ export function protectedCommand(cmd , pr ) {
175
+ const c = norm(cmd).toLowerCase()
176
+ if (DOT_GIT.test(c)) return 'the command names a .git directory (Stopbar state, git hooks, git config live there)'
177
+ if (DOT_CLAUDE.test(c)) return 'the command names a .claude directory (Claude Code settings hold the Stopbar hooks)'
178
+ if (isGitConfigWrite(cmd)) return '`git config` writes .git/config; only reads (--get, --list) are allowed'
179
+ if (c.includes(lc(pr.stateDir)) || c.includes(lc(pr.gitDir) + '/')) return 'the command names the git directory'
180
+ for (const d of pr.codeDirs) if (c.includes(lc(d))) return `the command names Stopbar code (${d})`
181
+ if (HUMAN_ONLY.test(cmd) || STOPBAR_ADMIN.test(cmd)) return 'human-only Stopbar command or setting'
182
+ return null
183
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,78 @@
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 local|project] [--no-pin] [--force] [--repo <dir>]
14
+ stopbar hook Claude Code hook (JSON on stdin): PreToolUse, PostToolUse, PostToolUseFailure, Stop
15
+ stopbar status [--json] gates, taint, budget, why a commit is blocked
16
+ stopbar approve-tests [--rev N] a human reviewed the changed tests/config up to revision N (default: current)
17
+ stopbar approve-shell a human allows ONE risky or outbound call after a secret was read
18
+ stopbar resume --extra N a human lifts a halt and adds N to the budget
19
+ stopbar reset a human starts a fresh kernel state (config and event log stay)
20
+ stopbar doctor [--json] environment, config, state, hooks and a dry run
21
+
22
+ Four pillars:
23
+ PROVE stopbar prove [--out f.json] [--lean f.lean] inductive proof of the kernel and the 10 mutants
24
+ (npm run verify:lean checks the Lean export with lake build in Docker)
25
+ PROBE stopbar probe [--target wrapper] [--runs 200] [--seed 1] [--jobs N] [--work dir] [--out dir]
26
+ stateful probing of the hooks against the proven kernel on real git repositories
27
+ GATE init, hook, status, approve-tests, approve-shell, resume, reset, doctor (above)
28
+ ATTEST stopbar attest [--format json|md] deterministic attestation: HEAD, tree, gates, human actions, log sha256
29
+ All commands take --repo <dir> (default: the current directory). 'verify' is an alias of 'prove'.`
30
+
31
+ function opts(a ) {
32
+ const get = (name ) => { const i = a.indexOf(`--${name}`); return i >= 0 && i + 1 < a.length ? a[i + 1] : undefined }
33
+ return {
34
+ get, has: (name ) => a.includes(`--${name}`),
35
+ int: (name , def ) => {
36
+ const raw = get(name); if (raw === undefined) return def
37
+ const n = Number(raw); if (!/^\d+$/.test(raw) || !Number.isSafeInteger(n)) throw new Error(`--${name} must be a non-negative integer`)
38
+ return n
39
+ },
40
+ }
41
+ }
42
+
43
+ async function main() {
44
+ if (cmd === 'hook') {
45
+ const {runHook} = await import('./hook.js')
46
+ let raw
47
+ try { raw = readFileSync(0, 'utf8') } catch (e) { return {code: 2, msg: `STOPBAR FAIL-CLOSED: cannot read stdin (${(e ).message})`} }
48
+ return runHook(raw, t0)
49
+ }
50
+ if (cmd === 'help' || cmd === '--help' || cmd === '-h') return {code: 0, msg: HELP}
51
+ if (cmd === '--version' || cmd === 'version') return {code: 0, msg: VERSION}
52
+ const o = opts(argv.slice(1))
53
+ if (cmd === 'init') return (await import('./commands.js')).init(o)
54
+ if (['status', 'approve-tests', 'approve-shell', 'resume', 'reset'].includes(cmd)) return (await import('./commands.js')).human(cmd, o)
55
+ if (cmd === 'doctor') return (await import('./doctor.js')).doctor({repo: o.get('repo'), json: o.has('json')})
56
+ if (cmd === 'prove' || cmd === 'verify') {
57
+ const r = await (await import('./verify.js')).verify({out: o.get('out'), lean: o.get('lean')})
58
+ return {code: r.ok ? 0 : 1}
59
+ }
60
+ if (cmd === 'probe') {
61
+ const P = await import('./probe/index.js')
62
+ if (o.has('worker')) { await P.worker(JSON.parse(o.get('worker') )); return {code: 0} }
63
+ const num = (n ) => (o.get(n) === undefined ? undefined : o.int(n, 0))
64
+ 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'),
65
+ regressions: o.get('regressions'), regressionsOnly: o.has('regressions-only')})
66
+ return {code: r.ok ? 0 : 1}
67
+ }
68
+ if (cmd === 'attest') return (await import('./attest.js')).attest({repo: o.get('repo'), format: o.get('format')})
69
+ return {code: 1, msg: `unknown command ${cmd}\n\n${HELP}`}
70
+ }
71
+
72
+ let res
73
+ try { res = await main() } catch (e) {
74
+ const {failMsg} = await import('./hook.js')
75
+ res = {code: 2, msg: failMsg(e)}
76
+ }
77
+ if (res.msg) (res.code === 0 ? process.stdout : process.stderr).write(res.msg + '\n')
78
+ process.exitCode = res.code
@@ -0,0 +1,164 @@
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, readFileSync, rmSync, writeFileSync} from 'node:fs'
5
+ import {dirname, join} from 'node:path'
6
+ import {hasChain} from './classify.js'
7
+ import { ConfigError, makeConfig, PROFILES} from './config.js'
8
+ import {decode, initKernel, kstep, MACHINE, } from './engine.js'
9
+ import {whyBlocked} from './hook.js'
10
+ import {PKG_ROOT} from './pkg.js'
11
+ import {FailClosed, findRepo, forgetSnapshots, markCounted, snapshot} from './repo.js'
12
+ import {appendEvent, paths, readConfig, readEvents, readState, VERSION, withLock, writeConfig, writeState} from './store.js'
13
+
14
+
15
+
16
+ export function fresh(r , c ) {
17
+ forgetSnapshots(r)
18
+ const params = {maxRetries: c.maxRetries, cap: c.cap}
19
+ const snap = snapshot(r)
20
+ markCounted(r)
21
+ return {version: 2, kernel: initKernel(params), snapshot: snap.id, params}
22
+ }
23
+
24
+ function humanStep(r , s , req , source ) {
25
+ s.kernel = kstep(s.params, s.kernel, req)
26
+ const after = decode(s.kernel)
27
+ appendEvent(r, {source, req, decision: after.decision, halted: after.halted, testsTainted: after.testsTainted,
28
+ shellToken: after.shellToken, treeRev: after.treeRev, spent: after.spent, capNow: after.capNow,
29
+ testFails: after.testFails, buildFails: after.buildFails})
30
+ return after
31
+ }
32
+
33
+ // ---------------------------------------------------------------- hooks config
34
+ export const HOOK_MATCHERS = {post: 'Edit|Write|MultiEdit|NotebookEdit|Bash|PowerShell'}
35
+ export function hookCommand(runtimeRoot ) {
36
+ return `node "${join(runtimeRoot, 'bin', 'stopbar.mjs').replace(/\\/g, '/')}" hook`
37
+ }
38
+ export function hooksConfig(command ) {
39
+ const h = (timeout ) => [{type: 'command', command, timeout}]
40
+ return {
41
+ hooks: {
42
+ PreToolUse: [{matcher: '*', hooks: h(30)}],
43
+ PostToolUse: [{matcher: HOOK_MATCHERS.post, hooks: h(60)}],
44
+ PostToolUseFailure: [{matcher: HOOK_MATCHERS.post, hooks: h(60)}],
45
+ Stop: [{hooks: h(30)}],
46
+ },
47
+ }
48
+ }
49
+ const isStopbarHook = (x ) => Array.isArray(x?.hooks) && x.hooks.some((y ) => typeof y?.command === 'string' && /stopbar(\.mjs)?"?\s+hook\b/.test(y.command))
50
+
51
+ /** Merges the Stopbar hooks into .claude/settings(.local).json of the repository. Other keys and hooks stay. */
52
+ export function writeHooks(root , which , command ) {
53
+ const f = join(root, '.claude', which === 'local' ? 'settings.local.json' : 'settings.json')
54
+ let cur = {}
55
+ if (existsSync(f)) {
56
+ const raw = readFileSync(f, 'utf8')
57
+ try { cur = raw.trim() ? JSON.parse(raw) : {} } catch (e) { throw new FailClosed(`${f} is not valid JSON (${(e ).message}); not overwriting it`, 'fix the file by hand, then run init again') }
58
+ }
59
+ const want = hooksConfig(command).hooks
60
+ cur.hooks = cur.hooks && typeof cur.hooks === 'object' ? cur.hooks : {}
61
+ for (const [ev, entries] of Object.entries(want)) {
62
+ const kept = Array.isArray(cur.hooks[ev]) ? cur.hooks[ev].filter((x ) => !isStopbarHook(x)) : []
63
+ cur.hooks[ev] = [...kept, ...entries]
64
+ }
65
+ mkdirSync(dirname(f), {recursive: true})
66
+ writeFileSync(f, JSON.stringify(cur, null, 2) + '\n')
67
+ return f
68
+ }
69
+
70
+ /** Frozen copy of the runtime (bin/, dist/, package.json) in <git-dir>/stopbar/runtime. The hooks run this copy, so an
71
+ * agent that edits or rebuilds a Stopbar checkout cannot change the code that judges it. No node_modules needed. */
72
+ export function pinRuntime(r ) {
73
+ const dst = join(r.stateDir, 'runtime')
74
+ rmSync(dst, {recursive: true, force: true})
75
+ mkdirSync(dst, {recursive: true})
76
+ for (const n of ['bin', 'dist']) cpSync(join(PKG_ROOT, n), join(dst, n), {recursive: true})
77
+ for (const n of ['package.json', 'LICENSE']) if (existsSync(join(PKG_ROOT, n))) cpSync(join(PKG_ROOT, n), join(dst, n))
78
+ return dst
79
+ }
80
+
81
+ // ---------------------------------------------------------------- commands
82
+
83
+
84
+ export function init(o ) {
85
+ const repo = findRepo(o.get('repo') ?? process.cwd())
86
+ const buildCmd = o.get('build') ?? '', fullTestCmd = o.get('test') ?? ''
87
+ if (!buildCmd.trim() || !fullTestCmd.trim()) return {code: 1, msg: 'init needs --build "<cmd>" and --test "<cmd>"'}
88
+ for (const [k, v] of [['--build', buildCmd], ['--test', fullTestCmd]]) {
89
+ 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`}
90
+ }
91
+ if (existsSync(paths(repo).config) && !o.has('force')) return {code: 1, msg: `already initialised (${paths(repo).config}); use --force to replace config and state`}
92
+ let cfg
93
+ try {
94
+ cfg = makeConfig({buildCmd, fullTestCmd, profile: o.get('profile'), maxRetries: o.int('max-retries', 3), cap: o.int('cap', 500), costPerCall: o.int('cost', 1)})
95
+ } catch (e) { if (e instanceof ConfigError) return {code: 1, msg: e.message}; throw e }
96
+ mkdirSync(repo.stateDir, {recursive: true})
97
+ return withLock(repo, () => {
98
+ writeConfig(repo, cfg)
99
+ writeState(repo, fresh(repo, cfg))
100
+ const pin = !o.has('no-pin')
101
+ const runtime = pin ? pinRuntime(repo) : PKG_ROOT
102
+ const command = hookCommand(runtime)
103
+ appendEvent(repo, {source: 'human:init', cfg, runtime, version: VERSION, kernel: MACHINE})
104
+ const lines = [`Stopbar ${VERSION} initialised in ${repo.stateDir}`, ` profile ${cfg.profile}; build: ${cfg.buildCmd}; full tests: ${cfg.fullTestCmd}`,
105
+ ` hooks run: ${command}`]
106
+ const which = o.get('hooks')
107
+ if (which === 'local' || which === 'project') lines.push(` hooks written to ${writeHooks(repo.root, which, command)}`)
108
+ else lines.push(' add these hooks to .claude/settings.local.json (or run init again with --hooks local):', JSON.stringify(hooksConfig(command), null, 2))
109
+ lines.push('Next: restart Claude Code in this repository and run `stopbar doctor`.')
110
+ return {code: 0, msg: lines.join('\n')}
111
+ })
112
+ }
113
+
114
+ function statusText(repo , cfg , s ) {
115
+ const v = decode(s.kernel)
116
+ const yn = (b ) => (b ? 'yes' : 'no')
117
+ const ok = (rev ) => (rev === v.treeRev ? `ok at revision ${rev}` : 'not at the current revision')
118
+ const commit = v.halted ? 'blocked: session halted' : v.buildOkRev === v.treeRev && v.testsOkRev === v.treeRev && !v.testsTainted ? 'allowed' : `blocked: ${whyBlocked(v, cfg)}`
119
+ const torn = readEvents(repo).torn.length
120
+ return [
121
+ `Stopbar ${VERSION} repo ${repo.root}`,
122
+ `revision ${v.treeRev} (tree ${s.snapshot.slice(0, 12)})`,
123
+ `build ${ok(v.buildOkRev)} (${cfg.buildCmd})`,
124
+ `full tests ${ok(v.testsOkRev)} (${cfg.fullTestCmd})`,
125
+ `tainted ${yn(v.testsTainted)} secret read ${yn(v.secretTainted)} shell approval held ${yn(v.shellToken)}`,
126
+ `session ${v.halted ? 'HALTED' : 'running'} spent ${v.spent}/${v.capNow} test failures ${v.testFails}/${s.params.maxRetries} build failures ${v.buildFails}/${s.params.maxRetries}`,
127
+ `commit ${commit}`,
128
+ ...(torn ? [`event log ${torn} torn line(s) kept as they are (see stopbar doctor)`] : []),
129
+ ].join('\n')
130
+ }
131
+
132
+ export function human(cmd , o ) {
133
+ const repo = findRepo(o.get('repo') ?? process.cwd())
134
+ const cfg = readConfig(repo)
135
+ return withLock(repo, () => {
136
+ if (cmd === 'reset') {
137
+ writeState(repo, fresh(repo, cfg))
138
+ appendEvent(repo, {source: 'human:reset'})
139
+ return {code: 0, msg: 'Stopbar state reset: run the build and the full test suite again before a commit'}
140
+ }
141
+ const s = readState(repo)
142
+ if (cmd === 'status') {
143
+ 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)}, null, 1) : statusText(repo, cfg, s)}
144
+ }
145
+ let res
146
+ if (cmd === 'approve-tests') {
147
+ const cur = decode(s.kernel)
148
+ const rev = o.int('rev', cur.treeRev)
149
+ const after = humanStep(repo, s, {op: 'APPROVE_TESTS', approveRev: rev}, 'human:approve-tests')
150
+ res = after.decision === 'ALLOW' ? {code: 0, msg: `approved: test changes up to revision ${rev}; tainted=${after.testsTainted}`}
151
+ : {code: 1, msg: after.halted ? 'refused: the session is halted; run `stopbar resume` first' : `refused: revision ${rev} is not the current revision ${after.treeRev}`}
152
+ } else if (cmd === 'approve-shell') {
153
+ const after = humanStep(repo, s, {op: 'APPROVE_SHELL'}, 'human:approve-shell')
154
+ res = after.shellToken ? {code: 0, msg: 'approved: one risky or outbound call'} : {code: 1, msg: 'refused: the session is halted; run `stopbar resume` first'}
155
+ } else if (cmd === 'resume') {
156
+ const after = humanStep(repo, s, {op: 'RESUME', extra: o.int('extra', 0)}, 'human:resume')
157
+ res = {code: 0, msg: `resumed: budget ${after.spent}/${after.capNow}, failure counters reset`}
158
+ } else return {code: 1, msg: `unknown command ${cmd}`}
159
+ writeState(repo, s)
160
+ return res
161
+ })
162
+ }
163
+
164
+ export const profiles = () => Object.keys(PROFILES)
package/dist/config.js ADDED
@@ -0,0 +1,85 @@
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
+ const TEST_COMMON = ['**/tests/**', '**/test/**', '**/__tests__/**']
18
+ const TEST_JS = ['**/*.test.*', '**/*.spec.*', '**/e2e/**']
19
+ const TEST_PY = ['**/test_*.py', '**/*_test.py']
20
+ const TEST_OTHER = ['**/*_test.go', '**/*_test.rs', '**/*Test.java', '**/*Tests.cs']
21
+
22
+ const CFG_COMMON = ['.gitignore', '.gitattributes', '.github/workflows/**', '.gitlab-ci.yml', '.pre-commit-config.yaml', 'Makefile']
23
+ const CFG_JS = ['package.json', 'tsconfig*.json', '.eslint*', 'eslint.config.*', 'vitest.config.*', 'vitest.workspace.*',
24
+ 'jest.config.*', 'playwright.config.*', '.mocharc*', 'ava.config.*', 'biome.json', '.c8rc*', '.nycrc*']
25
+ const CFG_PY = ['pyproject.toml', 'pytest.ini', 'conftest.py', 'tox.ini', 'setup.cfg', 'noxfile.py', '.coveragerc',
26
+ 'mypy.ini', '.mypy.ini', 'ruff.toml', '.ruff.toml']
27
+ const CFG_OTHER = ['Cargo.toml', 'go.mod']
28
+
29
+ const SECRETS = ['.env*', '*.pem', '*.key', '*.p12', '*.pfx', 'id_rsa*', 'id_ed25519*', 'id_ecdsa*', '**/secrets/**',
30
+ '**/.ssh/**', '*.kdbx', 'age-identity*', 'auth.json', 'credentials*.json', 'clerk-tokens.json', '.npmrc', '.pypirc', '.netrc']
31
+
32
+ /** Presets for `stopbar init --profile`. config.json keeps the expanded lists, so a team tunes them without code changes. */
33
+ export const PROFILES = {
34
+ default: {tests: [...TEST_COMMON, ...TEST_JS, ...TEST_PY, ...TEST_OTHER], testConfig: [...CFG_COMMON, ...CFG_JS, ...CFG_PY, ...CFG_OTHER], secrets: SECRETS},
35
+ ts: {tests: [...TEST_COMMON, ...TEST_JS], testConfig: [...CFG_COMMON, ...CFG_JS], secrets: SECRETS},
36
+ python: {tests: [...TEST_COMMON, ...TEST_PY], testConfig: [...CFG_COMMON, ...CFG_PY], secrets: SECRETS},
37
+ // strict: Python service with a quality script, a uv lock file and container-based checks; more config is suspicious
38
+ strict: {
39
+ tests: [...TEST_COMMON, ...TEST_PY],
40
+ testConfig: [...CFG_COMMON, ...CFG_PY, 'quality.sh', '**/quality*.sh', 'scripts/quality*', 'uv.lock', 'Dockerfile*', 'docker-compose*.yml', 'hypothesis*.ini'],
41
+ secrets: [...SECRETS, '*.age', 'secrets.*'],
42
+ },
43
+ }
44
+
45
+ export const DEFAULTS = {maxRetries: 3, cap: 500, costPerCall: 1}
46
+
47
+ export class ConfigError extends Error {}
48
+
49
+ function isNat(x ) { return typeof x === 'number' && Number.isSafeInteger(x) && x >= 0 }
50
+
51
+ /** Validates a parsed config.json. Throws ConfigError with a precise reason. */
52
+ export function validateConfig(c ) {
53
+ if (!c || typeof c !== 'object' || Array.isArray(c)) throw new ConfigError('config.json must hold a JSON object')
54
+ const o = c
55
+ if (o.version !== 1) throw new ConfigError(`config.version must be 1, got ${JSON.stringify(o.version)}`)
56
+ for (const k of ['buildCmd', 'fullTestCmd'] ) {
57
+ if (typeof o[k] !== 'string' || !(o[k] ).trim()) throw new ConfigError(`config.${k} must be a non-empty string`)
58
+ }
59
+ for (const k of ['maxRetries', 'cap', 'costPerCall'] ) {
60
+ if (!isNat(o[k])) throw new ConfigError(`config.${k} must be a safe non-negative integer`)
61
+ }
62
+ if ((o.maxRetries ) < 1 || (o.cap ) < 1) throw new ConfigError('config.maxRetries and config.cap must be >= 1')
63
+ const p = o.paths
64
+ if (!p || typeof p !== 'object') throw new ConfigError('config.paths must be an object with tests, testConfig and secrets')
65
+ for (const k of ['tests', 'testConfig', 'secrets'] ) {
66
+ const list = p[k]
67
+ 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`)
68
+ for (const g of list ) {
69
+ try { globToRegExp(g) } catch (e) { throw new ConfigError(`config.paths.${k}: ${(e ).message}`) }
70
+ }
71
+ }
72
+ if (typeof o.profile !== 'string') throw new ConfigError('config.profile must be a string')
73
+ return o
74
+ }
75
+
76
+ export function makeConfig(a ) {
77
+ const profile = a.profile ?? 'default'
78
+ const paths = PROFILES[profile]
79
+ if (!paths) throw new ConfigError(`unknown profile ${JSON.stringify(profile)}; known: ${Object.keys(PROFILES).join(', ')}`)
80
+ return validateConfig({
81
+ version: 1, profile, buildCmd: a.buildCmd.trim(), fullTestCmd: a.fullTestCmd.trim(),
82
+ maxRetries: a.maxRetries ?? DEFAULTS.maxRetries, cap: a.cap ?? DEFAULTS.cap, costPerCall: a.costPerCall ?? DEFAULTS.costPerCall,
83
+ paths: {tests: [...paths.tests], testConfig: [...paths.testConfig], secrets: [...paths.secrets]},
84
+ })
85
+ }