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 CHANGED
@@ -1,5 +1,53 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.2.2] (2026-11-27)
4
+
5
+ `src/kernel.ts` is unchanged (sha256 `c602fc4bcf8ffb2e...`); every kernel law holds as in 1.2.1. No new dependency.
6
+ `PreToolUse` still starts no git process. A `config.json` and a `state.json` from 1.0.0–1.2.1 work without migration;
7
+ the new test-config patterns below reach an existing repository with `stopbar init --force`.
8
+
9
+ - **Husky, Lefthook and a custom `core.hooksPath` are protected.** Edit and Write of `.husky/**`, `lefthook*.yml`,
10
+ `.lefthook*.yml` (also `.yaml`, `-local`), `.lefthook/**` and of every file in the custom `core.hooksPath` are
11
+ blocked; so are shell commands that name them (`sed -i '/git-hook/d' .husky/pre-commit`, `rm -rf .husky`), matched on
12
+ path-segment boundaries (an empty, `.` or `/` value protects nothing). The hook reads `core.hooksPath` from
13
+ `<common-dir>/config` and `config.worktree` itself (`readHooksPath`), without a git process. `.husky` and `.lefthook`
14
+ join the wildcard guard (`rm -rf .hu*`), and `pre-commit`, `pre-push` and `_` the names checked inside a guarded
15
+ directory. The same files are test config in every profile, so a change made outside the agent hooks taints.
16
+ - **`stopbar doctor` reports `[FAIL] hooks git` when a Stopbar git hook is gone**: written by the last `init` or a later
17
+ `upgrade` (the events now record `gitHooksWritten`), run since the last `init` or `reset` (`hook-timing` records
18
+ `gitHook`), called by the tracked hook file in `HEAD`, or the other hook is still in place and the log does not say
19
+ that Stopbar left this one out. A hook that was never set up stays `[WARN]`. Doctor only reads `events.jsonl`.
20
+ - **Portable hook line.** The `WARN` of `init`, the refusal of `--hooks git` and `doctor` print
21
+ `npx --no-install stopbar git-hook pre-commit|pre-push` (from `--cli`) first and, without a local `node_modules`,
22
+ `node "$(git rev-parse --git-dir)/stopbar/runtime/bin/stopbar.mjs" git-hook <name>`; no absolute path into `.git`.
23
+ - **Wildcards after `$(pwd)`.** `$(pwd)`, `"$(pwd)"`, `${PWD}`, `$PWD`, `` `pwd` `` (also quoted, `pwd -L|-P`) read as `.`
24
+ before the command is split, so `rm -rf $(pwd)/.g*` is blocked as `rm -rf $PWD/.g*` was, and `cat $(pwd)/.e*` is a
25
+ secret read.
26
+ - **`find` with a pattern.** `find` with `-name`, `-iname`, `-path`, `-ipath`, `-wholename` or `-iwholename` whose
27
+ pattern reaches `.git`, an agent settings directory, `.husky`, `.lefthook`, a Lefthook file or the custom
28
+ `core.hooksPath`, together with `-delete`, `-exec`, `-execdir`, `-ok` or `-okdir`, is blocked; a pattern that reaches a
29
+ secret name (`.e*`, `*.pem`, `*.key`, `*/.env*`) with an `-exec` action is a secret read. `find . -name "*.ts" -exec
30
+ wc -l {} +` and `find . -name "*.test.ts" -delete` stay allowed.
31
+ - **`stopbar doctor --strict`**: a `[WARN]` fails too (exit 1, `RESULT: FAIL (strict: N warning(s))`, `--json`
32
+ `ok: false, strict: true`). Without the flag nothing changes.
33
+ - **`init` notes.** Without `--require-run`, `init` names `--require-run` and `doctor --strict` for CI; with
34
+ `--hooks codex` it recommends `--require-run`, because Codex CLI passes no exit status to its hooks. The default stays
35
+ `requireRun: false`.
36
+ - **`init --force` keeps `safeTools`**, and `--safe-tools "<glob>,<glob>"` sets them. A damaged previous `config.json`
37
+ never blocks `--force` (then the default list).
38
+ - **`--help` / `-h` in every subcommand** prints the help and runs nothing (`stopbar reset --help` no longer resets). A
39
+ `--help` that is the value of a flag (`--cmd --help`) is not taken as a request for help.
40
+ - **`stopbar run` on Windows** starts the gate command without the `PWD` inherited from Git Bash, so a bash inside
41
+ the gate sets its own (`PATH="$PWD/node_modules/.bin:$PATH"` broke at the colon of `C:`, exit 127). `stopbar doctor`
42
+ warns when a gate starts with a bare `bash` and the first bash on `PATH` is WSL's.
43
+ - **`import 'stopbar/probe'` without `stopbar` in the project's `node_modules`.** `stopbar probe --target <file>`
44
+ resolves that specifier to its own SDK with a module resolve hook (`registerHooks`, `node:module`), in the runner and
45
+ in each worker.
46
+ - **Docs.** The PROBE guide moved from `README.md` to [`docs/probe.md`](docs/probe.md) (in the npm package). The README
47
+ starts with one statement of what is proven, what is tested and what needs an OS sandbox, without the repeated
48
+ paragraph. `SECURITY.md`: Known limits of 1.2.2.
49
+ - No `any` in `integrations.ts` and `store.ts` (typed JSON and event entries). Version 1.2.2.
50
+
3
51
  ## 1.2.1 (2026-11-27)
4
52
 
5
53
  `src/kernel.ts` is unchanged (sha256 `c602fc4bcf8ffb2e...`); every kernel law holds as in 1.2.0. No new dependency.
package/README.md CHANGED
@@ -11,7 +11,7 @@ command text and asks the kernel; it is covered by unit and E2E tests and statef
11
11
 
12
12
  | Proven (Lean 4.34.0) | Tested (wrapper + E2E + PROBE) | Not covered without OS sandbox |
13
13
  |---|---|---|
14
- | The decision rule `src/kernel.ts`: no commit without a passing build and full suite at the current revision (L1); test taint until a human approval (L2.x); pause of risky and outbound calls after a secret read (L3.x); halt on budget and retries (L4.x). 10 mutants each fall with a counterexample. | How tool calls become kernel requests: exact gate commands, content snapshots of the tree, test and secret path patterns, self-protection of `.git`, agent settings and the Stopbar code, the client adapters, the git hooks. | A path or name built at run time (`f=.e; cat ${f}nv`), a script the agent wrote and runs (`node /tmp/x.js`), code that the gate commands run, secrets in files with ordinary names. See [SECURITY.md](SECURITY.md) section 3. |
14
+ | The decision rule `src/kernel.ts`: no commit without a passing build and full suite at the current revision (L1); test taint until a human approval (L2.x); pause of risky and outbound calls after a secret read (L3.x); halt on budget and retries (L4.x). 10 mutants each fall with a counterexample. | How tool calls become kernel requests: exact gate commands, content snapshots of the tree, test and secret path patterns, self-protection of `.git`, agent settings, Husky and Lefthook hooks and the Stopbar code, the client adapters, the git hooks. | A path or name built at run time (`f=.e; cat ${f}nv`), a script the agent wrote and runs (`node /tmp/x.js`), code that the gate commands run, secrets in files with ordinary names. See [SECURITY.md](SECURITY.md) section 3. |
15
15
 
