stopbar 1.1.2 → 1.1.3

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,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.3 (2026-11-26)
4
+
5
+ `src/kernel.ts` is unchanged (sha256 `c602fc4bcf8ffb2e...`); every kernel law holds as in 1.1.2. A `config.json` and a
6
+ `state.json` from 1.0.0–1.1.2 work without migration.
7
+
8
+ - **Security fix (`init --force` and `reset` on a dirty tree):** both start a fresh kernel on the current working tree.
9
+ Before 1.1.3, uncommitted changes of existing tests or of test config vanished with the old state, so a commit after
10
+ green gates needed no `approve-tests`. Now both commands compare the working tree with `baseRef` (else `HEAD`) by the
11
+ same rule as the hooks. When a change is suspicious, they take one kernel step `EDIT_TEST` (`suspicious: true`,
12
+ `cost: 0`), save it in `state.json` and log it in `events.jsonl` (`init:dirty-tests` / `reset:dirty-tests`, with
13
+ `req` and every kernel field, so `stopbar attest` stays consistent). The output starts a `WARN:` line with the files.
14
+ The session then starts with `testsTainted = true` at the next revision (the kernel's first revision is 1, so 2)
15
+ until a human runs `stopbar approve-tests`. On a clean tree nothing changes.
16
+ - **`stopbar upgrade [--hooks <targets>] [--force-hooks]`:** re-pins the hook runtime (`.git/stopbar/runtime`) from the
17
+ installed package and, with `--hooks`, rewrites the hook configuration. It does not touch `state.json`,
18
+ `config.json` or the snapshot indexes: revision, gates, taint and budget stay. It needs a valid `config.json` and
19
+ `state.json` (else it fails closed with the fix), validates `--hooks` before it writes, and logs `human:upgrade`
20
+ (version, runtime, kernel; no `req`, so `attest` stays consistent and lists `upgrade` in `humanActions`). The agent
21
+ cannot run it (self-protection). `stopbar doctor` now names `stopbar upgrade` in `[WARN] pinned runtime`.
22
+ - **No false taint after `checkout` / `rebase` / `cherry-pick` from `baseRef`:** with `--base-ref`, the hooks compare
23
+ the blob id of each changed test and test-config file with `baseRef` (`refEntries`, one `git ls-tree` call, only when
24
+ such a file changed). A file with the same content as in `baseRef` is not suspicious, so tests and `package.json`
25
+ taken over from a newer `main` no longer taint. A test of `baseRef` with other content, or deleted, and a test-config
26
+ file that differs from `baseRef` (also a new one) are suspicious. The file mode is ignored (Windows). The tree
27
+ revision still grows with every change (the gates must run again), and a taint is never cleared by putting a file
28
+ back (law L2.2).
29
+ - **Without `--base-ref` the rule of 1.1.2 stays:** every change of an existing test (in `HEAD`) and of test config is
30
+ suspicious, also when the file equals `HEAD`. The agent's own git commands move `HEAD` (for example
31
+ `git stash && git checkout stash@{0}` in one call), so a content match with `HEAD` is no evidence.
32
+ - `repo.ts`: `changesSinceRef(r, ref, now)` (a non-`HEAD` ref that does not resolve fails closed), `refEntries`,
33
+ `oidOf`; `changesSinceHead`, `inRef` and `inHead` stay as before.
34
+ - Tests: unit tests for the blob-id rule, for `refEntries` / `changesSinceRef` and for blocking `stopbar upgrade`;
35
+ E2E scenarios S33 (`init --force` / `reset` on a dirty tree), S34 (`stopbar upgrade`) and S35 (`checkout`,
36
+ `cherry-pick` and `rebase` with `--base-ref main`, and the `HEAD` rule). The probe model follows both changes; half
37
+ of the seeds now run with a base ref, and a new action puts a file back to its base content.
38
+
3
39
  ## 1.1.2 (2026-11-26)
4
40
 
5
41
  `src/kernel.ts` is unchanged (sha256 `c602fc4bcf8ffb2e...`); every kernel law holds as in 1.1.1. A `config.json` from
package/README.md CHANGED
@@ -42,7 +42,7 @@ current tree, block it after an unapproved test change, and block a push after a
42
42
  |---|---|---|
43
43
  | 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. |
44
44
  | 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. v1.0 has one target, `wrapper` (Stopbar itself). |
45
- | GATE | `stopbar init`, `hook`, `git-hook`, `run`, `status`, `approve-tests`, `approve-shell`, `resume`, `reset`, `doctor` | The agent hooks, the git fallback and the human commands. |
45
+ | 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. |
46
46
  | ATTEST | `stopbar attest` | A deterministic attestation of the session: HEAD, tree, gates, human actions and the sha256 of the event log. |
47
47
 
48
48
  ## Set up in 3 steps
@@ -100,6 +100,7 @@ EOF
100
100
  | Command | Who | What it does |
101
101
  |---|---|---|
102
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. |
103
+ | `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`. |
103
104
  | `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). |
104
105
  | `stopbar git-hook pre-commit\|pre-push` | git | The git fallback gate. Exit 1 aborts the commit or push. |
105
106
  | `stopbar run build\|test` | human, agent, CI | Runs the configured gate command and records its real exit status. |
@@ -107,7 +108,7 @@ EOF
107
108
  | `stopbar approve-tests [--rev N]` | human | You reviewed the changed tests or test config up to revision N (default: the current one). |
108
109
  | `stopbar approve-shell` | human | Allows **one** risky or outbound call after a secret read. |
109
110
  | `stopbar resume --extra N` | human | Lifts a halt (retry limit or budget) and adds N to the budget. |
110
- | `stopbar reset` | human | Fresh kernel state. Config and event log stay. Also repairs a damaged `state.json`. |
111
+ | `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. |
111
112
  | `stopbar doctor [--json]` | human | Environment, config, state, hooks and a dry run. Exit 1 on a problem. |
