stopbar 1.0.0 → 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,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 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'
@@ -55,6 +56,7 @@ export function attestation(repoDir ) {
55
56
  repository: {head, headTree, snapshot: s.snapshot, workingTreeSnapshot: now.id, treeRevision: v.treeRev},
56
57
  config: {profile: cfg.profile, buildCmd: cfg.buildCmd, fullTestCmd: cfg.fullTestCmd, maxRetries: cfg.maxRetries, cap: cfg.cap, costPerCall: cfg.costPerCall},
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,
@@ -76,7 +78,7 @@ export function attestMarkdown(a ) {
76
78
  `| HEAD | \`${a.repository.head ?? '(none)'}\` |`, `| HEAD tree | \`${a.repository.headTree ?? '(none)'}\` |`,
77
79
  `| Counted snapshot | \`${a.repository.snapshot}\` (revision ${a.repository.treeRevision}) |`,
78
80
  `| 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)} |`,
81
+ `| Tests tainted | ${yn(g.tainted)} |`, `| Secret read | ${g.secretRead ? `yes: ${g.secretReadBy}` : 'no'} |`, `| Halted | ${yn(g.halted)} |`,
80
82
  `| Commit allowed now | ${yn(g.commitAllowedNow)}${g.why ? `: ${g.why}` : ''} |`,
81
83
  `| Budget | ${g.budget.spent}/${g.budget.cap} |`,
82
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'}) |`,
@@ -1,6 +1,6 @@
1
1
  {
2
- "version": "1.0.0",
2
+ "version": "1.1.0",
3
3
  "kernelSourceSha256": "c602fc4bcf8ffb2e312bf838986e6d4b006af6d0e6c7447c8c61d5888adc5ef8",
4
4
  "machineSha256": "b397085e0cb13e2e50aa655c54de0744d08f2ebf500bf32af8ff3e8a11ba7321",
5
- "files": 16
5
+ "files": 26
6
6
  }
package/dist/classify.js CHANGED
@@ -9,7 +9,12 @@ const norm = (p ) => p.replace(/\\/g, '/')
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
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)
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
13
18
 
14
19
  // ---------------------------------------------------------------- safe heredoc commit
15
20
  // The one form of command substitution the wrapper lets through, the way Claude Code writes commit messages:
@@ -104,19 +109,33 @@ const TEST_RUNNER = new RegExp([
104
109
  ].join('|'), 'i')
105
110
  export const looksLikeTests = (cmd ) => TEST_RUNNER.test(cmd)
106
111
 
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))
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
110
128
  }
129
+ export const mentionsSecret = (cmd , paths , exists ) => secretInCommand(cmd, paths, exists) !== null
111
130
 
112
131
 
113
132
 
114
133
 
115
134
 
116
-
135
+
117
136
 
118
137
  /** Exact match of gate commands: no chain operators, no extra arguments. `shell` is 'bash' or 'powershell'. */
119
- export function classifyBash(cmd , cfg , shell = 'bash') {
138
+ export function classifyBash(cmd , cfg , shell = 'bash', exists ) {
120
139
  const c = cmd.trim()
121
140
  const scan = shell === 'bash' ? scanShell(c) : scanPlain(c)
122
141
  if (COMMIT_RE.test(scan.heredoc ? commandPart(c) : c)) {
@@ -130,7 +149,7 @@ export function classifyBash(cmd , cfg
130
149
  if (c === cfg.buildCmd.trim()) return {kind: 'build'}
131
150
  if (c === cfg.fullTestCmd.trim()) return {kind: 'fulltest'}
132
151
  }
133
- return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: mentionsSecret(c, cfg.paths)}
152
+ return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: secretInCommand(c, cfg.paths, exists)}
134
153
  }
135
154
 
136
155
  /** Kind of a tree change from a list of (status, path) and a test for "the path exists in HEAD". */
@@ -154,19 +173,29 @@ export function classifyTreeChange(changes , in
154
173
  const lc = (p ) => norm(p).toLowerCase().replace(/\/+$/, '')
155
174
  const under = (a , dir ) => a === dir || a.startsWith(dir + '/')
156
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
+
157
185
  /** File path written by an Edit/Write tool. Returns the reason for a block, or null. */
158
186
  export function protectedPath(abs , root , pr ) {
159
187
  const a = lc(abs), r = lc(root)
160
188
  // inside the repository the .git test runs on the relative path; outside it on the whole path (other repositories)
161
189
  const tail = under(a, r) ? a.slice(r.length) : a
162
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)'
163
- if (/(^|\/)\.claude\/[^/]*settings[^/]*\.json$/.test(a)) return 'Claude Code settings (.claude/settings*.json) hold the Stopbar hooks'
191
+ for (const [re, what] of AGENT_CONFIG) if (re.test(a)) return `${what} hold the Stopbar hooks`
164
192
  for (const d of pr.codeDirs) if (under(a, lc(d))) return `Stopbar code (${d})`
165
193
  return null
166
194
  }
