stopbar 1.1.3 → 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/doctor.js CHANGED
@@ -69,8 +69,8 @@ function stopbarCommands(events )
69
69
  return out
70
70
  }
71
71
 
72
- /** Other clients and the git fallback. Returns how many have Stopbar hooks. */
73
- function checkOtherClients(repo , add ) {
72
+ /** Other clients and the git fallback. Returns how many clients have Stopbar hooks, and how many Stopbar git hooks exist. */
73
+ function checkOtherClients(repo , add ) {
74
74
  let found = 0
75
75
  const clients = [
76
76
  ['cursor', join(repo.root, '.cursor', 'hooks.json'), (j) => j.hooks, ['preToolUse', 'postToolUse', 'postToolUseFailure', 'stop']],
@@ -95,8 +95,11 @@ function checkOtherClients(repo , add
95
95
  let dir = join(repo.gitDir, 'hooks')
96
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
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
98
+ const lacking = ['pre-commit', 'pre-push'].filter((n) => !gh.includes(n))
99
+ // the git hooks close what an agent hook cannot see: git aliases, and on pre-push merge, cherry-pick, am and commit-tree
100
+ if (!lacking.length) add('OK', 'hooks git', `pre-commit, pre-push in ${dir}`)
101
+ else add('WARN', 'hooks git', `no Stopbar ${lacking.join(' and ')} hook in ${dir}: the git hooks close git aliases, and on pre-push merge, cherry-pick, am and commit-tree, which an agent hook does not see; a human runs \`stopbar upgrade --hooks git\``)
102
+ return {clients: found, git: gh.length}
100
103
  }
101
104
 
102
105
  /** The real hook pipeline (in process) on a scratch repository inside <git-dir>/stopbar/doctor-run. */
@@ -142,13 +145,16 @@ export async function doctor(o )
142
145
  add(maj > 22 || (maj === 22 && min >= 18) ? 'OK' : 'FAIL', 'node', `v${process.versions.node} (needs >= 22.18)`)
143
146
  try { add('OK', 'git', execFileSync('git', ['--version'], {encoding: 'utf8'}).trim()) } catch { add('FAIL', 'git', 'git not found on PATH') }
144
147
  add(MACHINE.name === 'stopbar_kernel_none' ? 'OK' : 'FAIL', 'kernel', `${MACHINE.name}, kernel.ts sha256 ${MACHINE.kernelSha256.slice(0, 16)}, machine sha256 ${MACHINE.machineSha256.slice(0, 16)}`)
145
- if (existsSync(join(PKG_ROOT, 'node_modules', 'gdp-wired')) && existsSync(join(PKG_ROOT, 'dist', 'kernel.js'))) {
148
+ // npm may hoist gdp-wired next to this package (npm install stopbar): resolve it as Node does, never by a fixed path
149
+ let prover = false
150
+ try { import.meta.resolve('gdp-wired/machine'); prover = true } catch { /* not resolvable: a pinned runtime has no node_modules */ }
151
+ if (prover && existsSync(join(PKG_ROOT, 'dist', 'kernel.js'))) {
146
152
  try {
147
153
  const {checkGenerated} = await import('./verify.js')
148
154
  const g = await checkGenerated(500)
149
155
  add(g.ok ? 'OK' : 'FAIL', 'kernel link', `compileJs(kernel.ts) == dist/kernel.gen.js: ${g.sameMachine}; kernel.ts hash: ${g.sameSource}; ${(g.differential ).steps} steps vs interpreter, ${(g.differential ).mismatches} mismatches`)
150
156
  } catch (e) { add('WARN', 'kernel link', `not checked: ${(e ).message}`) }
151
- } else add('WARN', 'kernel link', 'gdp-wired not installed next to this copy (pinned runtime): run `stopbar prove` in the package')
157
+ } else add('WARN', 'kernel link', 'gdp-wired cannot be resolved from this copy (a pinned runtime has no node_modules): run `stopbar prove` in the package')
152
158
 
153
159
  let repo = null
154
160
  try { repo = findRepo(o.repo ?? process.cwd()); add('OK', 'repository', `${repo.root} (state in ${repo.stateDir})`) } catch (e) { add('FAIL', 'repository', (e ).message) }
@@ -158,7 +164,7 @@ export async function doctor(o )
158
164
  const cfg = readConfig(repo); cfgOk = true
159
165
  add('OK', 'config.json', `profile ${cfg.profile}; build \`${cfg.buildCmd}\`; full tests \`${cfg.fullTestCmd}\`; maxRetries ${cfg.maxRetries}; cap ${cfg.cap}; ` +
160
166
  `${cfg.paths.tests.length}/${cfg.paths.testConfig.length}/${cfg.paths.secrets.length} test/config/secret patterns; safeTools ${JSON.stringify(cfg.safeTools ?? DEFAULT_SAFE_TOOLS)}${cfg.baseRef ? `; baseRef ${cfg.baseRef}` : ''}; ` +
161
- `stopGate ${cfg.stopGate ?? 'block'}; cli ${cliOf(cfg)}`)
167
+ `stopGate ${cfg.stopGate ?? 'block'}; cli ${cliOf(cfg)}${cfg.requireRun ? '; requireRun: true' : ''}`)
162
168
  if (cfg.stopGate === 'warn') add('WARN', 'stopGate', 'warn: Stop does not block a turn with unverified changes (logged as stop:warn); git commit and git push stay blocked until the gates pass')
163
169
  const safe = cfg.safeTools ?? DEFAULT_SAFE_TOOLS
164
170
  const missing = DEFAULT_SAFE_TOOLS.filter((t) => !safe.includes(t))
@@ -180,7 +186,11 @@ export async function doctor(o )
180
186
  } else if (cfgOk) add('WARN', 'pinned runtime', 'none: hooks run an unpinned copy (init --no-pin)')
181
187
  const others = checkOtherClients(repo, add)
182
188
  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 })
