stopbar 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/hook.js CHANGED
@@ -7,12 +7,29 @@ import * as K from './classify.js'
7
7
  import {cliOf, DEFAULT_SAFE_TOOLS} from './config.js'
8
8
  import {matchAny} from './glob.js'
9
9
  import {decode, kstep, } from './engine.js'
10
- import {changesSinceHead, countedEntries, diffEntries, differsFromHead, FailClosed, findRepo, gitCalls, inRef, markCounted, snapshot} from './repo.js'
10
+ import {changesSinceHead, countedEntries, diffEntries, differsFromHead, FailClosed, findRepo, gitCalls, markCounted, oidOf, refEntries, snapshot} from './repo.js'
11
11
  import {appendEvent, readConfig, readState, withLock, writeState} from './store.js'
12
12
  import {codeDirs} from './pkg.js'
13
13
 
14
14
 
15
15
 
16
+ /** A hook event: Claude Code's JSON object (adapters translate other clients into it). Fields are read with guards. */
17
+
18
+ /** Stopbar's own fields on an event: set by the adapters and by `stopbar run`, never by the agent's client. */
19
+
20
+
21
+ const obj = (x ) => (x && typeof x === 'object' && !Array.isArray(x) ? x : {})
22
+ const strings = (...xs ) => xs.flatMap((x) => (Array.isArray(x) ? x : [x])).filter((x) => typeof x === 'string' && x.length > 0)
23
+ function metaOf(x ) {
24
+ const m = obj(x)
25
+ return {
26
+ ...(typeof m.adapter === 'string' ? {adapter: m.adapter} : {}),
27
+ ...(m.rawKeys !== undefined ? {rawKeys: m.rawKeys} : {}),
28
+ ...(typeof m.expectedSnapshot === 'string' ? {expectedSnapshot: m.expectedSnapshot} : {}),
29
+ ...(typeof m.expectedRev === 'number' ? {expectedRev: m.expectedRev} : {}),
30
+ ...(m.requireExitCode === true ? {requireExitCode: true} : {}),
31
+ }
32
+ }
16
33
 
17
34
  const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
18
35
  const READ_TOOLS = new Set(['Read', 'Grep', 'Glob', 'LS'])
@@ -42,6 +59,18 @@ export function whyBlocked(v , cfg
42
59
  return r.join('; ') || 'kernel decision'
43
60
  }
44
61
 
62
+ /** Classifies changed paths against the reference tree (baseRef, else HEAD). One git process, and only when a test or
63
+ * (with baseRef) a test-config file changed: a code-only change costs no git process here. With baseRef, a test or
64
+ * test-config file whose blob id equals baseRef's is not suspicious (taken over from baseRef by checkout, rebase or
65
+ * cherry-pick, or put back to it). Shared by the hooks and by `init --force` / `reset` on a dirty tree. */
66
+ export function classifyChanges(repo , cfg , changes , now ) {
67
+ const ref = cfg.baseRef ?? 'HEAD'
68
+ const watched = changes.map((c) => c.path).filter((p) => K.isTestConfigPath(p, cfg.paths) ? !!cfg.baseRef : K.isTestPath(p, cfg.paths))
69
+ const inRef = refEntries(repo.root, ref, watched)
70
+ const same = cfg.baseRef ? (p ) => oidOf(now.get(p)) === oidOf(inRef.get(p)) : undefined
71
+ return K.classifyTreeChange(changes, (p) => inRef.has(p), cfg.paths, same)
72
+ }
73
+
45
74
  /** Counts a working-tree change the kernel has not seen yet. */