16
16
  **Without an OS sandbox, Stopbar stops shortcuts and mistakes of an agent; it is not a security boundary against a
17
17
  hostile agent.** A command can build a path at run time or hide it in a script that the text rules do not see. See
@@ -25,12 +25,11 @@ It stops an agent from:
25
25
  - looping on failing builds or tests, or going past a budget of tool calls;
26
26
  - switching itself off by editing the agent's hook configuration, git hooks or its own state.
27
27
 
28
- The decisions come from one rule, `src/kernel.ts`. gdp-wired 0.60.0 proves its laws by induction, and 10 mutants of
29
- the rule each fall with a counterexample. Every client goes through the same rule: an adapter translates the client's
30
- hook payload into one internal event and renders the decision in the client's own output format.
31
-
32
28
  ## Supported agents
33
29
 
30
+ Every client goes through the same rule: an adapter translates the client's hook payload into one internal event and
31
+ renders the decision in the client's own output format.
32
+
34
33
  | Agent | Config written by `init --hooks` | Events | Block protocol | Status |
35
34
  |---|---|---|---|---|
36
35
  | Claude Code | `claude`: `.claude/settings.local.json` (`claude-project`: `.claude/settings.json`) | PreToolUse, PostToolUse, PostToolUseFailure, Stop | exit 2, reason on stderr | live-verified (Claude Code 2.1.326) |
@@ -109,7 +108,7 @@ EOF
109
108
 
110
109
  | Command | Who | What it does |
111
110
  |---|---|---|
112
- | `stopbar init --build "<cmd>" --test "<cmd>" [--profile p] [--base-ref <ref>] [--cli "<cmd>"] [--stop-gate block\|warn] [--require-run] [--max-retries 3] [--cap 500] [--cost 1] [--hooks <targets>] [--no-git-hooks] [--no-pin] [--force] [--force-hooks]` | human | Writes `config.json` and a fresh state, pins the runtime, writes or prints the hooks. Targets: `claude` (`local`), `claude-project` (`project`), `cursor`, `codex`, `gemini`, `antigravity` (`agy`), `git`, comma separated; `git` is added to any other target unless `--no-git-hooks`. `--require-run`: the build and full test gates count only through `stopbar run build\|test`. `--build` and `--test` must be different commands. `--base-ref` sets the git ref used to judge whether a test file already existed (default `HEAD`). `--cli` sets the Stopbar command in hints (default `npx --no-install stopbar`). `--stop-gate warn` lets a turn end with unverified changes (default `block`); commit and push stay gated. |
111
+ | `stopbar init --build "<cmd>" --test "<cmd>" [--profile p] [--base-ref <ref>] [--cli "<cmd>"] [--stop-gate block\|warn] [--require-run] [--safe-tools "<glob>,<glob>"] [--max-retries 3] [--cap 500] [--cost 1] [--hooks <targets>] [--no-git-hooks] [--no-pin] [--force] [--force-hooks]` | human | Writes `config.json` and a fresh state, pins the runtime, writes or prints the hooks. Targets: `claude` (`local`), `claude-project` (`project`), `cursor`, `codex`, `gemini`, `antigravity` (`agy`), `git`, comma separated; `git` is added to any other target unless `--no-git-hooks`. `--require-run`: the build and full test gates count only through `stopbar run build\|test`. `--build` and `--test` must be different commands. `--base-ref` sets the git ref used to judge whether a test file already existed (default `HEAD`). `--cli` sets the Stopbar command in hints (default `npx --no-install stopbar`). `--stop-gate warn` lets a turn end with unverified changes (default `block`); commit and push stay gated. `--safe-tools` sets `safeTools` (comma separated globs); without it `--force` keeps the list of the previous `config.json`. |
113
112
  | `stopbar upgrade [--hooks <targets>] [--force-hooks]` | human | After you update the Stopbar package: re-pins the hook runtime in `.git/stopbar/runtime` and, with `--hooks`, rewrites the hooks. `state.json`, `config.json` and the snapshots stay as they are (revision, gates, taint, budget), so an active session keeps its green gates. Use it instead of `init --force`. |
114
113
  | `stopbar hook [--adapter auto\|claude\|cursor\|codex\|gemini\|antigravity]` | agent | The hook. JSON on stdin; the decision in the client's format (see Supported agents). |
115
114
  | `stopbar git-hook pre-commit\|pre-push` | git | The git fallback gate. Exit 1 aborts the commit or push. |
@@ -119,13 +118,14 @@ EOF
119
118
  | `stopbar approve-shell` | human | Allows **one** risky or outbound call after a secret read. |
120
119
  | `stopbar resume --extra N` | human | Lifts a halt (retry limit or budget) and adds N to the budget. |
121
120
  | `stopbar reset` | human | Fresh kernel state. Config and event log stay. Also repairs a damaged `state.json`. Uncommitted changes of existing tests or test config (against `baseRef`, else `HEAD`) are not forgotten: the session starts tainted, with a `WARN`, until `approve-tests`. `init --force` does the same. |
122
- | `stopbar doctor [--json]` | human | Environment, config, state, hooks and a dry run. Exit 1 on a problem. |
121
+ | `stopbar doctor [--json] [--strict]` | human, CI | Environment, config, state, hooks and a dry run. It only reads the repository's event log. Exit 1 on a problem; with `--strict` also on a warning (`RESULT: FAIL (strict: N warning(s))`, in `--json` `ok: false, strict: true`). |
123
122
  | `stopbar prove [--out f.json] [--lean f.lean]` | human, CI | PROVE: the inductive proof of the kernel and the 10 mutants. Exit 0 only if everything holds. `verify` is an alias. |
