stopbar 1.1.0 → 1.1.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,60 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.2 (2026-11-26)
4
+
5
+ `src/kernel.ts` is unchanged (sha256 `c602fc4bcf8ffb2e...`); every kernel law holds as in 1.1.1. A `config.json` from
6
+ 1.0.0–1.1.1 with two different gate commands works without migration.
7
+
8
+ - **`buildCmd` and `fullTestCmd` must differ.** The classifier matches `buildCmd` first, so with two equal commands
9
+ (after trimming) every run was recorded as a build and the full test gate could never pass. `validateConfig` now
10
+ refuses such a config with a `ConfigError` that says how to fix it; `stopbar init` exits 1 before it writes a file;
11
+ for an existing `config.json` with equal commands the hooks fail closed and `stopbar doctor` reports
12
+ `[FAIL] config.json` with the fix.
13
+ - **Claude Desktop session tools are local.** `DEFAULT_SAFE_TOOLS` is now `["mcp__ccd_turn__*",
14
+ "mcp__ccd_session_mgmt__*"]`, so a message to another local session after a secret read no longer causes a false
15
+ `PAUSE`. Other MCP tools stay outbound. An existing `config.json` keeps its own `safeTools`: add
16
+ `"mcp__ccd_session_mgmt__*"` or run `stopbar init --force ...`; `stopbar doctor` shows a `[WARN] safeTools` while a
17
+ default entry is missing.
18
+ - **`stopbar init --cli "<cmd>"` (`config.cliCmd`).** The hints in the commit refusal, in the block of a background gate
19
+ command (`PreToolUse` and `PostToolUse`) and in the note for a gate run without an exit status (Codex CLI) name
20
+ `<cliCmd> run build|test`. Without `--cli` they name `npx --no-install stopbar run build|test`, which never downloads
21
+ the package from the npm registry (1.1.1 said `npx stopbar`). `cliCmd` must be one command without shell operators
22
+ and must not name `.git` or an agent-settings directory; with `--no-pin`, `init` also refuses a `cliCmd` that points
23
+ at the hook runtime. `<cliCmd> run test` passes the hooks; `<cliCmd> approve-tests`, `approve-shell`, `resume`,
24
+ `reset` and `init` stay blocked.
25
+ - **`stopbar init --stop-gate block|warn` (`config.stopGate`, default `block`).** `warn` changes only the `Stop` hook:
26
+ with uncommitted changes that are not verified (no green build or full tests at the current revision, tainted tests,
27
+ or a halted session) it answers exit 0 with `WARN (stopbar): ...` and logs a `stop:warn` entry (reason, revisions,
28
+ taint, halt) in `events.jsonl`, without a kernel step. `git commit` and `git push` in the agent hooks and in the git
29
+ hooks stay gated by the kernel. All five adapters render this answer without blocking the turn. `status` (text and
30
+ `--json`), `doctor` and `attest` (`config.stopGate` in JSON, a `Stop gate` row in Markdown when `warn`) show the mode.
31
+ - Tests: unit tests for the new config rules and for the non-blocking Stop answer in every adapter; E2E scenarios S31
32
+ (equal gate commands, session tools, `--cli` with a pinned runtime) and S32 (`--stop-gate warn` with the agent hooks,
33
+ the git hooks and every adapter).
34
+
35
+ ## 1.1.1 (2026-11-26)
36
+
37
+ - **Security fix (background gate commands):** Claude Code fires `PostToolUse` immediately with `backgroundTaskId` when
38
+ a command runs with `run_in_background: true`, before the process finishes. Previously Stopbar treated that immediate
39
+ event as a passing gate. Now `PreToolUse` blocks `buildCmd` and `fullTestCmd` invoked with `run_in_background: true`
40
+ (guiding long-running gates to `npx stopbar run build|test`), and `PostToolUse` refuses to record any gate result that
41
+ carries `backgroundTaskId` or `run_in_background: true` (defense in depth, fail closed).
42
+ - **`stopbar run build|test` stale-tree check:** `stopbar run` captures the tree snapshot before starting the command
43
+ and discards the result if the working tree changes while it runs (for example during a background `stopbar run`), so
44
+ a gate started on an older revision never passes a newer one.
45
+ - **No secret false alarm on source code (`secrets.ts`):** `PROFILES.strict` replaces bare `secrets.*` with explicit
46
+ secret data/config extensions, and the matcher skips source-code extensions (`.ts`, `.js`, `.py`, `.go`, `.rs`, ...)
47
+ for legacy `secrets.*` patterns in existing `config.json` files. Explicit entries and data files (`secrets.json`,
48
+ `secrets.yaml`, `secrets.env`) still trigger the secret gate.
49
+ - **`--base-ref <ref>` on `stopbar init` (default `HEAD`):** marks which git ref defines an "existing" test file.
50
+ Agents on a multi-commit feature branch (e.g. `--base-ref main`) can iterate on new tests added on that branch across
51
+ commits without triggering `testsTainted`, while existing tests in `baseRef` and all test-config files remain
52
+ protected. `inRef` fails closed if a configured non-`HEAD` ref cannot be resolved; `status`, `doctor` and `attest`
53
+ report `baseRef`.
54
+ - **Plain `git commit -m` messages:** for a verified chain-free `git commit` command in Bash, self-protection strips
55
+ quoted `-m` / `--message` strings (matching the safe heredoc commit behaviour), so commit messages mentioning
56
+ `.git/stopbar`, `.claude` or `approve-tests` are not falsely blocked.
57
+
3
58
  ## 1.1.0 (2026-11-26)
4
59
 
5
60
  - Adapters for Cursor, Codex CLI, Gemini CLI and Antigravity CLI next to Claude Code. One internal event, one kernel;
package/README.md CHANGED
@@ -20,7 +20,7 @@ hook payload into one internal event and renders the decision in the client's ow
20
20
  |---|---|---|---|---|
21
21
  | 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) |
22
22
  | Cursor | `cursor`: `.cursor/hooks.json` (`failClosed: true`) | preToolUse, postToolUse, postToolUseFailure, stop (also beforeShellExecution, beforeMCPExecution, beforeReadFile, afterFileEdit, afterShellExecution) | exit 2 and `{"permission": "deny"}`; stop: `followup_message` | spec-tested (Cursor hooks reference) |
23
- | Codex CLI | `codex`: `.codex/hooks.json` | PreToolUse, PostToolUse, Stop | `hookSpecificOutput.permissionDecision: "deny"`; stop: `decision: "block"` | live-verified (Codex CLI 0.172.0): denied commit and config write, tree changes, Stop. Run the gates as `npx stopbar run build` / `npx stopbar run test`, because Codex reports no exit status to hooks. Codex loads project hooks only in a trusted folder |
23
+ | Codex CLI | `codex`: `.codex/hooks.json` | PreToolUse, PostToolUse, Stop | `hookSpecificOutput.permissionDecision: "deny"`; stop: `decision: "block"` | live-verified (Codex CLI 0.172.0): denied commit and config write, tree changes, Stop. Run the gates as `stopbar run build` / `stopbar run test` (the hint uses `--cli`, default `npx --no-install stopbar`), because Codex reports no exit status to hooks. Codex loads project hooks only in a trusted folder |
24
24
  | Gemini CLI | `gemini`: `.gemini/settings.json` | BeforeTool, AfterTool, AfterAgent | exit 2, reason on stderr; AfterAgent: `decision: "block"` | spec-tested (Gemini CLI hooks reference) |
25
25
  | Antigravity CLI | `antigravity` (alias `agy`): `.agents/hooks.json` | PreToolUse, PostToolUse, Stop | `{"decision": "deny"}`; stop: `decision: "continue"` | live-verified (Antigravity CLI 1.5.18): denied early commit and config write, build and full tests recorded, honest commit allowed, Stop |
26
26
  | Any tool, via git | `git`: `.git/hooks/pre-commit`, `.git/hooks/pre-push` | commit, push | exit 1 aborts git | tested with real git (E2E) |
@@ -33,7 +33,7 @@ client's published hook schema and the E2E suite runs it with payloads in that s
33
33
  working. An unknown or damaged payload fails closed (exit 2). The configs written by `init` pass `--adapter` explicitly.
34
34
 
35
35
  **Git fallback.** For a tool without hooks, run the gates through Stopbar so their real exit status counts:
36
- `npx stopbar run build` and `npx stopbar run test`. The git hooks then allow a commit only after both passed at the
36
+ `stopbar run build` and `stopbar run test`. The git hooks then allow a commit only after both passed at the
37
37
  current tree, block it after an unapproved test change, and block a push after a secret read without approval.
38
38
 
39
39
  ## Four pillars
@@ -76,8 +76,15 @@ Requirements: Node.js 22.18 or later, git, a git repository.
76
76
  `doctor` checks Node, git, the kernel link, `config.json`, `state.json`, the event log and the hooks of every client
77
77
  it finds, and makes a dry run of the real hook pipeline on a scratch repository.
78
78
 
79
- The agent must run the gate commands exactly as configured and alone, for example `npm test` and not
80
- `npm test | tail`. Commits must be one command. The quoted heredoc form that agents use is allowed:
79
+ The agent must run the gate commands exactly as configured, alone and in the foreground, for example `npm test` and not
80
+ `npm test | tail` or with `run_in_background`. For long-running gates (>10 min), run `stopbar run build` /
81
+ `stopbar run test` (safe to run in the background: Stopbar records the real exit status only when the process
82
+ finishes, and discards the result if the working tree changed in the meantime). The hints that Stopbar shows the agent
83
+ name this command as `npx --no-install stopbar run build|test`: `--no-install` uses an installed Stopbar and never
84
+ downloads the package from the npm registry. If Stopbar is installed elsewhere (a global install or a checkout outside
85
+ the project), set the command with `stopbar init --cli "<cmd>"`, for example
86
+ `--cli "node /opt/stopbar/bin/stopbar.mjs"`; the hints then say `node /opt/stopbar/bin/stopbar.mjs run test`. Commits must be one command. The quoted
87
+ heredoc form that agents use is allowed:
81
88
 
