stopbar 1.1.0 → 1.1.1
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 +23 -0
- package/README.md +15 -7
- package/SECURITY.md +17 -8
- package/dist/adapters/antigravity.js +1 -1
- package/dist/adapters/cursor.js +1 -1
- package/dist/adapters/gemini.js +1 -1
- package/dist/adapters/types.js +1 -1
- package/dist/attest.js +2 -1
- package/dist/build-info.json +1 -1
- package/dist/classify.js +52 -3
- package/dist/cli.js +1 -1
- package/dist/commands.js +7 -4
- package/dist/config.js +13 -2
- package/dist/doctor.js +3 -2
- package/dist/hook.js +39 -6
- package/dist/probe/wrapper.js +15 -4
- package/dist/repo.js +16 -4
- package/dist/run.js +10 -4
- package/dist/store.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.1.1 (2026-11-26)
|
|
4
|
+
|
|
5
|
+
- **Security fix (background gate commands):** Claude Code fires `PostToolUse` immediately with `backgroundTaskId` when
|
|
6
|
+
a command runs with `run_in_background: true`, before the process finishes. Previously Stopbar treated that immediate
|
|
7
|
+
event as a passing gate. Now `PreToolUse` blocks `buildCmd` and `fullTestCmd` invoked with `run_in_background: true`
|
|
8
|
+
(guiding long-running gates to `npx stopbar run build|test`), and `PostToolUse` refuses to record any gate result that
|
|
9
|
+
carries `backgroundTaskId` or `run_in_background: true` (defense in depth, fail closed).
|
|
10
|
+
- **`stopbar run build|test` stale-tree check:** `stopbar run` captures the tree snapshot before starting the command
|
|
11
|
+
and discards the result if the working tree changes while it runs (for example during a background `stopbar run`), so
|
|
12
|
+
a gate started on an older revision never passes a newer one.
|
|
13
|
+
- **No secret false alarm on source code (`secrets.ts`):** `PROFILES.strict` replaces bare `secrets.*` with explicit
|
|
14
|
+
secret data/config extensions, and the matcher skips source-code extensions (`.ts`, `.js`, `.py`, `.go`, `.rs`, ...)
|
|
15
|
+
for legacy `secrets.*` patterns in existing `config.json` files. Explicit entries and data files (`secrets.json`,
|
|
16
|
+
`secrets.yaml`, `secrets.env`) still trigger the secret gate.
|
|
17
|
+
- **`--base-ref <ref>` on `stopbar init` (default `HEAD`):** marks which git ref defines an "existing" test file.
|
|
18
|
+
Agents on a multi-commit feature branch (e.g. `--base-ref main`) can iterate on new tests added on that branch across
|
|
19
|
+
commits without triggering `testsTainted`, while existing tests in `baseRef` and all test-config files remain
|
|
20
|
+
protected. `inRef` fails closed if a configured non-`HEAD` ref cannot be resolved; `status`, `doctor` and `attest`
|
|
21
|
+
report `baseRef`.
|
|
22
|
+
- **Plain `git commit -m` messages:** for a verified chain-free `git commit` command in Bash, self-protection strips
|
|
23
|
+
quoted `-m` / `--message` strings (matching the safe heredoc commit behaviour), so commit messages mentioning
|
|
24
|
+
`.git/stopbar`, `.claude` or `approve-tests` are not falsely blocked.
|
|
25
|
+
|
|
3
26
|
## 1.1.0 (2026-11-26)
|
|
4
27
|
|
|
5
28
|
- Adapters for Cursor, Codex CLI, Gemini CLI and Antigravity CLI next to Claude Code. One internal event, one kernel;
|
package/README.md
CHANGED
|
@@ -76,8 +76,11 @@ 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
|
|
80
|
-
`npm test | tail
|
|
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 `npx stopbar run build` /
|
|
81
|
+
`npx 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). Commits must be one command. The quoted
|
|
83
|
+
heredoc form that agents use is allowed:
|
|
81
84
|
|
|
82
85
|
```sh
|
|
83
86
|
git commit -m "$(cat <<'EOF'
|
|
@@ -92,7 +95,7 @@ EOF
|
|
|
92
95
|
|
|
93
96
|
| Command | Who | What it does |
|
|
94
97
|
|---|---|---|
|
|
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. |
|
|
98
|
+
| `stopbar init --build "<cmd>" --test "<cmd>" [--profile p] [--base-ref <ref>] [--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. `--base-ref` sets the git ref used to judge whether a test file already existed (default `HEAD`). |
|
|
96
99
|
| `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
100
|
| `stopbar git-hook pre-commit\|pre-push` | git | The git fallback gate. Exit 1 aborts the commit or push. |
|
|
98
101
|
| `stopbar run build\|test` | human, agent, CI | Runs the configured gate command and records its real exit status. |
|
|
@@ -138,6 +141,11 @@ profile by editing the lists: no code change is necessary.
|
|
|
138
141
|
other pattern (`.env*`, `id_rsa*`) count always. `stopbar status` says why the secret gate is on, for example
|
|
139
142
|
`secret read yes (matched *.key (server.key) in Bash at rev 3)`; `events.jsonl` keeps the pattern and the token,
|
|
140
143
|
never the file content.
|
|
144
|
+
- **`baseRef`** (optional, set via `stopbar init --base-ref <ref>`) controls which git ref defines an "existing" test
|
|
145
|
+
file (default: `HEAD`). On a multi-commit feature branch, `--base-ref main` (or a base commit SHA) lets the agent
|
|
146
|
+
refine new test files it added on that branch across commits without triggering `testsTainted`, while existing tests
|
|
147
|
+
from `baseRef` and all test-config files remain protected. A configured non-`HEAD` ref that cannot be resolved fails
|
|
148
|
+
closed.
|
|
141
149
|
- **`safeTools`** (optional) lists glob patterns of tool names that are local and never outbound. The default is
|
|
142
150
|
`["mcp__ccd_turn__*"]`, the task-list and turn-summary tools of Claude Desktop. It only exempts tools from the
|
|
143
151
|
outbound gate (WebFetch, WebSearch, MCP tools); shell commands, edits and reads are gated as before, and a halted
|
|
@@ -196,12 +204,12 @@ latency. An earlier prototype that loaded the prover in every hook measured p50
|
|
|
196
204
|
|
|
197
205
|
| Platform | Node | git | Unit | E2E | `stopbar probe` | `stopbar prove` | `stopbar doctor` |
|
|
198
206
|
|---|---|---|---|---|---|---|---|
|
|
199
|
-
| Windows 11, Git for Windows | 24.19.0 | 2.56.0 |
|
|
200
|
-
| Linux, Debian 13 (container, no network) | 24.21.0 | 2.47.3 |
|
|
207
|
+
| Windows 11, Git for Windows | 24.19.0 | 2.56.0 | 31/31 | 258/258 | 202/202 sequences | proven, 10/10 mutants | OK |
|
|
208
|
+
| Linux, Debian 13 (container, no network) | 24.21.0 | 2.47.3 | 31/31 | 258/258 | 202/202 sequences | proven, 10/10 mutants | OK |
|
|
201
209
|
|
|
202
210
|
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
|
|
204
|
-
and
|
|
211
|
+
git commits and pushes. The probe runs the same 200 seeds plus 2 regressions on both platforms, with the same 5007 steps
|
|
212
|
+
and 7176 hook calls. `stopbar doctor` passes on a fresh repository with all six `--hooks` targets.
|
|
205
213
|
`npm run verify:lean` passes in the Lean 4.34.0 container: `lake build` exit 0, 0 errors, 0 `sorry`.
|
|
206
214
|
|
|
207
215
|
## 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
|
|
47
|
-
`;`, `&&`, `||`, `|`, a redirection or `$(...)`, the command is blocked
|
|
48
|
-
|
|
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
|
|
53
|
-
or to any test-config file, is suspicious.
|
|
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`,
|
|
@@ -89,8 +96,10 @@ that tries to defeat it:
|
|
|
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
97
|
Tools listed in `config.safeTools` (default: Claude Desktop's `mcp__ccd_turn__*` UI tools) are not treated as
|
|
91
98
|
outbound; a human who adds a glob there vouches that those tools send nothing out.
|
|
92
|
-
4. **Weak new tests
|
|
93
|
-
new file passes. Hard-coded answers in production code are an ordinary code edit.
|
|
99
|
+
4. **Weak new tests and mutable `baseRef`.** A new test file is not suspicious. A mock of the system under test or an
|
|
100
|
+
empty assertion in a new file passes. Hard-coded answers in production code are an ordinary code edit. When
|
|
101
|
+
`config.baseRef` is a mutable local branch name (such as `main`) rather than a commit SHA, an agent with shell access
|
|
102
|
+
can move that branch ref; pass a commit hash (`--base-ref <sha>`) if you want an immutable baseline.
|
|
94
103
|
5. **Ignored files.** Files ignored by `.gitignore` are invisible to the snapshot (for example patches in
|
|
95
104
|
`node_modules`). A change to `.gitignore` itself is suspicious.
|
|
96
105
|
6. **Other commit paths.** Git aliases, `git commit-tree`, `gh pr create` and similar are not detected. The Stop hook
|
|
@@ -122,7 +131,7 @@ For a hostile-agent threat model, run the agent in a container or VM: no network
|
|
|
122
131
|
read-write, `.git/stopbar` and `.claude` mounted read-only or owned by another user, and the human commands run outside
|
|
123
132
|
the sandbox. Stopbar's kernel then gives the proven decisions and the sandbox gives the boundary.
|
|
124
133
|
|
|
125
|
-
## Known limits of 1.1.
|
|
134
|
+
## Known limits of 1.1.1
|
|
126
135
|
|
|
127
136
|
- Lean: the check needs Docker and a one-time image build with network access. The base image is pinned by digest and
|
|
128
137
|
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}}
|
package/dist/adapters/cursor.js
CHANGED
|
@@ -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}}
|
package/dist/adapters/gemini.js
CHANGED
|
@@ -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}}
|
package/dist/adapters/types.js
CHANGED
|
@@ -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,7 @@ 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
58
|
gates: {build: v.buildOkRev === v.treeRev, fullTests: v.testsOkRev === v.treeRev, tainted: v.testsTainted, secretRead: v.secretTainted,
|
|
59
59
|
...(v.secretTainted ? {secretReadBy: secretReason(repo)?.text ?? 'not in the event log'} : {}),
|
|
60
60
|
shellApprovalHeld: v.shellToken, halted: v.halted, commitAllowedNow: commitNow, ...(commitNow ? {} : {why: v.halted ? 'session halted' : whyBlocked(v, cfg)}),
|
|
@@ -76,6 +76,7 @@ export function attestMarkdown(a ) {
|
|
|
76
76
|
`| Field | Value |`, `|---|---|`,
|
|
77
77
|
`| Stopbar | ${a.stopbar} |`, `| Kernel | ${a.kernel.name}, kernel.ts sha256 \`${a.kernel.kernelSha256}\` |`,
|
|
78
78
|
`| HEAD | \`${a.repository.head ?? '(none)'}\` |`, `| HEAD tree | \`${a.repository.headTree ?? '(none)'}\` |`,
|
|
79
|
+
...(a.config.baseRef ? [`| Base ref | \`${a.config.baseRef}\` |`] : []),
|
|
79
80
|
`| Counted snapshot | \`${a.repository.snapshot}\` (revision ${a.repository.treeRevision}) |`,
|
|
80
81
|
`| Build gate | ${yn(g.build)} (\`${a.config.buildCmd}\`) |`, `| Full test gate | ${yn(g.fullTests)} (\`${a.config.fullTestCmd}\`) |`,
|
|
81
82
|
`| Tests tainted | ${yn(g.tainted)} |`, `| Secret read | ${g.secretRead ? `yes: ${g.secretReadBy}` : 'no'} |`, `| Halted | ${yn(g.halted)} |`,
|
package/dist/build-info.json
CHANGED
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
|
-
|
|
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 (
|
|
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) =>
|
|
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,7 +9,7 @@ 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
14
|
stopbar hook [--adapter auto|claude|cursor|codex|gemini|antigravity]
|
|
15
15
|
the agent hook (JSON on stdin); auto detects the client from the payload
|
package/dist/commands.js
CHANGED
|
@@ -9,7 +9,7 @@ import { ConfigError, makeConfig, PROFILES} from './config.js'
|
|
|
9
9
|
import {decode, initKernel, kstep, MACHINE, } from './engine.js'
|
|
10
10
|
import {whyBlocked} from './hook.js'
|
|
11
11
|
import {PKG_ROOT} from './pkg.js'
|
|
12
|
-
import {findRepo, forgetSnapshots, markCounted, snapshot} from './repo.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
|
|
|
@@ -59,8 +59,11 @@ export function init(o ) {
|
|
|
59
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`}
|
|
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
63
|
} catch (e) { if (e instanceof ConfigError) return {code: 1, msg: e.message}; throw e }
|
|
64
|
+
if (cfg.baseRef && !hasRefTree(repo.root, cfg.baseRef)) {
|
|
65
|
+
return {code: 1, msg: `--base-ref ${JSON.stringify(cfg.baseRef)} does not resolve to a commit/tree in ${repo.root}`}
|
|
66
|
+
}
|
|
64
67
|
const hooksOpt = o.get('hooks')
|
|
65
68
|
const targets = hooksOpt === undefined ? [] : parseTargets(hooksOpt) // validated before anything is written
|
|
66
69
|
mkdirSync(repo.stateDir, {recursive: true})
|
|
@@ -71,7 +74,7 @@ export function init(o ) {
|
|
|
71
74
|
const runtime = pin ? pinRuntime(repo) : PKG_ROOT
|
|
72
75
|
const command = hookCommand(runtime)
|
|
73
76
|
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}`,
|
|
77
|
+
const lines = [`Stopbar ${VERSION} initialised in ${repo.stateDir}`, ` profile ${cfg.profile}; build: ${cfg.buildCmd}; full tests: ${cfg.fullTestCmd}${cfg.baseRef ? `; base ref: ${cfg.baseRef}` : ''}`,
|
|
75
78
|
` hooks run: ${command}`]
|
|
76
79
|
if (targets.length) for (const l of installHooks(repo, targets, runtime, o.has('force-hooks'))) lines.push(` hooks written: ${l}`)
|
|
77
80
|
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,7 +103,7 @@ function statusText(repo , cfg , s ) {
|
|
|
100
103
|
const torn = readEvents(repo).torn.length
|
|
101
104
|
return [
|
|
102
105
|
`Stopbar ${VERSION} repo ${repo.root}`,
|
|
103
|
-
`revision ${v.treeRev} (tree ${s.snapshot.slice(0, 12)})`,
|
|
106
|
+
`revision ${v.treeRev} (tree ${s.snapshot.slice(0, 12)})${cfg.baseRef ? ` base ref ${cfg.baseRef}` : ''}`,
|
|
104
107
|
`build ${ok(v.buildOkRev)} (${cfg.buildCmd})`,
|
|
105
108
|
`full tests ${ok(v.testsOkRev)} (${cfg.fullTestCmd})`,
|
|
106
109
|
`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)}`,
|
package/dist/config.js
CHANGED
|
@@ -14,6 +14,8 @@ import {globToRegExp} from './glob.js'
|
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
|
|
17
|
+
|
|
18
|
+
|
|
17
19
|
|
|
18
20
|
|
|
19
21
|
const TEST_COMMON = ['**/tests/**', '**/test/**', '**/__tests__/**']
|
|
@@ -40,7 +42,7 @@ export const PROFILES = {
|
|
|
40
42
|
strict: {
|
|
41
43
|
tests: [...TEST_COMMON, ...TEST_PY],
|
|
42
44
|
testConfig: [...CFG_COMMON, ...CFG_PY, 'quality.sh', '**/quality*.sh', 'scripts/quality*', 'uv.lock', 'Dockerfile*', 'docker-compose*.yml', 'hypothesis*.ini'],
|
|
43
|
-
secrets: [...SECRETS, '*.age', 'secrets
|
|
45
|
+
secrets: [...SECRETS, '*.age', 'secrets.{json,yaml,yml,toml,env,ini,txt,cfg,conf,xml,properties,age,enc,key,pem,local,prod,dev,staging}'],
|
|
44
46
|
},
|
|
45
47
|
}
|
|
46
48
|
|
|
@@ -80,17 +82,26 @@ export function validateConfig(c ) {
|
|
|
80
82
|
try { globToRegExp(g) } catch (e) { throw new ConfigError(`config.safeTools: ${(e ).message}`) }
|
|
81
83
|
}
|
|
82
84
|
}
|
|
85
|
+
if (o.baseRef !== undefined) {
|
|
86
|
+
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)}`)
|
|
87
|
+
}
|
|
83
88
|
return o
|
|
84
89
|
}
|
|
85
90
|
|
|
86
|
-
export function
|
|
91
|
+
export function isSafeRef(ref ) {
|
|
92
|
+
return ref.length > 0 && !ref.startsWith('-') && !ref.includes('..') && !ref.endsWith('.') && !ref.endsWith('/') && /^[A-Za-z0-9._/@^~-]+$/.test(ref)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function makeConfig(a ) {
|
|
87
96
|
const profile = a.profile ?? 'default'
|
|
88
97
|
const paths = PROFILES[profile]
|
|
89
98
|
if (!paths) throw new ConfigError(`unknown profile ${JSON.stringify(profile)}; known: ${Object.keys(PROFILES).join(', ')}`)
|
|
99
|
+
const baseRef = a.baseRef?.trim()
|
|
90
100
|
return validateConfig({
|
|
91
101
|
version: 1, profile, buildCmd: a.buildCmd.trim(), fullTestCmd: a.fullTestCmd.trim(),
|
|
92
102
|
maxRetries: a.maxRetries ?? DEFAULTS.maxRetries, cap: a.cap ?? DEFAULTS.cap, costPerCall: a.costPerCall ?? DEFAULTS.costPerCall,
|
|
93
103
|
paths: {tests: [...paths.tests], testConfig: [...paths.testConfig], secrets: [...paths.secrets]},
|
|
94
104
|
safeTools: [...DEFAULT_SAFE_TOOLS],
|
|
105
|
+
...(baseRef && baseRef !== 'HEAD' ? {baseRef} : {}),
|
|
95
106
|
})
|
|
96
107
|
}
|
package/dist/doctor.js
CHANGED
|
@@ -10,7 +10,7 @@ import {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,8 @@ 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
|
+
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
162
|
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
163
|
try {
|
|
163
164
|
const s = readState(repo), v = decode(s.kernel)
|
package/dist/hook.js
CHANGED
|
@@ -7,7 +7,7 @@ import * as K from './classify.js'
|
|
|
7
7
|
import { 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,
|
|
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
|
|
|
@@ -54,8 +54,8 @@ function syncTree(ctx , cost , source ) {
|
|
|
54
54
|
appendEvent(repo, {source: `${source}:fallback-diff`, note: 'counted snapshot copy missing; diff against HEAD'})
|
|
55
55
|
}
|
|
56
56
|
const testPaths = changes.map((c) => c.path).filter((p) => K.isTestPath(p, cfg.paths) && !K.isTestConfigPath(p, cfg.paths))
|
|
57
|
-
const
|
|
58
|
-
const cls = K.classifyTreeChange(changes, (p) =>
|
|
57
|
+
const existing = testPaths.length ? inRef(repo.root, cfg.baseRef ?? 'HEAD', testPaths) : new Set ()
|
|
58
|
+
const cls = K.classifyTreeChange(changes, (p) => existing.has(p), cfg.paths)
|
|
59
59
|
const {before, after} = step(ctx, {op: cls.op, suspicious: cls.suspicious, cost}, `${source}:tree ${cls.why.join(', ') || `${changes.length} file(s)`}`)
|
|
60
60
|
// not executed (halted or over budget): the change stays pending and is counted later
|
|
61
61
|
if (after.treeRev > before.treeRev) { s.snapshot = snap.id; markCounted(repo); ctx.dirty = true }
|
|
@@ -64,6 +64,16 @@ function syncTree(ctx , cost , source ) {
|
|
|
64
64
|
|
|
65
65
|
const block = (reason ) => ({code: 2, msg: `BLOCK (stopbar): ${reason}`})
|
|
66
66
|
|
|
67
|
+
function isBackgroundInput(ti ) {
|
|
68
|
+
return ti?.run_in_background === true || ti?.run_in_background === 'true' || ti?.background === true
|
|
69
|
+
}
|
|
70
|
+
function isBackgroundResponse(tr ) {
|
|
71
|
+
if (!tr || typeof tr !== 'object') return false
|
|
72
|
+
return (typeof tr.backgroundTaskId === 'string' && tr.backgroundTaskId.length > 0) ||
|
|
73
|
+
(typeof tr.background_task_id === 'string' && tr.background_task_id.length > 0) ||
|
|
74
|
+
tr.isAsync === true || tr.background === true
|
|
75
|
+
}
|
|
76
|
+
|
|
67
77
|
// ---------------------------------------------------------------- PreToolUse
|
|
68
78
|
function pre(ctx , input ) {
|
|
69
79
|
const tool = String(input.tool_name ?? ''), ti = input.tool_input ?? {}
|
|
@@ -78,8 +88,7 @@ function pre(ctx , input ) {
|
|
|
78
88
|
}
|
|
79
89
|
if (SHELL_TOOLS.has(tool)) {
|
|
80
90
|
const cmd = String(ti.command ?? '')
|
|
81
|
-
const
|
|
82
|
-
const why = K.protectedCommand(hd ? hd.prefix : cmd, ctx.protect)
|
|
91
|
+
const why = K.protectedCommand(K.commandForSelfProtect(cmd, tool === 'PowerShell' ? 'powershell' : 'bash'), ctx.protect)
|
|
83
92
|
if (why) { appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: why}); return block(`${why}. Ask the human.`) }
|
|
84
93
|
}
|
|
85
94
|
const v = decode(ctx.s.kernel)
|
|
@@ -111,7 +120,15 @@ function pre(ctx , input ) {
|
|
|
111
120
|
appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: `chained gate command (${k.reason})`})
|
|
112
121
|
return block(`run \`${k.gate}\` exactly as configured, alone: no ;, &&, ||, |, redirections or $(...). Chained operators hide its exit status.`)
|
|
113
122
|
}
|
|
114
|
-
if (k.kind === 'build' || k.kind === 'fulltest')
|
|
123
|
+
if (k.kind === 'build' || k.kind === 'fulltest') {
|
|
124
|
+
if (isBackgroundInput(ti)) {
|
|
125
|
+
const which = k.kind === 'build' ? 'build' : 'test'
|
|
126
|
+
const gate = k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd
|
|
127
|
+
appendEvent(repo, {source: 'pre', tool, wrapper: 'BLOCK', reason: `background gate command (${k.kind})`})
|
|
128
|
+
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 \`npx stopbar run ${which}\` in the background so Stopbar records the real exit status only when it finishes.`)
|
|
129
|
+
}
|
|
130
|
+
return {code: 0} // the result is recorded in PostToolUse
|
|
131
|
+
}
|
|
115
132
|
if (k.kind === 'commit') {
|
|
116
133
|
syncTree(ctx, 0, 'pre:commit-sync') // a change nobody reported (background job, human edit) is counted first
|
|
117
134
|
const {after} = step(ctx, {op: 'COMMIT', cost}, `pre:${tool}:commit${k.heredoc ? ':heredoc' : ''}`)
|
|
@@ -157,6 +174,9 @@ function post(ctx , input , failure ) {
|
|
|
157
174
|
const meta = input.stopbar ?? {}
|
|
158
175
|
appendEvent(repo, {source: `payload:${input.hook_event_name}`, tool, ...(meta.adapter ? {adapter: meta.adapter, rawKeys: meta.rawKeys} : {inputKeys: Object.keys(input)}),
|
|
159
176
|
toolResponseKeys: tr && typeof tr === 'object' ? Object.keys(tr) : typeof tr})
|
|
177
|
+
const bg = isBackgroundInput(ti) || isBackgroundResponse(tr)
|
|
178
|
+
const staleRun = typeof meta.expectedSnapshot === 'string' &&
|
|
179
|
+
(meta.expectedSnapshot !== ctx.s.snapshot || (typeof meta.expectedRev === 'number' && meta.expectedRev !== decode(ctx.s.kernel).treeRev))
|
|
160
180
|
const code = exitCodeOf(tr)
|
|
161
181
|
const flagged = input.is_error === true || tr?.is_error === true || tr?.interrupted === true
|
|
162
182
|
// some clients send the same post event for success and failure: then only an explicit exit code 0 is a pass
|
|
@@ -166,6 +186,19 @@ function post(ctx , input , failure ) {
|
|
|
166
186
|
if (failure && input.is_interrupt === true) {
|
|
167
187
|
// Ctrl+C by the user: not a failed gate and not a retry; the tree is still checked below
|
|
168
188
|
appendEvent(repo, {source: 'post:user-interrupt', tool, kind: k.kind})
|
|
189
|
+
} else if (!failure && bg && (k.kind === 'build' || k.kind === 'fulltest' || (k.kind === 'shell' && k.partialTests))) {
|
|
190
|
+
// a background launch fires PostToolUse before the process finishes (e.g. Claude Code backgroundTaskId): never count it
|
|
191
|
+
appendEvent(repo, {source: 'post:background-gate-ignored', tool, kind: k.kind === 'shell' ? 'partial-tests' : k.kind,
|
|
192
|
+
...(typeof tr?.backgroundTaskId === 'string' ? {backgroundTaskId: tr.backgroundTaskId} : typeof tr?.background_task_id === 'string' ? {backgroundTaskId: tr.background_task_id} : {})})
|
|
193
|
+
if (k.kind !== 'shell') {
|
|
194
|
+
const which = k.kind === 'build' ? 'build' : 'test'
|
|
195
|
+
const gate = k.kind === 'build' ? cfg.buildCmd : cfg.fullTestCmd
|
|
196
|
+
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 \`npx stopbar run ${which}\` in the background.`)
|
|
197
|
+
}
|
|
198
|
+
} else if (staleRun && (k.kind === 'build' || k.kind === 'fulltest')) {
|
|
199
|
+
const curRev = decode(ctx.s.kernel).treeRev
|
|
200
|
+
appendEvent(repo, {source: 'post:stale-gate-run', tool, kind: k.kind, expectedRev: meta.expectedRev, currentRev: curRev})
|
|
201
|
+
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
202
|
} else if (!failure && unknown && (k.kind === 'build' || k.kind === 'fulltest' || (k.kind === 'shell' && k.partialTests))) {
|
|
170
203
|
// no exit status in the client's post event: neither a pass nor a failure is recorded (no evidence either way)
|
|
171
204
|
appendEvent(repo, {source: 'post:gate-without-exit-code', tool, kind: k.kind})
|
package/dist/probe/wrapper.js
CHANGED
|
@@ -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
|
-
/**
|
|
171
|
-
export function
|
|
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',
|
|
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 {
|
|
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
|
|
27
|
-
|
|
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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stopbar",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.1",
|
|
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",
|