167
195
 
168
196
  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')
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']]
170
199
  const HUMAN_ONLY = /\b(approve-tests|approve-shell)\b|\bSTOPBAR_[A-Z_]+/i
171
200
  const STOPBAR_ADMIN = /stopbar[^\n]*\b(init|resume|reset|doctor\s+--fix)\b/i
172
201
 
@@ -174,7 +203,7 @@ const STOPBAR_ADMIN = /stopbar[^\n]*\b(init|resume|reset|doctor\s+--fix)\b/i
174
203
  export function protectedCommand(cmd , pr ) {
175
204
  const c = norm(cmd).toLowerCase()
176
205
  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)'
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)`
178
207
  if (isGitConfigWrite(cmd)) return '`git config` writes .git/config; only reads (--get, --list) are allowed'
179
208
  if (c.includes(lc(pr.stateDir)) || c.includes(lc(pr.gitDir) + '/')) return 'the command names the git directory'
180
209
  for (const d of pr.codeDirs) if (c.includes(lc(d))) return `the command names Stopbar code (${d})`
package/dist/cli.js CHANGED
@@ -10,8 +10,11 @@ const cmd = argv[0] ?? 'help'
10
10
  const HELP = `stopbar ${VERSION}: proven gates for coding agents (Claude Code hooks)
11
11
 
12
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
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, 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 ) {
@@ -93,6 +61,8 @@ export function init(o ) {
93
61
  try {
94
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)})
95
63
  } catch (e) { if (e instanceof ConfigError) return {code: 1, msg: e.message}; throw e }
64
+ const hooksOpt = o.get('hooks')
65
+ const targets = hooksOpt === undefined ? [] : parseTargets(hooksOpt) // validated before anything is written
96
66
  mkdirSync(repo.stateDir, {recursive: true})
97
67
  return withLock(repo, () => {
98
68
  writeConfig(repo, cfg)
@@ -103,14 +73,25 @@ export function init(o ) {
103
73
  appendEvent(repo, {source: 'human:init', cfg, runtime, version: VERSION, kernel: MACHINE})
104
74
  const lines = [`Stopbar ${VERSION} initialised in ${repo.stateDir}`, ` profile ${cfg.profile}; build: ${cfg.buildCmd}; full tests: ${cfg.fullTestCmd}`,
105
75
  ` 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`.')
76
+ if (targets.length) for (const l of installHooks(repo, targets, runtime, o.has('force-hooks'))) lines.push(` hooks written: ${l}`)
77
+ else lines.push(' add these hooks to .claude/settings.local.json (or run init again with --hooks claude,cursor,codex,gemini,antigravity,git):', JSON.stringify(hooksConfig(command), null, 2))
78
+ lines.push('Next: restart the agent in this repository and run `stopbar doctor`.')
110
79
  return {code: 0, msg: lines.join('\n')}
111
80
  })
112
81
  }
113
82
 
83
+ /** Why the secret gate is on: the first secret read since the last init or reset, from the event log. */
84
+ export function secretReason(repo ) {
85
+ const ev = readEvents(repo).events
86
+ let start = 0
87
+ ev.forEach((e, i) => { if (e.source === 'human:init' || e.source === 'human:reset') start = i + 1 })
88
+ const hit = ev.slice(start).find((e) => e.req?.op === 'READ_SECRET' && e.secretTainted === true)
89
+ if (!hit) return null
90
+ if (!hit.secret) return {text: `${hit.source} at rev ${hit.treeRev} (pattern not recorded)`, revision: hit.treeRev}
91
+ const {pattern, path, tool} = hit.secret
92
+ return {text: `matched ${pattern} (${path}) in ${tool} at rev ${hit.treeRev}`, pattern, path, tool, revision: hit.treeRev}
93
+ }
94
+
114
95
  function statusText(repo , cfg , s ) {
115
96
  const v = decode(s.kernel)
116
97
  const yn = (b ) => (b ? 'yes' : 'no')
@@ -122,7 +103,7 @@ function statusText(repo , cfg , s ) {
122
103
  `revision ${v.treeRev} (tree ${s.snapshot.slice(0, 12)})`,
123
104
  `build ${ok(v.buildOkRev)} (${cfg.buildCmd})`,
124
105
  `full tests ${ok(v.testsOkRev)} (${cfg.fullTestCmd})`,
125
- `tainted ${yn(v.testsTainted)} secret read ${yn(v.secretTainted)} shell approval held ${yn(v.shellToken)}`,
106
+ `tainted ${yn(v.testsTainted)} secret read ${v.secretTainted ? `yes (${secretReason(repo)?.text ?? 'reason not in the event log'})` : 'no'} shell approval held ${yn(v.shellToken)}`,
126
107
  `session ${v.halted ? 'HALTED' : 'running'} spent ${v.spent}/${v.capNow} test failures ${v.testFails}/${s.params.maxRetries} build failures ${v.buildFails}/${s.params.maxRetries}`,
127
108
  `commit ${commit}`,
128
109
  ...(torn ? [`event log ${torn} torn line(s) kept as they are (see stopbar doctor)`] : []),
@@ -140,7 +121,8 @@ export function human(cmd , o ) {
140
121
  }
141
122
  const s = readState(repo)
142
123
  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)}
124
+ return {code: 0, msg: o.has('json') ? JSON.stringify({version: VERSION, repo: repo.root, stateDir: repo.stateDir, config: cfg, snapshot: s.snapshot, params: s.params, kernel: decode(s.kernel),
125
+ secretRead: decode(s.kernel).secretTainted ? secretReason(repo) : null}, null, 1) : statusText(repo, cfg, s)}
144
126
  }