183
- if (claudeHas || others === 0) checkHooks(repo.root, add) // without any client hooks, report the Claude Code ones as missing (v1.0 output)
189
+ // Claude Code hooks named at the last init or upgrade must be there, also when other hooks (now the git hooks by
190
+ // default) exist; without any client hooks, the Claude Code ones are reported as missing (v1.0 output)
191
+ const named = ev.events.filter((e) => (e.source === 'human:init' || e.source === 'human:upgrade') && Array.isArray(e.hooks)).at(-1)?.hooks
192
+ const wantClaude = !!named?.some((t) => t === 'claude' || t === 'claude-project')
193
+ if (claudeHas || (others.clients === 0 && (others.git === 0 || wantClaude))) checkHooks(repo.root, add)
184
194
  try { dryRun(repo.stateDir, add) } catch (e) { add('FAIL', 'dry run', String(e)) }
185
195
  }
186
196
  const fails = checks.filter((c) => c.status === 'FAIL').length, warns = checks.filter((c) => c.status === 'WARN').length
package/dist/hook.js CHANGED
@@ -13,6 +13,23 @@ 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'])
@@ -77,42 +94,48 @@ function syncTree(ctx , cost , source ) {
77
94
 
78
95
  const block = (reason ) => ({code: 2, msg: `BLOCK (stopbar): ${reason}`})
79
96
 
80
- function isBackgroundInput(ti ) {
81
- 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
82
99
  }
83
- function isBackgroundResponse(tr ) {
84
- if (!tr || typeof tr !== 'object') return false
85
- return (typeof tr.backgroundTaskId === 'string' && tr.backgroundTaskId.length > 0) ||
86
- (typeof tr.background_task_id === 'string' && tr.background_task_id.length > 0) ||
87
- 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
88
105
  }
89
106
 
90
107
  // ---------------------------------------------------------------- PreToolUse
91
- function pre(ctx , input ) {
92
- 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)
93
110
  const {repo, cfg} = ctx
111
+ const shell = tool === 'PowerShell' ? 'powershell' : 'bash'
94
112
  // self-protection: unconditional, before the kernel, also when halted
95
113
  if (EDIT_TOOLS.has(tool)) {
96
- const list = [ti.file_path, ti.notebook_path, ti.path, ...(Array.isArray(ti.file_paths) ? ti.file_paths : [])]
97
- 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)) {
98
115
  const why = K.protectedPath(resolve(repo.root, p), repo.root, ctx.protect)
99
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.`) }
100
117
  }
101
118
  }
102
119
  if (SHELL_TOOLS.has(tool)) {
103
120
  const cmd = String(ti.command ?? '')
104
- 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)
105
122
  if (why) { appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: why}); return block(`${why}. Ask the human.`) }
106
123
  }
107
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
+ }
108
132
  if (v.halted) {
109
133
  appendEvent(repo, {source: 'pre', tool, wrapper: 'PAUSE', reason: 'halted'})
110
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>`}
111
135
  }