46
75
  function syncTree(ctx , cost , source ) {
47
76
  const {repo, s, cfg} = ctx
@@ -56,9 +85,7 @@ function syncTree(ctx , cost , source ) {
56
85
  changes = changesSinceHead(repo, snap.entries)
57
86
  appendEvent(repo, {source: `${source}:fallback-diff`, note: 'counted snapshot copy missing; diff against HEAD'})
58
87
  }
59
- const testPaths = changes.map((c) => c.path).filter((p) => K.isTestPath(p, cfg.paths) && !K.isTestConfigPath(p, cfg.paths))
60
- const existing = testPaths.length ? inRef(repo.root, cfg.baseRef ?? 'HEAD', testPaths) : new Set ()
61
- const cls = K.classifyTreeChange(changes, (p) => existing.has(p), cfg.paths)
88
+ const cls = classifyChanges(repo, cfg, changes, snap.entries)
62
89
  const {before, after} = step(ctx, {op: cls.op, suspicious: cls.suspicious, cost}, `${source}:tree ${cls.why.join(', ') || `${changes.length} file(s)`}`)
63
90
  // not executed (halted or over budget): the change stays pending and is counted later
64
91
  if (after.treeRev > before.treeRev) { s.snapshot = snap.id; markCounted(repo); ctx.dirty = true }
@@ -67,42 +94,48 @@ function syncTree(ctx , cost , source ) {
67
94
 
68
95
  const block = (reason ) => ({code: 2, msg: `BLOCK (stopbar): ${reason}`})
69
96
 
70
- function isBackgroundInput(ti ) {
71
- return ti?.run_in_background === true || ti?.run_in_background === 'true' || ti?.background === true
97
+ function isBackgroundInput(ti ) {
98
+ return ti.run_in_background === true || ti.run_in_background === 'true' || ti.background === true
72
99
  }
73
- function isBackgroundResponse(tr ) {
74
- if (!tr || typeof tr !== 'object') return false
75
- return (typeof tr.backgroundTaskId === 'string' && tr.backgroundTaskId.length > 0) ||
76
- (typeof tr.background_task_id === 'string' && tr.background_task_id.length > 0) ||
77
- tr.isAsync === true || tr.background === true
100
+ function isBackgroundResponse(tr ) {
101
+ const r = obj(tr)
102
+ return (typeof r.backgroundTaskId === 'string' && r.backgroundTaskId.length > 0) ||
103
+ (typeof r.background_task_id === 'string' && r.background_task_id.length > 0) ||
104
+ r.isAsync === true || r.background === true
78
105
  }
79
106
 
80
107
  // ---------------------------------------------------------------- PreToolUse
81
- function pre(ctx , input ) {
82
- const tool = String(input.tool_name ?? ''), ti = input.tool_input ?? {}
108
+ function pre(ctx , input ) {
109
+ const tool = String(input.tool_name ?? ''), ti = obj(input.tool_input)
83
110
  const {repo, cfg} = ctx
111
+ const shell = tool === 'PowerShell' ? 'powershell' : 'bash'
84
112
  // self-protection: unconditional, before the kernel, also when halted
85
113
  if (EDIT_TOOLS.has(tool)) {
86
- const list = [ti.file_path, ti.notebook_path, ti.path, ...(Array.isArray(ti.file_paths) ? ti.file_paths : [])]
87
- for (const p of list.filter((x) => typeof x === 'string' && x)) {
114
+ for (const p of strings(ti.file_path, ti.notebook_path, ti.path, ti.file_paths)) {
88
115
  const why = K.protectedPath(resolve(repo.root, p), repo.root, ctx.protect)
89
116
  if (why) { appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: why, path: p}); return block(`writing ${p} is not allowed: ${why}. Ask the human.`) }
90
117
  }
91
118
  }
92
119
  if (SHELL_TOOLS.has(tool)) {
93
120
  const cmd = String(ti.command ?? '')
94
- const why = K.protectedCommand(K.commandForSelfProtect(cmd, tool === 'PowerShell' ? 'powershell' : 'bash'), ctx.protect)
121
+ const why = K.protectedCommand(K.commandForSelfProtect(cmd, shell), ctx.protect, shell)
95
122
  if (why) { appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: why}); return block(`${why}. Ask the human.`) }
96
123
  }
97
124
  const v = decode(ctx.s.kernel)
125
+ // local tools in config.safeTools (task list, turn summary, messages between local sessions) never take a kernel step,
126
+ // so they stay allowed while halted: the agent can still ask a human for `stopbar resume`. File, shell and every
127
+ // other tool stay paused.
128
+ if (!EDIT_TOOLS.has(tool) && !READ_TOOLS.has(tool) && !SHELL_TOOLS.has(tool) && matchAny(tool, cfg.safeTools ?? DEFAULT_SAFE_TOOLS)) {
129
+ if (v.halted) appendEvent(repo, {source: 'pre', tool, wrapper: 'ALLOW', reason: 'safe tool while halted'})
130
+ return {code: 0}
131
+ }
98
132
  if (v.halted) {
99
133
  appendEvent(repo, {source: 'pre', tool, wrapper: 'PAUSE', reason: 'halted'})
100
134
  return {code: 2, msg: `PAUSE (stopbar): the session is halted (testFails=${v.testFails}, buildFails=${v.buildFails}, spent=${v.spent}/${v.capNow}). A human must run: stopbar resume --extra <n>`}
101
135
  }
102
136
  const cost = cfg.costPerCall
103
137
  if (READ_TOOLS.has(tool)) {
104
- const ps = [ti.file_path, ti.path, ti.glob, ti.pattern, ...(Array.isArray(ti.file_paths) ? ti.file_paths : [])].filter((x) => typeof x === 'string' && x)
105
- for (const p of ps) {
138
+ for (const p of strings(ti.file_path, ti.path, ti.glob, ti.pattern, ti.file_paths)) {
106
139
  const pattern = K.secretPattern(p, cfg.paths)
107
140
  if (pattern) { step(ctx, {op: 'READ_SECRET', cost}, `pre:${tool}`, {secret: {pattern, path: p, tool}}); break }
108
141
  }
@@ -113,7 +146,7 @@ function pre(ctx , input ) {
113
146
  const cmd = String(ti.command ?? '')
114
147
  const base = typeof input.cwd === 'string' && input.cwd ? input.cwd : repo.root
115
148
  const exists = (t ) => existsSync(resolve(base, t)) || existsSync(resolve(repo.root, t))
116
- const k = K.classifyBash(cmd, cfg, tool === 'PowerShell' ? 'powershell' : 'bash', exists)
149
+ const k = K.classifyBash(cmd, cfg, shell, exists)
117
150
  if (k.kind === 'commit-chained') {
118
151
  appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: `chained commit (${k.reason})`})
119
152
  return block(`run \`git commit\` / \`git push\` as a single command (${k.reason}): no &&, ;, |, redirections or $(...). ` +
@@ -150,8 +183,7 @@ function pre(ctx , input ) {
150
183
  }
151
184
  return {code: 0}
152
185
  }
153
- if (OUTBOUND(tool)) {
154
- if (matchAny(tool, cfg.safeTools ?? DEFAULT_SAFE_TOOLS)) return {code: 0} // local tools listed in config.safeTools
186
+ if (OUTBOUND(tool)) { // tools in config.safeTools returned above
155
187
  const {after} = step(ctx, {op: 'SHELL', risky: true, cost}, `pre:${tool}`)
156
188
  if (after.decision === 'PAUSE') return {code: 2, msg: `PAUSE (stopbar): ${tool} is outbound and a secret was read (or the budget is spent); a human runs \`stopbar approve-shell\` or \`stopbar resume\``}
157
189
  }
@@ -161,27 +193,27 @@ function pre(ctx , input ) {
161
193
  // ---------------------------------------------------------------- PostToolUse / PostToolUseFailure
162
194
  // Claude Code sends PostToolUse after success and PostToolUseFailure after an error (non-zero exit of Bash).
163
195
  // PostToolUse carries no exit code: success unless is_error / interrupted. Failure is the event type itself.
164
- function exitCodeOf(tr ) {
165
- if (!tr || typeof tr !== 'object') return undefined
166
- for (const k of ['exitCode', 'exit_code', 'returnCode', 'code']) if (typeof tr[k] === 'number') return tr[k]
196
+ function exitCodeOf(tr ) {
197
+ const r = obj(tr)
198
+ for (const k of ['exitCode', 'exit_code', 'returnCode', 'code']) { const v = r[k]; if (typeof v === 'number') return v }
167
199
  return undefined
168
200
  }
169
201
 
170
- function post(ctx , input , failure ) {
171
- const tool = String(input.tool_name ?? ''), ti = input.tool_input ?? {}
202
+ function post(ctx , input , failure ) {
203
+ const tool = String(input.tool_name ?? ''), ti = obj(input.tool_input)
172
204
  const {repo, cfg} = ctx
173
205
  const msgs = []
174
206
  if (SHELL_TOOLS.has(tool)) {
175
207
  const k = K.classifyBash(String(ti.command ?? ''), cfg, tool === 'PowerShell' ? 'powershell' : 'bash')
176
- const tr = input.tool_response
177
- const meta = input.stopbar ?? {}
178
- appendEvent(repo, {source: `payload:${input.hook_event_name}`, tool, ...(meta.adapter ? {adapter: meta.adapter, rawKeys: meta.rawKeys} : {inputKeys: Object.keys(input)}),
208
+ const tr = input.tool_response, r = obj(tr)
209
+ const meta = metaOf(input.stopbar)
210
+ appendEvent(repo, {source: `payload:${String(input.hook_event_name)}`, tool, ...(meta.adapter ? {adapter: meta.adapter, rawKeys: meta.rawKeys} : {inputKeys: Object.keys(input)}),
179
211
  toolResponseKeys: tr && typeof tr === 'object' ? Object.keys(tr) : typeof tr})
180
212
  const bg = isBackgroundInput(ti) || isBackgroundResponse(tr)
181
213
  const staleRun = typeof meta.expectedSnapshot === 'string' &&
182
214
  (meta.expectedSnapshot !== ctx.s.snapshot || (typeof meta.expectedRev === 'number' && meta.expectedRev !== decode(ctx.s.kernel).treeRev))
183
215
  const code = exitCodeOf(tr)
184
- const flagged = input.is_error === true || tr?.is_error === true || tr?.interrupted === true
216
+ const flagged = input.is_error === true || r.is_error === true || r.interrupted === true
185
217
  // some clients send the same post event for success and failure: then only an explicit exit code 0 is a pass
186
218
  const unknown = meta.requireExitCode === true && code === undefined
187
219
  const passed = failure ? false : code !== undefined ? code === 0 : !flagged && !unknown
@@ -189,10 +221,15 @@ function post(ctx , input , failure ) {
189
221
  if (failure && input.is_interrupt === true) {
190
222
  // Ctrl+C by the user: not a failed gate and not a retry; the tree is still checked below
191
223
  appendEvent(repo, {source: 'post:user-interrupt', tool, kind: k.kind})
224
+ } else if (cfg.requireRun === true && meta.adapter !== 'run' && (k.kind === 'build' || k.kind === 'fulltest')) {
225
+ // config.requireRun: a gate counts only through `stopbar run build|test`, never from the agent's own shell
226
+ const which = k.kind === 'build' ? 'build' : 'test'
227
+ appendEvent(repo, {source: 'post:require-run', tool, kind: k.kind, ...(meta.adapter ? {adapter: meta.adapter} : {})})
228
+ msgs.push(`NOTE (stopbar): this repository records gates only through \`${runHint(cfg, which)}\` (config.requireRun), so \`${k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd}\` run from the agent's shell is not recorded. Run \`${runHint(cfg, which)}\` instead: it runs the same command and records its real exit status.`)
192
229
  } else if (!failure && bg && (k.kind === 'build' || k.kind === 'fulltest' || (k.kind === 'shell' && k.partialTests))) {
193
230
  // a background launch fires PostToolUse before the process finishes (e.g. Claude Code backgroundTaskId): never count it
194
231
  appendEvent(repo, {source: 'post:background-gate-ignored', tool, kind: k.kind === 'shell' ? 'partial-tests' : k.kind,
195
- ...(typeof tr?.backgroundTaskId === 'string' ? {backgroundTaskId: tr.backgroundTaskId} : typeof tr?.background_task_id === 'string' ? {backgroundTaskId: tr.background_task_id} : {})})
232
+ ...(typeof r.backgroundTaskId === 'string' ? {backgroundTaskId: r.backgroundTaskId} : typeof r.background_task_id === 'string' ? {backgroundTaskId: r.background_task_id} : {})})
196
233
  if (k.kind !== 'shell') {
197
234
  const which = k.kind === 'build' ? 'build' : 'test'
198
235
  const gate = k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd
@@ -227,7 +264,7 @@ function post(ctx , input , failure ) {
227
264
  // ---------------------------------------------------------------- Stop: "I am done" = the COMMIT gate when the tree differs from HEAD
228
265
  // stopGate 'warn': the turn may end with unverified changes (e.g. to ask the human a question). Only the Stop hook
229
266
  // changes: no COMMIT step is taken, so `git commit` / `git push` in PreToolUse and the git hooks stay fully gated.
230
- function stop(ctx , input ) {
267
+ function stop(ctx , input ) {
231
268
  if (input.stop_hook_active) return {code: 0}
232
269
  syncTree(ctx, 0, 'stop:sync')
233
270
  if (!differsFromHead(ctx.repo, ctx.now .entries)) return {code: 0}
@@ -253,14 +290,14 @@ export function failMsg(e ) {
253
290
 
254
291
  /** One hook call with Claude Code's JSON on stdin (the v1.0 interface). Never throws. */
255
292
  export function runHook(raw , t0 = performance.now()) {
256
- let input
293
+ let input
257
294
  try { input = JSON.parse(raw) } catch (e) { return {code: 2, msg: `STOPBAR FAIL-CLOSED: hook input is not JSON (${(e ).message})`} }
258
295
  if (!input || typeof input !== 'object') return {code: 2, msg: 'STOPBAR FAIL-CLOSED: hook input must be a JSON object'}
259
- return runEvent(input, t0)
296
+ return runEvent(input , t0)
260
297
  }
261
298
 
262
299
  /** One normalised hook event (Claude Code's shape; adapters translate other clients into it). Never throws. */
263
- export function runEvent(input , t0 = performance.now()) {
300
+ export function runEvent(input , t0 = performance.now()) {
264
301
  try {
265
302
  const repo = findRepo(typeof input.cwd === 'string' && input.cwd ? input.cwd : process.cwd())
266
303
  const g0 = gitCalls
@@ -273,7 +310,7 @@ export function runEvent(input , t0 = performance.now()) {
273
310
  : ev === 'PostToolUseFailure' ? post(ctx, input, true)
274
311
  : ev === 'Stop' ? stop(ctx, input) : {code: 0}
275
312
  if (ctx.dirty) writeState(repo, ctx.s)
276
- appendEvent(repo, {source: 'hook-timing', event: ev, tool: input.tool_name, ...(input.stopbar?.adapter ? {adapter: input.stopbar.adapter} : {}), exit: res.code, gitCalls: gitCalls - g0,
313
+ appendEvent(repo, {source: 'hook-timing', event: ev, tool: input.tool_name, ...(metaOf(input.stopbar).adapter ? {adapter: metaOf(input.stopbar).adapter} : {}), exit: res.code, gitCalls: gitCalls - g0,
277
314
  handlerMs: Math.round(performance.now() - t0), processMs: Math.round(process.uptime() * 1000)})
278
315
  return res
279
316
  })
@@ -105,7 +105,10 @@ function antigravityFile(root , command ) {
105
105
  return f
106
106
  }
107
107
 
108
- function gitHooks(repo , runtimeRoot , force ) {
108
+ /** A foreign pre-commit or pre-push hook: 'fail' (git named in --hooks), 'backup' (--force-hooks: kept as
109
+ * <name>.stopbar-backup, then replaced) or 'keep' (git added by default: the foreign hook stays, with a warning). */
110
+
111
+ function gitHooks(repo , runtimeRoot , foreign , warn ) {
109
112
  const rel = git(repo.root, ['rev-parse', '--git-path', 'hooks'])
110
113
  const dir = isAbsolute(rel) ? rel : resolve(repo.root, rel)
111
114
  mkdirSync(dir, {recursive: true})
@@ -115,7 +118,11 @@ function gitHooks(repo , runtimeRoot , force ) {
115
118
  const f = join(dir, name)
116
119
  const body = `#!/bin/sh\n# Stopbar fallback gate, written by \`stopbar init --hooks git\`.\nexec node "${bin}" git-hook ${name}\n`
117
120
  if (existsSync(f) && !readFileSync(f, 'utf8').includes('stopbar.mjs" git-hook')) {
118
- if (!force) throw new FailClosed(`${f} exists and is not a Stopbar hook; not overwriting it`, 'remove it, chain it by hand, or run init again with --force-hooks (the old hook is kept as <name>.stopbar-backup)')
121
+ if (foreign === 'keep') {
122
+ warn(`WARN: ${f} exists and is not a Stopbar hook; kept it, so git ${name === 'pre-commit' ? 'commit' : 'push'} is not gated by Stopbar here. To replace it (the old hook is kept as ${name}.stopbar-backup): stopbar upgrade --hooks git --force-hooks`)
123
+ continue
124
+ }
125
+ if (foreign === 'fail') throw new FailClosed(`${f} exists and is not a Stopbar hook; not overwriting it`, 'remove it, chain it by hand, or run init again with --force-hooks (the old hook is kept as <name>.stopbar-backup)')
119
126
  renameSync(f, `${f}.stopbar-backup`)
120
127
  }
121
128
  writeFileSync(f, body)
@@ -125,9 +132,11 @@ function gitHooks(repo , runtimeRoot , force ) {
125
132
  return out
126
133
  }
127
134
 
128
- /** Installs every target; returns one line per written file. */
129
- export function installHooks(repo , targets , runtimeRoot , force ) {
135
+ /** Installs every target; returns one line per written file. `gitByDefault`: git was not named in --hooks but added by
136
+ * init, so a foreign git hook is kept with a warning (`warn`) instead of failing; --force-hooks still replaces it. */
137
+ export function installHooks(repo , targets , runtimeRoot , force , o = {}) {
130
138
  const lines = []
139
+ const foreign = force ? 'backup' : o.gitByDefault ? 'keep' : 'fail'
131
140
  for (const t of targets) {
132
141
  if (t === 'claude') lines.push(`claude: ${claudeFile(repo.root, 'settings.local.json', hookCommand(runtimeRoot))}`)
133
142
  else if (t === 'claude-project') lines.push(`claude: ${claudeFile(repo.root, 'settings.json', hookCommand(runtimeRoot))}`)
@@ -135,7 +144,7 @@ export function installHooks(repo , targets , runtimeRoot ,
135
144
  else if (t === 'codex') lines.push(`codex: ${codexFile(repo.root, hookCommand(runtimeRoot, 'codex'))}`)
136
145
  else if (t === 'gemini') lines.push(`gemini: ${geminiFile(repo.root, hookCommand(runtimeRoot, 'gemini'))}`)
137
146
  else if (t === 'antigravity') lines.push(`antigravity: ${antigravityFile(repo.root, hookCommand(runtimeRoot, 'antigravity'))}`)
138
- else if (t === 'git') for (const f of gitHooks(repo, runtimeRoot, force)) lines.push(`git: ${f}`)
147
+ else if (t === 'git') for (const f of gitHooks(repo, runtimeRoot, foreign, o.warn ?? (() => {}))) lines.push(`git: ${f}`)
139
148
  }
140
149
  return lines
141
150
  }