112
113
  | `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. |
113
114
  | `stopbar probe [--target wrapper] [--runs 200] [--seed 1] [--jobs N] [--work dir] [--out dir]` | human, CI | PROBE: stateful probing against the proven kernel. A failure is shrunk to a minimal JSON reproduction. Needs the full package (gdp-wired). |
@@ -154,7 +155,11 @@ profile by editing the lists: no code change is necessary.
154
155
  file (default: `HEAD`). On a multi-commit feature branch, `--base-ref main` (or a base commit SHA) lets the agent
155
156
  refine new test files it added on that branch across commits without triggering `testsTainted`, while existing tests
156
157
  from `baseRef` and all test-config files remain protected. A configured non-`HEAD` ref that cannot be resolved fails
157
- closed.
158
+ closed. With `baseRef`, Stopbar compares the content (blob id) of a changed test or test-config file with `baseRef`:
159
+ after `git checkout -b x main`, `git rebase main` or `git cherry-pick`, files that equal `main` do not taint, but the
160
+ tree revision grows and the gates must run again. Any other change of a test from `baseRef` or of test config taints,
161
+ and putting the file back later does not clear the taint. Without `baseRef`, every change of an existing test or of
162
+ test config taints, also when the file equals `HEAD`, because the agent's own git commands can move `HEAD`.
158
163
  - **`safeTools`** (optional) lists glob patterns of tool names that are local and never outbound. The default
159
164
  (`DEFAULT_SAFE_TOOLS`) is `["mcp__ccd_turn__*", "mcp__ccd_session_mgmt__*"]`: the task-list and turn-summary tools of
160
165
  Claude Desktop and its tools for messages between local sessions. It only exempts tools from the outbound gate
@@ -227,12 +232,12 @@ latency. An earlier prototype that loaded the prover in every hook measured p50
227
232
 
228
233
  | Platform | Node | git | Unit | E2E | `stopbar probe` | `stopbar prove` | `stopbar doctor` |
229
234
  |---|---|---|---|---|---|---|---|
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 |
235
+ | Windows 11, Git for Windows | 24.19.0 | 2.56.0 | 40/40 | 365/365 | 202/202 sequences | proven, 10/10 mutants | OK |
236
+ | Linux, Debian 13 (container, no network) | 24.21.0 | 2.47.3 | 40/40 | 365/365 | 202/202 sequences | proven, 10/10 mutants | OK |
232
237
 
233
238
  The E2E suite runs every adapter (Cursor, Codex CLI, Gemini CLI, Antigravity CLI) and the git fallback with real
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.
239
+ git commits and pushes. The probe runs the same 200 seeds plus 2 regressions on both platforms, with the same 5020 steps
240
+ and 7152 hook calls (half of the seeds with a base ref). `stopbar doctor` passes on a fresh repository with all six `--hooks` targets.
236
241
  `npm run verify:lean` passes in the Lean 4.34.0 container: `lake build` exit 0, 0 errors, 0 `sorry`.
237
242
 
238
243
  ## License
package/SECURITY.md CHANGED
@@ -53,9 +53,24 @@ There is no proof for them.
53
53
  - **Results from the event type.** Claude Code sends `PostToolUseFailure` for a failed command and `PostToolUse`
54
54
  without an exit code for a successful one. A user interrupt (`is_interrupt`) does not count as a failure.
55
55
  - **Tree changes from content.** A private git index in `.git/stopbar/` gives a content snapshot after every edit and
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`.
56
+ every shell call: edits, deletions and new files that are not ignored. Without `config.baseRef`, a change to a test
57
+ file that exists in `HEAD`, or to any test-config file, is suspicious. With `config.baseRef`, the wrapper compares the
58
+ blob id of each changed test and test-config file with `baseRef` (one `git ls-tree`, only when such a file changed):
59
+ a test of `baseRef` with other content or deleted, and a test-config file whose content differs from `baseRef` (also
60
+ a new one), are suspicious; a file equal to `baseRef` is not. The file mode is ignored. A configured non-`HEAD`
61
+ `baseRef` that cannot be resolved fails closed. Every change still raises the tree revision, so the gates must run
62
+ again. The path patterns are in `config.json`.
63
+ - **Fresh state on a dirty tree.** `stopbar init --force` and `stopbar reset` classify the uncommitted changes against
64
+ `baseRef` (else `HEAD`) by the same rule. A suspicious change is one kernel step `EDIT_TEST` (`suspicious: true`,
65
+ `cost: 0`), logged with every kernel field: the session starts tainted until `approve-tests`.
66
+ - **`git cherry-pick` and `git rebase`.** They are ordinary shell commands: Stopbar does not block them before the gates
67
+ and does not treat them as a commit, although they write commits. They change the working tree, so the next hook
68
+ counts a new revision and the build and full test gates must pass again. With `--base-ref`, the blob-id comparison
69
+ finds every change of an existing test of `baseRef` and of test config against `baseRef`, whichever command made it;
70
+ tests taken over unchanged from `baseRef` do not taint. Without `--base-ref`, every change of an existing test taints.
71
+ `git commit`, `git push` (agent hooks and git hooks) and a green `stopbar attest` still need green gates and no
72
+ unapproved taint. A commit that `cherry-pick` or `rebase` writes itself does not pass through the commit gate (see
73
+ "Other commit paths" below); a later `git push` does.
59
74
  - **Commits.** `git commit` and `git push` must be one command without operators, also with git global options before
60
75
  the subcommand. The one allowed form of command substitution is the quoted heredoc that Claude Code writes:
61
76
  `git commit ... -m "$(cat <<'EOF'` … `EOF` `)"`. The delimiter is in single quotes, so bash expands nothing in the
@@ -102,10 +117,14 @@ that tries to defeat it:
102
117
  4. **Weak new tests and mutable `baseRef`.** A new test file is not suspicious. A mock of the system under test or an
103
118
  empty assertion in a new file passes. Hard-coded answers in production code are an ordinary code edit. When
