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.
@@ -0,0 +1,63 @@
1
+ // Built from src/adapters/cursor.ts by scripts/build.ts. Do not edit.
2
+ // Cursor (.cursor/hooks.json, version 1). Every payload carries conversation_id, generation_id and cursor_version.
3
+ // Events: preToolUse / postToolUse / postToolUseFailure / stop, and the older beforeShellExecution, beforeMCPExecution,
4
+ // beforeReadFile, afterFileEdit, afterShellExecution. Permission events: exit 2 denies, and the JSON on stdout carries
5
+ // permission "deny" with user_message and agent_message. Other non-zero exits are fail-open unless the entry sets
6
+ // failClosed: true, so `stopbar init --hooks cursor` writes failClosed: true.
7
+ import { byName, commandText, edit, exitCodeIn, json, make, outbound, pathsOf, read, shell, } from './types.js'
8
+
9
+ function tool(name , ti ) {
10
+ if (name === 'Shell') return shell(commandText(ti.command))
11
+ if (name === 'Read') return read(pathsOf(ti))
12
+ if (['Write', 'Edit', 'Delete', 'StrReplace', 'MultiEdit', 'ApplyPatch'].includes(name)) return edit(pathsOf(ti))
13
+ if (name === 'Grep' || name === 'Glob') return {tool_name: name, tool_input: {pattern: ti.pattern, path: ti.path}}
14
+ if (name.startsWith('MCP:')) return outbound(`mcp__${name.slice(4)}`)
15
+ if (name === 'WebFetch' || name === 'WebSearch') return {tool_name: name, tool_input: ti}
16
+ return byName(name, ti, ti.command)
17
+ }
18
+ const toolInput = (x ) => {
19
+ if (typeof x === 'string') { try { const o = JSON.parse(x); return o && typeof o === 'object' ? o : {} } catch { return {} } }
20
+ return x && typeof x === 'object' ? (x ) : {}
21
+ }
22
+ const PERMISSION = new Set(['preToolUse', 'beforeShellExecution', 'beforeMCPExecution', 'beforeReadFile'])
23
+
24
+ export const cursor = {
25
+ name: 'cursor',
26
+ detect: (i) => typeof i.cursor_version === 'string' || (typeof i.conversation_id === 'string' && typeof i.generation_id === 'string'),
27
+ normalize(i) {
28
+ const ev = String(i.hook_event_name ?? '')
29
+ const cwd = typeof i.cwd === 'string' && i.cwd ? i.cwd : Array.isArray(i.workspace_roots) ? i.workspace_roots[0] : undefined
30
+ const base = (t ) => ({cwd, ...t})
31
+ switch (ev) {
32
+ case 'preToolUse': return {kind: 'pre-tool', event: make('cursor', i, ev, {hook_event_name: 'PreToolUse', ...base(tool(String(i.tool_name ?? ''), toolInput(i.tool_input)))}, {tool: i.tool_name})}
33
+ case 'beforeShellExecution': return {kind: 'pre-tool', event: make('cursor', i, ev, {hook_event_name: 'PreToolUse', ...base(shell(commandText(i.command)))})}
34
+ case 'beforeMCPExecution': return {kind: 'pre-tool', event: make('cursor', i, ev, {hook_event_name: 'PreToolUse', ...base(outbound(`mcp__${i.mcp_server_name ?? 'server'}__${i.tool_name ?? 'tool'}`))})}
35
+ case 'beforeReadFile': return {kind: 'pre-tool', event: make('cursor', i, ev, {hook_event_name: 'PreToolUse', ...base(read(pathsOf(i)))})}
36
+ case 'postToolUse': {
37
+ const out = toolInput(i.tool_output)
38
+ const code = exitCodeIn(out)
39
+ const failed = code !== undefined && code !== 0
40
+ return {kind: failed ? 'post-tool-failure' : 'post-tool', event: make('cursor', i, ev, {hook_event_name: failed ? 'PostToolUseFailure' : 'PostToolUse',
41
+ ...base(tool(String(i.tool_name ?? ''), toolInput(i.tool_input))), tool_response: code === undefined ? out : {exitCode: code}}, {tool: i.tool_name})}
42
+ }
43
+ case 'postToolUseFailure': return {kind: 'post-tool-failure', event: make('cursor', i, ev, {hook_event_name: 'PostToolUseFailure',
44
+ ...base(tool(String(i.tool_name ?? ''), toolInput(i.tool_input))), is_interrupt: i.is_interrupt === true || i.failure_type === 'permission_denied'}, {tool: i.tool_name})}
45
+ case 'afterFileEdit': return {kind: 'post-tool', event: make('cursor', i, ev, {hook_event_name: 'PostToolUse', ...base(edit(pathsOf(i)))})}
46
+ // no exit code in afterShellExecution: a gate command seen only here never passes (use postToolUse)
47
+ case 'afterShellExecution': return {kind: 'post-tool', event: make('cursor', i, ev, {hook_event_name: 'PostToolUse', ...base(shell(commandText(i.command)))}, {requireExitCode: true})}
48
+ case 'stop': return {kind: 'stop', event: make('cursor', i, ev, {hook_event_name: 'Stop', cwd, stop_hook_active: Number(i.loop_count) > 0})}
49
+ default: return {kind: 'other', event: null}
50
+ }
51
+ },
52
+ render(kind, out, input) {
53
+ const ev = String(input?.hook_event_name ?? 'preToolUse')
54
+ if (kind === 'pre-tool' || PERMISSION.has(ev)) {
55
+ if (out.code === 0) return {code: 0, stdout: json({permission: 'allow'}) + '\n'}
56
+ const m = out.msg ?? 'blocked by stopbar'
57
+ return {code: 2, stdout: json({permission: 'deny', user_message: m, agent_message: m}) + '\n', stderr: m + '\n'}
58
+ }
59
+ if (kind === 'stop') return out.code !== 0 && out.msg ? {code: 0, stdout: json({followup_message: out.msg}) + '\n'} : {code: 0, stdout: '{}\n'}
60
+ if (kind === 'post-tool' || kind === 'post-tool-failure') return out.msg ? {code: 0, stdout: json({additional_context: out.msg}) + '\n'} : {code: 0, stdout: '{}\n'}
61
+ return {code: 0, stdout: '{}\n'}
62
+ },
63
+ }
@@ -0,0 +1,47 @@
1
+ // Built from src/adapters/gemini.ts by scripts/build.ts. Do not edit.
2
+ // Gemini CLI (.gemini/settings.json "hooks"). Events BeforeTool, AfterTool and AfterAgent (the end of a turn). Exit 2 is
3
+ // a system block with the reason on stderr; any other non-zero exit is only a warning and the call proceeds, and
4
+ // invalid JSON on stdout counts as "allow". Stopbar exits 2 for every block and fail-closed error.
5
+ import { byName, commandText, edit, exitCodeIn, json, make, outbound, pathsOf, read, shell, } from './types.js'
6
+
7
+ const UNIQUE = new Set(['BeforeTool', 'AfterTool', 'BeforeAgent', 'AfterAgent', 'BeforeModel', 'AfterModel', 'BeforeToolSelection', 'PreCompress', 'Notification'])
8
+
9
+ function tool(name , ti ) {
10
+ switch (name) {
11
+ case 'run_shell_command': return shell(commandText(ti.command))
12
+ case 'write_file': case 'replace': return edit(pathsOf(ti))
13
+ case 'read_file': case 'read_many_files': return read([...pathsOf(ti), ...(Array.isArray(ti.include) ? ti.include : [])])
14
+ case 'glob': return {tool_name: 'Glob', tool_input: {pattern: ti.pattern, path: ti.dir_path}}
15
+ case 'grep_search': case 'search_file_content': return {tool_name: 'Grep', tool_input: {pattern: ti.pattern, path: ti.dir_path}}
16
+ case 'web_fetch': return {tool_name: 'WebFetch', tool_input: {}}
17
+ case 'google_web_search': return {tool_name: 'WebSearch', tool_input: {}}
18
+ }
19
+ if (name.startsWith('mcp_')) return outbound(`mcp__${name.slice(4)}`)
20
+ return byName(name, ti, ti.command)
21
+ }
22
+
23
+ export const gemini = {
24
+ name: 'gemini',
25
+ detect: (i) => typeof i.hook_event_name === 'string' && (UNIQUE.has(i.hook_event_name) || (typeof i.timestamp === 'string' && /^Session(Start|End)$/.test(i.hook_event_name))),
26
+ normalize(i) {
27
+ const ev = String(i.hook_event_name), ti = (i.tool_input && typeof i.tool_input === 'object' ? i.tool_input : {})
28
+ if (ev === 'BeforeTool') return {kind: 'pre-tool', event: make('gemini', i, ev, {hook_event_name: 'PreToolUse', cwd: i.cwd, ...tool(String(i.tool_name ?? ''), ti)}, {tool: i.tool_name})}
29
+ if (ev === 'AfterTool') {
30
+ const r = (i.tool_response ?? {})
31
+ const code = exitCodeIn(r)
32
+ const failed = !!r.error || (code !== undefined && code !== 0)
33
+ return {kind: failed ? 'post-tool-failure' : 'post-tool', event: make('gemini', i, ev, {hook_event_name: failed ? 'PostToolUseFailure' : 'PostToolUse', cwd: i.cwd,
34
+ ...tool(String(i.tool_name ?? ''), ti), tool_response: code === undefined ? r : {exitCode: code}}, {tool: i.tool_name})}
35
+ }
36
+ if (ev === 'AfterAgent') return {kind: 'stop', event: make('gemini', i, ev, {hook_event_name: 'Stop', cwd: i.cwd, stop_hook_active: i.stop_hook_active === true})}
37
+ return {kind: 'other', event: null}
38
+ },
39
+ render(kind, out) {
40
+ if (kind === 'pre-tool') return out.code === 0 ? {code: 0, stdout: '{}\n'} : {code: 2, stderr: (out.msg ?? 'blocked by stopbar') + '\n'}
41
+ if (kind === 'stop') return out.code !== 0 && out.msg ? {code: 0, stdout: json({decision: 'block', reason: out.msg}) + '\n'} : {code: 0, stdout: '{}\n'}
42
+ if (kind === 'post-tool' || kind === 'post-tool-failure') {
43
+ return out.msg ? {code: 0, stdout: json({hookSpecificOutput: {hookEventName: 'AfterTool', additionalContext: out.msg}}) + '\n'} : {code: 0, stdout: '{}\n'}
44
+ }
45
+ return {code: 0, stdout: '{}\n'}
46
+ },
47
+ }
@@ -0,0 +1,45 @@
1
+ // Built from src/adapters/index.ts by scripts/build.ts. Do not edit.
2
+ // `stopbar hook --adapter auto|claude|cursor|codex|gemini|antigravity`. Auto detection is deterministic and ordered by
3
+ // the most specific marker; a payload no adapter recognises fails closed (exit 2). Claude Code payloads (v1.0) are
4
+ // detected as claude, so existing settings keep working without --adapter.
5
+ import { runEvent} from '../hook.js'
6
+ import {antigravity} from './antigravity.js'
7
+ import {claude} from './claude.js'
8
+ import {codex} from './codex.js'
9
+ import {cursor} from './cursor.js'
10
+ import {gemini} from './gemini.js'
11
+ import {ADAPTERS, } from './types.js'
12
+
13
+ export const BY_NAME = {claude, codex, cursor, gemini, antigravity}
14
+ // order matters: camelCase Antigravity, Cursor ids, Gemini-only event names, Codex turn_id, then Claude Code
15
+ const ORDER = [antigravity, cursor, gemini, codex, claude]
16
+
17
+ export function detect(input ) {
18
+ for (const a of ORDER) if (a.detect(input)) return a
19
+ return null
20
+ }
21
+
22
+ const ALIASES = {agy: 'antigravity', 'claude-code': 'claude'}
23
+ export function adapterByName(n ) {
24
+ const k = (ALIASES[n] ?? n)
25
+ return ADAPTERS.includes(k) ? BY_NAME[k] : null
26
+ }
27
+
28
+ const failClosed = (why ) => ({code: 2, msg: `STOPBAR FAIL-CLOSED: ${why}`})
29
+
30
+ /** One hook call: raw stdin JSON in, the client's exit code and output out. Never throws. */
31
+ export function handle(raw , which = 'auto', t0 = performance.now()) {
32
+ const explicit = which === 'auto' ? null : adapterByName(which)
33
+ if (which !== 'auto' && !explicit) return claude.render('pre-tool', failClosed(`unknown adapter ${JSON.stringify(which)}; known: auto, ${ADAPTERS.join(', ')}`), null)
34
+ let input
35
+ try { input = JSON.parse(raw) } catch (e) { return (explicit ?? claude).render('pre-tool', failClosed(`hook input is not JSON (${(e ).message})`), null) }
36
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return (explicit ?? claude).render('pre-tool', failClosed('hook input must be a JSON object'), null)
37
+ const a = explicit ?? detect(input)
38
+ if (!a) return claude.render('pre-tool', failClosed('unknown hook payload: no adapter recognises it (use --adapter)'), null)
39
+ let n
40
+ try { n = a.normalize(input) } catch (e) { return a.render('pre-tool', failClosed(`cannot read the ${a.name} payload (${(e ).message})`), input) }
41
+ if (!n.event) return a.render('other', {code: 0}, input)
42
+ return a.render(n.kind, runEvent(n.event, t0), input)
43
+ }
44
+
45
+ export {ADAPTERS}
@@ -0,0 +1,103 @@
1
+ // Built from src/adapters/types.ts by scripts/build.ts. Do not edit.
2
+ // Adapter layer: every client's hook payload becomes one internal event, which has the shape of a Claude Code hook
3
+ // payload (the v1.0 interface): hook_event_name PreToolUse | PostToolUse | PostToolUseFailure | Stop, tool_name in Claude
4
+ // Code's vocabulary (Bash, Write, Read, Grep, Glob, WebFetch, WebSearch, mcp__*), tool_input with command or file_path(s).
5
+ // The same proven kernel then decides, and the adapter renders the result in the client's own output protocol.
6
+
7
+
8
+
9
+
10
+ export const ADAPTERS = ['claude', 'codex', 'cursor', 'gemini', 'antigravity']
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+ /** What the CLI writes and returns. */
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+ // ---------------------------------------------------------------- shared tool mapping
36
+
37
+
38
+ const strs = (...xs ) => xs.flatMap((x) => (Array.isArray(x) ? x : [x])).filter((x) => typeof x === 'string' && x.length > 0)
39
+
40
+ /** A shell command as text; argv arrays such as ["bash", "-lc", "cmd"] become "cmd". */
41
+ export function commandText(c ) {
42
+ if (typeof c === 'string') return c
43
+ if (Array.isArray(c) && c.every((x) => typeof x === 'string')) {
44
+ const a = c
45
+ if (a.length >= 3 && /(^|[\\/])(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i.test(a[0]) && /^(-l?c|-Command|\/c)$/i.test(a[1])) return a.slice(2).join(' ')
46
+ return a.map((x) => (/[\s"']/.test(x) ? JSON.stringify(x) : x)).join(' ')
47
+ }
48
+ return ''
49
+ }
50
+
51
+ /** File paths named in an apply_patch style patch (*** Add/Update/Delete File: path, *** Move to: path). */
52
+ export function patchPaths(patch ) {
53
+ if (typeof patch !== 'string') return []
54
+ return [...patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+?)\s*$/gm)].map((m) => m[1])
55
+ }
56
+
57
+ export const shell = (command ) => ({tool_name: 'Bash', tool_input: {command}})
58
+ export function edit(paths ) {
59
+ return {tool_name: 'Write', tool_input: {file_path: paths[0] ?? '', file_paths: paths}}
60
+ }
61
+ export const read = (paths ) => ({tool_name: 'Read', tool_input: {file_path: paths[0] ?? '', file_paths: paths}})
62
+ export const outbound = (name ) => ({tool_name: name.startsWith('mcp__') ? name : 'WebFetch', tool_input: {}})
63
+ export const other = (name ) => ({tool_name: `other:${name}`, tool_input: {}})
64
+
65
+ /** Paths from the usual argument keys of file tools (all clients). */
66
+ export function pathsOf(args ) {
67
+ if (!args || typeof args !== 'object') return []
68
+ const a = args
69
+ return strs(a.file_path, a.filePath, a.path, a.target_file, a.targetFile, a.TargetFile, a.AbsolutePath, a.FilePath, a.File, a.Path,
70
+ a.notebook_path, a.paths, a.file_paths, a.DirectoryPath, a.SearchPath, a.dir_path, a.source, a.destination, a.Source, a.Destination)
71
+ }
72
+
73
+ /** Fallback by name for tools a client adds later: shell, edit, read or outbound by keyword, else other. */
74
+ export function byName(name , args , command ) {
75
+ const n = name.toLowerCase()
76
+ if (/shell|terminal|command|exec|bash|run_/.test(n)) return shell(commandText(command ?? (args )?.command ?? (args )?.CommandLine ?? ''))
77
+ if (/write|edit|delete|replace|patch|create|move|rename|remove|change|propose|blob/.test(n)) return edit(pathsOf(args))
78
+ if (/read|view|open_file|cat|grep|search_file|find|glob|list/.test(n)) return read(pathsOf(args))
79
+ if (/fetch|web|browser|http|url|mcp/.test(n)) return outbound(n.startsWith('mcp') ? `mcp__${name}` : name)
80
+ return other(name)
81
+ }
82
+
83
+ export function make(adapter , raw , event , base , extra = {}) {
84
+ return {...base, stopbar: {adapter, rawKeys: Object.keys(raw), event, ...extra}}
85
+ }
86
+
87
+ /** Exit code inside a tool result: a number field, or text such as "Exit code: 1" / "exited with code 1" / "Exit Code: 1". */
88
+ export function exitCodeIn(r , depth = 0) {
89
+ if (r === null || r === undefined || depth > 3) return undefined
90
+ if (typeof r === 'string') {
91
+ const t = r.trim()
92
+ if (t.startsWith('{')) { try { return exitCodeIn(JSON.parse(t), depth + 1) } catch { /* plain text */ } }
93
+ const m = /(?:exit(?:ed with)?[ _]?code|exit status)\s*[:=]?\s*(-?\d+)/i.exec(t)
94
+ return m ? Number(m[1]) : undefined
95
+ }
96
+ if (typeof r !== 'object') return undefined
97
+ const o = r
98
+ for (const k of ['exitCode', 'exit_code', 'returnCode', 'code', 'status_code']) if (typeof o[k] === 'number') return o[k]
99
+ for (const k of ['metadata', 'result', 'output', 'llmContent', 'returnDisplay']) { const c = exitCodeIn(o[k], depth + 1); if (c !== undefined) return c }
100
+ return undefined
101
+ }
102
+
103
+ export const json = (o ) => JSON.stringify(o)
package/dist/attest.js ADDED
@@ -0,0 +1,97 @@
1
+ // Built from src/attest.ts by scripts/build.ts. Do not edit.
2
+ // ATTEST: a deterministic attestation of the session from the current state and the event log. The same state and log
3
+ // give the same report byte for byte (no clock, no machine name). The sha256 of events.jsonl is the anchor for signing in
4
+ // a later version. Read-only for Stopbar state: it refreshes only the private snapshot index to see the working tree.
5
+ import {createHash} from 'node:crypto'
6
+ import {existsSync, readFileSync} from 'node:fs'
7
+ import {decode, initKernel, MACHINE, } from './engine.js'
8
+ import {secretReason} from './commands.js'
9
+ import {whyBlocked} from './hook.js'
10
+ import {findRepo, git, snapshot} from './repo.js'
11
+ import {paths, readConfig, readState, VERSION, withLock} from './store.js'
12
+
13
+ const FIELDS = ['treeRev', 'buildOkRev', 'testsOkRev', 'spent', 'capNow', 'testFails', 'buildFails', 'halted', 'testsTainted', 'secretTainted', 'shellToken']
14
+
15
+ export function attestation(repoDir ) {
16
+ const repo = findRepo(repoDir)
17
+ return withLock(repo, () => {
18
+ const cfg = readConfig(repo), s = readState(repo), v = decode(s.kernel)
19
+ const f = paths(repo).events
20
+ const raw = existsSync(f) ? readFileSync(f) : Buffer.alloc(0)
21
+ const events = [], torn = []
22
+ raw.toString('utf8').split('\n').forEach((l, i) => { if (!l) return; try { events.push({line: i + 1, e: JSON.parse(l)}) } catch { torn.push(i + 1) } })
23
+ let head = null, headTree = null
24
+ try { head = git(repo.root, ['rev-parse', '-q', '--verify', 'HEAD']); headTree = git(repo.root, ['rev-parse', 'HEAD^{tree}']) } catch { /* no commit yet */ }
25
+ const now = snapshot(repo)
26
+
27
+ const steps = events.filter(({e}) => e.req && typeof e.req.op === 'string')
28
+ const human = events.filter(({e}) => typeof e.source === 'string' && e.source.startsWith('human:'))
29
+ const approvals = human.map(({line, e}) => ({line, ts: e.ts, action: e.source.slice('human:'.length),
30
+ ...(e.req?.approveRev !== undefined && e.source === 'human:approve-tests' ? {revision: e.req.approveRev} : {}),
31
+ ...(e.req?.extra !== undefined && e.source === 'human:resume' ? {extra: e.req.extra} : {}),
32
+ ...(e.decision ? {decision: e.decision} : {}), ...(e.shellToken !== undefined && e.source === 'human:approve-shell' ? {granted: e.shellToken} : {})}))
33
+ // a block is a wrapper BLOCK/PAUSE (self-protection, chained command, halted) or a kernel decision other than ALLOW on an agent action
34
+ const blocks = events.filter(({e}) => e.wrapper === 'BLOCK' || e.wrapper === 'PAUSE' || (e.req && e.decision && e.decision !== 'ALLOW' && !String(e.source).startsWith('human:'))).length
35
+ const decisions = {}
36
+ for (const {e} of steps) decisions[`${e.req.op}:${e.decision}`] = (decisions[`${e.req.op}:${e.decision}`] ?? 0) + 1
37
+ const commitsAllowed = steps.filter(({e}) => e.req.op === 'COMMIT' && e.decision === 'ALLOW' && String(e.source).startsWith('pre:')).length
38
+
39
+ // consistency: the state must be what the log says the last kernel step (or the last init/reset) left behind
40
+ const checks = []
41
+ const lastIdx = Math.max(...events.map((x, i) => (x.e.req || x.e.source === 'human:init' || x.e.source === 'human:reset' ? i : -1)), -1)
42
+ if (lastIdx < 0) checks.push({name: 'log matches state', ok: false, detail: 'no kernel step and no init in events.jsonl'})
43
+ else {
44
+ const last = events[lastIdx]
45
+ const expected = last.e.req ? last.e : decode(initKernel(s.params))
46
+ const diff = FIELDS.filter((k) => k in expected && expected[k] !== v[k])
47
+ checks.push({name: 'log matches state', ok: diff.length === 0, detail: diff.length ? `differs at ${diff.join(', ')} (line ${last.line})` : `last entry line ${last.line}`})
48
+ }
49
+ checks.push({name: 'config params = state params', ok: cfg.maxRetries === s.params.maxRetries && cfg.cap === s.params.cap, detail: `${JSON.stringify(s.params)}`})
50
+ checks.push({name: 'working tree counted', ok: now.id === s.snapshot, detail: now.id === s.snapshot ? 'no change the kernel has not seen' : 'uncounted change (counted at the next hook)'})
51
+
52
+ const commitNow = !v.halted && v.buildOkRev === v.treeRev && v.testsOkRev === v.treeRev && !v.testsTainted
53
+ return {
54
+ stopbar: VERSION,
55
+ kernel: MACHINE,
56
+ repository: {head, headTree, snapshot: s.snapshot, workingTreeSnapshot: now.id, treeRevision: v.treeRev},
57
+ config: {profile: cfg.profile, buildCmd: cfg.buildCmd, fullTestCmd: cfg.fullTestCmd, maxRetries: cfg.maxRetries, cap: cfg.cap, costPerCall: cfg.costPerCall},
58
+ gates: {build: v.buildOkRev === v.treeRev, fullTests: v.testsOkRev === v.treeRev, tainted: v.testsTainted, secretRead: v.secretTainted,
59
+ ...(v.secretTainted ? {secretReadBy: secretReason(repo)?.text ?? 'not in the event log'} : {}),
60
+ shellApprovalHeld: v.shellToken, halted: v.halted, commitAllowedNow: commitNow, ...(commitNow ? {} : {why: v.halted ? 'session halted' : whyBlocked(v, cfg)}),
61
+ budget: {spent: v.spent, cap: v.capNow}, failures: {tests: v.testFails, builds: v.buildFails}},
62
+ humanActions: approvals,
63
+ log: {file: 'events.jsonl', sha256: createHash('sha256').update(raw).digest('hex'), bytes: raw.length, entries: events.length, tornLines: torn,
64
+ kernelSteps: steps.length, blocks, commitsAllowed, decisions: Object.fromEntries(Object.entries(decisions).sort())},
65
+ consistent: checks.every((c) => c.ok || c.name === 'working tree counted'),
66
+ checks,
67
+ }
68
+ })
69
+ }
70
+
71
+ export function attestMarkdown(a ) {
72
+ const yn = (b ) => (b ? 'yes' : 'no')
73
+ const g = a.gates
74
+ return [
75
+ `# Stopbar attestation`, '',
76
+ `| Field | Value |`, `|---|---|`,
77
+ `| Stopbar | ${a.stopbar} |`, `| Kernel | ${a.kernel.name}, kernel.ts sha256 \`${a.kernel.kernelSha256}\` |`,
78
+ `| HEAD | \`${a.repository.head ?? '(none)'}\` |`, `| HEAD tree | \`${a.repository.headTree ?? '(none)'}\` |`,
79
+ `| Counted snapshot | \`${a.repository.snapshot}\` (revision ${a.repository.treeRevision}) |`,
80
+ `| Build gate | ${yn(g.build)} (\`${a.config.buildCmd}\`) |`, `| Full test gate | ${yn(g.fullTests)} (\`${a.config.fullTestCmd}\`) |`,
81
+ `| Tests tainted | ${yn(g.tainted)} |`, `| Secret read | ${g.secretRead ? `yes: ${g.secretReadBy}` : 'no'} |`, `| Halted | ${yn(g.halted)} |`,
82
+ `| Commit allowed now | ${yn(g.commitAllowedNow)}${g.why ? `: ${g.why}` : ''} |`,
83
+ `| Budget | ${g.budget.spent}/${g.budget.cap} |`,
84
+ `| events.jsonl sha256 | \`${a.log.sha256}\` (${a.log.bytes} bytes, ${a.log.entries} entries, torn lines: ${a.log.tornLines.length ? a.log.tornLines.join(', ') : 'none'}) |`,
85
+ `| Kernel steps / blocks / commits allowed | ${a.log.kernelSteps} / ${a.log.blocks} / ${a.log.commitsAllowed} |`,
86
+ `| Consistent | ${yn(a.consistent)} |`, '',
87
+ `## Human actions`, '', ...(a.humanActions.length ? a.humanActions.map((h) => `- line ${h.line}, ${h.ts}: ${h.action}${'revision' in h ? ` revision ${h.revision}` : ''}${'extra' in h ? ` extra ${h.extra}` : ''}${h.decision ? ` -> ${h.decision}` : ''}`) : ['- none']), '',
88
+ `## Checks`, '', ...a.checks.map((c) => `- [${c.ok ? 'x' : ' '}] ${c.name}: ${c.detail}`), '',
89
+ ].join('\n')
90
+ }
91
+
92
+ export function attest(o ) {
93
+ const fmt = o.format ?? 'json'
94
+ if (fmt !== 'json' && fmt !== 'md') return {code: 1, msg: '--format must be json or md'}
95
+ const a = attestation(o.repo ?? process.cwd())
96
+ return {code: a.consistent ? 0 : 1, msg: fmt === 'md' ? attestMarkdown(a) : JSON.stringify(a, null, 1)}
97
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "1.1.0",
3
+ "kernelSourceSha256": "c602fc4bcf8ffb2e312bf838986e6d4b006af6d0e6c7447c8c61d5888adc5ef8",
4
+ "machineSha256": "b397085e0cb13e2e50aa655c54de0744d08f2ebf500bf32af8ff3e8a11ba7321",
5
+ "files": 26
6
+ }
@@ -0,0 +1,212 @@
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
+ /** The first secret pattern a path matches, or null. Absolute paths match too (a pattern may match any suffix). */
13
+ export function secretPattern(p , paths ) {
14
+ for (const g of paths.secrets) if (matchAnySuffix(norm(p), [g])) return g
15
+ return null
16
+ }
17
+ export const isSecretPath = (p , paths ) => secretPattern(p, paths) !== null
18
+
19
+ // ---------------------------------------------------------------- safe heredoc commit
20
+ // The one form of command substitution the wrapper lets through, the way Claude Code writes commit messages:
21
+ // git commit [args] -m "$(cat <<'EOF'
22
+ // ...message...
23
+ // EOF
24
+ // )"
25
+ // The delimiter is in single quotes, so bash expands nothing in the body: no variables, no $(...), no backticks.
26
+ // The prefix before -m must be a plain git commit without operators; nothing may follow `)"`.
27
+ // Only spaces and tabs between tokens: a newline is a command separator in bash.
28
+ const HEREDOC_RE = /^([^\n]*?)[ \t]+-m[ \t]+"\$\(cat[ \t]*<<[ \t]*'([A-Za-z_][A-Za-z0-9_]*)'\n((?:[^\n]*\n)*?)\2\n\)"[ \t]*\n?$/
29
+
30
+
31
+
32
+ export function parseSafeHeredocCommit(cmd ) {
33
+ if (cmd.includes('\r') || cmd.includes('\0')) return null
34
+ const m = HEREDOC_RE.exec(cmd.replace(/^\s+/, ''))
35
+ if (!m) return null
36
+ const [, prefix, delimiter, message] = m
37
+ if (scanPlain(prefix).chain) return null
38
+ if (!COMMIT_ONLY_RE.test(prefix.trim())) return null
39
+ // the body may not contain the delimiter line (the lazy match already guarantees this; checked again for clarity)
40
+ if (message.split('\n').some((l) => l === delimiter)) return null
41
+ return {prefix: prefix.trim(), message: message.replace(/\n$/, ''), delimiter}
42
+ }
43
+
44
+ /** Shell scan as bash sees it: operators and redirections count only outside quotes. Inside '...' everything is literal.
45
+ * Inside "..." the escapes \" \\ \$ \` work, but $(...) and `...` still run, so they are a chain.
46
+ * An unterminated quote is a chain (fail closed). Outside quotes \x is a literal x. */
47
+ function scanPlain(cmd ) {
48
+ let q = ''
49
+ for (let i = 0; i < cmd.length; i++) {
50
+ const c = cmd[i], n = cmd[i + 1]
51
+ if (q === "'") { if (c === "'") q = ''; continue }
52
+ if (q === '"') {
53
+ if (c === '\\') { i++; continue }
54
+ if (c === '"') { q = ''; continue }
55
+ if (c === '`' || (c === '$' && n === '(')) return {chain: true, reason: 'command substitution inside double quotes'}
56
+ continue
57
+ }
58
+ if (c === '\\') { i++; continue }
59
+ if (c === "'" || c === '"') { q = c; continue }
60
+ if (c === '`' || (c === '$' && n === '(')) return {chain: true, reason: 'command substitution'}
61
+ if ('&|;<>\r\n'.includes(c)) return {chain: true, reason: `operator ${JSON.stringify(c)} outside quotes`}
62
+ }
63
+ return q ? {chain: true, reason: 'unterminated quote'} : {chain: false}
64
+ }
65
+
66
+ export function scanShell(cmd ) {
67
+ if (parseSafeHeredocCommit(cmd)) return {chain: false, heredoc: true}
68
+ return scanPlain(cmd)
69
+ }
70
+ export const hasChain = (cmd ) => scanShell(cmd).chain
71
+
72
+ // ---------------------------------------------------------------- risky / outbound shell
73
+ const NET_TOOLS = /\b(curl|wget|nc|ncat|netcat|socat|ssh|scp|sftp|rsync|ftp|tftp|telnet)\b/i
74
+ const PS_NET = /Invoke-WebRequest|Invoke-RestMethod|\biwr\b|\birm\b|Start-BitsTransfer|Net\.WebClient|System\.Net\.|Net\.Sockets/i
75
+ 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
76
+ const NET_WORDS = /https?:|fetch\(|\bnet\b|socket|urllib|requests|http\.client|dns|XMLHttpRequest|WebSocket/i
77
+ const OBFUSCATION = /base64\s+(-d|--decode)|FromBase64String|\beval\b|\biex\b|Invoke-Expression|-EncodedCommand|\bsh\s+-c\b|\bbash\s+-c\b/i
78
+ 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
79
+
80
+ /** RISKY_OR_OUTBOUND: network tool, inline code with network words, obfuscation or publication. */
81
+ export function isRiskyShell(cmd ) {
82
+ return NET_TOOLS.test(cmd) || PS_NET.test(cmd) || (INLINE_CODE.test(cmd) && NET_WORDS.test(cmd)) ||
83
+ OBFUSCATION.test(cmd) || PUBLISH.test(cmd)
84
+ }
85
+
86
+ // ---------------------------------------------------------------- git commands
87
+ // git global options before the subcommand: -c k=v, -C dir, --git-dir=..., --work-tree ..., --no-pager, -p (values may be quoted)
88
+ const GIT_GLOBALS = String.raw`(?:\s+(?:-[cC]\s*(?:"[^"]*"|'[^']*'|\S+)|--(?:git-dir|work-tree|namespace|exec-path|config-env)(?:=|\s+)(?:"[^"]*"|'[^']*'|\S+)|--[\w-]+|-[A-Za-z]))*`
89
+ const gitSub = (sub , flags = 'i') => new RegExp(String.raw`\bgit(?:\.exe)?${GIT_GLOBALS}\s+(?:${sub})\b`, flags)
90
+ const COMMIT_RE = gitSub('commit|push'), PUSH_RE = gitSub('push'), CONFIG_RE = gitSub('config')
91
+ const COMMIT_ONLY_RE = new RegExp(String.raw`^git(?:\.exe)?${GIT_GLOBALS}\s+commit\b`, 'i')
92
+ const CONFIG_READ = /\s(--get|--get-all|--get-regexp|--list|-l|--show-origin|--show-scope|get|list)(\s|=|$)/i
93
+
94
+ /** Text a commit/push decision is made on: for a safe heredoc commit only the prefix (the message is data). */
95
+ const commandPart = (cmd ) => parseSafeHeredocCommit(cmd)?.prefix ?? cmd
96
+ export const isCommitCmd = (cmd ) => COMMIT_RE.test(commandPart(cmd))
97
+ export const isPushCmd = (cmd ) => PUSH_RE.test(commandPart(cmd))
98
+ export const isGitConfigWrite = (cmd ) => CONFIG_RE.test(cmd) && !CONFIG_READ.test(cmd)
99
+
100
+ // 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).
101
+ const END = String.raw`(?![\w.\-/\\])`
102
+ const TEST_RUNNER = new RegExp([
103
+ String.raw`\bnode(?:\s+\S+)*?\s+--test${END}`,
104
+ String.raw`\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test(?![\w.\-/\\])`,
105
+ 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}`,
106
+ String.raw`\bplaywright\s+test${END}`,
107
+ String.raw`\bpython[0-9.]*(?:\s+\S+)*?\s+-m\s+(?:pytest|unittest)${END}`,
108
+ String.raw`\bgo\s+test${END}`, String.raw`\bcargo\s+test${END}`,
109
+ ].join('|'), 'i')
110
+ export const looksLikeTests = (cmd ) => TEST_RUNNER.test(cmd)
111
+
112
+ // Extension-only patterns such as *.key or *.pem: a bare token like `claim.key` or `self.key` is usually code (a field
113
+ // access), not a file. Such a token counts only when the file exists; a token with a path separator (`certs/a.key`)
114
+ // and every other pattern (`.env*`, `id_rsa*`, `auth.json`, `**/secrets/**`) count always.
115
+ const EXT_ONLY = /^\*\.[^/*?{}\[\]]+$/
116
+
117
+
118
+ /** The first secret path named in a command (e.g. `cat .env`, `type secrets\\db.txt`), with the pattern it matched. */
119
+ export function secretInCommand(cmd , paths , exists = () => true) {
120
+ for (const tok of cmd.split(/[\s'"=(),;|&<>@:]+/).filter(Boolean)) {
121
+ const hits = paths.secrets.filter((g) => matchAnySuffix(norm(tok), [g]))
122
+ if (!hits.length) continue
123
+ const strong = hits.find((g) => !EXT_ONLY.test(g))
124
+ if (strong) return {token: tok, pattern: strong}
125
+ if (/[\\/]/.test(tok) || exists(tok)) return {token: tok, pattern: hits[0]}
126
+ }
127
+ return null
128
+ }
129
+ export const mentionsSecret = (cmd , paths , exists ) => secretInCommand(cmd, paths, exists) !== null
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+ /** Exact match of gate commands: no chain operators, no extra arguments. `shell` is 'bash' or 'powershell'. */
138
+ export function classifyBash(cmd , cfg , shell = 'bash', exists ) {
139
+ const c = cmd.trim()
140
+ const scan = shell === 'bash' ? scanShell(c) : scanPlain(c)
141
+ if (COMMIT_RE.test(scan.heredoc ? commandPart(c) : c)) {
142
+ if (scan.chain) return {kind: 'commit-chained', reason: scan.reason ?? 'chain'}
143
+ return {kind: 'commit', heredoc: !!scan.heredoc, push: isPushCmd(c)}
144
+ }
145
+ // a gate command with operators (`node --test; echo $?`, `|| true`, `| tail`) hides its exit status: blocked in PreToolUse
146
+ if (scan.chain) {
147
+ 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'}
148
+ } else {
149
+ if (c === cfg.buildCmd.trim()) return {kind: 'build'}
150
+ if (c === cfg.fullTestCmd.trim()) return {kind: 'fulltest'}
151
+ }
152
+ return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: secretInCommand(c, cfg.paths, exists)}
153
+ }
154
+
155
+ /** Kind of a tree change from a list of (status, path) and a test for "the path exists in HEAD". */
156
+ export function classifyTreeChange(changes , inHead , paths ) {
157
+ let anyTest = false, suspicious = false
158
+ const why = []
159
+ for (const {status, path} of changes) {
160
+ if (isTestConfigPath(path, paths)) { anyTest = true; suspicious = true; why.push(`config ${status} ${path}`); continue }
161
+ if (isTestPath(path, paths)) {
162
+ anyTest = true
163
+ if (inHead(path)) { suspicious = true; why.push(`existing test ${status} ${path}`) } else why.push(`new test ${status} ${path}`)
164
+ }
165
+ }
166
+ return {op: anyTest ? 'EDIT_TEST' : 'EDIT_CODE' , suspicious, why}
167
+ }
168
+
169
+ // ---------------------------------------------------------------- self-protection
170
+ // Unconditional BLOCK in PreToolUse, outside the kernel. Paths are compared normalised: '/' separators, lower case.
171
+
172
+
173
+ const lc = (p ) => norm(p).toLowerCase().replace(/\/+$/, '')
174
+ const under = (a , dir ) => a === dir || a.startsWith(dir + '/')
175
+
176
+ // the hook configuration of every supported client (project and user level)
177
+ const AGENT_CONFIG = [
178
+ [/(^|\/)\.claude\/[^/]*settings[^/]*\.json$/, 'Claude Code settings (.claude/settings*.json)'],
179
+ [/(^|\/)\.cursor\/hooks\.json$/, 'Cursor hooks (.cursor/hooks.json)'],
180
+ [/(^|\/)\.codex\/(hooks\.json|config\.toml)$/, 'Codex CLI hooks (.codex/hooks.json, .codex/config.toml)'],
181
+ [/(^|\/)\.gemini\/([^/]*settings[^/]*\.json|(.*\/)?hooks\.json)$/, 'Gemini CLI and Antigravity settings (.gemini/settings*.json, .gemini/**/hooks.json)'],
182
+ [/(^|\/)\.agents\/hooks\.json$/, 'Antigravity CLI hooks (.agents/hooks.json)'],
183
+ ]
184
+
185
+ /** File path written by an Edit/Write tool. Returns the reason for a block, or null. */
186
+ export function protectedPath(abs , root , pr ) {
187
+ const a = lc(abs), r = lc(root)
188
+ // inside the repository the .git test runs on the relative path; outside it on the whole path (other repositories)
189
+ const tail = under(a, r) ? a.slice(r.length) : a
190
+ if (/(^|\/)\.git(\/|$)/.test(tail) || under(a, lc(pr.gitDir)) || under(a, lc(pr.stateDir))) return 'git metadata (.git/**, Stopbar state, git hooks, git config)'
191
+ for (const [re, what] of AGENT_CONFIG) if (re.test(a)) return `${what} hold the Stopbar hooks`
192
+ for (const d of pr.codeDirs) if (under(a, lc(d))) return `Stopbar code (${d})`
193
+ return null
194
+ }
195
+
196
+ const SEG = (name ) => new RegExp(String.raw`(^|[^a-z0-9_.\-])${name.replace(/\./g, '\\.')}([^a-z0-9_\-]|$)`, 'i')
197
+ const DOT_GIT = SEG('.git')
198
+ const AGENT_DIRS = [[SEG('.claude'), '.claude'], [SEG('.cursor'), '.cursor'], [SEG('.codex'), '.codex'], [SEG('.gemini'), '.gemini'], [SEG('.agents'), '.agents']]
199
+ const HUMAN_ONLY = /\b(approve-tests|approve-shell)\b|\bSTOPBAR_[A-Z_]+/i
200
+ const STOPBAR_ADMIN = /stopbar[^\n]*\b(init|resume|reset|doctor\s+--fix)\b/i
201
+
202
+ /** Shell command text. Returns the reason for a block, or null. Text matching only: see SECURITY.md. */
203
+ export function protectedCommand(cmd , pr ) {
204
+ const c = norm(cmd).toLowerCase()
205
+ if (DOT_GIT.test(c)) return 'the command names a .git directory (Stopbar state, git hooks, git config live there)'
206
+ for (const [re, d] of AGENT_DIRS) if (re.test(c)) return `the command names a ${d} directory (agent settings there hold the Stopbar hooks)`
207
+ if (isGitConfigWrite(cmd)) return '`git config` writes .git/config; only reads (--get, --list) are allowed'
208
+ if (c.includes(lc(pr.stateDir)) || c.includes(lc(pr.gitDir) + '/')) return 'the command names the git directory'
209
+ for (const d of pr.codeDirs) if (c.includes(lc(d))) return `the command names Stopbar code (${d})`
210
+ if (HUMAN_ONLY.test(cmd) || STOPBAR_ADMIN.test(cmd)) return 'human-only Stopbar command or setting'
211
+ return null
212
+ }