stopbar 1.2.1 → 1.2.2
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/CHANGELOG.md +48 -0
- package/README.md +46 -111
- package/SECURITY.md +25 -4
- package/dist/build-info.json +1 -1
- package/dist/classify.js +126 -8
- package/dist/cli.js +12 -4
- package/dist/commands.js +30 -7
- package/dist/config.js +8 -6
- package/dist/doctor.js +76 -25
- package/dist/hook.js +10 -5
- package/dist/integrations.js +62 -25
- package/dist/probe/index.js +14 -0
- package/dist/probe/init.js +1 -1
- package/dist/repo.js +62 -0
- package/dist/run.js +12 -1
- package/dist/store.js +5 -3
- package/docs/probe.md +94 -0
- package/package.json +2 -1
- package/skills/stopbar/SKILL.md +2 -1
package/dist/cli.js
CHANGED
|
@@ -11,12 +11,13 @@ const HELP = `stopbar ${VERSION}: proven gates for coding agents (Claude Code ho
|
|
|
11
11
|
|
|
12
12
|
stopbar init --build "<cmd>" --test "<cmd>" [--profile default|ts|python|strict] [--base-ref <ref>] [--max-retries 3] [--cap 500]
|
|
13
13
|
[--cost 1] [--hooks claude,claude-project,cursor,codex,gemini,antigravity,git] [--no-pin] [--force] [--force-hooks] [--repo <dir>]
|
|
14
|
-
[--cli "<cmd>"] [--stop-gate block|warn] [--require-run] [--no-git-hooks]
|
|
14
|
+
[--cli "<cmd>"] [--stop-gate block|warn] [--require-run] [--no-git-hooks] [--safe-tools "<glob>,<glob>"]
|
|
15
15
|
--hooks <clients> adds the git hooks (pre-commit, pre-push) unless --no-git-hooks;
|
|
16
16
|
a foreign git hook is kept with a warning (replace it: --hooks git --force-hooks)
|
|
17
17
|
--cli: command that starts Stopbar in hints (default: npx --no-install stopbar)
|
|
18
18
|
--stop-gate warn: Stop only warns; git commit and git push stay blocked until the gates pass
|
|
19
19
|
--require-run: build and full test gates count only through stopbar run build|test
|
|
20
|
+
--safe-tools: local tools that are never outbound (globs; --force keeps the previous list)
|
|
20
21
|
stopbar upgrade [--hooks <targets>] [--force-hooks] [--repo <dir>]
|
|
21
22
|
a human re-pins the hook runtime from this package (and rewrites hooks with --hooks);
|
|
22
23
|
state, gates, taint and budget stay as they are
|
|
@@ -29,7 +30,7 @@ const HELP = `stopbar ${VERSION}: proven gates for coding agents (Claude Code ho
|
|
|
29
30
|
stopbar approve-shell a human allows ONE risky or outbound call after a secret was read
|
|
30
31
|
stopbar resume --extra N a human lifts a halt and adds N to the budget
|
|
31
32
|
stopbar reset a human starts a fresh kernel state (config and event log stay)
|
|
32
|
-
stopbar doctor [--json]
|
|
33
|
+
stopbar doctor [--json] [--strict] environment, config, state, hooks and a dry run; --strict: a [WARN] fails (exit 1)
|
|
33
34
|
|
|
34
35
|
Four pillars:
|
|
35
36
|
PROVE stopbar prove [--out f.json] [--lean f.lean] inductive proof of the kernel and the 10 mutants
|
|
@@ -53,7 +54,7 @@ Four pillars:
|
|
|
53
54
|
GATE init, upgrade, hook, status, approve-tests, approve-shell, resume, reset, doctor (above)
|
|
54
55
|
ATTEST stopbar attest [--format json|md] deterministic attestation: HEAD, tree, gates, human actions, log sha256,
|
|
55
56
|
probe evidence (the latest probe:result per target, and whether it was taken at the current snapshot)
|
|
56
|
-
All commands take --repo <dir> (default: the current directory). 'verify' is an alias of 'prove'.`
|
|
57
|
+
All commands take --repo <dir> (default: the current directory) and --help / -h. 'verify' is an alias of 'prove'.`
|
|
57
58
|
|
|
58
59
|
function opts(a ) {
|
|
59
60
|
const get = (name ) => { const i = a.indexOf(`--${name}`); return i >= 0 && i + 1 < a.length ? a[i + 1] : undefined }
|
|
@@ -67,7 +68,14 @@ function opts(a ) {
|
|
|
67
68
|
}
|
|
68
69
|
}
|
|
69
70
|
|
|
71
|
+
// flags that take a value: a --help right after one of them is that value (e.g. --cmd --help), not a request for help
|
|
72
|
+
const VALUE_FLAGS = new Set(['build', 'test', 'profile', 'base-ref', 'max-retries', 'cap', 'cost', 'hooks', 'repo', 'cli', 'stop-gate', 'safe-tools', 'rev', 'extra',
|
|
73
|
+
'target', 'cmd', 'target-file', 'cmd-timeout', 'runs', 'seed', 'jobs', 'work', 'out', 'regressions', 'mutant-runs', 'lang', 'name', 'format', 'lean', 'adapter', 'worker', 'worker-file'].map((f) => `--${f}`))
|
|
74
|
+
/** --help or -h as a word of its own after the subcommand: print the help, run nothing. */
|
|
75
|
+
const wantsHelp = (a ) => a.some((x, i) => (x === '--help' || x === '-h') && !VALUE_FLAGS.has(a[i - 1] ?? ''))
|
|
76
|
+
|
|
70
77
|
async function main() {
|
|
78
|
+
if (wantsHelp(argv.slice(1))) return {code: 0, msg: HELP}
|
|
71
79
|
if (cmd === 'hook') {
|
|
72
80
|
const {handle} = await import('./adapters/index.js')
|
|
73
81
|
const i = argv.indexOf('--adapter')
|
|
@@ -87,7 +95,7 @@ async function main() {
|
|
|
87
95
|
if (cmd === 'init') return (await import('./commands.js')).init(o)
|
|
88
96
|
if (cmd === 'upgrade') return (await import('./commands.js')).upgrade(o)
|
|
89
97
|
if (['status', 'approve-tests', 'approve-shell', 'resume', 'reset'].includes(cmd)) return (await import('./commands.js')).human(cmd, o)
|
|
90
|
-
if (cmd === 'doctor') return (await import('./doctor.js')).doctor({repo: o.get('repo'), json: o.has('json')})
|
|
98
|
+
if (cmd === 'doctor') return (await import('./doctor.js')).doctor({repo: o.get('repo'), json: o.has('json'), strict: o.has('strict')})
|
|
91
99
|
if (cmd === 'prove' || cmd === 'verify') {
|
|
92
100
|
const r = await (await import('./verify.js')).verify({out: o.get('out'), lean: o.get('lean')})
|
|
93
101
|
return {code: r.ok ? 0 : 1}
|
package/dist/commands.js
CHANGED
|
@@ -83,11 +83,18 @@ export function init(o ) {
|
|
|
83
83
|
for (const [k, v] of [['--build', buildCmd], ['--test', fullTestCmd]]) {
|
|
84
84
|
if (hasChain(v)) return {code: 1, msg: `${k} ${JSON.stringify(v)} has shell operators; put it in one script (e.g. an npm script) so its exit status is the gate`}
|
|
85
85
|
}
|
|
86
|
-
for (const f of ['cli', 'stop-gate', 'hooks']) if (o.has(f) && o.get(f) === undefined) return {code: 1, msg: `--${f} needs a value`}
|
|
86
|
+
for (const f of ['cli', 'stop-gate', 'hooks', 'safe-tools']) if (o.has(f) && o.get(f) === undefined) return {code: 1, msg: `--${f} needs a value`}
|
|
87
|
+
// safeTools: --safe-tools, else (with --force) the list of a readable previous config.json, else the default
|
|
88
|
+
const safeOpt = o.get('safe-tools')
|
|
89
|
+
let safeTools = safeOpt === undefined ? undefined : safeOpt.split(',').map((x) => x.trim()).filter(Boolean)
|
|
90
|
+
let keptSafe = false
|
|
91
|
+
if (safeTools === undefined && o.has('force') && existsSync(paths(repo).config)) {
|
|
92
|
+
try { safeTools = readConfig(repo).safeTools; keptSafe = safeTools !== undefined } catch { /* a damaged config.json never blocks --force */ }
|
|
93
|
+
}
|
|
87
94
|
let cfg
|
|
88
95
|
try {
|
|
89
96
|
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'),
|
|
90
|
-
cliCmd: o.get('cli'), stopGate: o.get('stop-gate'), requireRun: o.has('require-run')})
|
|
97
|
+
cliCmd: o.get('cli'), stopGate: o.get('stop-gate'), requireRun: o.has('require-run'), safeTools})
|
|
91
98
|
} catch (e) { if (e instanceof ConfigError) return {code: 1, msg: e.message}; throw e }
|
|
92
99
|
if (existsSync(paths(repo).config) && !o.has('force')) return {code: 1, msg: `already initialised (${paths(repo).config}); use --force to replace config and state`}
|
|
93
100
|
const pin = !o.has('no-pin')
|
|
@@ -116,16 +123,28 @@ export function init(o ) {
|
|
|
116
123
|
writeState(repo, s)
|
|
117
124
|
const runtime = pin ? pinRuntime(repo) : PKG_ROOT
|
|
118
125
|
const command = hookCommand(runtime)
|
|
119
|
-
|
|
126
|
+
const warns = [], gitHooksWritten = []
|
|
127
|
+
let written = [], failed
|
|
128
|
+
if (targets.length) {
|
|
129
|
+
try { written = installHooks(repo, targets, runtime, o.has('force-hooks'), {gitByDefault, warn: (w) => warns.push(w), cli: cliOf(cfg), gitHooksWritten}) } catch (e) { failed = e }
|
|
130
|
+
}
|
|
131
|
+
// the log names the git hooks Stopbar wrote: `stopbar doctor` reports [FAIL] when one of them disappears later
|
|
132
|
+
appendEvent(repo, {source: 'human:init', cfg, runtime, version: VERSION, kernel: MACHINE, ...(targets.length ? {hooks: targets, gitHooksWritten} : {})})
|
|
133
|
+
if (failed !== undefined) throw failed
|
|
120
134
|
const warn = countDirtyTests(repo, s, dirty, 'init:dirty-tests')
|
|
121
135
|
const lines = [`Stopbar ${VERSION} initialised in ${repo.stateDir}`, ` profile ${cfg.profile}; build: ${cfg.buildCmd}; full tests: ${cfg.fullTestCmd}${cfg.baseRef ? `; base ref: ${cfg.baseRef}` : ''}`,
|
|
122
136
|
` stop gate: ${cfg.stopGate ?? 'block'}; gate hints use: ${cliOf(cfg)} run build|test${cfg.requireRun ? '; requireRun: true (gates count only through stopbar run build|test)' : ''}`,
|
|
123
137
|
` hooks run: ${command}`]
|
|
124
|
-
const
|
|
125
|
-
if (
|
|
138
|
+
const safe = cfg.safeTools ?? DEFAULT_SAFE_TOOLS
|
|
139
|
+
if (JSON.stringify(safe) !== JSON.stringify(DEFAULT_SAFE_TOOLS)) lines.push(` safeTools ${keptSafe ? 'kept from the previous config.json' : 'from --safe-tools'}: ${JSON.stringify(safe)}`)
|
|
140
|
+
if (targets.length) for (const l of written) lines.push(` hooks written: ${l}`)
|
|
126
141
|
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))
|
|
127
142
|
if (gitByDefault) lines.push(' git hooks (pre-commit, pre-push) were added to --hooks by default; pass --no-git-hooks to skip them')
|
|
128
143
|
else if (named.length && o.has('no-git-hooks')) lines.push(' WARN: --no-git-hooks: git aliases, merge, cherry-pick, am and commit-tree are not gated before a push; stopbar doctor reports it')
|
|
144
|
+
if (!cfg.requireRun) {
|
|
145
|
+
if (targets.includes('codex')) lines.push(` NOTE: Codex CLI does not pass the exit status of a shell command to its hooks, so the gates count through \`${cliOf(cfg)} run build|test\`; run init again with --require-run to count them only that way`)
|
|
146
|
+
lines.push(' tip: for CI or a strict setup use --require-run (gates count only through `stopbar run build|test`) and `stopbar doctor --strict` (a warning fails)')
|
|
147
|
+
}
|
|
129
148
|
lines.push(...warns.map((w) => ` ${w}`), ...warn, 'Next: restart the agent in this repository and run `stopbar doctor`.')
|
|
130
149
|
return {code: 0, msg: lines.join('\n')}
|
|
131
150
|
})
|
|
@@ -144,9 +163,13 @@ export function upgrade(o ) {
|
|
|
144
163
|
readState(repo) // a missing or damaged state fails closed here, with the fix
|
|
145
164
|
const had = existsSync(join(repo.stateDir, 'runtime'))
|
|
146
165
|
const runtime = pinRuntime(repo)
|
|
147
|
-
|
|
166
|
+
const gitHooksWritten = []
|
|
167
|
+
let written = [], failed
|
|
168
|
+
if (targets.length) { try { written = installHooks(repo, targets, runtime, o.has('force-hooks'), {cli: cliOf(cfg), gitHooksWritten}) } catch (e) { failed = e } }
|
|
169
|
+
appendEvent(repo, {source: 'human:upgrade', version: VERSION, runtime, kernel: MACHINE, ...(targets.length ? {hooks: targets, gitHooksWritten} : {})})
|
|
170
|
+
if (failed !== undefined) throw failed
|
|
148
171
|
const lines = [`Stopbar ${VERSION}: hook runtime re-pinned in ${runtime}`, ' state.json, config.json and the snapshots are unchanged (revision, gates, taint, budget)']
|
|
149
|
-
if (targets.length) for (const l of
|
|
172
|
+
if (targets.length) for (const l of written) lines.push(` hooks written: ${l}`)
|
|
150
173
|
else if (!had) lines.push(` there was no pinned runtime (init --no-pin): the hooks still run what they ran; add --hooks <targets> to point them at ${hookCommand(runtime)}`)
|
|
151
174
|
const missing = DEFAULT_SAFE_TOOLS.filter((t) => !(cfg.safeTools ?? DEFAULT_SAFE_TOOLS).includes(t))
|
|
152
175
|
if (missing.length) lines.push(` hint: config.safeTools lacks the default ${missing.join(', ')}; a human adds them to config.json (stopbar doctor shows it)`)
|
package/dist/config.js
CHANGED
|
@@ -35,7 +35,9 @@ const TEST_JS = ['**/*.test.*', '**/*.spec.*', '**/e2e/**']
|
|
|
35
35
|
const TEST_PY = ['**/test_*.py', '**/*_test.py']
|
|
36
36
|
const TEST_OTHER = ['**/*_test.go', '**/*_test.rs', '**/*Test.java', '**/*Tests.cs']
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
// the git hook managers (Husky, Lefthook): a change made outside the agent hooks still taints (defense in depth)
|
|
39
|
+
const CFG_COMMON = ['.gitignore', '.gitattributes', '.github/workflows/**', '.gitlab-ci.yml', '.pre-commit-config.yaml', 'Makefile',
|
|
40
|
+
'.husky/**', 'lefthook*.yml', '.lefthook*.yml', 'lefthook*.yaml', '.lefthook*.yaml', '.lefthook/**']
|
|
39
41
|
const CFG_JS = ['package.json', 'tsconfig*.json', '.eslint*', 'eslint.config.*', 'vitest.config.*', 'vitest.workspace.*',
|
|
40
42
|
'jest.config.*', 'playwright.config.*', '.mocharc*', 'ava.config.*', 'biome.json', '.c8rc*', '.nycrc*']
|
|
41
43
|
const CFG_PY = ['pyproject.toml', 'pytest.ini', 'conftest.py', 'tox.ini', 'setup.cfg', 'noxfile.py', '.coveragerc',
|
|
@@ -113,9 +115,9 @@ export function validateConfig(c ) {
|
|
|
113
115
|
return o
|
|
114
116
|
}
|
|
115
117
|
|
|
116
|
-
// A path segment such as .git or .
|
|
117
|
-
// names one, so a hint `<cliCmd> run test` with such a segment could never run.
|
|
118
|
-
const PROTECTED_SEGMENT = /(^|[^a-z0-9_.\-])\.(git|claude|cursor|codex|gemini|agents)([^a-z0-9_\-]|$)/i
|
|
118
|
+
// A path segment such as .git, .claude or .husky. Self-protection (classify.ts protectedCommand) blocks every shell
|
|
119
|
+
// command that names one, so a hint `<cliCmd> run test` with such a segment could never run.
|
|
120
|
+
const PROTECTED_SEGMENT = /(^|[^a-z0-9_.\-])\.(git|claude|cursor|codex|gemini|agents|husky|lefthook)([^a-z0-9_\-]|$)/i
|
|
119
121
|
|
|
120
122
|
/** Why a cliCmd value cannot be used, or null. */
|
|
121
123
|
export function cliCmdProblem(cmd ) {
|
|
@@ -135,7 +137,7 @@ export function isSafeRef(ref ) {
|
|
|
135
137
|
}
|
|
136
138
|
|
|
137
139
|
export function makeConfig(a
|
|
138
|
-
|
|
140
|
+
) {
|
|
139
141
|
const profile = a.profile ?? 'default'
|
|
140
142
|
const paths = PROFILES[profile]
|
|
141
143
|
if (!paths) throw new ConfigError(`unknown profile ${JSON.stringify(profile)}; known: ${Object.keys(PROFILES).join(', ')}`)
|
|
@@ -145,7 +147,7 @@ export function makeConfig(a
|
|
|
145
147
|
version: 1, profile, buildCmd: a.buildCmd.trim(), fullTestCmd: a.fullTestCmd.trim(),
|
|
146
148
|
maxRetries: a.maxRetries ?? DEFAULTS.maxRetries, cap: a.cap ?? DEFAULTS.cap, costPerCall: a.costPerCall ?? DEFAULTS.costPerCall,
|
|
147
149
|
paths: {tests: [...paths.tests], testConfig: [...paths.testConfig], secrets: [...paths.secrets]},
|
|
148
|
-
safeTools: [...DEFAULT_SAFE_TOOLS],
|
|
150
|
+
safeTools: [...(a.safeTools ?? DEFAULT_SAFE_TOOLS)],
|
|
149
151
|
...(baseRef && baseRef !== 'HEAD' ? {baseRef} : {}),
|
|
150
152
|
...(cliCmd !== undefined ? {cliCmd} : {}),
|
|
151
153
|
...(a.stopGate !== undefined ? {stopGate: a.stopGate} : {}),
|
package/dist/doctor.js
CHANGED
|
@@ -3,18 +3,19 @@
|
|
|
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, relative} from 'node:path'
|
|
7
7
|
import {hasChain} from './classify.js'
|
|
8
8
|
import {fresh, HOOK_MATCHERS} from './commands.js'
|
|
9
9
|
import {cliOf, DEFAULT_SAFE_TOOLS, makeConfig} from './config.js'
|
|
10
10
|
import {decode, MACHINE} from './engine.js'
|
|
11
11
|
import {runHook} from './hook.js'
|
|
12
|
-
import {gitHooksDir} from './integrations.js'
|
|
12
|
+
import {gitHooksDir, portableHookHint} from './integrations.js'
|
|
13
13
|
import {PKG_ROOT} from './pkg.js'
|
|
14
|
-
import {FailClosed, findRepo, hasRefTree, } from './repo.js'
|
|
15
|
-
import {paths, readConfig, readEvents, readState, VERSION, writeConfig, writeState} from './store.js'
|
|
14
|
+
import {FailClosed, findRepo, git, hasRefTree, } from './repo.js'
|
|
15
|
+
import { paths, readConfig, readEvents, readState, VERSION, writeConfig, writeState} from './store.js'
|
|
16
16
|
|
|
17
17
|
|
|
18
|
+
|
|
18
19
|
const sha = (f ) => createHash('sha256').update(readFileSync(f)).digest('hex')
|
|
19
20
|
|
|
20
21
|
|
|
@@ -80,7 +81,7 @@ function stopbarCommands(events )
|
|
|
80
81
|
}
|
|
81
82
|
|
|
82
83
|
/** Other clients and the git fallback. Returns how many clients have Stopbar hooks, and how many Stopbar git hooks exist. */
|
|
83
|
-
function checkOtherClients(repo , add ) {
|
|
84
|
+
function checkOtherClients(repo , ev , add ) {
|
|
84
85
|
let found = 0
|
|
85
86
|
const clients = [
|
|
86
87
|
['cursor', join(repo.root, '.cursor', 'hooks.json'), hooksOf, ['preToolUse', 'postToolUse', 'postToolUseFailure', 'stop']],
|
|
@@ -107,25 +108,71 @@ function checkOtherClients(repo , add
|
|
|
107
108
|
const {dir} = hd
|
|
108
109
|
// a Stopbar line that is not a comment: the hook init writes, or `stopbar git-hook <name>` chained by hand (Husky, Lefthook)
|
|
109
110
|
const calls = (n ) => new RegExp(`^[^#\\n]*stopbar(\\.mjs)?"?\\s+git-hook\\s+${n}\\b`, 'm')
|
|
110
|
-
const
|
|
111
|
-
const
|
|
111
|
+
const NAMES = ['pre-commit', 'pre-push']
|
|
112
|
+
const gh = NAMES.filter((n) => existsSync(join(dir, n)) && calls(n).test(readFileSync(join(dir, n), 'utf8')))
|
|
113
|
+
const lacking = NAMES.filter((n) => !gh.includes(n))
|
|
114
|
+
const verb = (ns ) => `git ${ns.map((n) => (n === 'pre-commit' ? 'commit' : 'push')).join(' and git ')} ${ns.length > 1 ? 'are' : 'is'}`
|
|
112
115
|
// the git hooks close what an agent hook cannot see: git aliases, and on pre-push merge, cherry-pick, am and commit-tree
|
|
113
|
-
if (!lacking.length) add('OK', 'hooks git', `pre-commit, pre-push in ${dir}`)
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
116
|
+
if (!lacking.length) { add('OK', 'hooks git', `pre-commit, pre-push in ${dir}`); return {clients: found, git: gh.length} }
|
|
117
|
+
let cli = cliOf({})
|
|
118
|
+
try { cli = cliOf(readConfig(repo)) } catch { /* reported by the config.json check */ }
|
|
119
|
+
const pinned = existsSync(join(repo.stateDir, 'runtime', 'bin', 'stopbar.mjs'))
|
|
120
|
+
const hint = portableHookHint(dir, repo.root, cli, pinned, lacking)
|
|
121
|
+
// a git hook that was there and is gone is a FAIL (an agent or a tool removed the gate); never configured is a WARN
|
|
122
|
+
const gone = lacking.map((n) => ({n, why: hookWasThere(repo, dir, n, ev, calls(n), gh.length === 1)})).filter((x) => x.why)
|
|
123
|
+
if (gone.length) {
|
|
124
|
+
add('FAIL', 'hooks git', `the Stopbar ${gone.map((g) => g.n).join(' and ')} hook ${gone.length > 1 ? 'were' : 'was'} configured and ${gone.length > 1 ? 'are' : 'is'} gone from ${dir} ` +
|
|
125
|
+
`(${gone.map((g) => `${g.n}: ${g.why}`).join('; ')}): ${verb(gone.map((g) => g.n))} NOT gated by Stopbar. A human restores ${hd.customHooksPath !== null ? `the line: ${hint}` : 'it: `stopbar upgrade --hooks git`'}`)
|
|
126
|
+
} else if (hd.customHooksPath !== null) {
|
|
127
|
+
add('WARN', 'hooks git', `no Stopbar ${lacking.join(' and ')} hook in the custom core.hooksPath (${dir}): ${verb(lacking)} NOT gated by Stopbar in this repository. ` +
|
|
128
|
+
`Stopbar does not write shared or tracked hooks; a human chains them in the existing hook manager: ${hint}; ` +
|
|
123
129
|
'or runs `stopbar upgrade --hooks git --force-hooks` to write them there, keeping a .stopbar-backup')
|
|
124
|
-
}
|
|
125
|
-
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\``)
|
|
130
|
+
} 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\``)
|
|
126
131
|
return {clients: found, git: gh.length}
|
|
127
132
|
}
|
|
128
133
|
|
|
134
|
+
/** Why the git hook `n` counts as configured before (so its absence is a FAIL), or null:
|
|
135
|
+
* - the last `human:init`, or an upgrade after it, wrote it (event field gitHooksWritten, since 1.2.2);
|
|
136
|
+
* - a `git-hook` run of it is logged since the last init or reset;
|
|
137
|
+
* - a tracked hook file (custom core.hooksPath inside the tree) calls it in HEAD;
|
|
138
|
+
* - the other hook is in place and the log does not say that Stopbar left this one out (`partial`).
|
|
139
|
+
* Reads only: the event log is never written here. */
|
|
140
|
+
function hookWasThere(repo , dir , n , ev , call , partial ) {
|
|
141
|
+
let lastInit = -1, lastStart = -1
|
|
142
|
+
ev.forEach((e, i) => { if (e.source === 'human:init') lastInit = i; if (e.source === 'human:init' || e.source === 'human:reset') lastStart = i })
|
|
143
|
+
let wroteBy = null, skipped = false
|
|
144
|
+
for (const e of ev.slice(Math.max(lastInit, 0))) {
|
|
145
|
+
if ((e.source !== 'human:init' && e.source !== 'human:upgrade') || !Array.isArray(e.gitHooksWritten)) continue
|
|
146
|
+
if ((e.gitHooksWritten ).includes(n)) wroteBy = e.source === 'human:upgrade' ? 'upgrade' : 'init'
|
|
147
|
+
else if (e.source === 'human:init') skipped = true
|
|
148
|
+
}
|
|
149
|
+
if (wroteBy) return `written by stopbar ${wroteBy}`
|
|
150
|
+
if (ev.slice(lastStart + 1).some((e) => e.source === 'hook-timing' && e.adapter === 'git' && e.gitHook === n)) return 'it ran since the last init or reset'
|
|
151
|
+
const rel = relative(repo.root, join(dir, n))
|
|
152
|
+
if (rel && !rel.startsWith('..') && !isAbsolute(rel)) {
|
|
153
|
+
try { if (call.test(git(repo.root, ['show', `HEAD:${rel.replace(/\\/g, '/')}`]))) return `HEAD:${rel.replace(/\\/g, '/')} calls it` } catch { /* not tracked */ }
|
|
154
|
+
}
|
|
155
|
+
if (partial && !skipped) return 'only the other hook is in place'
|
|
156
|
+
return null
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** On Windows, a gate command `bash ...` with a bare `bash` may start WSL's bash (System32 or WindowsApps) instead of Git
|
|
160
|
+
* Bash: another file system and PATH, so the gate fails or tests something else. */
|
|
161
|
+
export function wslBashWarning(cmds , whereBash , platform = process.platform) {
|
|
162
|
+
if (platform !== 'win32' || !cmds.some((c) => /^bash(?:\.exe)?\s/i.test(c.trim()))) return null
|
|
163
|
+
const first = whereBash()
|
|
164
|
+
if (!first || !/\\(?:WindowsApps|System32)\\bash\.exe$/i.test(first)) return null
|
|
165
|
+
return `buildCmd or fullTestCmd starts with a bare \`bash\`, and the first bash on PATH is WSL (${first}): the gate runs in WSL, not in Git Bash. ` +
|
|
166
|
+
'A human runs `stopbar init --force` with the full path to Git Bash in --build / --test (e.g. "C:/Program Files/Git/bin/bash.exe" ...)'
|
|
167
|
+
}
|
|
168
|
+
function checkWslBash(cmds , add ) {
|
|
169
|
+
const where = () => {
|
|
170
|
+
try { return execFileSync('where', ['bash'], {encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true}).split(/\r?\n/)[0].trim() || null } catch { return null }
|
|
171
|
+
}
|
|
172
|
+
const w = wslBashWarning(cmds, where)
|
|
173
|
+
if (w) add('WARN', 'gate shell', w)
|
|
174
|
+
}
|
|
175
|
+
|
|
129
176
|
/** The real hook pipeline (in process) on a scratch repository inside <git-dir>/stopbar/doctor-run. */
|
|
130
177
|
function dryRun(base , add ) {
|
|
131
178
|
const dir = join(base, 'doctor-run')
|
|
@@ -162,7 +209,8 @@ function dryRun(base , add
|
|
|
162
209
|
}
|
|
163
210
|
}
|
|
164
211
|
|
|
165
|
-
|
|
212
|
+
/** `strict`: a [WARN] fails too (exit 1), for CI. The repository's event log is only read (attest hashes it). */
|
|
213
|
+
export async function doctor(o ) {
|
|
166
214
|
const checks = []
|
|
167
215
|
const add = (status , name , detail ) => { checks.push({status, name, detail}) }
|
|
168
216
|
const [maj, min] = process.versions.node.split('.').map(Number)
|
|
@@ -196,6 +244,7 @@ export async function doctor(o )
|
|
|
196
244
|
if (missing.length) add('WARN', 'safeTools', `missing default ${missing.join(', ')}: these local tools count as outbound after a secret read; add them to config.safeTools or run \`stopbar init --force ...\``)
|
|
197
245
|
if (cfg.baseRef) add(hasRefTree(repo.root, cfg.baseRef) ? 'OK' : 'FAIL', 'baseRef', hasRefTree(repo.root, cfg.baseRef) ? `${cfg.baseRef} resolves to a tree` : `${cfg.baseRef} does not resolve in git (existing-test checks will fail closed)`)
|
|
198
246
|
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`)
|
|
247
|
+
checkWslBash([cfg.buildCmd, cfg.fullTestCmd], add)
|
|
199
248
|
try {
|
|
200
249
|
const s = readState(repo), v = decode(s.kernel)
|
|
201
250
|
add(v.halted ? 'WARN' : 'OK', 'state.json', `revision ${v.treeRev}; ${v.halted ? 'HALTED' : 'running'}; spent ${v.spent}/${v.capNow}; tainted ${v.testsTainted}`)
|
|
@@ -209,7 +258,7 @@ export async function doctor(o )
|
|
|
209
258
|
const same = existsSync(join(PKG_ROOT, 'dist', 'kernel.gen.js')) && sha(rt) === sha(join(PKG_ROOT, 'dist', 'kernel.gen.js'))
|
|
210
259
|
add(same ? 'OK' : 'WARN', 'pinned runtime', `${join(repo.stateDir, 'runtime')}${same ? ' (same kernel as this package)' : ' differs from this package: a human runs `stopbar upgrade` to re-pin (state and gates are kept)'}`)
|
|
211
260
|
} else if (cfgOk) add('WARN', 'pinned runtime', 'none: hooks run an unpinned copy (init --no-pin)')
|
|
212
|
-
const others = checkOtherClients(repo, add)
|
|
261
|
+
const others = checkOtherClients(repo, ev.events, add)
|
|
213
262
|
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 })
|
|
214
263
|
// Claude Code hooks named at the last init or upgrade must be there, also when other hooks (now the git hooks by
|
|
215
264
|
// default) exist; without any client hooks, the Claude Code ones are reported as missing (v1.0 output)
|
|
@@ -219,8 +268,10 @@ export async function doctor(o )
|
|
|
219
268
|
try { dryRun(repo.stateDir, add) } catch (e) { add('FAIL', 'dry run', String(e)) }
|
|
220
269
|
}
|
|
221
270
|
const fails = checks.filter((c) => c.status === 'FAIL').length, warns = checks.filter((c) => c.status === 'WARN').length
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
271
|
+
const strictFail = o.strict === true && warns > 0
|
|
272
|
+
const ok = fails === 0 && !strictFail
|
|
273
|
+
const msg = o.json ? JSON.stringify({version: VERSION, ok, fails, warns, ...(o.strict ? {strict: true} : {}), checks}, null, 1)
|
|
274
|
+
: [`stopbar doctor (Stopbar ${VERSION})${o.strict ? ' --strict' : ''}`, ...checks.map((c) => `[${c.status.padEnd(4)}] ${c.name.padEnd(18)} ${c.detail}`),
|
|
275
|
+
`RESULT: ${fails ? `FAIL (${fails} problem(s), ${warns} warning(s))` : strictFail ? `FAIL (strict: ${warns} warning(s))` : `OK (${warns} warning(s))`}`].join('\n')
|
|
276
|
+
return {code: ok ? 0 : 1, msg}
|
|
226
277
|
}
|
package/dist/hook.js
CHANGED
|
@@ -7,7 +7,7 @@ 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, markCounted, oidOf, refEntries, snapshot} from './repo.js'
|
|
10
|
+
import {changesSinceHead, countedEntries, diffEntries, differsFromHead, FailClosed, findRepo, gitCalls, markCounted, oidOf, readHooksPath, 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
|
|
|
@@ -16,7 +16,7 @@ import {codeDirs} from './pkg.js'
|
|
|
16
16
|
/** A hook event: Claude Code's JSON object (adapters translate other clients into it). Fields are read with guards. */
|
|
17
17
|
|
|
18
18
|
/** Stopbar's own fields on an event: set by the adapters and by `stopbar run`, never by the agent's client. */
|
|
19
|
-
|
|
19
|
+
|
|
20
20
|
|
|
21
21
|
const obj = (x ) => (x && typeof x === 'object' && !Array.isArray(x) ? x : {})
|
|
22
22
|
const strings = (...xs ) => xs.flatMap((x) => (Array.isArray(x) ? x : [x])).filter((x) => typeof x === 'string' && x.length > 0)
|
|
@@ -28,6 +28,7 @@ function metaOf(x ) {
|
|
|
28
28
|
...(typeof m.expectedSnapshot === 'string' ? {expectedSnapshot: m.expectedSnapshot} : {}),
|
|
29
29
|
...(typeof m.expectedRev === 'number' ? {expectedRev: m.expectedRev} : {}),
|
|
30
30
|
...(m.requireExitCode === true ? {requireExitCode: true} : {}),
|
|
31
|
+
...(typeof m.event === 'string' ? {event: m.event} : {}),
|
|
31
32
|
}
|
|
32
33
|
}
|
|
33
34
|
|
|
@@ -296,6 +297,10 @@ export function runHook(raw , t0 = performance.now()) {
|
|
|
296
297
|
return runEvent(input , t0)
|
|
297
298
|
}
|
|
298
299
|
|
|
300
|
+
/** Self-protection of this repository: .git, the Stopbar state and code, and a custom core.hooksPath read from the git
|
|
301
|
+
* config files (no git process). */
|
|
302
|
+
export const protectOf = (repo ) => ({gitDir: repo.gitDir, stateDir: repo.stateDir, codeDirs: codeDirs(), ...K.hooksProtect(repo.root, readHooksPath(repo))})
|
|
303
|
+
|
|
299
304
|
/** One normalised hook event (Claude Code's shape; adapters translate other clients into it). Never throws. */
|
|
300
305
|
export function runEvent(input , t0 = performance.now()) {
|
|
301
306
|
try {
|
|
@@ -303,14 +308,14 @@ export function runEvent(input , t0 = performance.now()) {
|
|
|
303
308
|
const g0 = gitCalls
|
|
304
309
|
return withLock(repo, () => {
|
|
305
310
|
const cfg = readConfig(repo)
|
|
306
|
-
const ctx = {repo, cfg, s: readState(repo), protect:
|
|
307
|
-
const ev = input.hook_event_name
|
|
311
|
+
const ctx = {repo, cfg, s: readState(repo), protect: protectOf(repo), dirty: false}
|
|
312
|
+
const ev = input.hook_event_name, meta = metaOf(input.stopbar)
|
|
308
313
|
const res = ev === 'PreToolUse' ? pre(ctx, input)
|
|
309
314
|
: ev === 'PostToolUse' ? post(ctx, input, false)
|
|
310
315
|
: ev === 'PostToolUseFailure' ? post(ctx, input, true)
|
|
311
316
|
: ev === 'Stop' ? stop(ctx, input) : {code: 0}
|
|
312
317
|
if (ctx.dirty) writeState(repo, ctx.s)
|
|
313
|
-
appendEvent(repo, {source: 'hook-timing', event: ev, tool: input.tool_name, ...(
|
|
318
|
+
appendEvent(repo, {source: 'hook-timing', event: ev, tool: input.tool_name, ...(meta.adapter ? {adapter: meta.adapter} : {}), ...(meta.adapter === 'git' && meta.event ? {gitHook: meta.event} : {}), exit: res.code, gitCalls: gitCalls - g0,
|
|
314
319
|
handlerMs: Math.round(performance.now() - t0), processMs: Math.round(process.uptime() * 1000)})
|
|
315
320
|
return res
|
|
316
321
|
})
|
package/dist/integrations.js
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
// and other hooks stay; earlier Stopbar entries are replaced). Targets: claude (alias local), claude-project (alias
|
|
4
4
|
// project), cursor, codex, gemini, antigravity (alias agy), git; several at once, comma separated.
|
|
5
5
|
import {chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync} from 'node:fs'
|
|
6
|
-
import {dirname, isAbsolute, join, resolve} from 'node:path'
|
|
6
|
+
import {dirname, isAbsolute, join, relative, resolve} from 'node:path'
|
|
7
|
+
import {DEFAULT_CLI} from './config.js'
|
|
7
8
|
import {FailClosed, git, } from './repo.js'
|
|
8
9
|
|
|
9
10
|
export const TARGETS = ['claude', 'claude-project', 'cursor', 'codex', 'gemini', 'antigravity', 'git']
|
|
@@ -36,19 +37,33 @@ export function claudeHooks(command ) {
|
|
|
36
37
|
}
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
|
|
40
|
+
|
|
41
|
+
const isJson = (x ) => !!x && typeof x === 'object' && !Array.isArray(x)
|
|
42
|
+
/** A JSON file as an object ({} when missing or empty). Not JSON: fails closed and the file is not overwritten. */
|
|
43
|
+
function readJson(f ) {
|
|
40
44
|
if (!existsSync(f)) return {}
|
|
41
45
|
const raw = readFileSync(f, 'utf8')
|
|
42
|
-
|
|
46
|
+
let v
|
|
47
|
+
try { v = raw.trim() ? JSON.parse(raw) : {} } catch (e) {
|
|
43
48
|
throw new FailClosed(`${f} is not valid JSON (${(e ).message}); not overwriting it`, 'fix the file by hand, then run init again')
|
|
44
49
|
}
|
|
50
|
+
return isJson(v) ? v : {}
|
|
51
|
+
}
|
|
52
|
+
/** The object under `key` of `o`; a missing value or one that is not an object is replaced by {}. */
|
|
53
|
+
function objAt(o , key ) {
|
|
54
|
+
const v = o[key]
|
|
55
|
+
if (isJson(v)) return v
|
|
56
|
+
const fresh = {}
|
|
57
|
+
o[key] = fresh
|
|
58
|
+
return fresh
|
|
45
59
|
}
|
|
46
60
|
function writeJson(f , o ) { mkdirSync(dirname(f), {recursive: true}); writeFileSync(f, JSON.stringify(o, null, 2) + '\n') }
|
|
47
61
|
const mentions = (x ) => STOPBAR_HOOK.test(JSON.stringify(x ?? ''))
|
|
48
62
|
/** Event arrays: drop earlier Stopbar entries, append ours. */
|
|
49
|
-
function mergeEvents(hooks
|
|
63
|
+
function mergeEvents(hooks , want ) {
|
|
50
64
|
for (const [ev, entries] of Object.entries(want)) {
|
|
51
|
-
const
|
|
65
|
+
const cur = hooks[ev]
|
|
66
|
+
const kept = Array.isArray(cur) ? (cur ).filter((x) => !mentions(x)) : []
|
|
52
67
|
hooks[ev] = [...kept, ...entries]
|
|
53
68
|
}
|
|
54
69
|
}
|
|
@@ -56,8 +71,7 @@ function mergeEvents(hooks , want ) {
|
|
|
56
71
|
function claudeFile(root , file , command ) {
|
|
57
72
|
const f = join(root, '.claude', file)
|
|
58
73
|
const cur = readJson(f)
|
|
59
|
-
cur
|
|
60
|
-
mergeEvents(cur.hooks, claudeHooks(command))
|
|
74
|
+
mergeEvents(objAt(cur, 'hooks'), claudeHooks(command))
|
|
61
75
|
writeJson(f, cur)
|
|
62
76
|
return f
|
|
63
77
|
}
|
|
@@ -66,9 +80,8 @@ function cursorFile(root , command ) {
|
|
|
66
80
|
const f = join(root, '.cursor', 'hooks.json')
|
|
67
81
|
const cur = readJson(f)
|
|
68
82
|
cur.version = cur.version ?? 1
|
|
69
|
-
cur.hooks = cur.hooks && typeof cur.hooks === 'object' ? cur.hooks : {}
|
|
70
83
|
const e = (timeout ) => [{command, timeout, failClosed: true}]
|
|
71
|
-
mergeEvents(cur
|
|
84
|
+
mergeEvents(objAt(cur, 'hooks'), {preToolUse: e(30), postToolUse: e(60), postToolUseFailure: e(60), stop: e(30)})
|
|
72
85
|
writeJson(f, cur)
|
|
73
86
|
return f
|
|
74
87
|
}
|
|
@@ -76,9 +89,8 @@ function cursorFile(root , command ) {
|
|
|
76
89
|
function codexFile(root , command ) {
|
|
77
90
|
const f = join(root, '.codex', 'hooks.json')
|
|
78
91
|
const cur = readJson(f)
|
|
79
|
-
cur.hooks = cur.hooks && typeof cur.hooks === 'object' ? cur.hooks : {}
|
|
80
92
|
const h = (timeout ) => [{hooks: [{type: 'command', command, timeout}]}]
|
|
81
|
-
mergeEvents(cur
|
|
93
|
+
mergeEvents(objAt(cur, 'hooks'), {PreToolUse: h(30), PostToolUse: h(60), Stop: h(30)})
|
|
82
94
|
writeJson(f, cur)
|
|
83
95
|
return f
|
|
84
96
|
}
|
|
@@ -86,9 +98,8 @@ function codexFile(root , command ) {
|
|
|
86
98
|
function geminiFile(root , command ) {
|
|
87
99
|
const f = join(root, '.gemini', 'settings.json')
|
|
88
100
|
const cur = readJson(f)
|
|
89
|
-
cur.hooks = cur.hooks && typeof cur.hooks === 'object' ? cur.hooks : {}
|
|
90
101
|
const h = (timeout ) => [{matcher: '*', hooks: [{name: 'stopbar', type: 'command', command, timeout}]}]
|
|
91
|
-
mergeEvents(cur
|
|
102
|
+
mergeEvents(objAt(cur, 'hooks'), {BeforeTool: h(30000), AfterTool: h(60000), AfterAgent: h(30000)})
|
|
92
103
|
writeJson(f, cur)
|
|
93
104
|
return f
|
|
94
105
|
}
|
|
@@ -124,11 +135,30 @@ export function gitHooksDir(repo )
|
|
|
124
135
|
|
|
125
136
|
|
|
126
137
|
const hookBin = (runtimeRoot ) => join(runtimeRoot, 'bin', 'stopbar.mjs').replace(/\\/g, '/')
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
|
|
138
|
+
const GIT_HOOK_NAMES = ['pre-commit', 'pre-push']
|
|
139
|
+
|
|
140
|
+
/** The lines a human adds to a shared or tracked hook (Husky, Lefthook, a custom core.hooksPath): first `<cli> git-hook
|
|
141
|
+
* <name>` (works on every machine with Stopbar in node_modules), then, without a local node_modules, the pinned runtime
|
|
142
|
+
* named relative to the repository's git dir (the state dir is <git-dir>/stopbar, also in a linked worktree), never an
|
|
143
|
+
* absolute path into .git. `pinned`: the hooks run the pinned runtime (init without --no-pin). */
|
|
144
|
+
export function portableHookLines(cli , pinned ) {
|
|
145
|
+
return {
|
|
146
|
+
primary: (n) => `${cli} git-hook ${n}`,
|
|
147
|
+
alt: pinned ? (n) => `node "$(git rev-parse --git-dir)/stopbar/runtime/bin/stopbar.mjs" git-hook ${n}` : null,
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** One sentence: which line goes into which hook file. `names`: the hooks that lack it. */
|
|
151
|
+
export function portableHookHint(dir , root , cli , pinned , names = GIT_HOOK_NAMES) {
|
|
152
|
+
const l = portableHookLines(cli, pinned)
|
|
153
|
+
const rel = (n ) => { const p = relative(root, join(dir, n)); return (p && !p.startsWith('..') && !isAbsolute(p) ? p : join(dir, n)).replace(/\\/g, '/') }
|
|
154
|
+
return `add the line \`${l.primary(names[0])}\` to ${rel(names[0])}` + names.slice(1).map((n) => ` and \`${l.primary(n)}\` to ${rel(n)}`).join('') +
|
|
155
|
+
(l.alt ? `; without Stopbar in the local node_modules use \`${l.alt(names[0])}\`${names.length > 1 ? ` (and ${names.slice(1).join(', ')})` : ''} instead` : '')
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const manualHooks = (hd , o ) => portableHookHint(hd.dir, o.root, o.cli, o.pinned)
|
|
159
|
+
function customHooksRefusal(hd , o ) {
|
|
130
160
|
return new FailClosed(`core.hooksPath (${hd.customHooksPath}) points git hooks outside .git/hooks, to ${hd.dir}; not writing shared or tracked hooks there`,
|
|
131
|
-
`chain them by hand: ${manualHooks(hd,
|
|
161
|
+
`chain them by hand: ${manualHooks(hd, o)}; or run again with --force-hooks to write them there (a foreign hook is kept as <name>.stopbar-backup)`)
|
|
132
162
|
}
|
|
133
163
|
|
|
134
164
|
/** A foreign pre-commit or pre-push hook: 'fail' (git named in --hooks), 'backup' (--force-hooks: kept as
|
|
@@ -136,17 +166,17 @@ function customHooksRefusal(hd , runtimeRoot ) {
|
|
|
136
166
|
* A custom core.hooksPath (shared or tracked hooks) is written only with 'backup'; 'keep' writes nothing there and
|
|
137
167
|
* warns, 'fail' refuses. */
|
|
138
168
|
|
|
139
|
-
function gitHooks(repo , runtimeRoot , foreign , warn , hd
|
|
169
|
+
function gitHooks(repo , runtimeRoot , foreign , warn , hd , ho , written ) {
|
|
140
170
|
const {dir} = hd
|
|
141
171
|
const bin = hookBin(runtimeRoot)
|
|
142
172
|
if (hd.customHooksPath !== null && foreign !== 'backup') {
|
|
143
|
-
if (foreign === 'fail') throw customHooksRefusal(hd,
|
|
144
|
-
warn(`WARN: this repository uses a custom core.hooksPath (${hd.customHooksPath} -> ${dir}); Stopbar did not touch those shared or tracked hooks, so git commit and git push are not gated by Stopbar here. To chain them by hand, ${manualHooks(hd,
|
|
173
|
+
if (foreign === 'fail') throw customHooksRefusal(hd, ho)
|
|
174
|
+
warn(`WARN: this repository uses a custom core.hooksPath (${hd.customHooksPath} -> ${dir}); Stopbar did not touch those shared or tracked hooks, so git commit and git push are not gated by Stopbar here. To chain them by hand, ${manualHooks(hd, ho)}; to write them there directly (a foreign hook is kept as <name>.stopbar-backup): stopbar upgrade --hooks git --force-hooks`)
|
|
145
175
|
return []
|
|
146
176
|
}
|
|
147
177
|
mkdirSync(dir, {recursive: true})
|
|
148
178
|
const out = []
|
|
149
|
-
for (const name of
|
|
179
|
+
for (const name of GIT_HOOK_NAMES) {
|
|
150
180
|
const f = join(dir, name)
|
|
151
181
|
const body = `#!/bin/sh\n# Stopbar fallback gate, written by \`stopbar init --hooks git\`.\nexec node "${bin}" git-hook ${name}\n`
|
|
152
182
|
if (existsSync(f) && !readFileSync(f, 'utf8').includes('stopbar.mjs" git-hook')) {
|
|
@@ -160,18 +190,25 @@ function gitHooks(repo , runtimeRoot , foreign , warn
|
|
|
160
190
|
writeFileSync(f, body)
|
|
161
191
|
chmodSync(f, 0o755)
|
|
162
192
|
out.push(f)
|
|
193
|
+
written.push(name)
|
|
163
194
|
}
|
|
164
195
|
return out
|
|
165
196
|
}
|
|
166
197
|
|
|
167
198
|
/** Installs every target; returns one line per written file. `gitByDefault`: git was not named in --hooks but added by
|
|
168
|
-
* init, so a foreign git hook is kept with a warning (`warn`) instead of failing; --force-hooks still replaces it.
|
|
169
|
-
|
|
199
|
+
* init, so a foreign git hook is kept with a warning (`warn`) instead of failing; --force-hooks still replaces it.
|
|
200
|
+
* `cli`: the command in the hint for shared or tracked hooks (config.cliCmd). `gitHooksWritten` receives the name of
|
|
201
|
+
* each git hook as it is written, also when a later target fails (the event log of init and upgrade keeps it, so
|
|
202
|
+
* `stopbar doctor` knows which git hooks Stopbar wrote). */
|
|
203
|
+
export function installHooks(repo , targets , runtimeRoot , force ,
|
|
204
|
+
o = {}) {
|
|
170
205
|
const lines = []
|
|
171
206
|
const foreign = force ? 'backup' : o.gitByDefault ? 'keep' : 'fail'
|
|
172
207
|
const hd = targets.includes('git') ? gitHooksDir(repo) : null
|
|
208
|
+
const ho = {cli: o.cli ?? DEFAULT_CLI, root: repo.root, pinned: resolve(runtimeRoot) === resolve(repo.stateDir, 'runtime')}
|
|
209
|
+
const written = o.gitHooksWritten ?? []
|
|
173
210
|
// a refusal (explicit --hooks git into a custom core.hooksPath) comes before any client file is written
|
|
174
|
-
if (hd && foreign === 'fail' && hd.customHooksPath !== null) throw customHooksRefusal(hd,
|
|
211
|
+
if (hd && foreign === 'fail' && hd.customHooksPath !== null) throw customHooksRefusal(hd, ho)
|
|
175
212
|
for (const t of targets) {
|
|
176
213
|
if (t === 'claude') lines.push(`claude: ${claudeFile(repo.root, 'settings.local.json', hookCommand(runtimeRoot))}`)
|
|
177
214
|
else if (t === 'claude-project') lines.push(`claude: ${claudeFile(repo.root, 'settings.json', hookCommand(runtimeRoot))}`)
|
|
@@ -179,7 +216,7 @@ export function installHooks(repo , targets , runtimeRoot ,
|
|
|
179
216
|
else if (t === 'codex') lines.push(`codex: ${codexFile(repo.root, hookCommand(runtimeRoot, 'codex'))}`)
|
|
180
217
|
else if (t === 'gemini') lines.push(`gemini: ${geminiFile(repo.root, hookCommand(runtimeRoot, 'gemini'))}`)
|
|
181
218
|
else if (t === 'antigravity') lines.push(`antigravity: ${antigravityFile(repo.root, hookCommand(runtimeRoot, 'antigravity'))}`)
|
|
182
|
-
else if (t === 'git') for (const f of gitHooks(repo, runtimeRoot, foreign, o.warn ?? (() => {}), hd
|
|
219
|
+
else if (t === 'git' && hd) for (const f of gitHooks(repo, runtimeRoot, foreign, o.warn ?? (() => {}), hd, ho, written)) lines.push(`git: ${f}`)
|
|
183
220
|
}
|
|
184
221
|
return lines
|
|
185
222
|
}
|
package/dist/probe/index.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
import {spawn} from 'node:child_process'
|
|
10
10
|
import {createHash} from 'node:crypto'
|
|
11
11
|
import {existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs'
|
|
12
|
+
import {registerHooks} from 'node:module'
|
|
12
13
|
import {availableParallelism, tmpdir} from 'node:os'
|
|
13
14
|
import {isAbsolute, join, relative, resolve} from 'node:path'
|
|
14
15
|
import {pathToFileURL} from 'node:url'
|
|
@@ -39,6 +40,18 @@ function isTarget(v ) {
|
|
|
39
40
|
|
|
40
41
|
|
|
41
42
|
|
|
43
|
+
let probeHook = false
|
|
44
|
+
/** `import ... from 'stopbar/probe'` in a target file resolves to this package's SDK, also where no node_modules on the
|
|
45
|
+
* way from the file has stopbar (a global install, a copy outside the project). Every other specifier resolves as
|
|
46
|
+
* Node resolves it. Synchronous module hooks (node:module registerHooks, Node >= 22.15), registered once per process
|
|
47
|
+
* (the runner and each worker). */
|
|
48
|
+
function resolveStopbarProbe() {
|
|
49
|
+
if (probeHook) return
|
|
50
|
+
probeHook = true
|
|
51
|
+
const sdk = pathToFileURL(join(PKG_ROOT, 'dist', 'probe', 'sdk.js')).href
|
|
52
|
+
registerHooks({resolve: (specifier, context, nextResolve) => (specifier === 'stopbar/probe' ? {url: sdk, shortCircuit: true} : nextResolve(specifier, context))})
|
|
53
|
+
}
|
|
54
|
+
|
|
42
55
|
/** A name in TARGETS, else a .ts/.mts/.js/.mjs file (absolute, or relative to `cwd`, then to `repo`) that exports a
|
|
43
56
|
* ProbeTarget as `default` or as `target`. */
|
|
44
57
|
export async function loadTarget(spec , cwd = process.cwd(), repo ) {
|
|
@@ -47,6 +60,7 @@ export async function loadTarget(spec , cwd = process.cwd(), repo
|
|
|
47
60
|
const file = cands.find((f) => existsSync(f))
|
|
48
61
|
if (!file) throw new ProbeError(`probe target ${JSON.stringify(spec)} is neither a known target (${Object.keys(TARGETS).join(', ')}) nor an existing file`)
|
|
49
62
|
if (!/\.(ts|mts|js|mjs)$/.test(file)) throw new ProbeError(`probe target ${file}: the file must end in .ts, .mts, .js or .mjs`)
|
|
63
|
+
resolveStopbarProbe()
|
|
50
64
|
let mod
|
|
51
65
|
try { mod = await import(pathToFileURL(file).href) } catch (e) {
|
|
52
66
|
throw new ProbeError(`probe target ${file} does not load: ${(e )?.message ?? e}`)
|