124
- | `stopbar probe [--target wrapper\|<file> \| --cmd "<command>" [--target-file <path>] [--cmd-timeout 300000]] [--runs 200] [--seed 1] [--jobs N] [--work dir] [--out dir] [--regressions dir] [--regressions-only] [--check-mutants] [--mutant-runs 50] [--no-record]` | human, CI | PROBE: stateful probing of the hooks against the proven kernel (`wrapper`, needs the full package with gdp-wired), of your own model in a `.ts`, `.mts`, `.js` or `.mjs` file, or of a program in any language over NDJSON (`--cmd`, see [PROBE for your project](#probe-for-your-project)). `--target` and `--cmd` exclude each other. A failure is shrunk to a minimal JSON reproduction. |
123
+ | `stopbar probe [--target wrapper\|<file> \| --cmd "<command>" [--target-file <path>] [--cmd-timeout 300000]] [--runs 200] [--seed 1] [--jobs N] [--work dir] [--out dir] [--regressions dir] [--regressions-only] [--check-mutants] [--mutant-runs 50] [--no-record]` | human, CI | PROBE: stateful probing of the hooks against the proven kernel (`wrapper`, needs the full package with gdp-wired), of your own model in a `.ts`, `.mts`, `.js` or `.mjs` file, or of a program in any language over NDJSON (`--cmd`, see [docs/probe.md](docs/probe.md)). `--target` and `--cmd` exclude each other. A failure is shrunk to a minimal JSON reproduction. |
125
124
  | `stopbar probe init [--lang ts\|py] [--name sample] [--out probes] [--force] [--repo <dir>]` | human, agent | Writes a starter target with 2 actions, 1 invariant and 2 mutants (`<name>.probe.ts` or `<name>_probe.py`) and prints the command that runs it. It does not overwrite a file without `--force`. |
126
125
  | `stopbar attest [--format json\|md]` | human, CI | ATTEST: the session attestation. The same state and log give the same output. Exit 1 if the state and the log disagree, exit 2 if a file is damaged. `probes` (Markdown: `## Probe evidence`) lists the latest `probe:result` per target since the last `init` or `reset`, with `atCurrentSnapshot`. |
127
126
 
128
- All commands take `--repo <dir>`. The agent cannot run the human commands: the hooks block them.
127
+ All commands take `--repo <dir>` and `--help` / `-h` (prints the help, runs nothing). The agent cannot run the human
128
+ commands: the hooks block them.
129
129
 
130
130
  State, configuration and the event log are in `<repo>/.git/stopbar/`: `config.json`, `state.json`, `events.jsonl`, the
131
131
  private snapshot index and the pinned runtime. They are outside the working tree, so they never change the tree hash.
@@ -137,7 +137,7 @@ The gate (GATE, with PROVE and ATTEST) is the product. PROBE is a test tool that
137
137
  | Part | Command | What it gives you |
138
138
  |---|---|---|
139
139
  | PROVE | `stopbar prove`, `npm run verify:lean` | The inductive proof of the kernel, 10 mutants that must fall with a counterexample, and (release gate) `lake build` of the Lean export in a pinned Lean 4.34.0 container without network. |
140
- | PROBE | `stopbar probe` | Stateful probing: at least 200 random multi-step sequences of hook events, human commands and damaged files on real git repositories, compared step by step with the proven kernel (target `wrapper`, Stopbar itself). Since 1.2.0 also your own project: a TS/JS model written with `defineModel` from `stopbar/probe`, or a program in any language (Python, Go, Rust, ...) that speaks NDJSON on stdin/stdout (`--cmd`), with mutants that must be caught. |
140
+ | PROBE | `stopbar probe` | Stateful probing: at least 200 random multi-step sequences of hook events, human commands and damaged files on real git repositories, compared step by step with the proven kernel (target `wrapper`, Stopbar itself). Since 1.2.0 also your own project: a TS/JS model written with `defineModel` from `stopbar/probe`, or a program in any language (Python, Go, Rust, ...) that speaks NDJSON on stdin/stdout (`--cmd`), with mutants that must be caught. Guide: [docs/probe.md](docs/probe.md). |
141
141
  | GATE | `stopbar init`, `upgrade`, `hook`, `git-hook`, `run`, `status`, `approve-tests`, `approve-shell`, `resume`, `reset`, `doctor` | The agent hooks, the git fallback and the human commands. |
142
142
  | ATTEST | `stopbar attest` | A deterministic attestation of the session: HEAD, tree, gates, human actions, probe evidence and the sha256 of the event log. |
143
143
 
@@ -145,93 +145,6 @@ The gate (GATE, with PROVE and ATTEST) is the product. PROBE is a test tool that
145
145
  sha256 of the prober file. It says what the prober saw on that tree. It is no proof against a hostile agent without an
146
146
  OS sandbox: an agent that can write `events.jsonl` can also write a false entry ([SECURITY.md](SECURITY.md) section 4).
147
147
 
148
- ## PROBE for your project
149
-
150
- `stopbar probe --target <file>` runs a model of any TS/JS code. The file exports (as `default` or as `target`) a
151
- target; `defineModel` from `stopbar/probe` builds one from a list of actions:
152
-
153
- ```ts
154
- import {defineModel} from 'stopbar/probe'
155
-
156
- export default defineModel<{q: BoundedQueue<number>; model: number[]}>({
157
- name: 'bounded-queue', description: 'FIFO queue with capacity 4 vs an array model',
158
- setup: () => ({q: new BoundedQueue<number>(4), model: []}),
159
- actions: [
160
- {name: 'push', weight: 3, gen: (r) => ({x: r.int(0, 99)}), run: (s, {x}, check) => {
161
- const accepted = s.model.length < 4
162
- check.eq('push result', s.q.push(x), accepted)
163
- if (accepted) s.model.push(x)
164
- }},
165
- {name: 'shift', gen: () => null, run: (s, _a, check) => check.eq('shift result', s.q.shift(), s.model.shift())},
166
- ],
167
- invariants: [{name: 'size', check: (s, check) => check.eq('size', s.q.size, s.model.length)}],
168
- mutants: {M1_dropCap: () => ({q: new BoundedQueue<number>(4, {checkCap: false}), model: []})},
169
- })
170
- ```
171
-
172
- - `gen(r)` returns pure JSON data for one step. `r` is a deterministic generator (`createRng`: xorshift32, the same
173
- numbers on Windows and Linux). A run is `{seed, actions: [{t: name, args}]}` with `minSteps`..`maxSteps` steps
174
- (default 15..40).
175
- - `run(state, args, check)` drives the real code and compares it with the model: `check.eq` (deep strict equality),
176
- `check.ok`, `check.fail`. A failed check, and any exception from the code under test, is a mismatch with the step and
177
- the action, not a crash. Invariants run after `setup` (step -1) and after every step. `teardown` runs after every run
178
- whose `setup` returned, also after a failure.
179
- - A failure is shrunk (cut after the failing step, then removal of blocks of half, a quarter, ... of the run, then of
180
- single steps) and written to `repro-<seed>.json` in `--out`. `--regressions <dir>` replays such files on every run.
181
- A file target replays only the regressions you name.
182
- - `--check-mutants`: each mutant replaces `setup` with a damaged system under test. The original must pass, and every
183
- mutant must fail within `--mutant-runs` seeds (default 50). Exit 0 only then. A survivor is named in the output and
184
- in `summary.json` (`mutants.survived`). A target without mutants is refused.
185
- - In a repository with Stopbar, every run appends a `probe:result` entry to `events.jsonl` (target, sha256 of the
186
- target file, tree snapshot, runs, steps, mutants, sha256 of `summary.json`). It is not a kernel step and does not
187
- change `state.json`. `stopbar attest` shows the latest entry per target and whether the tree is still the one that
188
- was probed. `--no-record` skips the entry. Outside a Stopbar repository nothing is recorded.
189
-
190
- A complete example with two mutants: [`examples/bounded-queue.probe.ts`](examples/bounded-queue.probe.ts)
191
- (`stopbar probe --target examples/bounded-queue.probe.ts --check-mutants`). TypeScript files need Node's type
192
- stripping (Node 22.18 or later): only erasable syntax, no `enum` and no constructor parameter properties.
193
-
194
- ### Any language: `--cmd`
195
-
196
- `stopbar probe --cmd "<command>"` probes a program in any language (Python, Go, Rust, ...). Each worker (`--jobs`)
197
- starts the command once, in a shell, in the current directory, and keeps it for all its runs, so the start-up cost
198
- is paid once per worker and not once per seed. Stopbar sends one JSON object per line on stdin and reads one answer
199
- per line on stdout (NDJSON):
200
-
201
- | Request | Answer |
202
- |---|---|
203
- | `{"op":"info"}` | `{"name":"<string>","description":"<string>","mutants":["M1",...]}` (`mutants` is optional) |
204
- | `{"op":"generate","seed":123}` | `{"seed":123,"actions":[...]}`: pure JSON data, the same for the same seed |
205
- | `{"op":"execute","run":{"seed":123,"actions":[...]},"dir":"<scratch dir>","mutant":"M1"}` | `{"ok":true,"steps":N,"cov":{"push":3}}` or `{"ok":false,"mismatch":{"step":2,"action":{...},"what":"...","expected":...,"actual":...}}` |
206
-
207
- - `mutant` is sent only with `--check-mutants`. `dir` is an empty scratch directory for each execution.
208
- - Any answer can be `{"error":"<text>"}`. stdout is for the protocol only: print logs to stderr.
209
- - An exception of the code under test is a finding: catch it in `execute` and answer with a mismatch (the
210
- templates do this). A process that exits, closes stdout, prints a line that is not JSON or gives no answer within
211
- `--cmd-timeout` ms (default 300000) stops the probe with exit 1 and the end of its stderr. When the probe ends,
212
- Stopbar closes stdin; a process that does not exit within 2 s is killed.
213
- - Shrinking, `--regressions` / `--regressions-only`, `--check-mutants`, `summary.json`, `repro-<seed>.json`,
214
- `probe:result` and `attest` work as for `--target <file>`. `target` in a reproduction is the `name` from `info`;
215
- `targetCmd` is the command. A `--cmd` target replays only the regressions in `--regressions <dir>`.
216
- - `targetSha256` is the sha256 of `--target-file <path>`, else of the first word after the interpreter that is an
217
- existing file (`python examples/bounded_queue_probe.py` hashes that file), else `null`.
218
-
219
- [`examples/bounded_queue_probe.py`](examples/bounded_queue_probe.py) is the same queue model in Python, with the
220
- standard library only:
221
-
222
- ```sh
223
- stopbar probe --cmd "python examples/bounded_queue_probe.py" --runs 200 --check-mutants
224
- ```
225
-
226
- ### A starter target: `stopbar probe init`
227
-
228
- `stopbar probe init --lang ts` writes `probes/sample.probe.ts` (`defineModel`), and `--lang py` writes
229
- `probes/sample_probe.py` (the NDJSON protocol, standard library only: `json`, `random`, `sys`). Both hold the same
230
- model with 2 actions, 1 invariant, 2 mutants and the rules for zero false positives, and `--check-mutants` passes on
231
- them as written. The command prints the line that runs the file. `--name` takes letters, digits, `-` and `_` only;
232
- `--out` (default `probes`) is relative to `--repo`, else to the current directory; an existing file stays unless you
233
- pass `--force`.
234
-
235
148
  ## Agent skill
236
149
 
237
150
  [`skills/stopbar/SKILL.md`](skills/stopbar/SKILL.md) tells an agent how to work under the gate (exact gate commands,
@@ -292,6 +205,8 @@ profile by editing the lists: no code change is necessary.
292
205
  A `config.json` written by 1.0.0–1.1.1 keeps its own list and keeps working; to stop false
293
206
  `PAUSE`s on the session tools after a secret read, add `"mcp__ccd_session_mgmt__*"` to `safeTools` or write the file
294
207
  again with `stopbar init --force ...`. `stopbar doctor` shows a `[WARN] safeTools` while a default entry is missing.
208
+ `stopbar init --safe-tools "<glob>,<glob>"` sets the list. Since 1.2.2 `init --force` without `--safe-tools` keeps
209
+ the list of the previous `config.json` (when that file is valid) and says so.
295
210
  - **`cliCmd`** (optional, set via `stopbar init --cli "<cmd>"`) is the command that starts Stopbar in the hints shown to
296
211
  the agent (`<cliCmd> run build|test`). Without it the hints say `npx --no-install stopbar`. It must be one command
297
212
  without shell operators and must not name a `.git` or agent-settings directory, because the agent's shell may not run
@@ -317,8 +232,24 @@ exit-code-only gates)` by default, `gates: stopbar run only (--require-run)` wit
317
232
  **Custom `core.hooksPath`** (Husky, Lefthook, a shared hooks directory): since 1.2.1 Stopbar does not write into it.
318
233
  `init --hooks <client>` then writes no git hook and prints a `WARN`; `init --hooks git` fails closed (exit 2);
319
234
  `stopbar doctor` reports `[WARN] hooks git`: git commit and git push are not gated by Stopbar until a human adds one
320
- line to each hook of the hook manager, `node "<runtime>/bin/stopbar.mjs" git-hook pre-commit` and `... git-hook
321
- pre-push` (doctor prints the exact lines), or runs `stopbar upgrade --hooks git --force-hooks`.
235
+ line to each hook of the hook manager, or runs `stopbar upgrade --hooks git --force-hooks`. The line works on every
236
+ machine, so it can go into a tracked hook such as `.husky/pre-commit`:
237
+
238
+ ```sh
239
+ npx --no-install stopbar git-hook pre-commit # .husky/pre-commit
240
+ npx --no-install stopbar git-hook pre-push # .husky/pre-push
241
+ # without Stopbar in the local node_modules: the pinned runtime, relative to the git dir (also in a linked worktree)
242
+ node "$(git rev-parse --git-dir)/stopbar/runtime/bin/stopbar.mjs" git-hook pre-commit
243
+ ```
244
+
245
+ The first command follows `--cli` (default `npx --no-install stopbar`). Since 1.2.2 the agent cannot remove that
246
+ line: Edit and Write of `.husky/**`, `lefthook*.yml`, `.lefthook*.yml`, `.lefthook/**` and of every file in the
247
+ custom `core.hooksPath` are blocked, and so are shell commands that name them (`sed -i '/git-hook/d' .husky/pre-commit`,
248
+ `rm -rf .husky`, `find . -name '.hu*' -delete`). The hook reads `core.hooksPath` from the git config files itself,
249
+ without a git process. These files are also test config, so a change made outside the agent hooks taints the
250
+ session. `stopbar doctor` reports `[FAIL] hooks git` (not `[WARN]`) when a Stopbar git hook that was there is gone:
251
+ written by the last `init` or a later `upgrade`, run since the last `init` or `reset`, called by the tracked hook
252
+ in `HEAD`, or the other of the two hooks is still in place.
322
253
 
323
254
  ## Hardening: OS sandbox + client deny rules
324
255
 
@@ -387,10 +318,13 @@ Ubuntu, Windows and macOS (Node 24); `npm run prove`; and `lake build` of the Le
387
318
  - run: npx stopbar prove --out stopbar-prove.json
388
319
  ```
389
320
 
390
- For headless agent runs in CI, initialise Stopbar in the job and keep the evidence:
321
+ For headless agent runs in CI, initialise Stopbar in the job with `--require-run` (the gates count only through
322
+ `stopbar run build|test`), check the setup with `stopbar doctor --strict` (a warning fails the job) and keep the
323
+ evidence:
391
324
 
392
325
  ```yaml
393
- - run: npx stopbar init --build "npm run build" --test "npm test" --hooks project
326
+ - run: npx stopbar init --build "npm run build" --test "npm test" --hooks project --require-run
327
+ - run: npx stopbar doctor --strict
394
328
  - run: claude -p "<task>" --setting-sources project,local --max-turns 20
395
329
  - run: npx stopbar status --json > stopbar-status.json
396
330
  - run: npx stopbar attest --format md > stopbar-attest.md
@@ -413,16 +347,16 @@ latency. An earlier prototype that loaded the prover in every hook measured p50
413
347
 
414
348
  | Platform | Node | git | Python | Typecheck | Unit | E2E | `stopbar probe` | `--cmd` Python example | `stopbar prove` | `stopbar doctor` |
415
349
  |---|---|---|---|---|---|---|---|---|---|---|
416
- | Windows 11, Git for Windows | 24.19.0 | 2.56.0 | 3.14.7 | 0 errors | 74/74 | 460/460 | 202/202 sequences | 200/200, mutants 2/2 | proven, 10/10 mutants | OK |
417
- | Linux, Debian 13 (container, no network) | 24.21.0 | 2.47.3 | 3.13.5 | 0 errors | 74/74 | 460/460 | 202/202 sequences | 200/200, mutants 2/2 | proven, 10/10 mutants | OK |
418
- | macOS 26.7.2 arm64 (`macos-latest`, GitHub Actions, CI of 1.2.0) | 24.22.3 | 2.56.1 | – | 0 errors | pass | 443/443 | 202/202 sequences | – | – | – |
350
+ | Windows 11, Git for Windows | 24.19.0 | 2.56.0 | 3.14.7 | 0 errors | 81/81 | 502/502 | 202/202 sequences | 200/200, mutants 2/2 | proven, 10/10 mutants | OK |
351
+ | Linux, Debian 13 (container, no network) | 24.21.0 | 2.47.3 | 3.13.5 | 0 errors | 81/81 | 502/502 | 202/202 sequences | 200/200, mutants 2/2 | proven, 10/10 mutants | OK |
352
+ | macOS 26.7.2 arm64 (`macos-latest`, GitHub Actions, CI of 1.2.1) | 24.22.3 | 2.56.1 | – | 0 errors | pass | 460/460 | 202/202 sequences | – | – | – |
419
353
  | Ubuntu, Windows (GitHub Actions) | 24 | runner | runner | CI | CI | CI | CI | – | CI (Ubuntu) | – |
420
354
 
421
- The first two rows are runs of 1.2.1 on our machines; both also pass `stopbar probe --target
422
- examples/bounded-queue.probe.ts --runs 50 --check-mutants` (50/50, mutants 2/2). The macOS row is the CI run of 1.2.0
423
- (commit `8bfd8cb`, workflow `.github/workflows/ci.yml`): build, typecheck, `npm test` (unit with the dot reporter, so no
424
- count in the log) and the same `bounded-queue` probe (50/50, mutants 2/2). The `prove` job of CI runs on Ubuntu only.
425
- CI runs after a push; the results of 1.2.1 will be on the repository's Actions page (see the CI badge).
355
+ The first two rows are runs of 1.2.2 on our machines; both also pass `stopbar probe --target
356
+ examples/bounded-queue.probe.ts --runs 50 --check-mutants` (50/50, mutants 2/2). The macOS row is the CI run of 1.2.1
357
+ (commit `fdd8360`, workflow `ci`, run #2; `.github/workflows/ci.yml`): build, typecheck, `npm test` (unit with the dot
358
+ reporter, so no count in the log) and the same `bounded-queue` probe (50/50, mutants 2/2). The `prove` job of CI runs
359
+ on Ubuntu only. CI runs after a push, so 1.2.2 has no CI run yet.
426
360
 
427
361
  The E2E suite runs every adapter (Cursor, Codex CLI, Gemini CLI, Antigravity CLI) and the git fallback with real
428
362
  git commits and pushes. The probe runs the same 200 seeds plus 2 regressions on both platforms, with the same 5020 steps
@@ -431,8 +365,9 @@ The `--cmd` column is `stopbar probe --cmd "<python> examples/bounded_queue_prob
431
365
  (3970 steps on both platforms). E2E scenario S37 runs `--cmd` with a Node target everywhere, and the Python example
432
366
  and the `--lang py` template only where `python3` or `python` is found.
433
367
  `npm run verify:lean` passes in the Lean 4.34.0 container: `lake build` exit 0, 0 errors, 0 `sorry` (run on the same
434
- `src/kernel.ts`, sha256 `c602fc4bcf8ffb2e...`, which 1.2.0 and 1.2.1 do not change). `node scripts/verify-lean.ts --local`
435
- gives the same result with Lean 4.34.0 on `PATH` (checked in a Debian 13 container with the toolchain of that image).
368
+ `src/kernel.ts`, sha256 `c602fc4bcf8ffb2e...`, which 1.2.0, 1.2.1 and 1.2.2 do not change; 18 theorems in
369
+ `StopbarKernel.lean`, axioms `Classical.choice`, `Quot.sound`, `propext` only). `node scripts/verify-lean.ts --local`
370
+ is the same check with Lean 4.34.0 on `PATH`; CI uses it.
436
371
 
437
372
  ## License
438
373
 
package/SECURITY.md CHANGED
@@ -108,6 +108,17 @@ There is no proof for them.
108
108
  cannot see it. A secret read is also: a command that prints the environment (`printenv`, a bare `env`,
109
109
  `Get-ChildItem Env:`, `/proc/self/environ`); a path with `..` segments (`cat src/../.env`); a live wildcard that
110
110
  reaches a secret name (`cat .en*`, `cat .en?`, `cat src/../.en*`). `env VAR=1 cmd` and `set` are not a read.
111
+ - **Since 1.2.2, git hook managers, `$(pwd)` and `find`.** Edit and Write may not touch `.husky/**`, `lefthook*.yml`,
112
+ `.lefthook*.yml` (also `.yaml` and `-local`), `.lefthook/**` or any file in a custom `core.hooksPath`, and a shell
113
+ command may not name them (matched on path-segment boundaries; an empty, `.` or `/` value is ignored, and a value that
114
+ is the working tree root or above it protects nothing). The hook reads `core.hooksPath` from `<common-dir>/config`
115
+ and `<git-dir>/config.worktree` (no git process; include files are not followed). These files are test config in
116
+ every profile. `.husky` and `.lefthook` are guarded against wildcards like `.git`. `$(pwd)`, `${PWD}`, `$PWD` and
117
+ `` `pwd` `` (also in double quotes) read as `.` for the wildcard and secret checks. `find` with a `-name`, `-iname`,
118
+ `-path`, `-ipath`, `-wholename` or `-iwholename` pattern (find expands it itself, also when quoted) that reaches a
119
+ guarded directory, with `-delete`, `-exec`, `-execdir`, `-ok` or `-okdir`, is blocked; one that reaches a secret name
120
+ with an `-exec` action is a secret read. `stopbar doctor` reports `[FAIL] hooks git` when a Stopbar git hook that
121
+ was written, has run, or is called in `HEAD` is gone, and `stopbar doctor --strict` fails on any `[WARN]` (CI).
111
122
  - **Halted sessions.** While halted, every tool is paused except the tools in `config.safeTools` (default:
112
123
  `mcp__ccd_turn__*` and `mcp__ccd_session_mgmt__*`, the local task-list, turn and session-message tools of Claude
113
124
  Desktop), so the agent can still ask a human for `stopbar resume`. These tools never take a kernel step, so they
@@ -225,14 +236,19 @@ command text:
225
236
  - For `--cmd`, `targetSha256` covers one file only: `--target-file`, else the first existing file after the
226
237
  interpreter, else nothing (`null`). Imports, libraries and the interpreter are not hashed.
227
238
 
228
- ## Known limits of 1.2.1
239
+ ## Known limits of 1.2.2
229
240
 
230
- What a regular expression cannot block (the unit test "1.2.1 known limits without an OS sandbox" keeps these visible):
241
+ 1.2.2 closes three ways around the wrapper that 1.2.1 listed or let through: removing the `stopbar git-hook` line
242
+ from a Husky or Lefthook hook (`Edit`, `sed -i '/git-hook/d' .husky/pre-commit`) with only a `[WARN]` from doctor,
243
+ `rm -rf $(pwd)/.g*`, and `find . -name '.g*' -delete` / `find . -name '.e*' -exec cat {} +`.
244
+
245
+ What a regular expression cannot block (the unit test "1.2.2 known limits without an OS sandbox" keeps these visible):
231
246
 
232
247
  - A name built at run time: `cat $(echo .e)nv`, `f=.e; cat ${f}nv`, `g=.g; rm -rf $g"it"`. The hook sees `.e` and
233
248
  `nv`, never `.env`. The same holds for aliases, shell functions and a backslash inside a word (`g\it`).
234
249
  - A script: `node /tmp/x.js`, `bash x.sh`. The text checks do not read the script.
235
- - A wildcard outside the cases of section 2: `find . -name '.g*' -delete`, `echo .g* | xargs rm -rf`, a PowerShell
250
+ - A wildcard outside the cases of section 2: `echo .g* | xargs rm -rf`, `find . -delete` or `find . -type f -exec
251
+ cat {} +` without a name pattern, `find . -name config -delete` (a name inside `.git`, not `.git` itself), a PowerShell
236
252
  `Remove-Item * -Recurse -Force` (on Windows `*` also matches dot directories), and directory wildcards on the way to a
237
253
  secret (`cat secre*/db.txt`). A bare `.*` in `echo .*` or `ls .*` counts as a secret read (it reaches `.env`).
238
254
  - One variable or another program: `echo $TOKEN`, `export -p`, `declare -x`, `node -e "console.log(process.env)"`.
@@ -250,7 +266,12 @@ Other limits:
250
266
  git action is not gated until a human runs `stopbar upgrade --hooks git --force-hooks`. With a custom
251
267
  `core.hooksPath` (Husky, Lefthook, a shared directory) Stopbar writes no git hook there without `--force-hooks`, so
252
268
  git commit and git push are not gated until a human adds the `git-hook` lines that `stopbar doctor` prints.
253
- `stopbar doctor` reports `[WARN] hooks git` (not `[FAIL]`) while a Stopbar git hook is missing.
269
+ `stopbar doctor` reports `[WARN] hooks git` while a Stopbar git hook was never set up, and `[FAIL]` only once one
270
+ that was written, ran, or is in `HEAD` is gone; a hook that was added by hand, never committed and never run is
271
+ only a `[WARN]` when it disappears. A hook path built at run time (`d=.hu; sed -i d ${d}sky/pre-commit`) passes like
272
+ any name built at run time, and a hook manager that keeps its configuration elsewhere (`package.json` for Husky 4,
273
+ `simple-git-hooks`) is not covered. `npx --no-install stopbar git-hook` runs the Stopbar in the project's
274
+ `node_modules`, not the pinned runtime.
254
275
  - `baseRef`: a mutable branch name can be moved by the agent (section 3, point 4). Use a commit SHA as `--base-ref`
255
276
  when the agent must not move the baseline. `stopbar status` prints a `note:` when the tree no longer differs from
256
277
  `baseRef` on existing tests; it never clears the taint (L2.2).
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.2.1",
2
+ "version": "1.2.2",
3
3
  "kernelSourceSha256": "c602fc4bcf8ffb2e312bf838986e6d4b006af6d0e6c7447c8c61d5888adc5ef8",
4
4
  "machineSha256": "b397085e0cb13e2e50aa655c54de0744d08f2ebf500bf32af8ff3e8a11ba7321",
5
5
  "files": 29
package/dist/classify.js CHANGED
@@ -286,6 +286,7 @@ function secretSamples(paths ) {
286
286
  * Also: a command that prints the environment (printenv, Get-ChildItem Env:), `..` segments (`src/../.env`), and a
287
287
  * wildcard that reaches a secret name (`.en*`, `.en?`, `src/../.e*`). */
288
288
  export function secretInCommand(cmd , paths , exists = () => true, shell = 'bash') {
289
+ cmd = normPwd(cmd)
289
290
  const words = (s ) => s.split(/[\s'"=(),;|&<>@:]+/).filter(Boolean)
290
291
  const texts = [cmd, unsplice(cmd), unquoteShellWords(cmd)]
291
292
  if (paths.secrets.length) {
@@ -319,6 +320,15 @@ export function secretInCommand(cmd , paths , exists
319
320
  if (pattern) return {token: tok, pattern}
320
321
  }
321
322
  }
323
+ // find -name/-path <pattern> -exec ...: find expands the pattern itself; also `*.key` (a.key) and `**/x/**` (x/a)
324
+ const extra = paths.secrets.flatMap((g) => {
325
+ const last = g.split('/').pop() ?? ''
326
+ if (EXT_ONLY.test(last)) return [`a${last.slice(1)}`]
327
+ const dir = /^\*\*\/([^*?[{\/]+)\/\*\*$/.exec(g)
328
+ return dir ? [`${dir[1]}/a`] : []
329
+ })
330
+ const f = findReaches(cmd, [...samples, ...extra], false)
331
+ if (f) { const pattern = secretPattern(f.name, paths); if (pattern) return {token: `find ${f.pat}`, pattern} }
322
332
  return null
323
333
  }
324
334
 
@@ -399,11 +409,23 @@ export function classifyTreeChange(changes , in
399
409
 
400
410
  // ---------------------------------------------------------------- self-protection
401
411
  // Unconditional BLOCK in PreToolUse, outside the kernel. Paths are compared normalised: '/' separators, lower case.
402
-
412
+ /** `hooksDir`: the directory a custom `core.hooksPath` points to (absolute; set only when it is outside the default
413
+ * .git/hooks and not the working tree root or above it); `hooksPathRaw`: the value as written in the git config. */
414
+
403
415
 
404
416
  const lc = (p ) => norm(p).toLowerCase().replace(/\/+$/, '')
405
417
  const under = (a , dir ) => a === dir || a.startsWith(dir + '/')
406
418
 
419
+ /** The Protect fields of a custom core.hooksPath (repo.ts readHooksPath). A value that names the working tree root or a
420
+ * directory above it would protect the whole tree: then only the raw value is kept (it is ignored when it is `.`). */
421
+ export function hooksProtect(root , hp ) {
422
+ if (!hp) return {}
423
+ return under(lc(root), lc(hp.dir)) ? {hooksPathRaw: hp.raw} : {hooksDir: hp.dir, hooksPathRaw: hp.raw}
424
+ }
425
+
426
+ // the files of the git hook managers Husky and Lefthook: a tracked hook there calls `stopbar git-hook`
427
+ const HOOK_MANAGER_PATH = /(^|\/)(?:\.husky(?:\/|$)|\.lefthook(?:\/|$)|\.?lefthook(?:-local)?\.ya?ml$)/
428
+
407
429
  // the hook configuration of every supported client (project and user level)
408
430
  const AGENT_CONFIG = [
409
431
  [/(^|\/)\.claude\/[^/]*settings[^/]*\.json$/, 'Claude Code settings (.claude/settings*.json)'],
@@ -420,6 +442,8 @@ export function protectedPath(abs , root , pr )
420
442
  const tail = under(a, r) ? a.slice(r.length) : a
421
443
  if (/(^|\/)\.git(\/|$)/.test(tail) || under(a, lc(pr.gitDir)) || under(a, lc(pr.stateDir))) return 'git metadata (.git/**, Stopbar state, git hooks, git config)'
422
444
  for (const [re, what] of AGENT_CONFIG) if (re.test(a)) return `${what} hold the Stopbar hooks`
445
+ if (HOOK_MANAGER_PATH.test(tail)) return 'git hook manager files (.husky/**, lefthook*.yml, .lefthook/**) call the Stopbar git hooks'
446
+ if (pr.hooksDir && under(a, lc(pr.hooksDir))) return `the custom core.hooksPath directory (${pr.hooksPathRaw ?? pr.hooksDir}) holds the git hooks`
423
447
  for (const d of pr.codeDirs) if (under(a, lc(d))) return `Stopbar code (${d})`
424
448
  return null
425
449
  }
@@ -427,6 +451,94 @@ export function protectedPath(abs , root , pr )
427
451
  const SEG = (name ) => new RegExp(String.raw`(^|[^a-z0-9_.\-])${name.replace(/\./g, '\\.')}([^a-z0-9_\-]|$)`, 'i')
428
452
  const DOT_GIT = SEG('.git')
429
453
  const AGENT_DIRS = [[SEG('.claude'), '.claude'], [SEG('.cursor'), '.cursor'], [SEG('.codex'), '.codex'], [SEG('.gemini'), '.gemini'], [SEG('.agents'), '.agents']]
454
+ const HOOK_MANAGERS = [[SEG('.husky'), '.husky'], [SEG('.lefthook'), '.lefthook'],
455
+ [/(^|[^a-z0-9_.\-])\.?lefthook(?:-local)?\.ya?ml([^a-z0-9_\-]|$)/i, 'lefthook*.yml']]
456
+ const LEFTHOOK_FILES = ['lefthook', '.lefthook', 'lefthook-local', '.lefthook-local'].flatMap((b) => [`${b}.yml`, `${b}.yaml`])
457
+ const reEsc = (s ) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
458
+ const PATH_END = String.raw`(?=[/\s'";&|)<>]|$)`
459
+
460
+ /** The custom core.hooksPath as a relative value (`./` and trailing `/` dropped), or null when it is empty, `.`, `..`,
461
+ * `/`, absolute or above the tree. */
462
+ function relHooksPath(pr ) {
463
+ const r = norm(pr.hooksPathRaw ?? '').replace(/^(?:\.\/)+/, '').replace(/\/+$/, '')
464
+ if (!r || r === '.' || r.startsWith('../') || r === '..' || /^(?:[a-z]:)?\//i.test(r) || r.startsWith('~')) return null
465
+ return r
466
+ }
467
+ /** Regular expressions for the custom core.hooksPath in a command (lower case text): the relative value as a path from
468
+ * the working tree (at a word start or after `./`), and the absolute directory (also as Git Bash writes it, /c/...). */
469
+ function hooksPathNeedles(pr ) {
470
+ const out = []
471
+ const rel = relHooksPath(pr)
472
+ if (rel) out.push(new RegExp(String.raw`(?:^|[\s'"=(;&|<>]|\./)${reEsc(rel.toLowerCase())}${PATH_END}`))
473
+ if (pr.hooksDir) {
474
+ const abs = lc(pr.hooksDir)
475
+ for (const a of new Set([abs, abs.replace(/^([a-z]):/, '/$1')])) out.push(new RegExp(reEsc(a) + PATH_END))
476
+ }
477
+ return out
478
+ }
479
+ /** Directory names a wildcard or a `find` pattern must not reach: .git, the agent settings and hook managers, and the
480
+ * first segment of a relative custom core.hooksPath (and its last one, for find). */
481
+ function guardedNames(pr , forFind ) {
482
+ const out = [...GUARDED]
483
+ const rel = pr ? relHooksPath(pr) : null
484
+ if (rel) {
485
+ const first = rel.split('/')[0]
486
+ if (forFind || first.startsWith('.')) out.push(first)
487
+ }
488
+ if (forFind && pr?.hooksDir) out.push(norm(pr.hooksDir).replace(/\/+$/, '').split('/').pop() )
489
+ return [...new Set(out.filter(Boolean))]
490
+ }
491
+ const guardReason = (d ) => d === '.git' ? 'Stopbar state, git hooks, git config live there'
492
+ : /^\.(?:claude|cursor|codex|gemini|agents)$/.test(d) ? 'agent settings there hold the Stopbar hooks' : 'the git hooks there call Stopbar'
493
+
494
+ /** `$(pwd)`, `"$(pwd)"`, `${PWD}`, `$PWD`, `` `pwd` `` (each also in double quotes, `pwd -L|-P` too) as `.`: the current
495
+ * directory, so `rm -rf $(pwd)/.g*` reads as `rm -rf ./.g*`. For the text scans only. */
496
+ const PWD_ONE = String.raw`\$\(\s*pwd(?:\s+-[LP])?\s*\)|\$\{PWD\}|\$PWD(?!\w)|\x60\s*pwd(?:\s+-[LP])?\s*\x60`
497
+ const PWD_FORMS = new RegExp(`"(?:${PWD_ONE})"|${PWD_ONE}`, 'g')
498
+ export const normPwd = (cmd ) => cmd.replace(PWD_FORMS, '.')
499
+
500
+ // `find` with a name or path predicate and an action. `find` expands the pattern itself, so a quoted `-name '.g*'` is a
501
+ // live wildcard (unlike a quoted word for bash).
502
+ const FIND_PRED = /^-i?(?:name|path|wholename)$/i
503
+ const FIND_EXEC = /^-(?:exec|execdir|ok|okdir)$/
504
+
505
+ function findCalls(cmd ) {
506
+ const out = []
507
+ let cur = null, start = true
508
+ const ws = shellWords(cmd)
509
+ for (let i = 0; i < ws.length; i++) {
510
+ const w = ws[i]
511
+ if (w.length === 1 && ';&|()\n'.includes(w)) { cur = null; start = true; continue }
512
+ const u = unquoteShellWords(w)
513
+ if (start) {
514
+ if (/^\w+=/.test(u) || /^(?:sudo|command|exec|nice|time|xargs|env)$/i.test(u)) continue
515
+ start = false
516
+ if (/^g?find$/i.test(norm(u).split('/').pop() .replace(/\.exe$/i, ''))) { cur = {preds: [], del: false, exec: false}; out.push(cur) }
517
+ continue
518
+ }
519
+ if (!cur) continue
520
+ if (FIND_PRED.test(u) && i + 1 < ws.length) {
521
+ const pat = unquoteShellWords(ws[++i]).replace(/\\(.)/g, '$1')
522
+ const re = globSegment(pat)
523
+ if (re) cur.preds.push({path: /path|wholename/i.test(u), pat, re})
524
+ } else if (u === '-delete') cur.del = true
525
+ else if (FIND_EXEC.test(u)) cur.exec = true
526
+ }
527
+ return out
528
+ }
529
+ /** The first name a find pattern reaches (`-name` on the last segment, `-path` on the path below `.`), for the find
530
+ * calls with -exec/-execdir/-ok/-okdir (and -delete when `withDelete`). */
531
+ function findReaches(cmd , names , withDelete ) {
532
+ for (const c of findCalls(cmd)) {
533
+ if (!(c.exec || (withDelete && c.del))) continue
534
+ for (const p of c.preds) for (const n of names) {
535
+ if (!p.path && n.includes('/')) continue
536
+ const cands = p.path ? [n, `./${n}`, `./a/${n}`, `./${n}/a`, `./a/${n}/a`] : [n]
537
+ if (cands.some((x) => p.re.test(x))) return {name: n, pat: p.pat}
538
+ }
539
+ }
540
+ return null
541
+ }
430
542
  const HUMAN_ONLY = /\b(approve-tests|approve-shell)\b|\bSTOPBAR_[A-Z_]+/i
431
543
  // an admin subcommand right after the program word (`stopbar`, `stopbar.mjs`, `stopbar@1.2.0`, `.../stopbar/dist/cli.js`,
432
544
  // quoted or not): `stopbar init` is human-only, `stopbar probe init` (a prober scaffold, SKILL.md) is the agent's
@@ -510,12 +622,12 @@ export function withoutStdinHeredoc(cmd ) {
510
622
  // A wildcard that reaches .git or an agent settings directory (`rm -rf .g*`, `mv .cl* x`, `Remove-Item .g*`): blocked
511
623
  // for the commands that delete or move, and for any command when the wildcard is followed by a path inside such a
512
624
  // directory (`cp x .g*/hooks/pre-commit`). Other wildcards (`rm *.log`, a `.*` in a grep pattern) stay allowed.
513
- const GUARDED = ['.git', '.claude', '.cursor', '.codex', '.gemini', '.agents']
625
+ const GUARDED = ['.git', '.claude', '.cursor', '.codex', '.gemini', '.agents', '.husky', '.lefthook']
514
626
  const DESTRUCTIVE = /^(?:rm|rmdir|unlink|shred|mv|del|erase|rd|move|remove-item|ri|move-item|mi)$/i
515
- const INSIDE = /^(?:hooks|config|stopbar|info|refs|head|index|objects|settings[\w.-]*\.json|hooks\.json)$/i
516
- const globDir = (seg ) => (HAS_GLOB.test(seg) && /^[.?[]/.test(seg) ? GUARDED.find((d) => globSegment(seg)?.test(d)) ?? null : null)
517
- /** `t`: the command with only live wildcards left (globView for bash). */
518
- function wildcardGuardedDir(t ) {
627
+ const INSIDE = /^(?:hooks|config|stopbar|info|refs|head|index|objects|settings[\w.-]*\.json|hooks\.json|pre-commit|pre-push|_)$/i
628
+ /** `t`: the command with only live wildcards left (globView for bash). `names`: guardedNames. */
629
+ function wildcardGuardedDir(t , names = GUARDED) {
630
+ const globDir = (seg ) => (HAS_GLOB.test(seg) && /^[.?[]/.test(seg) ? names.find((d) => globSegment(seg)?.test(d)) ?? null : null)
519
631
  for (const part of norm(t).split(/[;&|\n()`]+/)) {
520
632
  const ws = part.split(/[\s<>='"]+/).filter(Boolean)
521
633
  let k = 0
@@ -579,13 +691,19 @@ export function dynamicGitSubcommand(cmd ) {
579
691
  * .git, the agent settings directories and Stopbar code stay protected in it. */
580
692
  export function protectedCommand(cmd , pr , shell = 'bash') {
581
693
  const texts = [...new Set([cmd, unsplice(cmd), unquoteShellWords(cmd)])]
694
+ const needles = hooksPathNeedles(pr)
582
695
  for (const t of texts) {
583
696
  const c = norm(t).toLowerCase()
584
697
  if (DOT_GIT.test(c)) return 'the command names a .git directory (Stopbar state, git hooks, git config live there)'
585
698
  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)`
699
+ for (const [re, d] of HOOK_MANAGERS) if (re.test(c)) return `the command names ${d} (git hook manager files there call the Stopbar git hooks)`
700
+ if (needles.some((re) => re.test(c))) return `the command names the custom core.hooksPath directory (${pr.hooksPathRaw ?? pr.hooksDir}), which holds the git hooks`
586
701
  }
587
- const g = wildcardGuardedDir(shell === 'bash' ? globView(cmd) : unquoteShellWords(cmd))
588
- if (g) return `the command has a wildcard that reaches the ${g} directory (${g === '.git' ? 'Stopbar state, git hooks, git config live there' : 'agent settings there hold the Stopbar hooks'})`
702
+ const p = normPwd(cmd)
703
+ const g = wildcardGuardedDir(shell === 'bash' ? globView(p) : unquoteShellWords(p), guardedNames(pr, false))
704
+ if (g) return `the command has a wildcard that reaches the ${g} directory (${guardReason(g)})`
705
+ const f = findReaches(p, [...guardedNames(pr, true), ...LEFTHOOK_FILES], true)
706
+ if (f) return `find ${JSON.stringify(f.pat)} with -delete, -exec, -execdir, -ok or -okdir reaches ${f.name} (${LEFTHOOK_FILES.includes(f.name) ? 'the git hook manager file calls the Stopbar git hooks' : guardReason(f.name)})`
589
707
  const dyn = dynamicGitSubcommand(cmd)
590
708
  if (dyn) return `the git subcommand comes from an expansion (${dyn}), which hides it from the commit and push gates; write the subcommand out`
591
709
  for (const t of texts) {