82
89
  ```sh
83
90
  git commit -m "$(cat <<'EOF'
@@ -92,7 +99,7 @@ EOF
92
99
 
93
100
  | Command | Who | What it does |
94
101
  |---|---|---|
95
- | `stopbar init --build "<cmd>" --test "<cmd>" [--profile p] [--max-retries 3] [--cap 500] [--cost 1] [--hooks <targets>] [--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. |
102
+ | `stopbar init --build "<cmd>" --test "<cmd>" [--profile p] [--base-ref <ref>] [--cli "<cmd>"] [--stop-gate block\|warn] [--max-retries 3] [--cap 500] [--cost 1] [--hooks <targets>] [--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. `--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. |
96
103
  | `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). |
97
104
  | `stopbar git-hook pre-commit\|pre-push` | git | The git fallback gate. Exit 1 aborts the commit or push. |
98
105
  | `stopbar run build\|test` | human, agent, CI | Runs the configured gate command and records its real exit status. |
@@ -125,10 +132,15 @@ private snapshot index and the pinned runtime. They are outside the working tree
125
132
  "testConfig": ["package.json", "pyproject.toml", ".github/workflows/**"],
126
133
  "secrets": [".env*", "*.pem", "**/secrets/**"]
127
134
  },
128
- "safeTools": ["mcp__ccd_turn__*"]
135
+ "safeTools": ["mcp__ccd_turn__*", "mcp__ccd_session_mgmt__*"]
129
136
  }
130
137
  ```
131
138
 
139
+ `buildCmd` and `fullTestCmd` must be different commands. A command equal to `buildCmd` is always recorded as a build,
140
+ so with two equal commands the full test gate could never pass. `init` refuses such a pair, and a `config.json` that has
141
+ one makes every hook fail closed and `stopbar doctor` report `[FAIL] config.json` with the fix. Use one command for
142
+ lint, types and build and one for the full test suite, for example `--build "npm run build" --test "npm test"`.
143
+
132
144
  A pattern without `/` matches the file name anywhere. `**` is a whole path segment. Matching ignores case. Change a
133
145
  profile by editing the lists: no code change is necessary.
134
146
 
@@ -138,10 +150,29 @@ profile by editing the lists: no code change is necessary.
138
150
  other pattern (`.env*`, `id_rsa*`) count always. `stopbar status` says why the secret gate is on, for example
139
151
  `secret read yes (matched *.key (server.key) in Bash at rev 3)`; `events.jsonl` keeps the pattern and the token,
140
152
  never the file content.
141
- - **`safeTools`** (optional) lists glob patterns of tool names that are local and never outbound. The default is
142
- `["mcp__ccd_turn__*"]`, the task-list and turn-summary tools of Claude Desktop. It only exempts tools from the
143
- outbound gate (WebFetch, WebSearch, MCP tools); shell commands, edits and reads are gated as before, and a halted
144
- session still blocks every tool. A damaged or empty `config.json` or `state.json` blocks every
153
+ - **`baseRef`** (optional, set via `stopbar init --base-ref <ref>`) controls which git ref defines an "existing" test
154
+ file (default: `HEAD`). On a multi-commit feature branch, `--base-ref main` (or a base commit SHA) lets the agent
155
+ refine new test files it added on that branch across commits without triggering `testsTainted`, while existing tests
156
+ from `baseRef` and all test-config files remain protected. A configured non-`HEAD` ref that cannot be resolved fails
157
+ closed.
158
+ - **`safeTools`** (optional) lists glob patterns of tool names that are local and never outbound. The default
159
+ (`DEFAULT_SAFE_TOOLS`) is `["mcp__ccd_turn__*", "mcp__ccd_session_mgmt__*"]`: the task-list and turn-summary tools of
160
+ Claude Desktop and its tools for messages between local sessions. It only exempts tools from the outbound gate
161
+ (WebFetch, WebSearch, MCP tools); shell commands, edits and reads are gated as before, and a halted session still
162
+ blocks every tool. A `config.json` written by 1.0.0–1.1.1 keeps its own list and keeps working; to stop false
163
+ `PAUSE`s on the session tools after a secret read, add `"mcp__ccd_session_mgmt__*"` to `safeTools` or write the file
164
+ again with `stopbar init --force ...`. `stopbar doctor` shows a `[WARN] safeTools` while a default entry is missing.
165
+ - **`cliCmd`** (optional, set via `stopbar init --cli "<cmd>"`) is the command that starts Stopbar in the hints shown to
166
+ the agent (`<cliCmd> run build|test`). Without it the hints say `npx --no-install stopbar`. It must be one command
167
+ without shell operators and must not name a `.git` or agent-settings directory, because the agent's shell may not run
168
+ such a command. With `--no-pin`, `init` also refuses a `--cli` that points at the hook runtime itself. `approve-tests`,
169
+ `approve-shell`, `resume`, `reset` and `init` stay blocked for the agent whatever `cliCmd` is.
170
+ - **`stopGate`** (optional, set via `stopbar init --stop-gate block|warn`, default `block`) controls only the `Stop` hook.
171
+ `block`: the agent cannot declare "done" while the tree differs from `HEAD` and the gates have not passed (exit 2).
172
+ `warn`: for long tasks with one commit at the end, the turn may end with unverified changes (for example to ask the
173
+ human a question); Stopbar logs a `stop:warn` entry in `events.jsonl` and answers `WARN (stopbar): ...` without
174
+ blocking. `git commit` and `git push` in the agent hooks and in the git hooks stay fully gated by the kernel.
175
+ `status`, `doctor` and `attest` show the mode. A damaged or empty `config.json` or `state.json` blocks every
145
176
  tool call (exit 2) with a message that says how to repair it.
146
177
 
147
178
  ## Local use
@@ -196,12 +227,12 @@ latency. An earlier prototype that loaded the prover in every hook measured p50
196
227
 
197
228
  | Platform | Node | git | Unit | E2E | `stopbar probe` | `stopbar prove` | `stopbar doctor` |
198
229
  |---|---|---|---|---|---|---|---|
199
- | Windows 11, Git for Windows | 24.19.0 | 2.56.0 | 28/28 | 237/237 | 201/201 sequences | proven, 10/10 mutants | OK |
200
- | Linux, Debian 13 (container, no network) | 24.21.0 | 2.47.3 | 28/28 | 237/237 | 201/201 sequences | proven, 10/10 mutants | OK |
230
+ | Windows 11, Git for Windows | 24.19.0 | 2.56.0 | 38/38 | 305/305 | 202/202 sequences | proven, 10/10 mutants | OK |
231
+ | Linux, Debian 13 (container, no network) | 24.21.0 | 2.47.3 | 38/38 | 305/305 | 202/202 sequences | proven, 10/10 mutants | OK |
201
232
 
202
233
  The E2E suite runs every adapter (Cursor, Codex CLI, Gemini CLI, Antigravity CLI) and the git fallback with real
203
- git commits and pushes. The probe runs the same 200 seeds plus 1 regression on both platforms, with the same 5007 steps
204
- and 7085 hook calls. `stopbar doctor` passes on a fresh repository with all six `--hooks` targets.
234
+ git commits and pushes. The probe runs the same 200 seeds plus 2 regressions on both platforms, with the same 5007 steps
235
+ and 7176 hook calls. `stopbar doctor` passes on a fresh repository with all six `--hooks` targets.
205
236
  `npm run verify:lean` passes in the Lean 4.34.0 container: `lake build` exit 0, 0 errors, 0 `sorry`.
206
237
 
207
238
  ## License
package/SECURITY.md CHANGED
@@ -43,18 +43,25 @@ The wrapper turns tool calls into kernel requests. These rules are plain code. T
43
43
  stateful prober (`stopbar probe`, real git repositories, compared with gdp-wired's interpreter) test them.
44
44
  There is no proof for them.
45
45
 
46
- - **Gates by exact command.** Only the exact configured `buildCmd` and `fullTestCmd`, alone, count as gate runs. With
47
- `;`, `&&`, `||`, `|`, a redirection or `$(...)`, the command is blocked before it runs, because operators hide its exit
48
- status. Other test runners count as partial runs: they can fail a session, but they never pass the gate.
46
+ - **Gates by exact command, never in the background.** Only the exact configured `buildCmd` and `fullTestCmd`, alone and
47
+ in the foreground, count as gate runs. With `;`, `&&`, `||`, `|`, a redirection or `$(...)`, the command is blocked
48
+ before it runs, because operators hide its exit status. With `run_in_background: true`, the command is blocked before
49
+ it runs, and any `PostToolUse` carrying `backgroundTaskId` is ignored (never recorded as a pass), because clients fire
50
+ `PostToolUse` immediately before the background process exits. For long-running gates, use `stopbar run build|test`,
51
+ which records the real exit status only when the process completes and discards the result if the working tree changed
52
+ while it was running. Other test runners count as partial runs: they can fail a session, but they never pass the gate.
49
53
  - **Results from the event type.** Claude Code sends `PostToolUseFailure` for a failed command and `PostToolUse`
50
54
  without an exit code for a successful one. A user interrupt (`is_interrupt`) does not count as a failure.
51
55
  - **Tree changes from content.** A private git index in `.git/stopbar/` gives a content snapshot after every edit and
52
- every shell call: edits, deletions and new files that are not ignored. A change to a test file that exists in HEAD,
53
- or to any test-config file, is suspicious. The path patterns are in `config.json`.
56
+ every shell call: edits, deletions and new files that are not ignored. A change to a test file that exists in
57
+ `config.baseRef` (default `HEAD`), or to any test-config file, is suspicious. A configured non-`HEAD` `baseRef` that
58
+ cannot be resolved fails closed. The path patterns are in `config.json`.
54
59
  - **Commits.** `git commit` and `git push` must be one command without operators, also with git global options before
55
60
  the subcommand. The one allowed form of command substitution is the quoted heredoc that Claude Code writes:
56
61
  `git commit ... -m "$(cat <<'EOF'` … `EOF` `)"`. The delimiter is in single quotes, so bash expands nothing in the
57
62
  message. Nothing else may be in the command. Unquoted `<<EOF`, any other `$(...)`, backticks and chains are blocked.
63
+ For a chain-free `git commit` in Bash, quoted `-m` / `--message` text and the quoted heredoc body are treated as
64
+ commit-message data by self-protection.
58
65
  - **Self-protection, before the kernel, also when halted.** Edit and Write may not touch any `.git/` directory (Stopbar
59
66
  state, git hooks, `.git/config`), the hook configuration of a supported agent (`.claude/*settings*.json`,
60
67
  `.cursor/hooks.json`, `.codex/hooks.json`, `.codex/config.toml`, `.gemini/*settings*.json`, `.gemini/**/hooks.json`,
@@ -87,14 +94,23 @@ that tries to defeat it:
87
94
  ordinary files are not seen. The exfiltration gate works on command text only. In a shell command, a bare token
88
95
  that matches only an extension pattern such as `*.key` counts only if that file exists (a field access like
89
96
  `claim.key` is not a file); a command that names a `.key` file which does not exist yet is therefore not a read.
90
- Tools listed in `config.safeTools` (default: Claude Desktop's `mcp__ccd_turn__*` UI tools) are not treated as
91
- outbound; a human who adds a glob there vouches that those tools send nothing out.
92
- 4. **Weak new tests.** A new test file is not suspicious. A mock of the system under test or an empty assertion in a
93
- new file passes. Hard-coded answers in production code are an ordinary code edit.
97
+ Tools listed in `config.safeTools` (default: Claude Desktop's `mcp__ccd_turn__*` UI tools and its
98
+ `mcp__ccd_session_mgmt__*` tools for messages between local sessions) are not treated as outbound; a human who adds
99
+ a glob there vouches that those tools send nothing out. A message to another local session can carry text the agent
100
+ has read; that session runs under its own hooks. A `config.json` from 1.0.0–1.1.1 keeps its old list until a human
101
+ adds `mcp__ccd_session_mgmt__*` or runs `stopbar init --force ...`.
102
+ 4. **Weak new tests and mutable `baseRef`.** A new test file is not suspicious. A mock of the system under test or an
103
+ empty assertion in a new file passes. Hard-coded answers in production code are an ordinary code edit. When
104
+ `config.baseRef` is a mutable local branch name (such as `main`) rather than a commit SHA, an agent with shell access
105
+ can move that branch ref; pass a commit hash (`--base-ref <sha>`) if you want an immutable baseline.
94
106
  5. **Ignored files.** Files ignored by `.gitignore` are invisible to the snapshot (for example patches in
95
107
  `node_modules`). A change to `.gitignore` itself is suspicious.
96
108
  6. **Other commit paths.** Git aliases, `git commit-tree`, `gh pr create` and similar are not detected. The Stop hook
97
- catches uncommitted work only.
109
+ catches uncommitted work only. With `config.stopGate: "warn"` it does not even block that: the turn ends with a
110
+ `WARN (stopbar)` answer and a `stop:warn` entry in `events.jsonl`. This mode takes no kernel step at Stop and does not
111
+ weaken the commit gate: `git commit` and `git push` in the agent hooks and in the git hooks are judged by the kernel
112
+ exactly as in `block` mode (laws L1, L2.1 and L3.x). What `warn` gives up is the reminder at the end of a turn, so
113
+ unverified work can stay uncommitted in the working tree.
98
114
  7. **Concurrency and humans.** A change made between two hook calls (a background job, a human edit) is counted as the
99
115
  agent's change at the next hook. With parallel tool calls a change can be attributed to the wrong call.
100
116
  8. **Agent configuration.** Settings outside the repository (user settings, managed settings, `--settings`,
@@ -122,7 +138,17 @@ For a hostile-agent threat model, run the agent in a container or VM: no network
122
138
  read-write, `.git/stopbar` and `.claude` mounted read-only or owned by another user, and the human commands run outside
123
139
  the sandbox. Stopbar's kernel then gives the proven decisions and the sandbox gives the boundary.
124
140
 
125
- ## Known limits of 1.1.0
141
+ ## Known limits of 1.1.2
142
+
143
+ - `stopGate: "warn"`: in Cursor, Codex CLI, Gemini CLI and Antigravity CLI the WARN text is not shown to the agent,
144
+ because their Stop protocols have no non-blocking message (a `followup_message`, `decision: "block"` or
145
+ `decision: "continue"` would start another turn). The entry in `events.jsonl` and `stopbar status` show it.
146
+ Claude Code gets the text on stdout with exit 0.
147
+ - `cliCmd` is checked as text: one command, no shell operators, no `.git` or agent-settings directory. Stopbar does not
148
+ check that the command really starts Stopbar; a wrong `cliCmd` gives the agent a hint that does not work, and the
149
+ gates still count only real runs. Self-protection still blocks the human-only commands through `cliCmd`.
150
+ - `buildCmd` and `fullTestCmd` that differ only in whitespace at the ends count as equal and are refused. Two different
151
+ commands that run the same script (for example `npm test` and `npm run test`) are not detected.
126
152
 
127
153
  - Lean: the check needs Docker and a one-time image build with network access. The base image is pinned by digest and
128
154
  the Lean archive by sha256, both recorded at the first build (trust on first use). The Lean export is not
@@ -12,7 +12,7 @@ const READ = new Set(['view_file', 'view_file_outline', 'view_code_item', 'view_
12
12
  const OUT = new Set(['read_url_content', 'search_web', 'open_browser_url', 'read_browser_page', 'execute_browser_javascript', 'click_browser_pixel', 'mcp_tool', 'call_mcp_tool'])
13
13
 
14
14
  function tool(name , args ) {
15
- if (name === 'run_command' || name === 'shell_exec' || name === 'send_command_input' || name === 'notebook_execution') return shell(commandText(args.CommandLine ?? args.Command ?? args.command ?? args.Input ?? ''))
15
+ if (name === 'run_command' || name === 'shell_exec' || name === 'send_command_input' || name === 'notebook_execution') return shell(commandText(args.CommandLine ?? args.Command ?? args.command ?? args.Input ?? ''), args.IsDaemon === true)
16
16
  if (EDIT.has(name)) return edit(pathsOf(args))
17
17
  if (READ.has(name)) return read(pathsOf(args))
18
18
  if (name === 'grep_search') return {tool_name: 'Grep', tool_input: {pattern: args.Query ?? args.query, path: args.SearchPath ?? args.SearchDirectory}}
@@ -7,7 +7,7 @@
7
7
  import { byName, commandText, edit, exitCodeIn, json, make, outbound, pathsOf, read, shell, } from './types.js'
8
8
 
9
9
  function tool(name , ti ) {
10
- if (name === 'Shell') return shell(commandText(ti.command))
10
+ if (name === 'Shell') return shell(commandText(ti.command), ti.is_background === true || ti.run_in_background === true)
11
11
  if (name === 'Read') return read(pathsOf(ti))
12
12
  if (['Write', 'Edit', 'Delete', 'StrReplace', 'MultiEdit', 'ApplyPatch'].includes(name)) return edit(pathsOf(ti))
13
13
  if (name === 'Grep' || name === 'Glob') return {tool_name: name, tool_input: {pattern: ti.pattern, path: ti.path}}
@@ -8,7 +8,7 @@ const UNIQUE = new Set(['BeforeTool', 'AfterTool', 'BeforeAgent', 'AfterAgent',
8
8
 
9
9
  function tool(name , ti ) {
10
10
  switch (name) {
11
- case 'run_shell_command': return shell(commandText(ti.command))
11
+ case 'run_shell_command': return shell(commandText(ti.command), ti.is_background === true || ti.run_in_background === true)
12
12
  case 'write_file': case 'replace': return edit(pathsOf(ti))
13
13
  case 'read_file': case 'read_many_files': return read([...pathsOf(ti), ...(Array.isArray(ti.include) ? ti.include : [])])
14
14
  case 'glob': return {tool_name: 'Glob', tool_input: {pattern: ti.pattern, path: ti.dir_path}}
@@ -54,7 +54,7 @@ export function patchPaths(patch ) {
54
54
  return [...patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+?)\s*$/gm)].map((m) => m[1])
55
55
  }
56
56
 
57
- export const shell = (command ) => ({tool_name: 'Bash', tool_input: {command}})
57
+ export const shell = (command , background = false) => ({tool_name: 'Bash', tool_input: background ? {command, run_in_background: true} : {command}})
58
58
  export function edit(paths ) {
59
59
  return {tool_name: 'Write', tool_input: {file_path: paths[0] ?? '', file_paths: paths}}
60
60
  }
package/dist/attest.js CHANGED
@@ -54,7 +54,8 @@ export function attestation(repoDir ) {
54
54
  stopbar: VERSION,
55
55
  kernel: MACHINE,
56
56
  repository: {head, headTree, snapshot: s.snapshot, workingTreeSnapshot: now.id, treeRevision: v.treeRev},
57
- config: {profile: cfg.profile, buildCmd: cfg.buildCmd, fullTestCmd: cfg.fullTestCmd, maxRetries: cfg.maxRetries, cap: cfg.cap, costPerCall: cfg.costPerCall},
57
+ config: {profile: cfg.profile, buildCmd: cfg.buildCmd, fullTestCmd: cfg.fullTestCmd, maxRetries: cfg.maxRetries, cap: cfg.cap, costPerCall: cfg.costPerCall, ...(cfg.baseRef ? {baseRef: cfg.baseRef} : {}),
58
+ stopGate: cfg.stopGate ?? 'block', ...(cfg.cliCmd ? {cliCmd: cfg.cliCmd} : {})},
58
59
  gates: {build: v.buildOkRev === v.treeRev, fullTests: v.testsOkRev === v.treeRev, tainted: v.testsTainted, secretRead: v.secretTainted,
59
60
  ...(v.secretTainted ? {secretReadBy: secretReason(repo)?.text ?? 'not in the event log'} : {}),
60
61
  shellApprovalHeld: v.shellToken, halted: v.halted, commitAllowedNow: commitNow, ...(commitNow ? {} : {why: v.halted ? 'session halted' : whyBlocked(v, cfg)}),
@@ -76,6 +77,8 @@ export function attestMarkdown(a ) {
76
77
  `| Field | Value |`, `|---|---|`,
77
78
  `| Stopbar | ${a.stopbar} |`, `| Kernel | ${a.kernel.name}, kernel.ts sha256 \`${a.kernel.kernelSha256}\` |`,
78
79
  `| HEAD | \`${a.repository.head ?? '(none)'}\` |`, `| HEAD tree | \`${a.repository.headTree ?? '(none)'}\` |`,
80
+ ...(a.config.baseRef ? [`| Base ref | \`${a.config.baseRef}\` |`] : []),
81
+ ...(a.config.stopGate === 'warn' ? ['| Stop gate | warn (Stop does not block a turn; git commit and git push stay gated) |'] : []),
79
82
  `| Counted snapshot | \`${a.repository.snapshot}\` (revision ${a.repository.treeRevision}) |`,
80
83
  `| Build gate | ${yn(g.build)} (\`${a.config.buildCmd}\`) |`, `| Full test gate | ${yn(g.fullTests)} (\`${a.config.fullTestCmd}\`) |`,
81
84
  `| Tests tainted | ${yn(g.tainted)} |`, `| Secret read | ${g.secretRead ? `yes: ${g.secretReadBy}` : 'no'} |`, `| Halted | ${yn(g.halted)} |`,
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.1.0",
2
+ "version": "1.1.2",
3
3
  "kernelSourceSha256": "c602fc4bcf8ffb2e312bf838986e6d4b006af6d0e6c7447c8c61d5888adc5ef8",
4
4
  "machineSha256": "b397085e0cb13e2e50aa655c54de0744d08f2ebf500bf32af8ff3e8a11ba7321",
5
5
  "files": 26
package/dist/classify.js CHANGED
@@ -8,10 +8,21 @@ const norm = (p ) => p.replace(/\\/g, '/')
8
8
 
9
9
  export const isTestPath = (p , paths ) => matchAny(norm(p), paths.tests)
10
10
  export const isTestConfigPath = (p , paths ) => matchAny(norm(p), paths.testConfig)
11
- /** Secret by file name. Absolute paths match too (a pattern may match any suffix of the path). */
11
+ // Source-code extensions that a wildcard `secrets.*` pattern must not treat as secret data files
12
+ // (e.g. `src/integration/secrets.ts` is a TypeScript module, not a secret store).
13
+ const CODE_EXT = /\.(?:[cm]?[jt]sx?|py|go|rs|java|cs|rb|php|swift|kt|scala|c|cc|cpp|h|hpp|md)$/i
14
+ const WILDCARD_EXT_SECRET = /^(?:\*\*\/)?secrets\.\*$/i
15
+
16
+ function matchesSecretGlob(p , g ) {
17
+ const n = norm(p)
18
+ if (!matchAnySuffix(n, [g])) return false
19
+ if (WILDCARD_EXT_SECRET.test(g) && CODE_EXT.test(n)) return false
20
+ return true
21
+ }
22
+
12
23
  /** The first secret pattern a path matches, or null. Absolute paths match too (a pattern may match any suffix). */
13
24
  export function secretPattern(p , paths ) {
14
- for (const g of paths.secrets) if (matchAnySuffix(norm(p), [g])) return g
25
+ for (const g of paths.secrets) if (matchesSecretGlob(p, g)) return g
15
26
  return null
16
27
  }
17
28
  export const isSecretPath = (p , paths ) => secretPattern(p, paths) !== null
@@ -118,7 +129,7 @@ const EXT_ONLY = /^\*\.[^/*?{}\[\]]+$/
118
129
  /** The first secret path named in a command (e.g. `cat .env`, `type secrets\\db.txt`), with the pattern it matched. */
119
130
  export function secretInCommand(cmd , paths , exists = () => true) {
120
131
  for (const tok of cmd.split(/[\s'"=(),;|&<>@:]+/).filter(Boolean)) {
121
- const hits = paths.secrets.filter((g) => matchAnySuffix(norm(tok), [g]))
132
+ const hits = paths.secrets.filter((g) => matchesSecretGlob(tok, g))
122
133
  if (!hits.length) continue
123
134
  const strong = hits.find((g) => !EXT_ONLY.test(g))
124
135
  if (strong) return {token: tok, pattern: strong}
@@ -199,6 +210,44 @@ const AGENT_DIRS = [[SEG('.claude'), '.claude'], [SEG('.curs
199
210
  const HUMAN_ONLY = /\b(approve-tests|approve-shell)\b|\bSTOPBAR_[A-Z_]+/i
200
211
  const STOPBAR_ADMIN = /stopbar[^\n]*\b(init|resume|reset|doctor\s+--fix)\b/i
201
212
 
213
+ /** Command text inspected by self-protection. For a plain single-command `git commit` (chain-free, no substitution),
214
+ * strips the commit message (safe heredoc body or quoted `-m` / `--message` string) because git treats it as data. */
215
+ export function commandForSelfProtect(cmd , shell = 'bash') {
216
+ if (shell !== 'bash') return cmd
217
+ const c = cmd.trim()
218
+ const hd = parseSafeHeredocCommit(c)
219
+ if (hd) return hd.prefix
220
+ if (!COMMIT_ONLY_RE.test(c) || scanPlain(c).chain) return cmd
221
+ // Quote-aware strip of top-level `-m "..."` / `-am '...'` / `--message="..."` literals.
222
+ let out = ''
223
+ for (let i = 0; i < c.length;) {
224
+ const ch = c[i]
225
+ if (ch === "'" || ch === '"') {
226
+ const start = i++
227
+ while (i < c.length && c[i] !== ch) { if (ch === '"' && c[i] === '\\') i++; i++ }
228
+ i++
229
+ out += c.slice(start, i)
230
+ continue
231
+ }
232
+ if (ch === '\\') { out += c.slice(i, i + 2); i += 2; continue }
233
+ const atWordStart = i === 0 || /\s/.test(c[i - 1])
234
+ if (atWordStart && ch === '-') {
235
+ const m = /^(?:-[a-zA-Z]*m(?:\s+|(?=["']))|--message(?:=|\s+))/.exec(c.slice(i))
236
+ if (m) {
237
+ const after = i + m[0].length
238
+ const q = c[after]
239
+ if (q === '"' || q === "'") {
240
+ let j = after + 1
241
+ while (j < c.length && c[j] !== q) { if (q === '"' && c[j] === '\\') j++; j++ }
242
+ if (j < c.length) { out += '-m ""'; i = j + 1; continue }
243
+ }
244
+ }
245
+ }
246
+ out += ch; i++
247
+ }
248
+ return out
249
+ }
250
+
202
251
  /** Shell command text. Returns the reason for a block, or null. Text matching only: see SECURITY.md. */
203
252
  export function protectedCommand(cmd , pr ) {
204
253
  const c = norm(cmd).toLowerCase()
package/dist/cli.js CHANGED
@@ -9,8 +9,11 @@ const cmd = argv[0] ?? 'help'
9
9
 
10
10
  const HELP = `stopbar ${VERSION}: proven gates for coding agents (Claude Code hooks)
11
11
 
12
- stopbar init --build "<cmd>" --test "<cmd>" [--profile default|ts|python|strict] [--max-retries 3] [--cap 500]
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]
15
+ --cli: command that starts Stopbar in hints (default: npx --no-install stopbar)
16
+ --stop-gate warn: Stop only warns; git commit and git push stay blocked until the gates pass
14
17
  stopbar hook [--adapter auto|claude|cursor|codex|gemini|antigravity]
15
18
  the agent hook (JSON on stdin); auto detects the client from the payload
16
19
  stopbar git-hook pre-commit|pre-push fallback gate run by git (installed by init --hooks git)
package/dist/commands.js CHANGED
@@ -3,13 +3,13 @@
3
3
  // through its shell (classify.ts protectedCommand) and cannot edit their files (protectedPath).
4
4
  import {cpSync, existsSync, mkdirSync, rmSync} from 'node:fs'
5
5
  import {join} from 'node:path'
6
- import {hasChain} from './classify.js'
6
+ import {hasChain, protectedCommand} from './classify.js'
7
7
  import {CLAUDE_POST_MATCHER, claudeHooks, hookCommand, installHooks, parseTargets} from './integrations.js'
8
- import { ConfigError, makeConfig, PROFILES} from './config.js'
8
+ import {cliOf, ConfigError, makeConfig, PROFILES} from './config.js'
9
9
  import {decode, initKernel, kstep, MACHINE, } from './engine.js'
10
10
  import {whyBlocked} from './hook.js'
11
- import {PKG_ROOT} from './pkg.js'
12
- import {findRepo, forgetSnapshots, markCounted, snapshot} from './repo.js'
11
+ import {CODE_PARTS, PKG_ROOT} from './pkg.js'
12
+ import {findRepo, forgetSnapshots, hasRefTree, markCounted, snapshot} from './repo.js'
13
13
  import {appendEvent, paths, readConfig, readEvents, readState, VERSION, withLock, writeConfig, writeState} from './store.js'
14
14
 
15
15
 
@@ -56,22 +56,35 @@ export function init(o ) {
56
56
  for (const [k, v] of [['--build', buildCmd], ['--test', fullTestCmd]]) {
57
57
  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`}
58
58
  }
59
- if (existsSync(paths(repo).config) && !o.has('force')) return {code: 1, msg: `already initialised (${paths(repo).config}); use --force to replace config and state`}
59
+ for (const f of ['cli', 'stop-gate']) if (o.has(f) && o.get(f) === undefined) return {code: 1, msg: `--${f} needs a value`}
60
60
  let cfg
61
61
  try {
62
- cfg = makeConfig({buildCmd, fullTestCmd, profile: o.get('profile'), maxRetries: o.int('max-retries', 3), cap: o.int('cap', 500), costPerCall: o.int('cost', 1)})
62
+ cfg = makeConfig({buildCmd, fullTestCmd, profile: o.get('profile'), maxRetries: o.int('max-retries', 3), cap: o.int('cap', 500), costPerCall: o.int('cost', 1), baseRef: o.get('base-ref'),
63
+ cliCmd: o.get('cli'), stopGate: o.get('stop-gate')})
63
64
  } catch (e) { if (e instanceof ConfigError) return {code: 1, msg: e.message}; throw e }
65
+ if (existsSync(paths(repo).config) && !o.has('force')) return {code: 1, msg: `already initialised (${paths(repo).config}); use --force to replace config and state`}
66
+ const pin = !o.has('no-pin')
67
+ if (cfg.cliCmd) {
68
+ // the hint `<cli> run test` must pass self-protection with the runtime the hooks will use
69
+ const rt = pin ? join(repo.stateDir, 'runtime') : PKG_ROOT
70
+ const protect = {gitDir: repo.gitDir, stateDir: repo.stateDir, codeDirs: CODE_PARTS.map((n) => join(rt, n))}
71
+ const why = protectedCommand(`${cfg.cliCmd} run test`, protect)
72
+ if (why) return {code: 1, msg: `--cli ${JSON.stringify(cfg.cliCmd)}: the agent could not run \`${cfg.cliCmd} run test\` (${why}); point --cli at a Stopbar install outside the hook runtime`}
73
+ }
74
+ if (cfg.baseRef && !hasRefTree(repo.root, cfg.baseRef)) {
75
+ return {code: 1, msg: `--base-ref ${JSON.stringify(cfg.baseRef)} does not resolve to a commit/tree in ${repo.root}`}
76
+ }
64
77
  const hooksOpt = o.get('hooks')
65
78
  const targets = hooksOpt === undefined ? [] : parseTargets(hooksOpt) // validated before anything is written
66
79
  mkdirSync(repo.stateDir, {recursive: true})
67
80
  return withLock(repo, () => {
68
81
  writeConfig(repo, cfg)
69
82
  writeState(repo, fresh(repo, cfg))
70
- const pin = !o.has('no-pin')
71
83
  const runtime = pin ? pinRuntime(repo) : PKG_ROOT
72
84
  const command = hookCommand(runtime)
73
85
  appendEvent(repo, {source: 'human:init', cfg, runtime, version: VERSION, kernel: MACHINE})
74
- const lines = [`Stopbar ${VERSION} initialised in ${repo.stateDir}`, ` profile ${cfg.profile}; build: ${cfg.buildCmd}; full tests: ${cfg.fullTestCmd}`,
86
+ const lines = [`Stopbar ${VERSION} initialised in ${repo.stateDir}`, ` profile ${cfg.profile}; build: ${cfg.buildCmd}; full tests: ${cfg.fullTestCmd}${cfg.baseRef ? `; base ref: ${cfg.baseRef}` : ''}`,
87
+ ` stop gate: ${cfg.stopGate ?? 'block'}; gate hints use: ${cliOf(cfg)} run build|test`,
75
88
  ` hooks run: ${command}`]
76
89
  if (targets.length) for (const l of installHooks(repo, targets, runtime, o.has('force-hooks'))) lines.push(` hooks written: ${l}`)
77
90
  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))
@@ -100,12 +113,13 @@ function statusText(repo , cfg , s ) {
100
113
  const torn = readEvents(repo).torn.length
101
114
  return [
102
115
  `Stopbar ${VERSION} repo ${repo.root}`,
103
- `revision ${v.treeRev} (tree ${s.snapshot.slice(0, 12)})`,
116
+ `revision ${v.treeRev} (tree ${s.snapshot.slice(0, 12)})${cfg.baseRef ? ` base ref ${cfg.baseRef}` : ''}`,
104
117
  `build ${ok(v.buildOkRev)} (${cfg.buildCmd})`,
105
118
  `full tests ${ok(v.testsOkRev)} (${cfg.fullTestCmd})`,
106
119
  `tainted ${yn(v.testsTainted)} secret read ${v.secretTainted ? `yes (${secretReason(repo)?.text ?? 'reason not in the event log'})` : 'no'} shell approval held ${yn(v.shellToken)}`,
107
120
  `session ${v.halted ? 'HALTED' : 'running'} spent ${v.spent}/${v.capNow} test failures ${v.testFails}/${s.params.maxRetries} build failures ${v.buildFails}/${s.params.maxRetries}`,
108
121
  `commit ${commit}`,
122
+ `stop gate ${cfg.stopGate ?? 'block'}${cfg.stopGate === 'warn' ? ' (Stop only warns; git commit and git push stay blocked until the gates pass)' : ''}`,
109
123
  ...(torn ? [`event log ${torn} torn line(s) kept as they are (see stopbar doctor)`] : []),
110
124
  ].join('\n')
111
125
  }
@@ -121,7 +135,7 @@ export function human(cmd , o ) {
121
135
  }
122
136
  const s = readState(repo)
123
137
  if (cmd === 'status') {
124
- return {code: 0, msg: o.has('json') ? JSON.stringify({version: VERSION, repo: repo.root, stateDir: repo.stateDir, config: cfg, snapshot: s.snapshot, params: s.params, kernel: decode(s.kernel),
138
+ return {code: 0, msg: o.has('json') ? JSON.stringify({version: VERSION, repo: repo.root, stateDir: repo.stateDir, config: cfg, stopGate: cfg.stopGate ?? 'block', snapshot: s.snapshot, params: s.params, kernel: decode(s.kernel),
125
139
  secretRead: decode(s.kernel).secretTainted ? secretReason(repo) : null}, null, 1) : statusText(repo, cfg, s)}
126
140
  }
127
141
  let res
package/dist/config.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Built from src/config.ts by scripts/build.ts. Do not edit.
2
2
  // config.json: gate commands, limits and path patterns. Lives in <git-dir>/stopbar/, out of the agent's reach.
3
+ import {hasChain} from './classify.js'
3
4
  import {globToRegExp} from './glob.js'
4
5
 
5
6
 
@@ -14,7 +15,17 @@ import {globToRegExp} from './glob.js'
14
15
 
15
16
 
16
17
 
18
+
19
+
20
+
21
+
22
+
23
+
17
24
 
25
+
26
+ export const STOP_GATES = ['block', 'warn']
27
+ /** Hint command when config.cliCmd is not set: uses an installed stopbar only, never downloads it from the registry. */
28
+ export const DEFAULT_CLI = 'npx --no-install stopbar'
18
29
 
19
30
  const TEST_COMMON = ['**/tests/**', '**/test/**', '**/__tests__/**']
20
31
  const TEST_JS = ['**/*.test.*', '**/*.spec.*', '**/e2e/**']
@@ -40,13 +51,13 @@ export const PROFILES = {
40
51
  strict: {
41
52
  tests: [...TEST_COMMON, ...TEST_PY],
42
53
  testConfig: [...CFG_COMMON, ...CFG_PY, 'quality.sh', '**/quality*.sh', 'scripts/quality*', 'uv.lock', 'Dockerfile*', 'docker-compose*.yml', 'hypothesis*.ini'],
43
- secrets: [...SECRETS, '*.age', 'secrets.*'],
54
+ secrets: [...SECRETS, '*.age', 'secrets.{json,yaml,yml,toml,env,ini,txt,cfg,conf,xml,properties,age,enc,key,pem,local,prod,dev,staging}'],
44
55
  },
45
56
  }
46
57
 
47
58
  export const DEFAULTS = {maxRetries: 3, cap: 500, costPerCall: 1}
48
- // local UI tools of Claude Desktop (task list and turn summary): no network, no files
49
- export const DEFAULT_SAFE_TOOLS = ['mcp__ccd_turn__*']
59
+ // local tools of Claude Desktop: task list and turn summary, and messages between local sessions (no network, no files)
60
+ export const DEFAULT_SAFE_TOOLS = ['mcp__ccd_turn__*', 'mcp__ccd_session_mgmt__*']
50
61
 
51
62
  export class ConfigError extends Error {}
52
63
 
@@ -60,6 +71,11 @@ export function validateConfig(c ) {
60
71
  for (const k of ['buildCmd', 'fullTestCmd'] ) {
61
72
  if (typeof o[k] !== 'string' || !(o[k] ).trim()) throw new ConfigError(`config.${k} must be a non-empty string`)
62
73
  }
74
+ if ((o.buildCmd ).trim() === (o.fullTestCmd ).trim()) {
75
+ throw new ConfigError(`config.buildCmd and config.fullTestCmd must be different commands (both are ${JSON.stringify((o.buildCmd ).trim())}): ` +
76
+ 'a command equal to buildCmd is always recorded as a build, so the full test gate can never pass. Use one command for lint/types/build ' +
77
+ 'and another one for the full test suite (e.g. --build "npm run build" --test "npm test")')
78
+ }
63
79
  for (const k of ['maxRetries', 'cap', 'costPerCall'] ) {
64
80
  if (!isNat(o[k])) throw new ConfigError(`config.${k} must be a safe non-negative integer`)
65
81
  }
@@ -80,17 +96,54 @@ export function validateConfig(c ) {
80
96
  try { globToRegExp(g) } catch (e) { throw new ConfigError(`config.safeTools: ${(e ).message}`) }
81
97
  }
82
98
  }
99
+ if (o.baseRef !== undefined) {
100
+ if (typeof o.baseRef !== 'string' || !isSafeRef(o.baseRef)) throw new ConfigError(`config.baseRef must be a valid git ref (no whitespace, ranges or leading '-'), got ${JSON.stringify(o.baseRef)}`)
101
+ }
102
+ if (o.cliCmd !== undefined) {
103
+ const why = typeof o.cliCmd === 'string' ? cliCmdProblem(o.cliCmd) : 'must be a string'
104
+ if (why) throw new ConfigError(`config.cliCmd ${why}, got ${JSON.stringify(o.cliCmd)}`)
105
+ }
106
+ if (o.stopGate !== undefined && !STOP_GATES.includes(o.stopGate )) {
107
+ throw new ConfigError(`config.stopGate must be ${STOP_GATES.map((g) => JSON.stringify(g)).join(' or ')}, got ${JSON.stringify(o.stopGate)}`)
108
+ }
83
109
  return o
84
110
  }
85
111
 
86
- export function makeConfig(a ) {
112
+ // A path segment such as .git or .claude. Self-protection (classify.ts protectedCommand) blocks every shell command that
113
+ // names one, so a hint `<cliCmd> run test` with such a segment could never run.
114
+ const PROTECTED_SEGMENT = /(^|[^a-z0-9_.\-])\.(git|claude|cursor|codex|gemini|agents)([^a-z0-9_\-]|$)/i
115
+
116
+ /** Why a cliCmd value cannot be used, or null. */
117
+ export function cliCmdProblem(cmd ) {
118
+ const c = cmd.trim()
119
+ if (!c) return 'must be a non-empty command'
120
+ if (hasChain(c)) return 'must be one command without shell operators (;, &&, ||, |, redirections or $(...))'
121
+ const seg = PROTECTED_SEGMENT.exec(c.replace(/\\/g, '/'))
122
+ if (seg) return `must not name a .${seg[2].toLowerCase()} directory (the agent's shell may not run commands that name it; point it at a Stopbar install outside .git and the agent settings directories)`
123
+ return null
124
+ }
125
+
126
+ /** The command that starts the Stopbar CLI in hints shown to the agent. */
127
+ export const cliOf = (cfg ) => cfg.cliCmd?.trim() || DEFAULT_CLI
128
+
129
+ export function isSafeRef(ref ) {
130
+ return ref.length > 0 && !ref.startsWith('-') && !ref.includes('..') && !ref.endsWith('.') && !ref.endsWith('/') && /^[A-Za-z0-9._/@^~-]+$/.test(ref)
131
+ }
132
+
133
+ export function makeConfig(a
134
+ ) {
87
135
  const profile = a.profile ?? 'default'
88
136
  const paths = PROFILES[profile]
89
137
  if (!paths) throw new ConfigError(`unknown profile ${JSON.stringify(profile)}; known: ${Object.keys(PROFILES).join(', ')}`)
138
+ const baseRef = a.baseRef?.trim()
139
+ const cliCmd = a.cliCmd?.trim()
90
140
  return validateConfig({
91
141
  version: 1, profile, buildCmd: a.buildCmd.trim(), fullTestCmd: a.fullTestCmd.trim(),
92
142
  maxRetries: a.maxRetries ?? DEFAULTS.maxRetries, cap: a.cap ?? DEFAULTS.cap, costPerCall: a.costPerCall ?? DEFAULTS.costPerCall,
93
143
  paths: {tests: [...paths.tests], testConfig: [...paths.testConfig], secrets: [...paths.secrets]},
94
144
  safeTools: [...DEFAULT_SAFE_TOOLS],
145
+ ...(baseRef && baseRef !== 'HEAD' ? {baseRef} : {}),
146
+ ...(cliCmd !== undefined ? {cliCmd} : {}),
147
+ ...(a.stopGate !== undefined ? {stopGate: a.stopGate} : {}),
95
148
  })
96
149
  }
package/dist/doctor.js CHANGED
@@ -6,11 +6,11 @@ import {existsSync, mkdirSync, readFileSync, rmSync, writeFileSync} from 'node:f
6
6
  import {isAbsolute, join} from 'node:path'
7
7
  import {hasChain} from './classify.js'
8
8
  import {fresh, HOOK_MATCHERS} from './commands.js'
9
- import {DEFAULT_SAFE_TOOLS, makeConfig} from './config.js'
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
12
  import {PKG_ROOT} from './pkg.js'
13
- import {FailClosed, findRepo, } from './repo.js'
13
+ import {FailClosed, findRepo, hasRefTree, } from './repo.js'
14
14
  import {paths, readConfig, readEvents, readState, VERSION, writeConfig, writeState} from './store.js'
15
15
 
16
16
 
@@ -157,7 +157,13 @@ export async function doctor(o )
157
157
  try {
158
158
  const cfg = readConfig(repo); cfgOk = true
159
159
  add('OK', 'config.json', `profile ${cfg.profile}; build \`${cfg.buildCmd}\`; full tests \`${cfg.fullTestCmd}\`; maxRetries ${cfg.maxRetries}; cap ${cfg.cap}; ` +
160
- `${cfg.paths.tests.length}/${cfg.paths.testConfig.length}/${cfg.paths.secrets.length} test/config/secret patterns; safeTools ${JSON.stringify(cfg.safeTools ?? DEFAULT_SAFE_TOOLS)}`)
160
+ `${cfg.paths.tests.length}/${cfg.paths.testConfig.length}/${cfg.paths.secrets.length} test/config/secret patterns; safeTools ${JSON.stringify(cfg.safeTools ?? DEFAULT_SAFE_TOOLS)}${cfg.baseRef ? `; baseRef ${cfg.baseRef}` : ''}; ` +
161
+ `stopGate ${cfg.stopGate ?? 'block'}; cli ${cliOf(cfg)}`)
162
+ if (cfg.stopGate === 'warn') add('WARN', 'stopGate', 'warn: Stop does not block a turn with unverified changes (logged as stop:warn); git commit and git push stay blocked until the gates pass')
163
+ const safe = cfg.safeTools ?? DEFAULT_SAFE_TOOLS
164
+ const missing = DEFAULT_SAFE_TOOLS.filter((t) => !safe.includes(t))
165
+ 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 ...\``)
166
+ 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)`)
161
167
  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`)
162
168
  try {
163
169
  const s = readState(repo), v = decode(s.kernel)
package/dist/hook.js CHANGED
@@ -4,10 +4,10 @@
4
4
  import {existsSync} from 'node:fs'
5
5
  import {resolve} from 'node:path'
6
6
  import * as K from './classify.js'
7
- import { DEFAULT_SAFE_TOOLS} from './config.js'
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, inHead, markCounted, snapshot} from './repo.js'
10
+ import {changesSinceHead, countedEntries, diffEntries, differsFromHead, FailClosed, findRepo, gitCalls, inRef, markCounted, snapshot} from './repo.js'
11
11
  import {appendEvent, readConfig, readState, withLock, writeState} from './store.js'
12
12
  import {codeDirs} from './pkg.js'
13
13
 
@@ -31,10 +31,13 @@ function step(ctx , req , source , extra
31
31
  return {before, after}
32
32
  }
33
33
 
34
- export function whyBlocked(v , cfg ) {
34
+ /** `<cli> run build|test`: the Stopbar command that runs a gate and records its real exit status (config.cliCmd). */
35
+ export const runHint = (cfg , which ) => `${cliOf(cfg)} run ${which}`
36
+
37
+ export function whyBlocked(v , cfg ) {
35
38
  const r = []
36
- if (v.buildOkRev !== v.treeRev) r.push(`no passing build at revision ${v.treeRev} (run \`${cfg.buildCmd}\` exactly, alone, or \`npx stopbar run build\`)`)
37
- if (v.testsOkRev !== v.treeRev) r.push(`no passing FULL test suite at revision ${v.treeRev} (run \`${cfg.fullTestCmd}\` exactly, alone, or \`npx stopbar run test\`)`)
39
+ if (v.buildOkRev !== v.treeRev) r.push(`no passing build at revision ${v.treeRev} (run \`${cfg.buildCmd}\` exactly, alone, or \`${runHint(cfg, 'build')}\`)`)
40
+ if (v.testsOkRev !== v.treeRev) r.push(`no passing FULL test suite at revision ${v.treeRev} (run \`${cfg.fullTestCmd}\` exactly, alone, or \`${runHint(cfg, 'test')}\`)`)
38
41
  if (v.testsTainted) r.push(`existing tests or test config changed: a human must review and run \`stopbar approve-tests --rev ${v.treeRev}\``)
39
42
  return r.join('; ') || 'kernel decision'
40
43
  }
@@ -54,8 +57,8 @@ function syncTree(ctx , cost , source ) {
54
57
  appendEvent(repo, {source: `${source}:fallback-diff`, note: 'counted snapshot copy missing; diff against HEAD'})
55
58
  }
56
59
  const testPaths = changes.map((c) => c.path).filter((p) => K.isTestPath(p, cfg.paths) && !K.isTestConfigPath(p, cfg.paths))
57
- const head = testPaths.length ? inHead(repo.root, testPaths) : new Set ()
58
- const cls = K.classifyTreeChange(changes, (p) => head.has(p), cfg.paths)
60
+ const existing = testPaths.length ? inRef(repo.root, cfg.baseRef ?? 'HEAD', testPaths) : new Set ()
61
+ const cls = K.classifyTreeChange(changes, (p) => existing.has(p), cfg.paths)
59
62
  const {before, after} = step(ctx, {op: cls.op, suspicious: cls.suspicious, cost}, `${source}:tree ${cls.why.join(', ') || `${changes.length} file(s)`}`)
60
63
  // not executed (halted or over budget): the change stays pending and is counted later
61
64
  if (after.treeRev > before.treeRev) { s.snapshot = snap.id; markCounted(repo); ctx.dirty = true }
@@ -64,6 +67,16 @@ function syncTree(ctx , cost , source ) {
64
67
 
65
68
  const block = (reason ) => ({code: 2, msg: `BLOCK (stopbar): ${reason}`})
66
69
 
70
+ function isBackgroundInput(ti ) {
71
+ return ti?.run_in_background === true || ti?.run_in_background === 'true' || ti?.background === true
72
+ }
73
+ function isBackgroundResponse(tr ) {
74
+ if (!tr || typeof tr !== 'object') return false
75
+ return (typeof tr.backgroundTaskId === 'string' && tr.backgroundTaskId.length > 0) ||
76
+ (typeof tr.background_task_id === 'string' && tr.background_task_id.length > 0) ||
77
+ tr.isAsync === true || tr.background === true
78
+ }
79
+
67
80
  // ---------------------------------------------------------------- PreToolUse
68
81
  function pre(ctx , input ) {
69
82
  const tool = String(input.tool_name ?? ''), ti = input.tool_input ?? {}
@@ -78,8 +91,7 @@ function pre(ctx , input ) {
78
91
  }
79
92
  if (SHELL_TOOLS.has(tool)) {
80
93
  const cmd = String(ti.command ?? '')
81
- const hd = tool === 'Bash' ? K.parseSafeHeredocCommit(cmd.trim()) : null
82
- const why = K.protectedCommand(hd ? hd.prefix : cmd, ctx.protect)
94
+ const why = K.protectedCommand(K.commandForSelfProtect(cmd, tool === 'PowerShell' ? 'powershell' : 'bash'), ctx.protect)
83
95
  if (why) { appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: why}); return block(`${why}. Ask the human.`) }
84
96
  }
85
97
  const v = decode(ctx.s.kernel)
@@ -111,7 +123,15 @@ function pre(ctx , input ) {
111
123
  appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: `chained gate command (${k.reason})`})
112
124
  return block(`run \`${k.gate}\` exactly as configured, alone: no ;, &&, ||, |, redirections or $(...). Chained operators hide its exit status.`)
113
125
  }
114
- if (k.kind === 'build' || k.kind === 'fulltest') return {code: 0} // the result is recorded in PostToolUse
126
+ if (k.kind === 'build' || k.kind === 'fulltest') {
127
+ if (isBackgroundInput(ti)) {
128
+ const which = k.kind === 'build' ? 'build' : 'test'
129
+ const gate = k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd
130
+ appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: `background gate command (${k.kind})`})
131
+ return block(`do not run \`${gate}\` in the background (run_in_background): the hook fires before the process finishes, so its exit status is unknown. Run \`${gate}\` in the foreground, or start \`${runHint(cfg, which)}\` in the background so Stopbar records the real exit status only when it finishes.`)
132
+ }
133
+ return {code: 0} // the result is recorded in PostToolUse
134
+ }
115
135
  if (k.kind === 'commit') {
116
136
  syncTree(ctx, 0, 'pre:commit-sync') // a change nobody reported (background job, human edit) is counted first
117
137
  const {after} = step(ctx, {op: 'COMMIT', cost}, `pre:${tool}:commit${k.heredoc ? ':heredoc' : ''}`)
@@ -157,6 +177,9 @@ function post(ctx , input , failure ) {
157
177
  const meta = input.stopbar ?? {}
158
178
  appendEvent(repo, {source: `payload:${input.hook_event_name}`, tool, ...(meta.adapter ? {adapter: meta.adapter, rawKeys: meta.rawKeys} : {inputKeys: Object.keys(input)}),
159
179
  toolResponseKeys: tr && typeof tr === 'object' ? Object.keys(tr) : typeof tr})
180
+ const bg = isBackgroundInput(ti) || isBackgroundResponse(tr)
181
+ const staleRun = typeof meta.expectedSnapshot === 'string' &&
182
+ (meta.expectedSnapshot !== ctx.s.snapshot || (typeof meta.expectedRev === 'number' && meta.expectedRev !== decode(ctx.s.kernel).treeRev))
160
183
  const code = exitCodeOf(tr)
161
184
  const flagged = input.is_error === true || tr?.is_error === true || tr?.interrupted === true
162
185
  // some clients send the same post event for success and failure: then only an explicit exit code 0 is a pass
@@ -166,10 +189,23 @@ function post(ctx , input , failure ) {
166
189
  if (failure && input.is_interrupt === true) {
167
190
  // Ctrl+C by the user: not a failed gate and not a retry; the tree is still checked below
168
191
  appendEvent(repo, {source: 'post:user-interrupt', tool, kind: k.kind})
192
+ } else if (!failure && bg && (k.kind === 'build' || k.kind === 'fulltest' || (k.kind === 'shell' && k.partialTests))) {
193
+ // a background launch fires PostToolUse before the process finishes (e.g. Claude Code backgroundTaskId): never count it
194
+ appendEvent(repo, {source: 'post:background-gate-ignored', tool, kind: k.kind === 'shell' ? 'partial-tests' : k.kind,
195
+ ...(typeof tr?.backgroundTaskId === 'string' ? {backgroundTaskId: tr.backgroundTaskId} : typeof tr?.background_task_id === 'string' ? {backgroundTaskId: tr.background_task_id} : {})})
196
+ if (k.kind !== 'shell') {
197
+ const which = k.kind === 'build' ? 'build' : 'test'
198
+ const gate = k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd
199
+ msgs.push(`BLOCK (stopbar): \`${gate}\` was started in the background, so its exit status is not known yet and the run is not recorded. Run \`${gate}\` in the foreground, or start \`${runHint(cfg, which)}\` in the background.`)
200
+ }
201
+ } else if (staleRun && (k.kind === 'build' || k.kind === 'fulltest')) {
202
+ const curRev = decode(ctx.s.kernel).treeRev
203
+ appendEvent(repo, {source: 'post:stale-gate-run', tool, kind: k.kind, expectedRev: meta.expectedRev, currentRev: curRev})
204
+ msgs.push(`NOTE (stopbar): working tree changed while \`${k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd}\` was running (started at revision ${meta.expectedRev}, now ${curRev}), so the result was not recorded. Re-run on the current tree.`)
169
205
  } else if (!failure && unknown && (k.kind === 'build' || k.kind === 'fulltest' || (k.kind === 'shell' && k.partialTests))) {
170
206
  // no exit status in the client's post event: neither a pass nor a failure is recorded (no evidence either way)
171
207
  appendEvent(repo, {source: 'post:gate-without-exit-code', tool, kind: k.kind})
172
- if (k.kind !== 'shell') msgs.push(`NOTE (stopbar): this client does not report the exit status of \`${k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd}\`, so the run is not recorded. Run \`npx stopbar run ${k.kind === 'build' ? 'build' : 'test'}\` instead: it runs the same command and records its real exit status.`)
208
+ if (k.kind !== 'shell') msgs.push(`NOTE (stopbar): this client does not report the exit status of \`${k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd}\`, so the run is not recorded. Run \`${runHint(cfg, k.kind === 'build' ? 'build' : 'test')}\` instead: it runs the same command and records its real exit status.`)
173
209
  } else if (k.kind === 'build') {
174
210
  step(ctx, {op: 'RUN_BUILD', passed, cost: cfg.costPerCall}, `post:build${note}`)
175
211
  } else if (k.kind === 'fulltest') {
@@ -189,10 +225,21 @@ function post(ctx , input , failure ) {
189
225
  }
190
226
 
191
227
  // ---------------------------------------------------------------- Stop: "I am done" = the COMMIT gate when the tree differs from HEAD
228
+ // stopGate 'warn': the turn may end with unverified changes (e.g. to ask the human a question). Only the Stop hook
229
+ // changes: no COMMIT step is taken, so `git commit` / `git push` in PreToolUse and the git hooks stay fully gated.
192
230
  function stop(ctx , input ) {
193
231
  if (input.stop_hook_active) return {code: 0}
194
232
  syncTree(ctx, 0, 'stop:sync')
195
233
  if (!differsFromHead(ctx.repo, ctx.now .entries)) return {code: 0}
234
+ if (ctx.cfg.stopGate === 'warn') {
235
+ const v = decode(ctx.s.kernel)
236
+ const commitOk = !v.halted && v.buildOkRev === v.treeRev && v.testsOkRev === v.treeRev && !v.testsTainted
237
+ if (!commitOk) {
238
+ const reason = v.halted ? 'session halted' : whyBlocked(v, ctx.cfg)
239
+ appendEvent(ctx.repo, {source: 'stop:warn', reason, treeRev: v.treeRev, buildOkRev: v.buildOkRev, testsOkRev: v.testsOkRev, testsTainted: v.testsTainted, halted: v.halted})
240
+ return {code: 0, msg: `WARN (stopbar): uncommitted changes are not yet verified (${reason}); commit remains blocked until gates pass.`}
241
+ }
242
+ }
196
243
  const {after} = step(ctx, {op: 'COMMIT'}, 'stop:declare-done')
197
244
  return after.decision === 'ALLOW' ? {code: 0}
198
245
  : {code: 2, msg: `Not done (stopbar): uncommitted changes and ${after.halted ? 'the session is halted' : whyBlocked(after, ctx.cfg)}.`}
package/dist/pkg.js CHANGED
@@ -7,7 +7,9 @@ import {fileURLToPath} from 'node:url'
7
7
  /** Package root: the directory with bin/, dist/ and package.json (dist/pkg.js -> ..). */
8
8
  export const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
9
9
 
10
+ /** Parts of a Stopbar install that self-protection guards (relative to its root). */
11
+ export const CODE_PARTS = ['bin', 'dist', 'src', 'scripts', 'node_modules', 'package.json', 'package-lock.json']
12
+
10
13
  export function codeDirs() {
11
- const names = ['bin', 'dist', 'src', 'scripts', 'node_modules', 'package.json', 'package-lock.json']
12
- return names.map((n) => join(PKG_ROOT, n)).filter((p) => existsSync(p))
14
+ return CODE_PARTS.map((n) => join(PKG_ROOT, n)).filter((p) => existsSync(p))
13
15
  }
@@ -19,8 +19,8 @@ import {runHook} from '../hook.js'
19
19
 
20
20
 
21
21
 
22
-
23
-
22
+
23
+
24
24
 
25
25
 
26
26
 
@@ -57,8 +57,8 @@ function genRun(seed ) {
57
57
  [4, () => ({t: 'shellEdit', file: anyFile(), content: content()})],
58
58
  [2, () => ({t: 'shellDelete', file: anyFile()})],
59
59
  [2, () => ({t: 'humanEdit', file: anyFile(), content: content()})],
60
- [10, () => ({t: 'build', outcome: pick(['pass', 'pass', 'pass', 'fail', 'interrupt', 'interrupted'] )})],
61
- [10, () => ({t: 'fulltest', outcome: pick(['pass', 'pass', 'pass', 'fail', 'fail', 'interrupt', 'interrupted'] )})],
60
+ [10, () => ({t: 'build', outcome: pick(['pass', 'pass', 'pass', 'fail', 'interrupt', 'interrupted', 'bgPre', 'bgPost'] )})],
61
+ [10, () => ({t: 'fulltest', outcome: pick(['pass', 'pass', 'pass', 'fail', 'fail', 'interrupt', 'interrupted', 'bgPre', 'bgPost'] )})],
62
62
  [3, () => ({t: 'partial', pass: r() < 0.6})],
63
63
  [5, () => ({t: 'shell', cmd: pick(['ls -la', 'curl --version', 'cat .env', 'git status'] )})],
64
64
  [4, () => ({t: 'read', file: pick(['.env', 'src/c0.mjs', 'secrets/key.txt', 'README.md'])})],
@@ -189,8 +189,19 @@ async function execute(run , dir ) {
189
189
  case 'humanEdit': put(a.file, a.content); break
190
190
  case 'build': case 'fulltest': {
191
191
  const command = a.t === 'build' ? 'node build.mjs' : 'node --test'
192
+ if (a.outcome === 'bgPre') {
193
+ expCode = 2
194
+ gotCode = hook('PreToolUse', 'Bash', {command, run_in_background: true})
195
+ break
196
+ }
192
197
  expCode = expectPre(); gotCode = hook('PreToolUse', 'Bash', {command})
193
198
  if (gotCode !== 0 || expCode !== 0) break
199
+ if (a.outcome === 'bgPost') {
200
+ mSync(0)
201
+ expCode = 2
202
+ gotCode = hook('PostToolUse', 'Bash', {command}, {tool_response: {...okResp.tool_response, backgroundTaskId: 'bg-task-1'}})
203
+ break
204
+ }
194
205
  const op = a.t === 'build' ? 'RUN_BUILD' : 'RUN_TESTS'
195
206
  if (a.outcome !== 'interrupt') kstep({op, passed: a.outcome === 'pass', fullSuite: a.t === 'fulltest', cost})
196
207
  expCode = postCode(mSync(0))
package/dist/repo.js CHANGED
@@ -167,11 +167,23 @@ export function differsFromHead(r , now ) {
167
167
  }
168
168
  }
169
169
 
170
- /** Which of `paths` exist in HEAD (one git process, only when test files changed). */
171
- export function inHead(root , paths ) {
170
+ /** Does `ref` resolve to a git tree? */
171
+ export function hasRefTree(root , ref ) {
172
+ try { git(root, ['rev-parse', '-q', '--verify', `${ref}^{tree}`]); return true } catch { return false }
173
+ }
174
+
175
+ /** Which of `paths` exist in `ref` (one git process, only when test files changed).
176
+ * For an explicit non-HEAD ref, fails closed if the ref cannot be resolved so existing tests are never treated as new. */
177
+ export function inRef(root , ref , paths ) {
172
178
  if (!paths.length) return new Set()
173
179
  try {
174
- const out = git(root, ['--literal-pathspecs', '-c', 'core.quotepath=false', 'ls-tree', '-r', '-z', '--name-only', '--full-tree', 'HEAD', '--', ...paths])
180
+ const out = git(root, ['--literal-pathspecs', '-c', 'core.quotepath=false', 'ls-tree', '-r', '-z', '--name-only', '--full-tree', ref, '--', ...paths])
175
181
  return new Set(out.split('\0').filter(Boolean))
176
- } catch { return new Set() }
182
+ } catch {
183
+ if (ref === 'HEAD') return new Set()
184
+ throw new FailClosed(`baseRef ${JSON.stringify(ref)} could not be resolved in git`, 'a human restores the ref or runs `stopbar init --force ... --base-ref <ref>`')
185
+ }
177
186
  }
187
+
188
+ /** Which of `paths` exist in HEAD (one git process, only when test files changed). */
189
+ export const inHead = (root , paths ) => inRef(root, 'HEAD', paths)
package/dist/run.js CHANGED
@@ -4,9 +4,10 @@
4
4
  // synced before the run; the result is recorded at that revision and a change made during the run is counted after it,
5
5
  // so a run never passes a revision it did not see.
6
6
  import {spawnSync} from 'node:child_process'
7
+ import {decode} from './engine.js'
7
8
  import {runEvent} from './hook.js'
8
9
  import {findRepo} from './repo.js'
9
- import {readConfig} from './store.js'
10
+ import {readConfig, readState} from './store.js'
10
11
 
11
12
 
12
13
 
@@ -19,10 +20,15 @@ export function runGate(which , o ) {
19
20
  const meta = (event ) => ({adapter: 'run', rawKeys: [], event})
20
21
  const before = runEvent({hook_event_name: 'PostToolUse', cwd: repo.root, tool_name: 'Bash', tool_input: {command: ':'}, tool_response: {exitCode: 0}, stopbar: meta('sync')})
21
22
  if (before.code !== 0 && /FAIL-CLOSED|halted/.test(before.msg ?? '')) return {code: 2, msg: before.msg}
23
+ const s0 = readState(repo)
24
+ const expectedSnapshot = s0.snapshot, expectedRev = decode(s0.kernel).treeRev
22
25
  const r = spawnSync(command, {cwd: repo.root, shell: true, stdio: 'inherit'})
23
26
  const exit = r.status ?? 1
24
27
  const after = runEvent({hook_event_name: exit === 0 ? 'PostToolUse' : 'PostToolUseFailure', cwd: repo.root, tool_name: 'Bash', tool_input: {command},
25
- tool_response: {exitCode: exit}, stopbar: meta(which)})
26
- const msg = `stopbar run ${which}: \`${command}\` exited ${exit}; recorded as ${exit === 0 ? 'a pass' : 'a failure'}${after.msg ? `\n${after.msg}` : ''}`
27
- return {code: exit === 0 && after.code === 0 ? 0 : exit || 2, msg}
28
+ tool_response: {exitCode: exit}, stopbar: {...meta(which), expectedSnapshot, expectedRev}})
29
+ const stale = /working tree changed while/.test(after.msg ?? '')
30
+ const msg = stale
31
+ ? `stopbar run ${which}: \`${command}\` exited ${exit}, but was not recorded\n${after.msg}`
32
+ : `stopbar run ${which}: \`${command}\` exited ${exit}; recorded as ${exit === 0 ? 'a pass' : 'a failure'}${after.msg ? `\n${after.msg}` : ''}`
33
+ return {code: !stale && exit === 0 && after.code === 0 ? 0 : exit || 2, msg}
28
34
  }
package/dist/store.js CHANGED
@@ -6,7 +6,7 @@ import { ConfigError, validateConfig} from './config.js'
6
6
  import {CODEC} from './kernel.gen.js'
7
7
  import {FailClosed, } from './repo.js'
8
8
 
9
- export const VERSION = '1.1.0'
9
+ export const VERSION = '1.1.2'
10
10
 
11
11
 
12
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stopbar",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "A formally proven execution gate for AI coding agents: hooks for Claude Code, Cursor, Codex CLI, Gemini CLI and Antigravity CLI, plus git hooks. No commit without a passing build and full test suite, no silent test weakening, no exfiltration after a secret read.",
5
5
  "author": "Paweł Olszewski <kontakt@polszewski.com>",
6
6
  "license": "MIT",