145
127
  let res
146
128
  if (cmd === 'approve-tests') {
package/dist/config.js CHANGED
@@ -12,6 +12,8 @@ import {globToRegExp} from './glob.js'
12
12
 
13
13
 
14
14
 
15
+
16
+
15
17
 
16
18
 
17
19
  const TEST_COMMON = ['**/tests/**', '**/test/**', '**/__tests__/**']
@@ -43,6 +45,8 @@ export const PROFILES = {
43
45
  }
44
46
 
45
47
  export const DEFAULTS = {maxRetries: 3, cap: 500, costPerCall: 1}
48
+ // local UI tools of Claude Desktop (task list and turn summary): no network, no files
49
+ export const DEFAULT_SAFE_TOOLS = ['mcp__ccd_turn__*']
46
50
 
47
51
  export class ConfigError extends Error {}
48
52
 
@@ -70,6 +74,12 @@ export function validateConfig(c ) {
70
74
  }
71
75
  }
72
76
  if (typeof o.profile !== 'string') throw new ConfigError('config.profile must be a string')
77
+ if (o.safeTools !== undefined) {
78
+ if (!Array.isArray(o.safeTools) || !o.safeTools.every((x) => typeof x === 'string' && x.length > 0)) throw new ConfigError('config.safeTools must be a list of glob strings')
79
+ for (const g of o.safeTools ) {
80
+ try { globToRegExp(g) } catch (e) { throw new ConfigError(`config.safeTools: ${(e ).message}`) }
81
+ }
82
+ }
73
83
  return o
74
84
  }
75
85
 
@@ -81,5 +91,6 @@ export function makeConfig(a
81
91
  version: 1, profile, buildCmd: a.buildCmd.trim(), fullTestCmd: a.fullTestCmd.trim(),
82
92
  maxRetries: a.maxRetries ?? DEFAULTS.maxRetries, cap: a.cap ?? DEFAULTS.cap, costPerCall: a.costPerCall ?? DEFAULTS.costPerCall,
83
93
  paths: {tests: [...paths.tests], testConfig: [...paths.testConfig], secrets: [...paths.secrets]},
94
+ safeTools: [...DEFAULT_SAFE_TOOLS],
84
95
  })
85
96
  }
package/dist/doctor.js CHANGED
@@ -3,10 +3,10 @@
3
3
  import {execFileSync} from 'node:child_process'
4
4
  import {createHash} from 'node:crypto'