104
119
  `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.
120
+ can move that branch ref; pass a commit hash (`--base-ref <sha>`) if you want an immutable baseline. Since 1.1.3 this
121
+ matters more: a test that equals `baseRef` does not taint, so an agent that moves the `baseRef` branch to a commit
122
+ with weakened tests (for example `git branch -f main <commit>` or `git update-ref`) and then checks it out is not
123
+ flagged. Stopbar does not watch the ref itself.
106
124
  5. **Ignored files.** Files ignored by `.gitignore` are invisible to the snapshot (for example patches in
107
125
  `node_modules`). A change to `.gitignore` itself is suspicious.
108
- 6. **Other commit paths.** Git aliases, `git commit-tree`, `gh pr create` and similar are not detected. The Stop hook
126
+ 6. **Other commit paths.** Git aliases, `git commit-tree`, `git stash`, `git cherry-pick`, `git rebase`, `gh pr create`
127
+ and similar are not detected as commits. The Stop hook
109
128
  catches uncommitted work only. With `config.stopGate: "warn"` it does not even block that: the turn ends with a
110
129
  `WARN (stopbar)` answer and a `stop:warn` entry in `events.jsonl`. This mode takes no kernel step at Stop and does not
111
130
  weaken the commit gate: `git commit` and `git push` in the agent hooks and in the git hooks are judged by the kernel
@@ -138,6 +157,16 @@ For a hostile-agent threat model, run the agent in a container or VM: no network
138
157
  read-write, `.git/stopbar` and `.claude` mounted read-only or owned by another user, and the human commands run outside
139
158
  the sandbox. Stopbar's kernel then gives the proven decisions and the sandbox gives the boundary.
140
159
 
160
+ ## Known limits of 1.1.3
161
+
162
+ - The blob-id comparison trusts `baseRef`: see point 4 of section 3 (a mutable branch name can be moved by the agent).
163
+ Use a commit SHA as `--base-ref` when the agent must not be able to move the baseline.
164
+ - `init --force` and `reset` count all suspicious uncommitted changes as one kernel step. A test file that changed in
165
+ a branch commit against `baseRef` counts too, even if a human approved it in an earlier session: after `reset` such
166
+ a branch starts tainted until `approve-tests`.
167
+ - `stopbar upgrade` re-pins the runtime from the package that runs the command. It does not check that the package is
168
+ newer, and it does not change `config.json`; new defaults (for example `safeTools`) are only named as a hint.
169
+
141
170
  ## Known limits of 1.1.2
142
171
 
143
172
  - `stopGate: "warn"`: in Cursor, Codex CLI, Gemini CLI and Antigravity CLI the WARN text is not shown to the agent,
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.1.2",
2
+ "version": "1.1.3",
3
3
  "kernelSourceSha256": "c602fc4bcf8ffb2e312bf838986e6d4b006af6d0e6c7447c8c61d5888adc5ef8",
4
4
  "machineSha256": "b397085e0cb13e2e50aa655c54de0744d08f2ebf500bf32af8ff3e8a11ba7321",
5
5
  "files": 26
package/dist/classify.js CHANGED
@@ -163,15 +163,28 @@ export function classifyBash(cmd , cfg
163
163
  return {kind: 'shell', risky: isRiskyShell(c), partialTests: looksLikeTests(c), secret: secretInCommand(c, cfg.paths, exists)}
164
164
  }
165
165
 
166
- /** Kind of a tree change from a list of (status, path) and a test for "the path exists in HEAD". */
167
- export function classifyTreeChange(changes , inHead , paths ) {
166
+ /** Kind of a tree change from a list of (status, path) and a test for "the path exists in the reference tree"
167
+ * (baseRef, else HEAD).
168
+ * `sameAsRef` (given with an explicit baseRef): "the file now has the same blob id as in baseRef, or is absent from
169
+ * both". Then a test-config file is suspicious only when its content differs from baseRef, and an existing test only
170
+ * when it differs from baseRef (changed or deleted), so tests taken over unchanged from baseRef (checkout, rebase,
171
+ * cherry-pick) do not taint. Without `sameAsRef` (no baseRef: HEAD, which the agent's own git commands can move),
172
+ * every change of test config and of an existing test is suspicious. */
173
+ export function classifyTreeChange(changes , inHead , paths , sameAsRef ) {
168
174
  let anyTest = false, suspicious = false
169
175
  const why = []
170
176
  for (const {status, path} of changes) {
171
- if (isTestConfigPath(path, paths)) { anyTest = true; suspicious = true; why.push(`config ${status} ${path}`); continue }
177
+ if (isTestConfigPath(path, paths)) {
178
+ anyTest = true
179
+ if (sameAsRef?.(path)) why.push(`config ${status} ${path} (same as base ref)`)
180
+ else { suspicious = true; why.push(`config ${status} ${path}`) }
181
+ continue
182
+ }
172
183
  if (isTestPath(path, paths)) {
173
184
  anyTest = true
174
- if (inHead(path)) { suspicious = true; why.push(`existing test ${status} ${path}`) } else why.push(`new test ${status} ${path}`)
185
+ if (!inHead(path)) why.push(`new test ${status} ${path}`)
186
+ else if (sameAsRef?.(path)) why.push(`existing test ${status} ${path} (same as base ref)`)
187
+ else { suspicious = true; why.push(`existing test ${status} ${path}`) }
175
188
  }
176
189
  }
177
190
  return {op: anyTest ? 'EDIT_TEST' : 'EDIT_CODE' , suspicious, why}
@@ -208,7 +221,7 @@ const SEG = (name ) => new RegExp(String.raw`(^|[^a-z0-9_.\-])${name.repl
208
221
  const DOT_GIT = SEG('.git')
209
222
  const AGENT_DIRS = [[SEG('.claude'), '.claude'], [SEG('.cursor'), '.cursor'], [SEG('.codex'), '.codex'], [SEG('.gemini'), '.gemini'], [SEG('.agents'), '.agents']]
210
223
  const HUMAN_ONLY = /\b(approve-tests|approve-shell)\b|\bSTOPBAR_[A-Z_]+/i
211
- const STOPBAR_ADMIN = /stopbar[^\n]*\b(init|resume|reset|doctor\s+--fix)\b/i
224
+ const STOPBAR_ADMIN = /stopbar[^\n]*\b(init|resume|reset|upgrade|doctor\s+--fix)\b/i
212
225
 
213
226
  /** Command text inspected by self-protection. For a plain single-command `git commit` (chain-free, no substitution),
214
227
  * strips the commit message (safe heredoc body or quoted `-m` / `--message` string) because git treats it as data. */
package/dist/cli.js CHANGED
@@ -14,6 +14,9 @@ const HELP = `stopbar ${VERSION}: proven gates for coding agents (Claude Code ho
14
14
  [--cli "<cmd>"] [--stop-gate block|warn]
15
15
  --cli: command that starts Stopbar in hints (default: npx --no-install stopbar)
16
16
  --stop-gate warn: Stop only warns; git commit and git push stay blocked until the gates pass
17
+ stopbar upgrade [--hooks <targets>] [--force-hooks] [--repo <dir>]
18
+ a human re-pins the hook runtime from this package (and rewrites hooks with --hooks);
19
+ state, gates, taint and budget stay as they are
17
20
  stopbar hook [--adapter auto|claude|cursor|codex|gemini|antigravity]
18
21
  the agent hook (JSON on stdin); auto detects the client from the payload
19
22
  stopbar git-hook pre-commit|pre-push fallback gate run by git (installed by init --hooks git)
@@ -30,7 +33,7 @@ Four pillars:
30
33
  (npm run verify:lean checks the Lean export with lake build in Docker)
31
34
  PROBE stopbar probe [--target wrapper] [--runs 200] [--seed 1] [--jobs N] [--work dir] [--out dir]
32
35
  stateful probing of the hooks against the proven kernel on real git repositories
33
- GATE init, hook, status, approve-tests, approve-shell, resume, reset, doctor (above)
36
+ GATE init, upgrade, hook, status, approve-tests, approve-shell, resume, reset, doctor (above)
34
37
  ATTEST stopbar attest [--format json|md] deterministic attestation: HEAD, tree, gates, human actions, log sha256
35
38
  All commands take --repo <dir> (default: the current directory). 'verify' is an alias of 'prove'.`
36
39
 
@@ -64,6 +67,7 @@ async function main() {
64
67
  if (cmd === '--version' || cmd === 'version') return {code: 0, msg: VERSION}
65
68
  const o = opts(argv.slice(1))
66
69
  if (cmd === 'init') return (await import('./commands.js')).init(o)
70
+ if (cmd === 'upgrade') return (await import('./commands.js')).upgrade(o)
67
71
  if (['status', 'approve-tests', 'approve-shell', 'resume', 'reset'].includes(cmd)) return (await import('./commands.js')).human(cmd, o)
68
72
  if (cmd === 'doctor') return (await import('./doctor.js')).doctor({repo: o.get('repo'), json: o.has('json')})
69
73
  if (cmd === 'prove' || cmd === 'verify') {
package/dist/commands.js CHANGED
@@ -1,25 +1,51 @@
1
1
  // Built from src/commands.ts by scripts/build.ts. Do not edit.
2
- // Human commands: init, status, approve-tests, approve-shell, resume, reset. The agent cannot run them
2
+ // Human commands: init, upgrade, status, approve-tests, approve-shell, resume, reset. The agent cannot run them
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
6
  import {hasChain, protectedCommand} from './classify.js'
7
7
  import {CLAUDE_POST_MATCHER, claudeHooks, hookCommand, installHooks, parseTargets} from './integrations.js'
8
- import {cliOf, ConfigError, makeConfig, PROFILES} from './config.js'
8
+ import {cliOf, ConfigError, DEFAULT_SAFE_TOOLS, makeConfig, PROFILES} from './config.js'
9
9
  import {decode, initKernel, kstep, MACHINE, } from './engine.js'
10
- import {whyBlocked} from './hook.js'
10
+ import {classifyChanges, whyBlocked} from './hook.js'
11
11
  import {CODE_PARTS, PKG_ROOT} from './pkg.js'
12
- import {findRepo, forgetSnapshots, hasRefTree, markCounted, snapshot} from './repo.js'
12
+ import {changesSinceRef, 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
 
16
16
 
17
- export function fresh(r , c ) {
17
+ function freshWithSnap(r , c ) {
18
18
  forgetSnapshots(r)
19
19
  const params = {maxRetries: c.maxRetries, cap: c.cap}
20
20
  const snap = snapshot(r)
21
21
  markCounted(r)
22
- return {version: 2, kernel: initKernel(params), snapshot: snap.id, params}
22
+ return {s: {version: 2, kernel: initKernel(params), snapshot: snap.id, params}, snap}
23
+ }
24
+ export const fresh = (r , c ) => freshWithSnap(r, c).s
25
+
26
+ /** `init --force` and `reset` start a fresh kernel on the current working tree. Uncommitted changes of existing tests or
27
+ * of test config (against baseRef, else HEAD) must not vanish with the old state: they are counted as one suspicious
28
+ * EDIT_TEST step of the kernel (testsTainted until `stopbar approve-tests`), written to state.json and to events.jsonl
29
+ * with every kernel field, so `stopbar attest` stays consistent.
30
+ * `dirtyTests` only reads (it fails closed on a broken baseRef before anything is written); `countDirtyTests` runs under
31
+ * the lock, after the human:init / human:reset entry. */
32
+
33
+ function dirtyTests(r , cfg , snap ) {
34
+ const ref = cfg.baseRef ?? 'HEAD'
35
+ const cls = classifyChanges(r, cfg, changesSinceRef(r, ref, snap.entries), snap.entries)
36
+ return {ref, suspicious: cls.suspicious, files: cls.why.filter((w) => !w.startsWith('new test') && !w.endsWith('(same as base ref)'))}
37
+ }
38
+ function countDirtyTests(r , s , d , source ) {
39
+ if (!d.suspicious) return []
40
+ const req = {op: 'EDIT_TEST', suspicious: true, cost: 0}
41
+ s.kernel = kstep(s.params, s.kernel, req)
42
+ writeState(r, s)
43
+ const a = decode(s.kernel)
44
+ appendEvent(r, {source, req, decision: a.decision, halted: a.halted, testsTainted: a.testsTainted,
45
+ secretTainted: a.secretTainted, shellToken: a.shellToken, treeRev: a.treeRev, buildOkRev: a.buildOkRev, testsOkRev: a.testsOkRev,
46
+ spent: a.spent, capNow: a.capNow, testFails: a.testFails, buildFails: a.buildFails, commitExecuted: a.commitExecuted, ref: d.ref, changes: d.files})
47
+ return [`WARN: uncommitted test or test-config changes against ${d.ref}: ${d.files.join(', ')}`,
48
+ ` the session starts with testsTainted = true (revision ${a.treeRev}); a commit stays blocked until a human reviews them and runs \`stopbar approve-tests\``]
23
49
  }
24
50
 
25
51
  function humanStep(r , s , req , source ) {
@@ -78,17 +104,44 @@ export function init(o ) {
78
104
  const targets = hooksOpt === undefined ? [] : parseTargets(hooksOpt) // validated before anything is written
79
105
  mkdirSync(repo.stateDir, {recursive: true})
80
106
  return withLock(repo, () => {
107
+ const {s, snap} = freshWithSnap(repo, cfg)
108
+ const dirty = dirtyTests(repo, cfg, snap)
81
109
  writeConfig(repo, cfg)
82
- writeState(repo, fresh(repo, cfg))
110
+ writeState(repo, s)
83
111
  const runtime = pin ? pinRuntime(repo) : PKG_ROOT
84
112
  const command = hookCommand(runtime)
85
113
  appendEvent(repo, {source: 'human:init', cfg, runtime, version: VERSION, kernel: MACHINE})
114
+ const warn = countDirtyTests(repo, s, dirty, 'init:dirty-tests')
86
115
  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
116
  ` stop gate: ${cfg.stopGate ?? 'block'}; gate hints use: ${cliOf(cfg)} run build|test`,
88
117
  ` hooks run: ${command}`]
89
118
  if (targets.length) for (const l of installHooks(repo, targets, runtime, o.has('force-hooks'))) lines.push(` hooks written: ${l}`)
90
119
  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))
91
- lines.push('Next: restart the agent in this repository and run `stopbar doctor`.')
120
+ lines.push(...warn, 'Next: restart the agent in this repository and run `stopbar doctor`.')
121
+ return {code: 0, msg: lines.join('\n')}
122
+ })
123
+ }
124
+
125
+ /** `stopbar upgrade`: re-pins the hook runtime (<git-dir>/stopbar/runtime) from this package and, with --hooks, rewrites
126
+ * the hook configuration. state.json, config.json and the snapshots stay as they are (revision, gates, taint, budget), so
127
+ * active sessions keep their green gates. The log entry has no `req`: it is no kernel step and attest stays consistent. */
128
+ export function upgrade(o ) {
129
+ const repo = findRepo(o.get('repo') ?? process.cwd())
130
+ const hooksOpt = o.get('hooks')
131
+ if (o.has('hooks') && hooksOpt === undefined) return {code: 1, msg: '--hooks needs a value'}
132
+ const targets = hooksOpt === undefined ? [] : parseTargets(hooksOpt) // validated before anything is written
133
+ return withLock(repo, () => {
134
+ const cfg = readConfig(repo)
135
+ readState(repo) // a missing or damaged state fails closed here, with the fix
136
+ const had = existsSync(join(repo.stateDir, 'runtime'))
137
+ const runtime = pinRuntime(repo)
138
+ appendEvent(repo, {source: 'human:upgrade', version: VERSION, runtime, kernel: MACHINE, ...(targets.length ? {hooks: targets} : {})})
139
+ const lines = [`Stopbar ${VERSION}: hook runtime re-pinned in ${runtime}`, ' state.json, config.json and the snapshots are unchanged (revision, gates, taint, budget)']
140
+ if (targets.length) for (const l of installHooks(repo, targets, runtime, o.has('force-hooks'))) lines.push(` hooks written: ${l}`)
141
+ else if (!had) lines.push(` there was no pinned runtime (init --no-pin): the hooks still run what they ran; add --hooks <targets> to point them at ${hookCommand(runtime)}`)
142
+ const missing = DEFAULT_SAFE_TOOLS.filter((t) => !(cfg.safeTools ?? DEFAULT_SAFE_TOOLS).includes(t))
143
+ if (missing.length) lines.push(` hint: config.safeTools lacks the default ${missing.join(', ')}; a human adds them to config.json (stopbar doctor shows it)`)
144
+ lines.push('Next: run `stopbar doctor`.')
92
145
  return {code: 0, msg: lines.join('\n')}
93
146
  })
94
147
  }
@@ -129,9 +182,12 @@ export function human(cmd , o ) {
129
182
  const cfg = readConfig(repo)
130
183
  return withLock(repo, () => {
131
184
  if (cmd === 'reset') {
132
- writeState(repo, fresh(repo, cfg))
185
+ const {s, snap} = freshWithSnap(repo, cfg)
186
+ const dirty = dirtyTests(repo, cfg, snap)
187
+ writeState(repo, s)
133
188
  appendEvent(repo, {source: 'human:reset'})
134
- return {code: 0, msg: 'Stopbar state reset: run the build and the full test suite again before a commit'}
189
+ const warn = countDirtyTests(repo, s, dirty, 'reset:dirty-tests')
190
+ return {code: 0, msg: ['Stopbar state reset: run the build and the full test suite again before a commit', ...warn].join('\n')}
135
191
  }
136
192
  const s = readState(repo)
137
193
  if (cmd === 'status') {
package/dist/doctor.js CHANGED
@@ -176,7 +176,7 @@ export async function doctor(o )
176
176
  const rt = join(repo.stateDir, 'runtime', 'dist', 'kernel.gen.js')
177
177
  if (existsSync(rt)) {
178
178
  const same = existsSync(join(PKG_ROOT, 'dist', 'kernel.gen.js')) && sha(rt) === sha(join(PKG_ROOT, 'dist', 'kernel.gen.js'))
179
- add(same ? 'OK' : 'WARN', 'pinned runtime', `${join(repo.stateDir, 'runtime')}${same ? ' (same kernel as this package)' : ' differs from this package: a human runs `stopbar init --force ...` to re-pin'}`)
179
+ add(same ? 'OK' : 'WARN', 'pinned runtime', `${join(repo.stateDir, 'runtime')}${same ? ' (same kernel as this package)' : ' differs from this package: a human runs `stopbar upgrade` to re-pin (state and gates are kept)'}`)
180
180
  } else if (cfgOk) add('WARN', 'pinned runtime', 'none: hooks run an unpinned copy (init --no-pin)')
181
181
  const others = checkOtherClients(repo, add)
182
182
  const claudeHas = ['settings.json', 'settings.local.json'].some((n) => { const h = hooksIn(join(repo .root, '.claude', n)); return h !== null && Object.keys(stopbarCommands(h)).length > 0 })
package/dist/hook.js CHANGED
@@ -7,7 +7,7 @@ import * as K from './classify.js'
7
7
  import {cliOf, DEFAULT_SAFE_TOOLS} from './config.js'
8
8
  import {matchAny} from './glob.js'
9
9
  import {decode, kstep, } from './engine.js'
10
- import {changesSinceHead, countedEntries, diffEntries, differsFromHead, FailClosed, findRepo, gitCalls, inRef, markCounted, snapshot} from './repo.js'
10
+ import {changesSinceHead, countedEntries, diffEntries, differsFromHead, FailClosed, findRepo, gitCalls, markCounted, oidOf, refEntries, snapshot} from './repo.js'
11
11
  import {appendEvent, readConfig, readState, withLock, writeState} from './store.js'
12
12
  import {codeDirs} from './pkg.js'
13
13
 
@@ -42,6 +42,18 @@ export function whyBlocked(v , cfg
42
42
  return r.join('; ') || 'kernel decision'
43
43
  }
44
44
 
45
+ /** Classifies changed paths against the reference tree (baseRef, else HEAD). One git process, and only when a test or
46
+ * (with baseRef) a test-config file changed: a code-only change costs no git process here. With baseRef, a test or
47
+ * test-config file whose blob id equals baseRef's is not suspicious (taken over from baseRef by checkout, rebase or
48
+ * cherry-pick, or put back to it). Shared by the hooks and by `init --force` / `reset` on a dirty tree. */
49
+ export function classifyChanges(repo , cfg , changes , now ) {
50
+ const ref = cfg.baseRef ?? 'HEAD'
51
+ const watched = changes.map((c) => c.path).filter((p) => K.isTestConfigPath(p, cfg.paths) ? !!cfg.baseRef : K.isTestPath(p, cfg.paths))
52
+ const inRef = refEntries(repo.root, ref, watched)
53
+ const same = cfg.baseRef ? (p ) => oidOf(now.get(p)) === oidOf(inRef.get(p)) : undefined
54
+ return K.classifyTreeChange(changes, (p) => inRef.has(p), cfg.paths, same)
55
+ }
56
+
45
57
  /** Counts a working-tree change the kernel has not seen yet. */
46
58
  function syncTree(ctx , cost , source ) {
47
59
  const {repo, s, cfg} = ctx
@@ -56,9 +68,7 @@ function syncTree(ctx , cost , source ) {
56
68
  changes = changesSinceHead(repo, snap.entries)
57
69
  appendEvent(repo, {source: `${source}:fallback-diff`, note: 'counted snapshot copy missing; diff against HEAD'})
58
70
  }
59
- const testPaths = changes.map((c) => c.path).filter((p) => K.isTestPath(p, cfg.paths) && !K.isTestConfigPath(p, cfg.paths))
60
- const existing = testPaths.length ? inRef(repo.root, cfg.baseRef ?? 'HEAD', testPaths) : new Set ()
61
- const cls = K.classifyTreeChange(changes, (p) => existing.has(p), cfg.paths)
71
+ const cls = classifyChanges(repo, cfg, changes, snap.entries)
62
72
  const {before, after} = step(ctx, {op: cls.op, suspicious: cls.suspicious, cost}, `${source}:tree ${cls.why.join(', ') || `${changes.length} file(s)`}`)
63
73
  // not executed (halted or over budget): the change stays pending and is counted later
64
74
  if (after.treeRev > before.treeRev) { s.snapshot = snap.id; markCounted(repo); ctx.dirty = true }
@@ -18,6 +18,7 @@ import {runHook} from '../hook.js'
18
18
 
19
19
 
20
20
 
21
+
21
22
 
22
23
 
23
24
 
@@ -36,7 +37,9 @@ import {runHook} from '../hook.js'
36
37
 
37
38
 
38
39
 
39
-
40
+ // baseRef: init --base-ref on a branch at the base commit that never moves (HEAD moves with every commit); saved runs
41
+ // without the field run without a base ref, as before 1.1.3
42
+
40
43
 
41
44
  function rng(seed ) { let x = (seed * 2654435761) >>> 0 || 7; return () => { x ^= x << 13; x >>>= 0; x ^= x >>> 17; x ^= x << 5; x >>>= 0; return x / 2 ** 32 } }
42
45
 
@@ -56,6 +59,7 @@ function genRun(seed ) {
56
59
  [6, () => ({t: 'edit', tool: pick(['Write', 'Edit'] ), file: pick([...TESTS, `tests/n${Math.floor(r() * 3)}.test.mjs`, CONFIG]), content: content()})],
57
60
  [4, () => ({t: 'shellEdit', file: anyFile(), content: content()})],
58
61
  [2, () => ({t: 'shellDelete', file: anyFile()})],
62
+ [3, () => ({t: 'restore', file: r() < 0.7 ? pick([...TESTS, CONFIG]) : anyFile()})],
59
63
  [2, () => ({t: 'humanEdit', file: anyFile(), content: content()})],
60
64
  [10, () => ({t: 'build', outcome: pick(['pass', 'pass', 'pass', 'fail', 'interrupt', 'interrupted', 'bgPre', 'bgPost'] )})],
61
65
  [10, () => ({t: 'fulltest', outcome: pick(['pass', 'pass', 'pass', 'fail', 'fail', 'interrupt', 'interrupted', 'bgPre', 'bgPost'] )})],
@@ -92,7 +96,8 @@ function genRun(seed ) {
92
96
  let x = r() * total
93
97
  for (const [w, f] of W) { if ((x -= w) < 0) { actions.push(f()); break } }
94
98
  }
95
- return {seed, params: {maxRetries: 1 + Math.floor(r() * 3), cap: 10 + Math.floor(r() * 60), cost: Math.floor(r() * 3)}, actions: actions.slice(0, 30)}
99
+ // baseRef from the seed's parity, not from r(): the action sequence of a seed stays what it was before 1.1.3
100
+ return {seed, params: {maxRetries: 1 + Math.floor(r() * 3), cap: 10 + Math.floor(r() * 60), cost: Math.floor(r() * 3), baseRef: seed % 2 === 1}, actions: actions.slice(0, 30)}
96
101
  }
97
102
 
98
103
  // ---------------------------------------------------------------- execution against the real wrapper + the model
@@ -101,7 +106,7 @@ async function execute(run , dir ) {
101
106
  // the model needs the prover package (gdp-wired); the hooks under test never load it
102
107
  const {kernel} = await import('../kernel.js')
103
108
  const R = kernel('none'), IT = R.interpreter()
104
- const {maxRetries, cap, cost} = run.params
109
+ const {maxRetries, cap, cost} = run.params, useBase = run.params.baseRef === true
105
110
  const P = R.encodeParams({maxRetries, cap})
106
111
 
107
112
  rmSync(dir, {recursive: true, force: true, maxRetries: 5})
@@ -114,10 +119,14 @@ async function execute(run , dir ) {
114
119
  writeFileSync(join(dir, '.gitignore'), '.env\nsecrets/\n'); work.set('.gitignore', '.env\nsecrets/\n')
115
120
  writeFileSync(join(dir, '.env'), 'X=1\n')
116
121
  g('init', '-q'); g('config', 'core.autocrlf', 'false'); g('add', '-A'); g('commit', '-qm', 'base')
122
+ g('branch', 'probe-base') // the base commit; the base ref of runs with params.baseRef
117
123
  const opts = (o ) => ({get: (k ) => o[k], has: (k ) => k in o, int: (k , d ) => (k in o ? Number(o[k]) : d)})
118
- const ini = C.init(opts({repo: dir, build: 'node build.mjs', test: 'node --test', 'max-retries': String(maxRetries), cap: String(cap), cost: String(cost), 'no-pin': ''}))
124
+ const ini = C.init(opts({repo: dir, build: 'node build.mjs', test: 'node --test', 'max-retries': String(maxRetries), cap: String(cap), cost: String(cost), 'no-pin': '', ...(useBase ? {'base-ref': 'probe-base'} : {})}))
119
125
  if (ini.code !== 0) throw new Error(`init failed: ${ini.msg}`)
120
126
 
127
+ const cov = {}
128
+ const inc = (k ) => { cov[k] = (cov[k] ?? 0) + 1 }
129
+
121
130
  // ---- model
122
131
  let st = IT.init(P)
123
132
  let modelSteps = 0
@@ -130,6 +139,11 @@ async function execute(run , dir ) {
130
139
  }
131
140
  const same = (a , b ) => a.size === b.size && [...a].every(([k, v]) => b.get(k) === v)
132
141
  const isTest = (f ) => f.startsWith('tests/')
142
+ const isCfg = (f ) => f === CONFIG || f === '.gitignore'
143
+ const baseTree = new Map(work) // the tree of the base ref (it never moves in a run)
144
+ // with a base ref: suspicious = test config whose content differs from the base ref, or a test of the base ref whose
145
+ // content differs from it (changed or deleted); a file equal to the base ref is not (checkout, rebase, cherry-pick)
146
+ const differsFromRef = (f , ref ) => (isCfg(f) || (isTest(f) && ref.has(f))) && work.get(f) !== ref.get(f)
133
147
  const mSync = (c ) => {
134
148
  if (same(work, counted)) return null
135
149
  const base = countedCopy ? counted : head
@@ -138,7 +152,8 @@ async function execute(run , dir ) {
138
152
  // the counted copy was lost and the tree equals HEAD: the wrapper still sees a new snapshot id with no changes
139
153
  }
140
154
  const anyTest = changed.some((f) => isTest(f) || f === CONFIG || f === '.gitignore')
141
- const suspicious = changed.some((f) => f === CONFIG || f === '.gitignore' || (isTest(f) && head.has(f)))
155
+ const suspicious = useBase ? changed.some((f) => differsFromRef(f, baseTree)) : changed.some((f) => isCfg(f) || (isTest(f) && head.has(f)))
156
+ if (useBase && changed.some((f) => (isCfg(f) || (isTest(f) && baseTree.has(f))) && !differsFromRef(f, baseTree))) inc('sameAsBaseRef')
142
157
  const before = view().treeRev
143
158
  const after = kstep({op: anyTest ? 'EDIT_TEST' : 'EDIT_CODE', suspicious, cost: c})
144
159
  if (after.treeRev > before) { counted = new Map(work); countedCopy = true }
@@ -154,8 +169,6 @@ async function execute(run , dir ) {
154
169
  const loggedSteps = () => readFileSync(join(sd, 'events.jsonl'), 'utf8').split('\n').filter((l) => { try { return !!JSON.parse(l).req } catch { return false } }).length
155
170
  const initSteps = loggedSteps()
156
171
 
157
- const cov = {}
158
- const inc = (k ) => { cov[k] = (cov[k] ?? 0) + 1 }
159
172
  for (let i = 0; i < run.actions.length; i++) {
160
173
  const a = run.actions[i]
161
174
  const v0 = view()
@@ -186,6 +199,19 @@ async function execute(run , dir ) {
186
199
  gotCode = hook('PostToolUse', 'Bash', {command}, okResp)
187
200
  break
188
201
  }
202
+ case 'restore': {
203
+ const command = `git checkout -q probe-base -- ${a.file}`
204
+ expCode = expectPre()
205
+ if (!halted()) { const v = kstep({op: 'SHELL', risky: false, cost}); if (v.decision === 'PAUSE') expCode = 2 }
206
+ gotCode = hook('PreToolUse', 'Bash', {command})
207
+ if (gotCode !== 0 || expCode !== 0) break
208
+ const was = baseTree.get(a.file)
209
+ if (was !== undefined) put(a.file, was)
210
+ else { rmSync(join(dir, a.file), {force: true}); work.delete(a.file) }
211
+ expCode = postCode(mSync(0))
212
+ gotCode = hook('PostToolUse', 'Bash', {command}, okResp)
213
+ break
214
+ }
189
215
  case 'humanEdit': put(a.file, a.content); break
190
216
  case 'build': case 'fulltest': {
191
217
  const command = a.t === 'build' ? 'node build.mjs' : 'node --test'
@@ -289,6 +315,9 @@ async function execute(run , dir ) {
289
315
  if (gotCode !== 2) break
290
316
  if (readFileSync(join(sd, 'events.jsonl'), 'utf8') !== logBefore) { gotCode = -1; break } // fail closed writes nothing
291
317
  st = IT.init(P); counted = new Map(work); countedCopy = true
318
+ // reset on a dirty tree: test or test-config changes against the base ref (else HEAD) keep the session tainted
319
+ const ref = useBase ? baseTree : head
320
+ if ([...new Set([...ref.keys(), ...work.keys()])].some((f) => differsFromRef(f, ref))) { kstep({op: 'EDIT_TEST', suspicious: true, cost: 0}); inc('resetDirtyTests') }
292
321
  expCode = 0; gotCode = C.human('reset', opts({repo: dir})).code
293
322
  break
294
323
  }
package/dist/repo.js CHANGED
@@ -143,19 +143,45 @@ export function diffEntries(a , b )
143
143
  return out.sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : 0))
144
144
  }
145
145
 
146
- /** Fallback diff when the counted copy is gone: the current snapshot against HEAD (one git process). */
147
- export function changesSinceHead(r , now ) {
146
+ const refFailed = (ref ) => new FailClosed(`baseRef ${JSON.stringify(ref)} could not be resolved in git`,
147
+ 'a human restores the ref or runs `stopbar init --force ... --base-ref <ref>`')
148
+
149
+ /** `git ls-tree -r` of `ref` as entries (path -> "<mode> <oid>", leading zeros of the mode dropped as in the index).
150
+ * `paths` limits the listing (literal pathspecs); null lists the whole tree. One git process.
151
+ * A ref that does not resolve: HEAD (no commit yet) = empty tree; any other ref fails closed. */
152
+ function lsTree(root , ref , paths ) {
153
+ const out = new Map()
154
+ let raw
148
155
  try {
149
- const out = git(r.root, ['-c', 'core.quotepath=false', 'ls-tree', '-r', '-z', '--full-tree', 'HEAD'])
150
- const head = new Map()
151
- for (const rec of out.split('\0')) {
152
- const m = /^(\d+) \w+ ([0-9a-f]+)\t(.*)$/s.exec(rec)
153
- if (m) head.set(m[3], `${m[1].replace(/^0+/, '')} ${m[2]}`)
154
- }
155
- return diffEntries(head, now)
156
- } catch { return diffEntries(new Map(), now) }
156
+ raw = git(root, ['--literal-pathspecs', '-c', 'core.quotepath=false', 'ls-tree', '-r', '-z', '--full-tree', ref, ...(paths ? ['--', ...paths] : [])])
157
+ } catch {
158
+ if (ref === 'HEAD') return out
159
+ throw refFailed(ref)
160
+ }
161
+ for (const rec of raw.split('\0')) {
162
+ const m = /^(\d+) \w+ ([0-9a-f]+)\t(.*)$/s.exec(rec)
163
+ if (m) out.set(m[3], `${m[1].replace(/^0+/, '')} ${m[2]}`)
164
+ }
165
+ return out
157
166
  }
158
167
 
168
+ /** The entries of `paths` in `ref` (path -> "<mode> <oid>"; a path missing from the map is not in `ref`).
169
+ * One git process, called only when test files or test config changed. Non-HEAD ref that does not resolve: FailClosed. */
170
+ export function refEntries(root , ref , paths ) {
171
+ return paths.length ? lsTree(root, ref, paths) : new Map()
172
+ }
173
+
174
+ /** The blob id of an entry "<mode> <oid>" (the mode is ignored: on Windows the file mode is not reliable). */
175
+ export const oidOf = (v ) => v?.split(' ')[1]
176
+
177
+ /** The current snapshot against `ref` (one git process). Non-HEAD ref that does not resolve: FailClosed. */
178
+ export function changesSinceRef(r , ref , now ) {
179
+ return diffEntries(lsTree(r.root, ref, null), now)
180
+ }
181
+
182
+ /** Fallback diff when the counted copy is gone: the current snapshot against HEAD (one git process). */
183
+ export const changesSinceHead = (r , now ) => changesSinceRef(r, 'HEAD', now)
184
+
159
185
  /** Does the current private index differ from HEAD? (one git process; no HEAD = differs unless empty) */
160
186
  export function differsFromHead(r , now ) {
161
187
  try {
@@ -181,7 +207,7 @@ export function inRef(root , ref , paths ) {
181
207
  return new Set(out.split('\0').filter(Boolean))
182
208
  } catch {
183
209
  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>`')
210
+ throw refFailed(ref)
185
211
  }
186
212
  }
187
213
 
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.2'
9
+ export const VERSION = '1.1.3'
10
10
 
11
11
 
12
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stopbar",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
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",