stopbar 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 (2026-11-26)
4
+
5
+ First public release.
6
+
7
+ - Four pillars in one CLI:
8
+ - PROVE: `stopbar prove` (alias `verify`) runs the inductive proof of the kernel and refutes 10 mutants with
9
+ concrete counterexample runs. `npm run verify:lean` checks the Lean export with `lake build` in a pinned
10
+ Lean 4.34.0 container without network.
11
+ - PROBE: `stopbar probe --target wrapper` runs stateful sequences of hook events, human commands and damaged files on
12
+ real git repositories and compares every step with the proven kernel.
13
+ - GATE: `init`, `hook`, `status`, `approve-tests`, `approve-shell`, `resume`, `reset`, `doctor`.
14
+ - ATTEST: `stopbar attest --format json|md` gives a deterministic attestation of the session with the sha256 of the
15
+ event log.
16
+ - The hooks run a step function generated from the proven kernel with gdp-wired `compileJs`; they never load the prover.
17
+ - Self-protection: no edits of `.git/**`, `.claude/*settings*.json` or the Stopbar code; the runtime is pinned in
18
+ `.git/stopbar/runtime`.
19
+ - The quoted heredoc commit `git commit -m "$(cat <<'EOF' ... EOF)"` is allowed; every other command substitution and
20
+ chain in a commit is blocked.
21
+ - Fail closed on a damaged `config.json` or `state.json`. A torn last line of `events.jsonl` never swallows the next
22
+ entry.
23
+ - Path patterns for tests, test config and secrets in `config.json`; profiles `default`, `ts`, `python`, `strict`.
24
+ - Hook latency: no git process in `PreToolUse`, one in `PostToolUse`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paweł Olszewski <kontakt@polszewski.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,165 @@
1
- # Temporary Holding Version
1
+ # Stopbar
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Stopbar is a set of Claude Code hooks with a formally proven decision kernel. It stops a coding agent from:
4
+
5
+ - committing without a passing build and a passing **full** test suite at the current revision of the working tree;
6
+ - weakening existing tests or test configuration without a human approval;
7
+ - running risky or outbound commands after it read a secret, unless a human allows one call;
8
+ - looping on failing builds or tests, or going past a budget of tool calls.
9
+
10
+ The decisions come from one rule, `src/kernel.ts`. gdp-wired 0.60.0 proves its laws by induction, and 10 mutants of
11
+ the rule each fall with a counterexample. The hooks run a step function generated from the same rule, without the prover.
12
+ See [SECURITY.md](SECURITY.md) for what is proven, what the wrapper enforces and what needs an OS sandbox.
13
+
14
+ ## Four pillars
15
+
16
+ | Pillar | Command | What it gives you |
17
+ |---|---|---|
18
+ | 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. |
19
+ | 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). |
20
+ | GATE | `stopbar init`, `hook`, `status`, `approve-tests`, `approve-shell`, `resume`, `reset`, `doctor` | The Claude Code hooks and the human commands. |
21
+ | ATTEST | `stopbar attest` | A deterministic attestation of the session: HEAD, tree, gates, human actions and the sha256 of the event log. |
22
+
23
+ ## Set up with Claude Code in 3 steps
24
+
25
+ Requirements: Node.js 22.18 or later, git, a git repository.
26
+
27
+ 1. **Install** Stopbar in the repository (or globally):
28
+
29
+ ```sh
30
+ npm install --save-dev stopbar
31
+ ```
32
+
33
+ 2. **Initialise** with your exact build and full-test commands, and write the hooks into the local Claude Code settings:
34
+
35
+ ```sh
36
+ npx stopbar init --build "npm run build" --test "npm test" --hooks local
37
+ ```
38
+
39
+ Profiles for the path patterns: `--profile default|ts|python|strict`. `init` copies the runtime to
40
+ `.git/stopbar/runtime/` and points the 4 hooks (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`) to it
41
+ in `.claude/settings.local.json`. Without `--hooks`, it prints the JSON to paste. A template is in
42
+ [claude-hooks.example.json](claude-hooks.example.json).
43
+
44
+ 3. **Check** the setup, then restart Claude Code in the repository:
45
+
46
+ ```sh
47
+ npx stopbar doctor
48
+ ```
49
+
50
+ `doctor` checks Node, git, the kernel link, `config.json`, `state.json`, the event log and the hooks, and makes a dry
51
+ run of the real hook pipeline on a scratch repository.
52
+
53
+ The agent must run the gate commands exactly as configured and alone, for example `npm test` and not
54
+ `npm test | tail`. Commits must be one command. The commit form that Claude Code uses is allowed:
55
+
56
+ ```sh
57
+ git commit -m "$(cat <<'EOF'
58
+ Fix the parser
59
+
60
+ Reviewed-by: Jane Doe <jane@example.invalid>
61
+ EOF
62
+ )"
63
+ ```
64
+
65
+ ## Commands
66
+
67
+ | Command | Who | What it does |
68
+ |---|---|---|
69
+ | `stopbar init --build "<cmd>" --test "<cmd>" [--profile p] [--max-retries 3] [--cap 500] [--cost 1] [--hooks local\|project] [--no-pin] [--force]` | human | Writes `config.json` and a fresh state, pins the runtime, writes or prints the hooks. |
70
+ | `stopbar hook` | Claude Code | The hook. JSON on stdin. Exit 0 allows, exit 2 blocks (the reason goes to the agent). |
71
+ | `stopbar status [--json]` | human | Revision, gates, taint, budget, and why a commit is blocked. |
72
+ | `stopbar approve-tests [--rev N]` | human | You reviewed the changed tests or test config up to revision N (default: the current one). |
73
+ | `stopbar approve-shell` | human | Allows **one** risky or outbound call after a secret read. |
74
+ | `stopbar resume --extra N` | human | Lifts a halt (retry limit or budget) and adds N to the budget. |
75
+ | `stopbar reset` | human | Fresh kernel state. Config and event log stay. Also repairs a damaged `state.json`. |
76
+ | `stopbar doctor [--json]` | human | Environment, config, state, hooks and a dry run. Exit 1 on a problem. |
77
+ | `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. |
78
+ | `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). |
79
+ | `stopbar attest [--format json\|md]` | human, CI | ATTEST: the session attestation. The same state and log give the same output. Exit 1 if the state and the log disagree, exit 2 if a file is damaged. |
80
+
81
+ All commands take `--repo <dir>`. The agent cannot run the human commands: the hooks block them.
82
+
83
+ State, configuration and the event log are in `<repo>/.git/stopbar/`: `config.json`, `state.json`, `events.jsonl`, the
84
+ private snapshot index and the pinned runtime. They are outside the working tree, so they never change the tree hash.
85
+
86
+ ## Configuration
87
+
88
+ `config.json` keeps the gate commands, the limits and three lists of glob patterns:
89
+
90
+ ```json
91
+ {
92
+ "version": 1, "profile": "default",
93
+ "buildCmd": "npm run build", "fullTestCmd": "npm test",
94
+ "maxRetries": 3, "cap": 500, "costPerCall": 1,
95
+ "paths": {
96
+ "tests": ["**/tests/**", "**/*.test.*", "**/test_*.py"],
97
+ "testConfig": ["package.json", "pyproject.toml", ".github/workflows/**"],
98
+ "secrets": [".env*", "*.pem", "**/secrets/**"]
99
+ }
100
+ }
101
+ ```
102
+
103
+ A pattern without `/` matches the file name anywhere. `**` is a whole path segment. Matching ignores case. Change a
104
+ profile by editing the lists: no code change is necessary. A damaged or empty `config.json` or `state.json` blocks every
105
+ tool call (exit 2) with a message that says how to repair it.
106
+
107
+ ## Local use
108
+
109
+ - `npm run build` builds `dist/` from `src/` with Node's own type stripping and generates `dist/kernel.gen.js` from
110
+ the kernel with gdp-wired's `compileJs`. There is no TypeScript compiler and no bundler.
111
+ - `npm test` runs the unit tests, the E2E suite (real git repositories, a separate hook process for each call) and the
112
+ stateful fuzzer (200 random sequences of 20–30 steps, compared with the proven kernel). It takes about 3 minutes.
113
+ In Claude Code, give the Bash tool enough time, for example `"env": {"BASH_DEFAULT_TIMEOUT_MS": "600000"}` in the
114
+ settings.
115
+ - `npm run prove` builds and runs `stopbar prove` (about 3 minutes). `npm run verify` is the same.
116
+ - `npm run verify:lean` exports the Lean project (`leanProject()` of gdp-wired) and runs `lake build` in the
117
+ container from `docker/lean.Dockerfile` with `--network none`. It is the release gate for changes of `src/kernel.ts`,
118
+ not part of `npm test`. Build the image once (this needs the network):
119
+ `docker build -f docker/lean.Dockerfile -t stopbar-lean:4.34.0 docker`.
120
+ - `npm run bench` measures the hook latency.
121
+ - `npm run test:e2e` or `npm run test:fuzz` runs only the E2E suite or only the stateful prober.
122
+
123
+ ## Use in CI
124
+
125
+ Prove the kernel and run the tests on every change of Stopbar itself:
126
+
127
+ ```yaml
128
+ - run: npm ci
129
+ - run: npm test
130
+ - run: npx stopbar prove --out stopbar-prove.json
131
+ ```
132
+
133
+ For headless agent runs in CI, initialise Stopbar in the job and keep the evidence:
134
+
135
+ ```yaml
136
+ - run: npx stopbar init --build "npm run build" --test "npm test" --hooks project
137
+ - run: claude -p "<task>" --setting-sources project,local --max-turns 20
138
+ - run: npx stopbar status --json > stopbar-status.json
139
+ - run: npx stopbar attest --format md > stopbar-attest.md
140
+ - run: cp .git/stopbar/events.jsonl stopbar-events.jsonl
141
+ ```
142
+
143
+ `stopbar attest` tells whether a commit is allowed at the end and lists every human action. Its sha256 of
144
+ `events.jsonl` ties the report to the log, which has one line for each kernel step and each block, with the reason.
145
+
146
+ ## Hook latency
147
+
148
+ Each hook is a separate Node process. The hooks never load the prover. `PreToolUse` makes no git call. `PostToolUse` and
149
+ a commit check make one: `git add -A` on a private index, which the hook then reads itself. `Stop` makes two. On
150
+ Windows 11 with a 330-file repository: p50 127 ms and p95 219 ms over all hook processes. An earlier prototype that
151
+ loaded the prover in every hook measured p50 981 ms and p95 1613 ms. `npm run bench` repeats the measurement.
152
+
153
+ ## Tested platforms
154
+
155
+ | Platform | Node | git | Unit | E2E | `stopbar probe` | `stopbar prove` | `stopbar doctor` |
156
+ |---|---|---|---|---|---|---|---|
157
+ | Windows 11, Git for Windows | 24.19.0 | 2.56.0 | 19/19 | 149/149 | 201/201 sequences | proven, 10/10 mutants | OK |
158
+ | Linux, Debian 13 (container, no network) | 24.21.0 | 2.47.3 | 19/19 | 149/149 | 201/201 sequences | proven, 10/10 mutants | OK |
159
+
160
+ The probe runs the same 200 seeds plus 1 regression on both platforms, with the same 5007 steps and 7085 hook calls.
161
+ `npm run verify:lean` passes in the Lean 4.34.0 container: `lake build` exit 0, 0 errors, 0 `sorry`.
162
+
163
+ ## License
164
+
165
+ MIT. Stopbar depends on [gdp-wired](https://github.com/monotykamary/gdp-wired) (MIT), pinned to 0.60.0.
package/SECURITY.md ADDED
@@ -0,0 +1,111 @@
1
+ # Security model
2
+
3
+ Stopbar is a set of Claude Code hooks with a formally proven decision kernel. This file says what is proven, what the
4
+ wrapper enforces, and what Stopbar cannot give you without an operating-system sandbox. Read the last part before you
5
+ rely on Stopbar against a hostile agent.
6
+
7
+ ## 1. What is proven
8
+
9
+ The decision rule is `src/kernel.ts`, written in the gdp-wired 0.60.0 DSL. `stopbar prove` runs an inductive proof of
10
+ all laws together with the lemmas I1–I5. The proof result is `proven: true, checked: true`: gdp-wired's proof kernel
11
+ checked the certificate. The laws hold for every sequence of requests, every budget and every retry limit:
12
+
13
+ | Law | Statement |
14
+ |---|---|
15
+ | L1 | A commit executes only after a passing build and a passing full test suite since the last tree change. |
16
+ | L2.1 | A commit executes only when every suspicious test or test-config edit is covered by a human approval of that revision or a later one. |
17
+ | L2.2 | Taint survives every action except a human test approval. A passing test run does not clear it. |
18
+ | L3.1 | "A secret was read" never resets. |
19
+ | L3.2 | A risky or outbound shell call after a secret read pauses, unless a one-time human approval is held. |
20
+ | L3.3 | The risky call that the approval allows uses it up. |
21
+ | L4.1 | In the halted state only RESUME unblocks. There is no ALLOW, no BLOCK and no commit. |
22
+ | L4.2 | Reaching the budget cap halts the session at once. |
23
+ | L4.3a, L4.3b | `maxRetries` failed test runs without a full pass, or `maxRetries` failed builds, halt the session. |
24
+ | L4.4 | In the halted state no action except RESUME changes the key state fields. |
25
+
26
+ Ten mutants of the rule (M1a–M7) each break one requirement. For each of them the prover must fail, and a concrete
27
+ counterexample run must break a law on the mutant and break no law on the original (gdp-wired `replayRefutation`).
28
+ This shows that the laws are not vacuous.
29
+
30
+ How the proof reaches the hooks: the build runs gdp-wired's `compileJs` on the proven machine and writes
31
+ `dist/kernel.gen.js`. The hooks run only that file and never load the prover. `stopbar prove`, `stopbar doctor` and the
32
+ test suite regenerate it and compare it byte for byte, check the sha256 of `src/kernel.ts`, and replay thousands of
33
+ random steps against gdp-wired's interpreter. This link is a check, not a proof: you trust gdp-wired's code generator.
34
+
35
+ The Lean gate (`npm run verify:lean`) exports the full Lean project with gdp-wired's `leanProject()` and runs
36
+ `lake build` with Lean 4.34.0 in a container without network (`docker/lean.Dockerfile`). It passes only with exit 0,
37
+ 0 errors and 0 `sorry`. It is a release gate for changes of `src/kernel.ts`, not part of `npm test`. It writes the result and the sha256 of the
38
+ checked `.lean` file to `results/lean/lean-verify.json`.
39
+
40
+ ## 2. What the wrapper enforces (tested, not proven)
41
+
42
+ The wrapper turns tool calls into kernel requests. These rules are plain code. The E2E suite, the unit tests and the
43
+ stateful prober (`stopbar probe`, real git repositories, compared with gdp-wired's interpreter) test them.
44
+ There is no proof for them.
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.
49
+ - **Results from the event type.** Claude Code sends `PostToolUseFailure` for a failed command and `PostToolUse`
50
+ without an exit code for a successful one. A user interrupt (`is_interrupt`) does not count as a failure.
51
+ - **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`.
54
+ - **Commits.** `git commit` and `git push` must be one command without operators, also with git global options before
55
+ the subcommand. The one allowed form of command substitution is the quoted heredoc that Claude Code writes:
56
+ `git commit ... -m "$(cat <<'EOF'` … `EOF` `)"`. The delimiter is in single quotes, so bash expands nothing in the
57
+ message. Nothing else may be in the command. Unquoted `<<EOF`, any other `$(...)`, backticks and chains are blocked.
58
+ - **Self-protection, before the kernel, also when halted.** Edit and Write may not touch any `.git/` directory (Stopbar
59
+ state, git hooks, `.git/config`), `.claude/*settings*.json`, or the Stopbar code that runs the hooks. A shell command
60
+ may not name a `.git` or `.claude` directory, write git config (`git config` without `--get` or `--list`), name the
61
+ Stopbar code, use a `STOPBAR_*` variable, or run a human command (`approve-tests`, `approve-shell`, `stopbar
62
+ init/resume/reset`).
63
+ - **Pinned runtime.** `stopbar init` copies the runtime to `.git/stopbar/runtime/` and points the hooks there. An agent
64
+ that edits or rebuilds a Stopbar checkout cannot change the code that judges it.
65
+ - **Fail closed.** Bad hook input, a missing or damaged `config.json` or `state.json`, a busy lock, or any internal
66
+ error gives exit 2 with a fix on stderr. Every tool call is then blocked until a human repairs the state.
67
+ - **Event log.** `events.jsonl` gets one JSON line per kernel step. If a crash left the last line torn, the next entry
68
+ starts on a new line, so it is never glued to the fragment.
69
+
70
+ ## 3. What Stopbar does not give you without an OS sandbox
71
+
72
+ An agent with a shell runs with your user's rights. The hooks see the text of a command, not what it does. Under these
73
+ conditions Stopbar is a strong guard against shortcuts and mistakes. It is **not** a security boundary against an agent
74
+ that tries to defeat it:
75
+
76
+ 1. **Indirect execution.** A script written to a normal file and then run (`node x.js`, `bash x.sh`) can do anything:
77
+ delete `.git/stopbar`, edit `.claude/settings.local.json`, run `stopbar approve-tests`. The text checks do not see
78
+ inside the script. Obfuscation (`c=cu; ${c}rl`), aliases and shell functions also pass the text checks.
79
+ 2. **Gate commands run arbitrary code.** `buildCmd` and `fullTestCmd` run the repository's code. A new test file is
80
+ trusted. It can read secrets, use the network or weaken other checks at run time.
81
+ 3. **Secrets by file name only.** Secrets in environment variables, in files with ordinary names, or found with Grep in
82
+ ordinary files are not seen. The exfiltration gate works on command text only.
83
+ 4. **Weak new tests.** A new test file is not suspicious. A mock of the system under test or an empty assertion in a
84
+ new file passes. Hard-coded answers in production code are an ordinary code edit.
85
+ 5. **Ignored files.** Files ignored by `.gitignore` are invisible to the snapshot (for example patches in
86
+ `node_modules`). A change to `.gitignore` itself is suspicious.
87
+ 6. **Other commit paths.** Git aliases, `git commit-tree`, `gh pr create` and similar are not detected. The Stop hook
88
+ catches uncommitted work only.
89
+ 7. **Concurrency and humans.** A change made between two hook calls (a background job, a human edit) is counted as the
90
+ agent's change at the next hook. With parallel tool calls a change can be attributed to the wrong call.
91
+ 8. **Claude Code configuration.** Settings outside the repository (user settings, managed settings, `--settings`,
92
+ `disableAllHooks`) can remove the hooks. The hooks cover what Claude Code sends to them.
93
+ 9. **Human approvals.** `approve-tests` and `approve-shell` are only as good as the human review behind them.
94
+
95
+ For a hostile-agent threat model, run the agent in a container or VM: no network by default, the repository mounted
96
+ read-write, `.git/stopbar` and `.claude` mounted read-only or owned by another user, and the human commands run outside
97
+ the sandbox. Stopbar's kernel then gives the proven decisions and the sandbox gives the boundary.
98
+
99
+ ## Known limits of 1.0.0
100
+
101
+ - Lean: the check needs Docker and a one-time image build with network access. The base image is pinned by digest and
102
+ the Lean archive by sha256, both recorded at the first build (trust on first use). The Lean export is not
103
+ deterministic: each export is a different proof tree, and the gate checks the one it exports.
104
+ - Platforms: the unit tests, E2E, `stopbar probe` and `stopbar prove` pass on Windows 11 with Git for Windows and on
105
+ Linux (Debian 13, Node 24, git 2.47). A live Claude Code session ran on Windows. macOS is not tested.
106
+ - Hook latency: Windows starts a process in 50–70 ms, so a hook with one git process takes about 120–200 ms in all.
107
+
108
+ ## Reporting a vulnerability
109
+
110
+ Send a private report to the maintainers before you publish it. Include the Stopbar version, `stopbar doctor --json`
111
+ and `stopbar attest` output and a minimal reproduction (the probe's JSON format in `tests/regressions/` is welcome).
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ // Entry point. Loads only the compiled dist/ (no TypeScript, no prover in hooks).
3
+ import('../dist/cli.js').catch((e) => {
4
+ process.stderr.write(`STOPBAR FAIL-CLOSED: cannot load dist/cli.js (${e && e.message}). Run: npm run build\n`)
5
+ process.exitCode = 2
6
+ })
@@ -0,0 +1,27 @@
1
+ {
2
+ "hooks": {
3
+ "PreToolUse": [
4
+ {
5
+ "matcher": "*",
6
+ "hooks": [{"type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.git/stopbar/runtime/bin/stopbar.mjs\" hook", "timeout": 30}]
7
+ }
8
+ ],
9
+ "PostToolUse": [
10
+ {
11
+ "matcher": "Edit|Write|MultiEdit|NotebookEdit|Bash|PowerShell",
12
+ "hooks": [{"type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.git/stopbar/runtime/bin/stopbar.mjs\" hook", "timeout": 60}]
13
+ }
14
+ ],
15
+ "PostToolUseFailure": [
16
+ {
17
+ "matcher": "Edit|Write|MultiEdit|NotebookEdit|Bash|PowerShell",
18
+ "hooks": [{"type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.git/stopbar/runtime/bin/stopbar.mjs\" hook", "timeout": 60}]
19
+ }
20
+ ],
21
+ "Stop": [
22
+ {
23
+ "hooks": [{"type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.git/stopbar/runtime/bin/stopbar.mjs\" hook", "timeout": 30}]
24
+ }
25
+ ]
26
+ }
27
+ }
package/dist/attest.js ADDED
@@ -0,0 +1,95 @@
1
+ // Built from src/attest.ts by scripts/build.ts. Do not edit.
2
+ // ATTEST: a deterministic attestation of the session from the current state and the event log. The same state and log
3
+ // give the same report byte for byte (no clock, no machine name). The sha256 of events.jsonl is the anchor for signing in
4
+ // a later version. Read-only for Stopbar state: it refreshes only the private snapshot index to see the working tree.
5
+ import {createHash} from 'node:crypto'
6
+ import {existsSync, readFileSync} from 'node:fs'
7
+ import {decode, initKernel, MACHINE, } from './engine.js'
8
+ import {whyBlocked} from './hook.js'
9
+ import {findRepo, git, snapshot} from './repo.js'
10
+ import {paths, readConfig, readState, VERSION, withLock} from './store.js'
11
+
12
+ const FIELDS = ['treeRev', 'buildOkRev', 'testsOkRev', 'spent', 'capNow', 'testFails', 'buildFails', 'halted', 'testsTainted', 'secretTainted', 'shellToken']
13
+
14
+ export function attestation(repoDir ) {
15
+ const repo = findRepo(repoDir)
16
+ return withLock(repo, () => {
17
+ const cfg = readConfig(repo), s = readState(repo), v = decode(s.kernel)
18
+ const f = paths(repo).events
19
+ const raw = existsSync(f) ? readFileSync(f) : Buffer.alloc(0)
20
+ const events = [], torn = []
21
+ raw.toString('utf8').split('\n').forEach((l, i) => { if (!l) return; try { events.push({line: i + 1, e: JSON.parse(l)}) } catch { torn.push(i + 1) } })
22
+ let head = null, headTree = null
23
+ try { head = git(repo.root, ['rev-parse', '-q', '--verify', 'HEAD']); headTree = git(repo.root, ['rev-parse', 'HEAD^{tree}']) } catch { /* no commit yet */ }
24
+ const now = snapshot(repo)
25
+
26
+ const steps = events.filter(({e}) => e.req && typeof e.req.op === 'string')
27
+ const human = events.filter(({e}) => typeof e.source === 'string' && e.source.startsWith('human:'))
28
+ const approvals = human.map(({line, e}) => ({line, ts: e.ts, action: e.source.slice('human:'.length),
29
+ ...(e.req?.approveRev !== undefined && e.source === 'human:approve-tests' ? {revision: e.req.approveRev} : {}),
30
+ ...(e.req?.extra !== undefined && e.source === 'human:resume' ? {extra: e.req.extra} : {}),
31
+ ...(e.decision ? {decision: e.decision} : {}), ...(e.shellToken !== undefined && e.source === 'human:approve-shell' ? {granted: e.shellToken} : {})}))
32
+ // a block is a wrapper BLOCK/PAUSE (self-protection, chained command, halted) or a kernel decision other than ALLOW on an agent action
33
+ const blocks = events.filter(({e}) => e.wrapper === 'BLOCK' || e.wrapper === 'PAUSE' || (e.req && e.decision && e.decision !== 'ALLOW' && !String(e.source).startsWith('human:'))).length
34
+ const decisions = {}
35
+ for (const {e} of steps) decisions[`${e.req.op}:${e.decision}`] = (decisions[`${e.req.op}:${e.decision}`] ?? 0) + 1
36
+ const commitsAllowed = steps.filter(({e}) => e.req.op === 'COMMIT' && e.decision === 'ALLOW' && String(e.source).startsWith('pre:')).length
37
+
38
+ // consistency: the state must be what the log says the last kernel step (or the last init/reset) left behind
39
+ const checks = []
40
+ const lastIdx = Math.max(...events.map((x, i) => (x.e.req || x.e.source === 'human:init' || x.e.source === 'human:reset' ? i : -1)), -1)
41
+ if (lastIdx < 0) checks.push({name: 'log matches state', ok: false, detail: 'no kernel step and no init in events.jsonl'})
42
+ else {
43
+ const last = events[lastIdx]
44
+ const expected = last.e.req ? last.e : decode(initKernel(s.params))
45
+ const diff = FIELDS.filter((k) => k in expected && expected[k] !== v[k])
46
+ checks.push({name: 'log matches state', ok: diff.length === 0, detail: diff.length ? `differs at ${diff.join(', ')} (line ${last.line})` : `last entry line ${last.line}`})
47
+ }
48
+ checks.push({name: 'config params = state params', ok: cfg.maxRetries === s.params.maxRetries && cfg.cap === s.params.cap, detail: `${JSON.stringify(s.params)}`})
49
+ checks.push({name: 'working tree counted', ok: now.id === s.snapshot, detail: now.id === s.snapshot ? 'no change the kernel has not seen' : 'uncounted change (counted at the next hook)'})
50
+
51
+ const commitNow = !v.halted && v.buildOkRev === v.treeRev && v.testsOkRev === v.treeRev && !v.testsTainted
52
+ return {
53
+ stopbar: VERSION,
54
+ kernel: MACHINE,
55
+ repository: {head, headTree, snapshot: s.snapshot, workingTreeSnapshot: now.id, treeRevision: v.treeRev},
56
+ config: {profile: cfg.profile, buildCmd: cfg.buildCmd, fullTestCmd: cfg.fullTestCmd, maxRetries: cfg.maxRetries, cap: cfg.cap, costPerCall: cfg.costPerCall},
57
+ gates: {build: v.buildOkRev === v.treeRev, fullTests: v.testsOkRev === v.treeRev, tainted: v.testsTainted, secretRead: v.secretTainted,
58
+ shellApprovalHeld: v.shellToken, halted: v.halted, commitAllowedNow: commitNow, ...(commitNow ? {} : {why: v.halted ? 'session halted' : whyBlocked(v, cfg)}),
59
+ budget: {spent: v.spent, cap: v.capNow}, failures: {tests: v.testFails, builds: v.buildFails}},
60
+ humanActions: approvals,
61
+ log: {file: 'events.jsonl', sha256: createHash('sha256').update(raw).digest('hex'), bytes: raw.length, entries: events.length, tornLines: torn,
62
+ kernelSteps: steps.length, blocks, commitsAllowed, decisions: Object.fromEntries(Object.entries(decisions).sort())},
63
+ consistent: checks.every((c) => c.ok || c.name === 'working tree counted'),
64
+ checks,
65
+ }
66
+ })
67
+ }
68
+
69
+ export function attestMarkdown(a ) {
70
+ const yn = (b ) => (b ? 'yes' : 'no')
71
+ const g = a.gates
72
+ return [
73
+ `# Stopbar attestation`, '',
74
+ `| Field | Value |`, `|---|---|`,
75
+ `| Stopbar | ${a.stopbar} |`, `| Kernel | ${a.kernel.name}, kernel.ts sha256 \`${a.kernel.kernelSha256}\` |`,
76
+ `| HEAD | \`${a.repository.head ?? '(none)'}\` |`, `| HEAD tree | \`${a.repository.headTree ?? '(none)'}\` |`,
77
+ `| Counted snapshot | \`${a.repository.snapshot}\` (revision ${a.repository.treeRevision}) |`,
78
+ `| Build gate | ${yn(g.build)} (\`${a.config.buildCmd}\`) |`, `| Full test gate | ${yn(g.fullTests)} (\`${a.config.fullTestCmd}\`) |`,
79
+ `| Tests tainted | ${yn(g.tainted)} |`, `| Secret read | ${yn(g.secretRead)} |`, `| Halted | ${yn(g.halted)} |`,
80
+ `| Commit allowed now | ${yn(g.commitAllowedNow)}${g.why ? `: ${g.why}` : ''} |`,
81
+ `| Budget | ${g.budget.spent}/${g.budget.cap} |`,
82
+ `| events.jsonl sha256 | \`${a.log.sha256}\` (${a.log.bytes} bytes, ${a.log.entries} entries, torn lines: ${a.log.tornLines.length ? a.log.tornLines.join(', ') : 'none'}) |`,
83
+ `| Kernel steps / blocks / commits allowed | ${a.log.kernelSteps} / ${a.log.blocks} / ${a.log.commitsAllowed} |`,
84
+ `| Consistent | ${yn(a.consistent)} |`, '',
85
+ `## Human actions`, '', ...(a.humanActions.length ? a.humanActions.map((h) => `- line ${h.line}, ${h.ts}: ${h.action}${'revision' in h ? ` revision ${h.revision}` : ''}${'extra' in h ? ` extra ${h.extra}` : ''}${h.decision ? ` -> ${h.decision}` : ''}`) : ['- none']), '',
86
+ `## Checks`, '', ...a.checks.map((c) => `- [${c.ok ? 'x' : ' '}] ${c.name}: ${c.detail}`), '',
87
+ ].join('\n')
88
+ }
89
+
90
+ export function attest(o ) {
91
+ const fmt = o.format ?? 'json'
92
+ if (fmt !== 'json' && fmt !== 'md') return {code: 1, msg: '--format must be json or md'}
93
+ const a = attestation(o.repo ?? process.cwd())
94
+ return {code: a.consistent ? 0 : 1, msg: fmt === 'md' ? attestMarkdown(a) : JSON.stringify(a, null, 1)}
95
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "1.0.0",
3
+ "kernelSourceSha256": "c602fc4bcf8ffb2e312bf838986e6d4b006af6d0e6c7447c8c61d5888adc5ef8",
4
+ "machineSha256": "b397085e0cb13e2e50aa655c54de0744d08f2ebf500bf32af8ff3e8a11ba7321",
5
+ "files": 16
6
+ }