5
5
  import {existsSync, mkdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs'
6
- import {join} from 'node:path'
6
+ import {isAbsolute, join} from 'node:path'
7
7
  import {hasChain} from './classify.js'
8
8
  import {fresh, HOOK_MATCHERS} from './commands.js'
9
- import {makeConfig} from './config.js'
9
+ import {DEFAULT_SAFE_TOOLS, makeConfig} from './config.js'
10
10
  import {decode, MACHINE} from './engine.js'
11
11
  import {runHook} from './hook.js'
12
12
  import {PKG_ROOT} from './pkg.js'
@@ -49,6 +49,56 @@ function checkHooks(root , add
49
49
  }
50
50
  }
51
51
 
52
+ const STOPBAR = /stopbar(\.mjs)?"?\s+(hook|git-hook)\b/
53
+ const scriptOf = (cmd ) => /node\s+"?([^"]+?stopbar\.mjs)"?\s+(?:git-)?hook/.exec(cmd)?.[1]
54
+ function readJsonOrInvalid(f ) {
55
+ if (!existsSync(f)) return null
56
+ try { return JSON.parse(readFileSync(f, 'utf8')) } catch { return 'invalid' }
57
+ }
58
+ /** Commands of Stopbar hooks per event, from any nesting of {command} objects under each event. */
59
+ function stopbarCommands(events ) {
60
+ const out = {}
61
+ const walk = (ev , x ) => {
62
+ if (Array.isArray(x)) { for (const y of x) walk(ev, y); return }
63
+ if (!x || typeof x !== 'object') return
64
+ const o = x
65
+ if (typeof o.command === 'string' && STOPBAR.test(o.command)) (out[ev] ??= []).push(o.command)
66
+ if (o.hooks) walk(ev, o.hooks)
67
+ }
68
+ for (const [ev, v] of Object.entries(events ?? {})) walk(ev, v)
69
+ return out
70
+ }
71
+
72
+ /** Other clients and the git fallback. Returns how many have Stopbar hooks. */
73
+ function checkOtherClients(repo , add ) {
74
+ let found = 0
75
+ const clients = [
76
+ ['cursor', join(repo.root, '.cursor', 'hooks.json'), (j) => j.hooks, ['preToolUse', 'postToolUse', 'postToolUseFailure', 'stop']],
77
+ ['codex', join(repo.root, '.codex', 'hooks.json'), (j) => j.hooks, ['PreToolUse', 'PostToolUse', 'Stop']],
78
+ ['gemini', join(repo.root, '.gemini', 'settings.json'), (j) => j.hooks, ['BeforeTool', 'AfterTool', 'AfterAgent']],
79
+ ['antigravity', join(repo.root, '.agents', 'hooks.json'), (j) => Object.assign({}, ...Object.values(j).filter((v) => v && typeof v === 'object' && (v ).enabled !== false)), ['PreToolUse', 'PostToolUse', 'Stop']],
80
+ ]
81
+ for (const [name, f, events, need] of clients) {
82
+ const j = readJsonOrInvalid(f)
83
+ if (j === null) continue
84
+ if (j === 'invalid') { add('FAIL', `hooks ${name}`, `${f} is not valid JSON`); found++; continue }
85
+ const cmds = stopbarCommands(events(j))
86
+ if (!Object.keys(cmds).length) continue
87
+ found++
88
+ const missing = need.filter((e) => !cmds[e]?.length)
89
+ const script = scriptOf(Object.values(cmds)[0][0])
90
+ if (missing.length) add('FAIL', `hooks ${name}`, `${f}: no Stopbar hook for ${missing.join(', ')}`)
91
+ else if (script && !existsSync(script)) add('FAIL', `hooks ${name}`, `script not found: ${script}`)
92
+ else if (name === 'cursor' && JSON.stringify(j.hooks).includes('"failClosed":false')) add('WARN', `hooks ${name}`, `${f}: failClosed is false, so a crash of the hook lets the action run`)
93
+ else add('OK', `hooks ${name}`, `${need.join(', ')} (${f.replace(/\\/g, '/').split('/').slice(-2).join('/')})`)
94
+ }
95
+ let dir = join(repo.gitDir, 'hooks')
96
+ try { const rel = execFileSync('git', ['rev-parse', '--git-path', 'hooks'], {cwd: repo.root, encoding: 'utf8'}).trim(); dir = isAbsolute(rel) ? rel : join(repo.root, rel) } catch { /* default */ }
97
+ const gh = ['pre-commit', 'pre-push'].filter((n) => existsSync(join(dir, n)) && readFileSync(join(dir, n), 'utf8').includes('stopbar.mjs" git-hook'))
98
+ if (gh.length) { found++; add(gh.length === 2 ? 'OK' : 'WARN', 'hooks git', `${gh.join(', ')} in ${dir}${gh.length === 2 ? '' : ' (one of pre-commit, pre-push is missing)'}`) }
99
+ return found
100
+ }
101
+
52
102
  /** The real hook pipeline (in process) on a scratch repository inside <git-dir>/stopbar/doctor-run. */
