stopbar 1.0.0 → 1.1.1

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,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 , background = false) => ({tool_name: 'Bash', tool_input: background ? {command, run_in_background: true} : {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 CHANGED
@@ -5,6 +5,7 @@
5
5
  import {createHash} from 'node:crypto'
6
6
  import {existsSync, readFileSync} from 'node:fs'
7
7
  import {decode, initKernel, MACHINE, } from './engine.js'
8
+ import {secretReason} from './commands.js'
8
9
  import {whyBlocked} from './hook.js'
9
10
  import {findRepo, git, snapshot} from './repo.js'
10
11
  import {paths, readConfig, readState, VERSION, withLock} from './store.js'
@@ -53,8 +54,9 @@ export function attestation(repoDir ) {
53
54
  stopbar: VERSION,
54
55
  kernel: MACHINE,
55
56
  repository: {head, headTree, snapshot: s.snapshot, workingTreeSnapshot: now.id, treeRevision: v.treeRev},
56
- config: {profile: cfg.profile, buildCmd: cfg.buildCmd, fullTestCmd: cfg.fullTestCmd, maxRetries: cfg.maxRetries, cap: cfg.cap, costPerCall: cfg.costPerCall},
57
+ config: {profile: cfg.profile, buildCmd: cfg.buildCmd, fullTestCmd: cfg.fullTestCmd, maxRetries: cfg.maxRetries, cap: cfg.cap, costPerCall: cfg.costPerCall, ...(cfg.baseRef ? {baseRef: cfg.baseRef} : {})},
57
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'} : {}),
58
60
  shellApprovalHeld: v.shellToken, halted: v.halted, commitAllowedNow: commitNow, ...(commitNow ? {} : {why: v.halted ? 'session halted' : whyBlocked(v, cfg)}),
59
61
  budget: {spent: v.spent, cap: v.capNow}, failures: {tests: v.testFails, builds: v.buildFails}},
60
62
  humanActions: approvals,
@@ -74,9 +76,10 @@ export function attestMarkdown(a ) {
74
76
  `| Field | Value |`, `|---|---|`,
75
77
  `| Stopbar | ${a.stopbar} |`, `| Kernel | ${a.kernel.name}, kernel.ts sha256 \`${a.kernel.kernelSha256}\` |`,
76
78
  `| HEAD | \`${a.repository.head ?? '(none)'}\` |`, `| HEAD tree | \`${a.repository.headTree ?? '(none)'}\` |`,
79
+ ...(a.config.baseRef ? [`| Base ref | \`${a.config.baseRef}\` |`] : []),
77
80
  `| Counted snapshot | \`${a.repository.snapshot}\` (revision ${a.repository.treeRevision}) |`,
78
81
  `| Build gate | ${yn(g.build)} (\`${a.config.buildCmd}\`) |`, `| Full test gate | ${yn(g.fullTests)} (\`${a.config.fullTestCmd}\`) |`,
79
- `| Tests tainted | ${yn(g.tainted)} |`, `| Secret read | ${yn(g.secretRead)} |`, `| Halted | ${yn(g.halted)} |`,
82
+ `| Tests tainted | ${yn(g.tainted)} |`, `| Secret read | ${g.secretRead ? `yes: ${g.secretReadBy}` : 'no'} |`, `| Halted | ${yn(g.halted)} |`,
80
83
  `| Commit allowed now | ${yn(g.commitAllowedNow)}${g.why ? `: ${g.why}` : ''} |`,
81
84
  `| Budget | ${g.budget.spent}/${g.budget.cap} |`,
82
85
  `| 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'}) |`,
@@ -1,6 +1,6 @@
1
1
  {
2
- "version": "1.0.0",
2
+ "version": "1.1.1",
3
3
  "kernelSourceSha256": "c602fc4bcf8ffb2e312bf838986e6d4b006af6d0e6c7447c8c61d5888adc5ef8",
4
4
  "machineSha256": "b397085e0cb13e2e50aa655c54de0744d08f2ebf500bf32af8ff3e8a11ba7321",
5
- "files": 16
5
+ "files": 26
6
6
  }
package/dist/classify.js CHANGED
@@ -8,8 +8,24 @@ const norm = (p ) => p.replace(/\\/g, '/')
8
8
 
9
9
  export const isTestPath = (p , paths ) => matchAny(norm(p), paths.tests)
10
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)
11
+ // Source-code extensions that a wildcard `secrets.*` pattern must not treat as secret data files
12
+ // (e.g. `src/integration/secrets.ts` is a TypeScript module, not a secret store).
13
+ const CODE_EXT = /\.(?:[cm]?[jt]sx?|py|go|rs|java|cs|rb|php|swift|kt|scala|c|cc|cpp|h|hpp|md)$/i
14
+ const WILDCARD_EXT_SECRET = /^(?:\*\*\/)?secrets\.\*$/i
15
+
16
+ function matchesSecretGlob(p , g ) {
17
+ const n = norm(p)
18
+ if (!matchAnySuffix(n, [g])) return false
19
+ if (WILDCARD_EXT_SECRET.test(g) && CODE_EXT.test(n)) return false
20
+ return true
21
+ }
22
+
23
+ /** The first secret pattern a path matches, or null. Absolute paths match too (a pattern may match any suffix). */
24
+ export function secretPattern(p , paths ) {
25
+ for (const g of paths.secrets) if (matchesSecretGlob(p, g)) return g
26
+ return null
27
+ }
28
+ export const isSecretPath = (p , paths ) => secretPattern(p, paths) !== null
13
29
 
14
30
  // ---------------------------------------------------------------- safe heredoc commit
15
31
  // The one form of command substitution the wrapper lets through, the way Claude Code writes commit messages:
@@ -104,19 +120,33 @@ const TEST_RUNNER = new RegExp([
104
120
  ].join('|'), 'i')
105
121
  export const looksLikeTests = (cmd ) => TEST_RUNNER.test(cmd)
106
122
 
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))
123
+ // Extension-only patterns such as *.key or *.pem: a bare token like `claim.key` or `self.key` is usually code (a field
124
+ // access), not a file. Such a token counts only when the file exists; a token with a path separator (`certs/a.key`)
125
+ // and every other pattern (`.env*`, `id_rsa*`, `auth.json`, `**/secrets/**`) count always.
126
+ const EXT_ONLY = /^\*\.[^/*?{}\[\]]+$/
127
+
128
+
129
+ /** The first secret path named in a command (e.g. `cat .env`, `type secrets\\db.txt`), with the pattern it matched. */
130
+ export function secretInCommand(cmd , paths , exists = () => true) {
131
+ for (const tok of cmd.split(/[\s'"=(),;|&<>@:]+/).filter(Boolean)) {
132
+ const hits = paths.secrets.filter((g) => matchesSecretGlob(tok, g))
133
+ if (!hits.length) continue
134
+ const strong = hits.find((g) => !EXT_ONLY.test(g))
135
+ if (strong) return {token: tok, pattern: strong}
136
+ if (/[\\/]/.test(tok) || exists(tok)) return {token: tok, pattern: hits[0]}
137
+ }
138
+ return null
110
139
  }
140
+ export const mentionsSecret = (cmd , paths , exists ) => secretInCommand(cmd, paths, exists) !== null
111
141
 
112
142
 
113
143
 
114
144
 
115
145
 
116
-
146
+
117
147
 
118
148
  /** Exact match of gate commands: no chain operators, no extra arguments. `shell` is 'bash' or 'powershell'. */
119
- export function classifyBash(cmd , cfg , shell = 'bash') {
149
+ export function classifyBash(cmd , cfg , shell = 'bash', exists ) {
120
150
  const c = cmd.trim()
121
151
  const scan = shell === 'bash' ? scanShell(c) : scanPlain(c)
122
152
  if (COMMIT_RE.test(scan.heredoc ? commandPart(c) : c)) {
@@ -130,7 +160,7 @@ export function classifyBash(cmd , cfg
130
160
  if (c === cfg.buildCmd.trim()) return {kind: 'build'}
131
161
  if (c === cfg.fullTestCmd.trim()) return {kind: 'fulltest'}
132
162
  }
133
- return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: mentionsSecret(c, cfg.paths)}
163
+ return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: secretInCommand(c, cfg.paths, exists)}
134
164
  }
135
165
 
136
166
  /** Kind of a tree change from a list of (status, path) and a test for "the path exists in HEAD". */
@@ -154,27 +184,75 @@ export function classifyTreeChange(changes , in
154
184
  const lc = (p ) => norm(p).toLowerCase().replace(/\/+$/, '')
155
185
  const under = (a , dir ) => a === dir || a.startsWith(dir + '/')
156
186
 
187
+ // the hook configuration of every supported client (project and user level)
188
+ const AGENT_CONFIG = [
189
+ [/(^|\/)\.claude\/[^/]*settings[^/]*\.json$/, 'Claude Code settings (.claude/settings*.json)'],
190
+ [/(^|\/)\.cursor\/hooks\.json$/, 'Cursor hooks (.cursor/hooks.json)'],
191
+ [/(^|\/)\.codex\/(hooks\.json|config\.toml)$/, 'Codex CLI hooks (.codex/hooks.json, .codex/config.toml)'],
192
+ [/(^|\/)\.gemini\/([^/]*settings[^/]*\.json|(.*\/)?hooks\.json)$/, 'Gemini CLI and Antigravity settings (.gemini/settings*.json, .gemini/**/hooks.json)'],
193
+ [/(^|\/)\.agents\/hooks\.json$/, 'Antigravity CLI hooks (.agents/hooks.json)'],
194
+ ]
195
+
157
196
  /** File path written by an Edit/Write tool. Returns the reason for a block, or null. */
158
197
  export function protectedPath(abs , root , pr ) {
159
198
  const a = lc(abs), r = lc(root)
160
199
  // inside the repository the .git test runs on the relative path; outside it on the whole path (other repositories)
161
200
  const tail = under(a, r) ? a.slice(r.length) : a
162
201
  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'
202
+ for (const [re, what] of AGENT_CONFIG) if (re.test(a)) return `${what} hold the Stopbar hooks`
164
203
  for (const d of pr.codeDirs) if (under(a, lc(d))) return `Stopbar code (${d})`
165
204
  return null
166
205
  }
167
206
 
168
207
  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')
208
+ const DOT_GIT = SEG('.git')
209
+ const AGENT_DIRS = [[SEG('.claude'), '.claude'], [SEG('.cursor'), '.cursor'], [SEG('.codex'), '.codex'], [SEG('.gemini'), '.gemini'], [SEG('.agents'), '.agents']]
170
210
  const HUMAN_ONLY = /\b(approve-tests|approve-shell)\b|\bSTOPBAR_[A-Z_]+/i
171
211
  const STOPBAR_ADMIN = /stopbar[^\n]*\b(init|resume|reset|doctor\s+--fix)\b/i
172
212
 
213
+ /** Command text inspected by self-protection. For a plain single-command `git commit` (chain-free, no substitution),
214
+ * strips the commit message (safe heredoc body or quoted `-m` / `--message` string) because git treats it as data. */
215
+ export function commandForSelfProtect(cmd , shell = 'bash') {
216
+ if (shell !== 'bash') return cmd
217
+ const c = cmd.trim()
218
+ const hd = parseSafeHeredocCommit(c)
219
+ if (hd) return hd.prefix
220
+ if (!COMMIT_ONLY_RE.test(c) || scanPlain(c).chain) return cmd
221
+ // Quote-aware strip of top-level `-m "..."` / `-am '...'` / `--message="..."` literals.
222
+ let out = ''
223
+ for (let i = 0; i < c.length;) {
224
+ const ch = c[i]
225
+ if (ch === "'" || ch === '"') {
226
+ const start = i++
227
+ while (i < c.length && c[i] !== ch) { if (ch === '"' && c[i] === '\\') i++; i++ }
228
+ i++
229
+ out += c.slice(start, i)
230
+ continue
231
+ }
232
+ if (ch === '\\') { out += c.slice(i, i + 2); i += 2; continue }
233
+ const atWordStart = i === 0 || /\s/.test(c[i - 1])
234
+ if (atWordStart && ch === '-') {
235
+ const m = /^(?:-[a-zA-Z]*m(?:\s+|(?=["']))|--message(?:=|\s+))/.exec(c.slice(i))
236
+ if (m) {
237
+ const after = i + m[0].length
238
+ const q = c[after]
239
+ if (q === '"' || q === "'") {
240
+ let j = after + 1
241
+ while (j < c.length && c[j] !== q) { if (q === '"' && c[j] === '\\') j++; j++ }
242
+ if (j < c.length) { out += '-m ""'; i = j + 1; continue }
243
+ }
244
+ }
245
+ }
246
+ out += ch; i++
247
+ }
248
+ return out
249
+ }
250
+
173
251
  /** Shell command text. Returns the reason for a block, or null. Text matching only: see SECURITY.md. */
174
252
  export function protectedCommand(cmd , pr ) {
175
253
  const c = norm(cmd).toLowerCase()
176
254
  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)'
255
+ 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)`
178
256
  if (isGitConfigWrite(cmd)) return '`git config` writes .git/config; only reads (--get, --list) are allowed'
179
257
  if (c.includes(lc(pr.stateDir)) || c.includes(lc(pr.gitDir) + '/')) return 'the command names the git directory'
180
258
  for (const d of pr.codeDirs) if (c.includes(lc(d))) return `the command names Stopbar code (${d})`
package/dist/cli.js CHANGED
@@ -9,9 +9,12 @@ const cmd = argv[0] ?? 'help'
9
9
 
10
10
  const HELP = `stopbar ${VERSION}: proven gates for coding agents (Claude Code hooks)
11
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
12
+ stopbar init --build "<cmd>" --test "<cmd>" [--profile default|ts|python|strict] [--base-ref <ref>] [--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
15
18
  stopbar status [--json] gates, taint, budget, why a commit is blocked
16
19
  stopbar approve-tests [--rev N] a human reviewed the changed tests/config up to revision N (default: current)
17
20
  stopbar approve-shell a human allows ONE risky or outbound call after a secret was read
@@ -42,11 +45,18 @@ function opts(a ) {
42
45
 
43
46
  async function main() {
44
47
  if (cmd === 'hook') {
45
- const {runHook} = await import('./hook.js')
48
+ const {handle} = await import('./adapters/index.js')
49
+ const i = argv.indexOf('--adapter')
50
+ const which = i >= 0 ? argv[i + 1] ?? '' : 'auto'
46
51
  let raw
47
52
  try { raw = readFileSync(0, 'utf8') } catch (e) { return {code: 2, msg: `STOPBAR FAIL-CLOSED: cannot read stdin (${(e ).message})`} }
48
- return runHook(raw, t0)
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}
49
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)))
50
60
  if (cmd === 'help' || cmd === '--help' || cmd === '-h') return {code: 0, msg: HELP}
51
61
  if (cmd === '--version' || cmd === 'version') return {code: 0, msg: VERSION}
52
62
  const o = opts(argv.slice(1))
package/dist/commands.js CHANGED
@@ -1,14 +1,15 @@
1
1
  // Built from src/commands.ts by scripts/build.ts. Do not edit.
2
2
  // Human commands: init, status, approve-tests, approve-shell, resume, reset. The agent cannot run them
3
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'
4
+ import {cpSync, existsSync, mkdirSync, rmSync} from 'node:fs'
5
+ import {join} from 'node:path'
6
6
  import {hasChain} from './classify.js'
7
+ import {CLAUDE_POST_MATCHER, claudeHooks, hookCommand, installHooks, parseTargets} from './integrations.js'
7
8
  import { ConfigError, makeConfig, PROFILES} from './config.js'
8
9
  import {decode, initKernel, kstep, MACHINE, } from './engine.js'
9
10
  import {whyBlocked} from './hook.js'
10
11
  import {PKG_ROOT} from './pkg.js'
11
- import {FailClosed, findRepo, forgetSnapshots, markCounted, snapshot} from './repo.js'
12
+ import {findRepo, forgetSnapshots, hasRefTree, markCounted, snapshot} from './repo.js'
12
13
  import {appendEvent, paths, readConfig, readEvents, readState, VERSION, withLock, writeConfig, writeState} from './store.js'
13
14
 
14
15
 
@@ -30,43 +31,10 @@ function humanStep(r , s , req , source ) {
30
31
  return after
31
32
  }
32
33
 
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
-
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)})
70
38
  /** Frozen copy of the runtime (bin/, dist/, package.json) in <git-dir>/stopbar/runtime. The hooks run this copy, so an
71
39
  * agent that edits or rebuilds a Stopbar checkout cannot change the code that judges it. No node_modules needed. */
72
40
  export function pinRuntime(r ) {
@@ -91,8 +59,13 @@ export function init(o ) {
91
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`}
92
60
  let cfg
93
61
  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)})
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), baseRef: o.get('base-ref')})
95
63
  } catch (e) { if (e instanceof ConfigError) return {code: 1, msg: e.message}; throw e }
64
+ if (cfg.baseRef && !hasRefTree(repo.root, cfg.baseRef)) {
65
+ return {code: 1, msg: `--base-ref ${JSON.stringify(cfg.baseRef)} does not resolve to a commit/tree in ${repo.root}`}
66
+ }
67
+ const hooksOpt = o.get('hooks')
68
+ const targets = hooksOpt === undefined ? [] : parseTargets(hooksOpt) // validated before anything is written
96
69
  mkdirSync(repo.stateDir, {recursive: true})
97
70
  return withLock(repo, () => {
98
71
  writeConfig(repo, cfg)
@@ -101,16 +74,27 @@ export function init(o ) {
101
74
  const runtime = pin ? pinRuntime(repo) : PKG_ROOT
102
75
  const command = hookCommand(runtime)
103
76
  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}`,
77
+ const lines = [`Stopbar ${VERSION} initialised in ${repo.stateDir}`, ` profile ${cfg.profile}; build: ${cfg.buildCmd}; full tests: ${cfg.fullTestCmd}${cfg.baseRef ? `; base ref: ${cfg.baseRef}` : ''}`,
105
78
  ` 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`.')
79
+ if (targets.length) for (const l of installHooks(repo, targets, runtime, o.has('force-hooks'))) lines.push(` hooks written: ${l}`)
80
+ 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))
81
+ lines.push('Next: restart the agent in this repository and run `stopbar doctor`.')
110
82
  return {code: 0, msg: lines.join('\n')}
111
83
  })
112
84
  }
113
85
 
86
+ /** Why the secret gate is on: the first secret read since the last init or reset, from the event log. */
87
+ export function secretReason(repo ) {
88
+ const ev = readEvents(repo).events
89
+ let start = 0
90
+ ev.forEach((e, i) => { if (e.source === 'human:init' || e.source === 'human:reset') start = i + 1 })
91
+ const hit = ev.slice(start).find((e) => e.req?.op === 'READ_SECRET' && e.secretTainted === true)
92
+ if (!hit) return null
93
+ if (!hit.secret) return {text: `${hit.source} at rev ${hit.treeRev} (pattern not recorded)`, revision: hit.treeRev}
94
+ const {pattern, path, tool} = hit.secret
95
+ return {text: `matched ${pattern} (${path}) in ${tool} at rev ${hit.treeRev}`, pattern, path, tool, revision: hit.treeRev}
96
+ }
97
+
114
98
  function statusText(repo , cfg , s ) {
115
99
  const v = decode(s.kernel)
116
100
  const yn = (b ) => (b ? 'yes' : 'no')
@@ -119,10 +103,10 @@ function statusText(repo , cfg , s ) {
119
103
  const torn = readEvents(repo).torn.length
120
104
  return [
121
105
  `Stopbar ${VERSION} repo ${repo.root}`,
122
- `revision ${v.treeRev} (tree ${s.snapshot.slice(0, 12)})`,
106
+ `revision ${v.treeRev} (tree ${s.snapshot.slice(0, 12)})${cfg.baseRef ? ` base ref ${cfg.baseRef}` : ''}`,
123
107
  `build ${ok(v.buildOkRev)} (${cfg.buildCmd})`,
124
108
  `full tests ${ok(v.testsOkRev)} (${cfg.fullTestCmd})`,
125
- `tainted ${yn(v.testsTainted)} secret read ${yn(v.secretTainted)} shell approval held ${yn(v.shellToken)}`,
109
+ `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)}`,
126
110
  `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
111
  `commit ${commit}`,
128
112
  ...(torn ? [`event log ${torn} torn line(s) kept as they are (see stopbar doctor)`] : []),
@@ -140,7 +124,8 @@ export function human(cmd , o ) {
140
124
  }
141
125
  const s = readState(repo)
142
126
  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)}
127
+ 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),
128
+ secretRead: decode(s.kernel).secretTainted ? secretReason(repo) : null}, null, 1) : statusText(repo, cfg, s)}
144
129
  }
145
130
  let res
146
131
  if (cmd === 'approve-tests') {
package/dist/config.js CHANGED
@@ -12,6 +12,10 @@ import {globToRegExp} from './glob.js'
12
12
 
13
13
 
14
14
 
15
+
16
+
17
+
18
+
15
19
 
16
20
 
17
21
  const TEST_COMMON = ['**/tests/**', '**/test/**', '**/__tests__/**']
@@ -38,11 +42,13 @@ export const PROFILES = {
38
42
  strict: {
39
43
  tests: [...TEST_COMMON, ...TEST_PY],
40
44
  testConfig: [...CFG_COMMON, ...CFG_PY, 'quality.sh', '**/quality*.sh', 'scripts/quality*', 'uv.lock', 'Dockerfile*', 'docker-compose*.yml', 'hypothesis*.ini'],
41
- secrets: [...SECRETS, '*.age', 'secrets.*'],
45
+ secrets: [...SECRETS, '*.age', 'secrets.{json,yaml,yml,toml,env,ini,txt,cfg,conf,xml,properties,age,enc,key,pem,local,prod,dev,staging}'],
42
46
  },
43
47
  }
44
48
 
45
49
  export const DEFAULTS = {maxRetries: 3, cap: 500, costPerCall: 1}
50
+ // local UI tools of Claude Desktop (task list and turn summary): no network, no files
51
+ export const DEFAULT_SAFE_TOOLS = ['mcp__ccd_turn__*']
46
52
 
47
53
  export class ConfigError extends Error {}
48
54
 
@@ -70,16 +76,32 @@ export function validateConfig(c ) {
70
76
  }
71
77
  }
72
78
  if (typeof o.profile !== 'string') throw new ConfigError('config.profile must be a string')
79
+ if (o.safeTools !== undefined) {
80
+ 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')
81
+ for (const g of o.safeTools ) {
82
+ try { globToRegExp(g) } catch (e) { throw new ConfigError(`config.safeTools: ${(e ).message}`) }
83
+ }
84
+ }
85
+ if (o.baseRef !== undefined) {
86
+ if (typeof o.baseRef !== 'string' || !isSafeRef(o.baseRef)) throw new ConfigError(`config.baseRef must be a valid git ref (no whitespace, ranges or leading '-'), got ${JSON.stringify(o.baseRef)}`)
87
+ }
73
88
  return o
74
89
  }
75
90
 
76
- export function makeConfig(a ) {
91
+ export function isSafeRef(ref ) {
92
+ return ref.length > 0 && !ref.startsWith('-') && !ref.includes('..') && !ref.endsWith('.') && !ref.endsWith('/') && /^[A-Za-z0-9._/@^~-]+$/.test(ref)
93
+ }
94
+
95
+ export function makeConfig(a ) {
77
96
  const profile = a.profile ?? 'default'
78
97
  const paths = PROFILES[profile]
79
98
  if (!paths) throw new ConfigError(`unknown profile ${JSON.stringify(profile)}; known: ${Object.keys(PROFILES).join(', ')}`)
99
+ const baseRef = a.baseRef?.trim()
80
100
  return validateConfig({
81
101
  version: 1, profile, buildCmd: a.buildCmd.trim(), fullTestCmd: a.fullTestCmd.trim(),
82
102
  maxRetries: a.maxRetries ?? DEFAULTS.maxRetries, cap: a.cap ?? DEFAULTS.cap, costPerCall: a.costPerCall ?? DEFAULTS.costPerCall,
83
103
  paths: {tests: [...paths.tests], testConfig: [...paths.testConfig], secrets: [...paths.secrets]},
104
+ safeTools: [...DEFAULT_SAFE_TOOLS],
105
+ ...(baseRef && baseRef !== 'HEAD' ? {baseRef} : {}),
84
106
  })
85
107
  }