112
136
  const cost = cfg.costPerCall
113
137
  if (READ_TOOLS.has(tool)) {
114
- 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)
115
- for (const p of ps) {
138
+ for (const p of strings(ti.file_path, ti.path, ti.glob, ti.pattern, ti.file_paths)) {
116
139
  const pattern = K.secretPattern(p, cfg.paths)
117
140
  if (pattern) { step(ctx, {op: 'READ_SECRET', cost}, `pre:${tool}`, {secret: {pattern, path: p, tool}}); break }
118
141
  }
@@ -123,7 +146,7 @@ function pre(ctx , input ) {
123
146
  const cmd = String(ti.command ?? '')
124
147
  const base = typeof input.cwd === 'string' && input.cwd ? input.cwd : repo.root
125
148
  const exists = (t ) => existsSync(resolve(base, t)) || existsSync(resolve(repo.root, t))
126
- const k = K.classifyBash(cmd, cfg, tool === 'PowerShell' ? 'powershell' : 'bash', exists)
149
+ const k = K.classifyBash(cmd, cfg, shell, exists)
127
150
  if (k.kind === 'commit-chained') {
128
151
  appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: `chained commit (${k.reason})`})
129
152
  return block(`run \`git commit\` / \`git push\` as a single command (${k.reason}): no &&, ;, |, redirections or $(...). ` +
@@ -160,8 +183,7 @@ function pre(ctx , input ) {
160
183
  }
161
184
  return {code: 0}
162
185
  }
163
- if (OUTBOUND(tool)) {
164
- 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
165
187
  const {after} = step(ctx, {op: 'SHELL', risky: true, cost}, `pre:${tool}`)
166
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\``}
167
189
  }
@@ -171,27 +193,27 @@ function pre(ctx , input ) {
171
193
  // ---------------------------------------------------------------- PostToolUse / PostToolUseFailure
172
194
  // Claude Code sends PostToolUse after success and PostToolUseFailure after an error (non-zero exit of Bash).
173
195
  // PostToolUse carries no exit code: success unless is_error / interrupted. Failure is the event type itself.
174
- function exitCodeOf(tr ) {
175
- if (!tr || typeof tr !== 'object') return undefined
176
- 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 }
177
199
  return undefined
178
200
  }
179
201
 
180
- function post(ctx , input , failure ) {
181
- 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)
182
204
  const {repo, cfg} = ctx
183
205
  const msgs = []
184
206
  if (SHELL_TOOLS.has(tool)) {
185
207
  const k = K.classifyBash(String(ti.command ?? ''), cfg, tool === 'PowerShell' ? 'powershell' : 'bash')
186
- const tr = input.tool_response
187
- const meta = input.stopbar ?? {}
188
- 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)}),
189
211
  toolResponseKeys: tr && typeof tr === 'object' ? Object.keys(tr) : typeof tr})
190
212
  const bg = isBackgroundInput(ti) || isBackgroundResponse(tr)