53
103
  function dryRun(base , add ) {
54
104
  const dir = join(base, 'doctor-run')
@@ -107,7 +157,7 @@ export async function doctor(o )
107
157
  try {
108
158
  const cfg = readConfig(repo); cfgOk = true
109
159
  add('OK', 'config.json', `profile ${cfg.profile}; build \`${cfg.buildCmd}\`; full tests \`${cfg.fullTestCmd}\`; maxRetries ${cfg.maxRetries}; cap ${cfg.cap}; ` +
110
- `${cfg.paths.tests.length}/${cfg.paths.testConfig.length}/${cfg.paths.secrets.length} test/config/secret patterns`)
160
+ `${cfg.paths.tests.length}/${cfg.paths.testConfig.length}/${cfg.paths.secrets.length} test/config/secret patterns; safeTools ${JSON.stringify(cfg.safeTools ?? DEFAULT_SAFE_TOOLS)}`)
111
161
  for (const [k, v] of [['buildCmd', cfg.buildCmd], ['fullTestCmd', cfg.fullTestCmd]]) if (hasChain(v)) add('FAIL', 'config.json', `${k} has shell operators: it can never pass as a gate`)
112
162
  try {
113
163
  const s = readState(repo), v = decode(s.kernel)
@@ -122,7 +172,9 @@ export async function doctor(o )
122
172
  const same = existsSync(join(PKG_ROOT, 'dist', 'kernel.gen.js')) && sha(rt) === sha(join(PKG_ROOT, 'dist', 'kernel.gen.js'))
123
173
  add(same ? 'OK' : 'WARN', 'pinned runtime', `${join(repo.stateDir, 'runtime')}${same ? ' (same kernel as this package)' : ' differs from this package: a human runs `stopbar init --force ...` to re-pin'}`)
124
174
  } else if (cfgOk) add('WARN', 'pinned runtime', 'none: hooks run an unpinned copy (init --no-pin)')
125
- checkHooks(repo.root, add)
175
+ const others = checkOtherClients(repo, add)
176
+ const claudeHas = ['settings.json', 'settings.local.json'].some((n) => { const h = hooksIn(join(repo .root, '.claude', n)); return h !== null && Object.keys(stopbarCommands(h)).length > 0 })
177
+ if (claudeHas || others === 0) checkHooks(repo.root, add) // without any client hooks, report the Claude Code ones as missing (v1.0 output)
126
178
  try { dryRun(repo.stateDir, add) } catch (e) { add('FAIL', 'dry run', String(e)) }
127
179
  }
128
180
  const fails = checks.filter((c) => c.status === 'FAIL').length, warns = checks.filter((c) => c.status === 'WARN').length
@@ -0,0 +1,17 @@
1
+ // Built from src/githook.ts by scripts/build.ts. Do not edit.
2
+ // `stopbar git-hook pre-commit|pre-push`: the fallback gate for tools without their own hook system. Git runs it from
3
+ // .git/hooks; it goes through the same path as an agent's `git commit` / `git push` (the generated kernel step): the
4
+ // working tree is synced, then COMMIT must be allowed (passing build and full suite at this revision, no unapproved
5
+ // test changes); a push is also a risky outbound call, paused after a secret read without a human approval.
6
+ // Exit 0 lets git go on, exit 1 aborts the commit or push (git's convention).
7
+ import {runEvent} from './hook.js'
8
+
9
+
10
+
11
+ export function gitHook(which , o ) {
12
+ if (which !== 'pre-commit' && which !== 'pre-push') return {code: 1, msg: 'usage: stopbar git-hook pre-commit|pre-push'}
13
+ const out = runEvent({hook_event_name: 'PreToolUse', cwd: o.get('repo') ?? process.cwd(), tool_name: 'Bash',
14
+ tool_input: {command: which === 'pre-commit' ? 'git commit' : 'git push'}, stopbar: {adapter: 'git', rawKeys: [], event: which}})
15
+ if (out.code === 0) return {code: 0}
16
+ return {code: 1, msg: `stopbar ${which}: ${out.msg ?? 'blocked'}`}
17
+ }