191
213
  const staleRun = typeof meta.expectedSnapshot === 'string' &&
192
214
  (meta.expectedSnapshot !== ctx.s.snapshot || (typeof meta.expectedRev === 'number' && meta.expectedRev !== decode(ctx.s.kernel).treeRev))
193
215
  const code = exitCodeOf(tr)
194
- 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
195
217
  // some clients send the same post event for success and failure: then only an explicit exit code 0 is a pass
196
218
  const unknown = meta.requireExitCode === true && code === undefined
197
219
  const passed = failure ? false : code !== undefined ? code === 0 : !flagged && !unknown
@@ -199,10 +221,15 @@ function post(ctx , input , failure ) {
199
221
  if (failure && input.is_interrupt === true) {
200
222
  // Ctrl+C by the user: not a failed gate and not a retry; the tree is still checked below
201
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.`)
202
229
  } else if (!failure && bg && (k.kind === 'build' || k.kind === 'fulltest' || (k.kind === 'shell' && k.partialTests))) {
203
230
  // a background launch fires PostToolUse before the process finishes (e.g. Claude Code backgroundTaskId): never count it
204
231
  appendEvent(repo, {source: 'post:background-gate-ignored', tool, kind: k.kind === 'shell' ? 'partial-tests' : k.kind,
205
- ...(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} : {})})
206
233
  if (k.kind !== 'shell') {
207
234
  const which = k.kind === 'build' ? 'build' : 'test'
208
235
  const gate = k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd
@@ -237,7 +264,7 @@ function post(ctx , input , failure ) {
237
264
  // ---------------------------------------------------------------- Stop: "I am done" = the COMMIT gate when the tree differs from HEAD
238
265
  // stopGate 'warn': the turn may end with unverified changes (e.g. to ask the human a question). Only the Stop hook
239
266
  // changes: no COMMIT step is taken, so `git commit` / `git push` in PreToolUse and the git hooks stay fully gated.
240
- function stop(ctx , input ) {
267
+ function stop(ctx , input ) {
241
268
  if (input.stop_hook_active) return {code: 0}
242
269
  syncTree(ctx, 0, 'stop:sync')
243
270
  if (!differsFromHead(ctx.repo, ctx.now .entries)) return {code: 0}
@@ -263,14 +290,14 @@ export function failMsg(e ) {
263
290
 
264
291
  /** One hook call with Claude Code's JSON on stdin (the v1.0 interface). Never throws. */
265
292
  export function runHook(raw , t0 = performance.now()) {
266
- let input
293
+ let input
267
294
  try { input = JSON.parse(raw) } catch (e) { return {code: 2, msg: `STOPBAR FAIL-CLOSED: hook input is not JSON (${(e ).message})`} }
268
295
  if (!input || typeof input !== 'object') return {code: 2, msg: 'STOPBAR FAIL-CLOSED: hook input must be a JSON object'}
269
- return runEvent(input, t0)
296
+ return runEvent(input , t0)
270
297
  }
271
298
 
272
299
  /** One normalised hook event (Claude Code's shape; adapters translate other clients into it). Never throws. */
273
- export function runEvent(input , t0 = performance.now()) {
300
+ export function runEvent(input , t0 = performance.now()) {
274
301
  try {
275
302
  const repo = findRepo(typeof input.cwd === 'string' && input.cwd ? input.cwd : process.cwd())
276
303
  const g0 = gitCalls
@@ -283,7 +310,7 @@ export function runEvent(input , t0 = performance.now()) {
283
310
  : ev === 'PostToolUseFailure' ? post(ctx, input, true)
284
311
  : ev === 'Stop' ? stop(ctx, input) : {code: 0}
285
312
  if (ctx.dirty) writeState(repo, ctx.s)
286
- 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,
287
314
  handlerMs: Math.round(performance.now() - t0), processMs: Math.round(process.uptime() * 1000)})
288
315
  return res
289
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
  }