diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fbb711..6504b59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ ### Added -- Behavioral coverage for the full six-entry-point trust/configuration matrix, including fail-closed settle behavior, configuration re-arming after `edit`/`write`, abort handling, and the continuation cap. +- Behavioral coverage for the full six-entry-point trust/configuration matrix, including fail-closed settle behavior, configuration re-arming after a mutation-capable tool, abort invariants, custom-run budget preservation, and the continuation cap. - Real JVM smoke tests (`npm run test:jvm`) against the vendored jar, plus a Gitea Actions verification workflow for Node 24 and Java 11. ### Changed @@ -26,6 +26,7 @@ - Explicit `run_gates` and `/verify` filters that match no gates are errors instead of green zero-gate results. - The deletion guard now runs on the deletion policy: it recognizes `git clean`, quoted paths, `sudo`, subshell and command-substitution segments, and `bash -c`/`sh -c` bodies; uncertain commands confirm, and headless sessions block instead of silently allowing deletions. - The legacy unchecked configuration loader and duplicate gate execution path were removed. +- The On-settle Gate lifecycle now lives in one Settle Policy module: the dirty set is mutation-capable tools (including the opt-in `codemode`, `subagent`, and `subagent_async` tools, but not `bash`), completed attempts re-arm only after a new mutation, custom runs never reset the budget, and aborted attempts burn no continuation and leave the dirty cycle armed. The cap remains 3. ## [1.0.0] - 2026-11-23 diff --git a/GLOSSARY.md b/GLOSSARY.md index 0594205..6444d03 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -16,6 +16,10 @@ _Avoid_: Exit status, tool failure (when naming the classification) A Verification Gate selected to run automatically before the agent settles. Untrusted projects never supply On-settle Gates. _Avoid_: Idle check, final test +**Settle Policy**: +The pure module that owns the On-settle Gate lifecycle: the mutation-capable dirty set, reset and re-arm rules, the per-prompt continuation budget, abort invariants, and the settle decision. The Pi adapter translates session events onto it; configuration resolution, gate execution, status, and message formatting stay in the adapter. +_Avoid_: Dirty flag, continuation counter + **Project Trust**: Pi's decision about whether project-local configuration and resources may be honored; it is not a command sandbox. An untrusted project cannot supply Verification Gates or TLA+ tool jars. _Avoid_: Command permission, sandbox approval diff --git a/README.md b/README.md index 5854b17..f3e3295 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Both runners bound each stream at 20 MB. On overflow the JVM path keeps the head ### Hooks (deterministic enforcement) - **Auto-SANY** (`tool_result`): every `edit`/`write` of a `*.tla` file is parsed immediately and the verdict is appended to the tool result, so parse errors land in the agent's context without it asking. A trusted malformed or unreadable configuration is appended as a concise configuration error and SANY is not run; missing toolchain stays silent. Untrusted projects use safe TLA+ settings without reading the project configuration. -- **Gate-before-idle** (`agent_before_settle`): when the agent finishes a run that edited files, gates marked `"on_settle": true` run automatically from the session project root. If any is red, the failures are injected into the conversation with one requested continuation — the agent must fix before settling. Bounded at 3 continuations per user prompt; resets on each new prompt. Trusted malformed or unreadable configuration fails closed as a red settle result with no gate execution; missing configuration, zero On-settle Gates, and untrusted projects are normal skips. Abort requests no continuation. +- **Gate-before-idle** (`agent_before_settle`): when the agent finishes a run, gates marked `"on_settle": true` run automatically from the session project root only when a mutation-capable tool has completed successfully since the last completed settle attempt. The dirty set is `edit`, `write`, `tla_check`, `tlc`, plus the opt-in extension tools `codemode`, `subagent`, and `subagent_async`; error results and other tools do not arm it. A completed attempt consumes the cycle, so gates re-run only after a new mutation; an agent that re-settles without changing anything settles silently. If any gate is red, the failures are injected into the conversation with one requested continuation — the agent must fix before settling; trusted malformed or unreadable configuration also fails closed as a red settle result with no gate execution. Missing configuration, zero On-settle Gates, and untrusted projects are normal skips. The continuation budget is capped at 3; only `session_start` and runs started by a human (`messageType: "user"`) reset it, so programmatic `"custom"` runs never grant a fresh budget. An aborted attempt burns no budget, requests no continuation, and leaves the dirty cycle armed; an abort observed at settle entry executes no gates. Bash-driven mutations never arm the cycle — an accepted limitation, since command strings are not inspected; `run_gates` and CI remain the explicit verification contract. - **Test/spec deletion guard** (`tool_call`): in-scope bash commands that can delete files are `rm`, `git rm`, `git clean`, and a piped zero-operand `rm` (`… | xargs rm`). Recognition happens at command start, after unquoted separators (`;`, `&`, `|`, parentheses and command substitution, backticks, newlines), after `sudo` (including its flags), after a leading `xargs`, and inside `bash -c`/`sh -c` bodies. Test/spec targets are `/`-separated segments `test`, `tests`, `__tests__`, `spec`, or `specs`, or basenames with a delimited marker (`Spec.tla`, `foo.test.ts`, `utils_test.py`, `foo_spec.rb`, `test-utils.ts`; not `contest.ts` or `latest.ts`). Quoted operands stay one path and are judged by that content (`rm -rf "tests"` targets `tests`; `'tests dir'` is a directory named `tests dir`). TUI mode asks for confirmation before deletion; headless blocks because there is no approver. Uncertainty also confirms: pathless `git clean`, globs that do not match the vocabulary (`rm -rf *`, `rm -rf *.log`), wholesale operands (`.`, `./`, `~`, `..`, `../`, `/`), `$` expansion (`rm -rf $TESTS`), xargs-led `rm` (which always appends upstream paths), and unparseable input. `git clean -n`/`--dry-run` is allowed. Not covered: `mv`, `find -delete`/`-exec`, `truncate`, `git checkout --`/`git reset --hard`, `rsync --delete`, other interpreters (`zsh -c`, `python -c`, `node -e`), deep quoting, cross-segment `cd` tracking, filesystem state, and command words supplied by expansion (`$(echo rm) -rf tests`). ### Command @@ -92,7 +92,7 @@ Pi's Project Trust controls whether project-local configuration and resources ma - `run_gates` and `/verify` with no configured gates report the existing no-gates guidance. - A filter matching zero configured gates is an error in both `run_gates` and `/verify`. - A settle cycle with zero On-settle Gates is a normal skip, as are missing configuration and untrusted projects. -- Trusted malformed or unreadable configuration at settle consumes the dirty cycle, sets a red status when UI is available, injects an actionable error, and requests one continuation only while the per-prompt cap of 3 allows it and the context is not aborted. No gate executes. A successful `edit`/`write` after the fix re-arms the next settle check. +- Trusted malformed or unreadable configuration at settle consumes the dirty cycle, sets a red status when UI is available, injects an actionable error, and requests one continuation only while the per-prompt cap of 3 allows it and the context is not aborted. No gate executes. A successful mutation-capable tool after the fix re-arms the next settle check. - Each POSIX gate runs in its own process group. Timeout, abort, and output overflow terminate that group, including bash-spawned children still in it; `/verify` forwards the session abort signal and never reports an aborted run green. Output is bounded at 20 MB per stream, so overflow on stdout or stderr is red with an actionable diagnostic even when the command exits 0. Returned tails are bounded and Unicode-safe. - A deliberately detached descendant that leaves the gate's process group (for example via `setsid`) is outside the group-termination guarantee and is not claimed as killed. It cannot delay the result indefinitely because finalization is bounded. @@ -129,6 +129,7 @@ Development and CI use Node 24 (the test suites use Node's built-in `node:test`) ### Module map - `extensions/verify.ts` — Pi registration and formatting adapter. The only module that reads Pi context (`ctx.cwd`, `ctx.isProjectTrusted()`, `ctx.signal`), registers tools/hooks/commands, and renders results. +- `extensions/verify/settle.ts` — pure Settle Policy module: mutation-capable dirty tracking, reset and re-arm rules, the continuation budget, abort invariants, and the settle decision; no Pi imports or I/O. - `extensions/verify/config.ts` — the single owner of Project Trust, configuration reading, strict validation, defaults, and safe TLA+/gate resolution. - `extensions/verify/gates.ts` — sequential gate selection, process-group execution, timeout/abort/output-overflow termination, per-stream output bounding, and `GateResult` construction over validated trusted input; it never re-reads configuration. - `extensions/verify/tla.ts` — deep TLA+ toolchain module for SANY, PlusCal, TLC, JVM execution, and jar resolution; it receives resolved safe settings. diff --git a/extensions/verify.ts b/extensions/verify.ts index 287ea72..017368a 100644 --- a/extensions/verify.ts +++ b/extensions/verify.ts @@ -44,6 +44,11 @@ import { runGates as runValidatedGates, type GateResult, } from "./verify/gates.ts"; +import { + createSettlePolicy, + type SettleConfig, + type SettlePolicy, +} from "./verify/settle.ts"; import { createTlaVerification, type ModelOutcome, @@ -53,7 +58,6 @@ import { import { tail } from "./verify/process.ts"; const CONFIG_DIR_NAME = ".pi"; -const MAX_SETTLE_CONTINUATIONS = 3; const JAVA_NOT_FOUND_TEXT = "Java not found on PATH. Install Java 11+ (e.g. `sudo apt-get install default-jre`)."; @@ -394,6 +398,8 @@ function formatGateResults(results: GateResult[], ms: number): string { export interface VerifyExtensionOptions { /** Injectable deep TLA+ module for behavioral tests. */ tla?: TlaVerification; + /** Injectable Settle Policy for adapter tests. */ + settle?: SettlePolicy; } export default function verifyExtension( @@ -401,6 +407,7 @@ export default function verifyExtension( options: VerifyExtensionOptions = {}, ) { const tla = options.tla ?? createTlaVerification(); + const settle = options.settle ?? createSettlePolicy(); const rootFor = (ctx: ProjectContext | undefined) => sessionRoot(ctx); // ------------------------------------------------------------------ tools @@ -557,46 +564,50 @@ export default function verifyExtension( }); // Gate-before-idle: run on_settle gates; if red, inject failures and request one continuation. - let dirty = false; - let settleContinuations = 0; - pi.on("session_start", () => { - dirty = false; - settleContinuations = 0; + settle.noteSessionStart(); }); pi.on("before_agent_start", (event) => { - if (event.messageType === "user") { - dirty = false; - settleContinuations = 0; - } + settle.noteRunStart(event.messageType); }); pi.on("tool_execution_end", (event) => { - if ((event.toolName === "edit" || event.toolName === "write") && !event.isError) dirty = true; + settle.noteToolResult(event.toolName, event.isError); }); pi.on("agent_before_settle", async (event, ctx) => { - if (!dirty || settleContinuations >= MAX_SETTLE_CONTINUATIONS) return; + const aborted = () => !!ctx.signal?.aborted; + if (settle.beginSettle(aborted()) === "skip") return; + const root = rootFor(ctx); const resolution = resolveGateConfiguration({ root, configDirName: CONFIG_DIR_NAME, trusted: projectTrusted(ctx), }); - if (!resolution.ok) { - if (resolution.reason === "project-not-trusted") return; - - dirty = false; // this cycle re-arms only when new edits land - settleContinuations++; - if (ctx.signal?.aborted) return; + let config: SettleConfig; + let configurationError = ""; + if (resolution.ok) { + config = resolution.project.gates.some((gate) => gate.on_settle) + ? { kind: "run" } + : { kind: "no-on-settle-gates" }; + } else if (resolution.reason === "project-not-trusted") { + config = { kind: "untrusted" }; + } else { + config = { kind: "config-error" }; + configurationError = resolution.error; + } + const classification = settle.classify(config, aborted()); + if (classification === "settle") return; + if (classification === "fail-closed") { if (ctx.hasUI) ctx.ui.setStatus("verify", "gates red: configuration error"); const msg = [ "The project verification configuration is broken, so no verification gates ran.", "Fix the configuration before settling, then re-run verification.", "", - resolution.error, + configurationError, ].join("\n"); return { entries: [ @@ -612,21 +623,19 @@ export default function verifyExtension( }; } - const project = resolution.project; - if (!project.gates.some((gate) => gate.on_settle)) return; - dirty = false; // this cycle re-arms only when new edits land - const signal = ctx.signal; - const results = await runValidatedGates(project, { + // classify("run") implies resolved configuration with On-settle Gates. + if (!resolution.ok) return; + const results = await runValidatedGates(resolution.project, { onlyOnSettle: true, - signal, + signal: ctx.signal, }); - if (signal?.aborted) return; - const failed = results.filter((r) => r.outcome !== "pass"); - if (failed.length === 0) { - if (ctx.hasUI) ctx.ui.setStatus("verify", ""); + const green = results.every((r) => r.outcome === "pass"); + const abortedAtCompletion = aborted(); + if (settle.completeSettle(green, abortedAtCompletion) === "settle") { + if (green && !abortedAtCompletion && ctx.hasUI) ctx.ui.setStatus("verify", ""); return; } - settleContinuations++; + const failed = results.filter((r) => r.outcome !== "pass"); const report = failed .map((r) => `### ${r.name} — ${gateOutcomeLabel(r)}\n${r.output}`) .join("\n\n"); diff --git a/test/behavior/gates-adapter.test.ts b/test/behavior/gates-adapter.test.ts index 9aa67ba..7105a44 100644 --- a/test/behavior/gates-adapter.test.ts +++ b/test/behavior/gates-adapter.test.ts @@ -3,6 +3,10 @@ import * as fs from "node:fs"; import * as path from "node:path"; import { test } from "node:test"; import verifyExtension from "../../extensions/verify.ts"; +import { + createSettlePolicy, + type SettlePolicy, +} from "../../extensions/verify/settle.ts"; import type { ModelCheckRequest, ModelOutcome, @@ -123,9 +127,9 @@ function makeContext( }; } -function makeAdapter(): FakePi { +function makeAdapter(options: { settle?: SettlePolicy } = {}): FakePi { const pi = new FakePi(); - verifyExtension(pi as never, { tla: new FakeTla() }); + verifyExtension(pi as never, { tla: new FakeTla(), settle: options.settle }); return pi; } @@ -188,10 +192,27 @@ async function callSettle( )) as SettleResult | undefined; } -async function markSuccessfulTool(pi: FakePi, toolName = "edit"): Promise { +async function markTool( + pi: FakePi, + toolName: string, + isError = false, +): Promise { const handler = pi.handlers.get("tool_execution_end")?.[0]; assert.ok(handler, "tool_execution_end handler is registered"); - await handler({ type: "tool_execution_end", toolName, isError: false }, {}); + await handler({ type: "tool_execution_end", toolName, isError }, {}); +} + +async function markSuccessfulTool(pi: FakePi, toolName = "edit"): Promise { + await markTool(pi, toolName); +} + +async function startRun( + pi: FakePi, + messageType: "user" | "custom", +): Promise { + const handler = pi.handlers.get("before_agent_start")?.[0]; + assert.ok(handler, "before_agent_start handler is registered"); + await handler({ type: "before_agent_start", messageType }, {}); } function settleText(result: SettleResult): string { @@ -614,6 +635,151 @@ test("an aborted settle context requests no continuation for broken configuratio } }); +test("an aborted configuration-error settle burns no continuation and keeps the cycle armed", async () => { + const root = makeTempDir(); + try { + writeFile(root, ".pi/verify.json", '{"gates": ['); + const controller = new AbortController(); + const real = createSettlePolicy(); + let abortOnBegin = true; + const settle: SettlePolicy = { + noteSessionStart: () => real.noteSessionStart(), + noteRunStart: (messageType) => real.noteRunStart(messageType), + noteToolResult: (toolName, isError) => + real.noteToolResult(toolName, isError), + beginSettle: (aborted) => { + const action = real.beginSettle(aborted); + if (abortOnBegin) { + abortOnBegin = false; + controller.abort(); + } + return action; + }, + classify: (config, aborted) => real.classify(config, aborted), + completeSettle: (green, aborted) => real.completeSettle(green, aborted), + get dirty() { + return real.dirty; + }, + get continuationsUsed() { + return real.continuationsUsed; + }, + }; + const pi = makeAdapter({ settle }); + const context = makeContext(root, { + hasUI: true, + signal: controller.signal, + }); + + await markSuccessfulTool(pi); + assert.equal(await callSettle(pi, context), undefined); + assert.equal(settle.continuationsUsed, 0, "the aborted attempt burns no continuation"); + assert.equal(settle.dirty, true, "the aborted attempt leaves the cycle armed"); + assert.equal(context.ui.statuses.length, 0, "no red status is set"); + + const retry = makeContext(root, { hasUI: true }); + const result = await callSettle(pi, retry); + assert.ok(result, "the next settle sees the still-armed cycle"); + assert.equal(result.continue, true); + assert.match(settleText(result), /Malformed configuration/); + assert.equal(settle.continuationsUsed, 1, "the completed attempt burns exactly one"); + assert.equal(settle.dirty, false); + } finally { + cleanup(root); + } +}); + +test("an abort at settle entry runs no gates, requests no continuation, and leaves the cycle armed", async () => { + const root = makeTempDir(); + try { + writeGateConfig(root, [ + { + name: "on-settle check", + command: "printf 'ran\\n' > executed.txt", + on_settle: true, + }, + ]); + const pi = makeAdapter(); + const controller = new AbortController(); + controller.abort(); + const context = makeContext(root, { + hasUI: true, + signal: controller.signal, + }); + + await markSuccessfulTool(pi); + assert.equal(await callSettle(pi, context), undefined); + assert.equal(readMarker(root), "", "an aborted attempt executes no gate"); + assert.equal(context.ui.statuses.length, 0, "an aborted attempt sets no status"); + + context.signal = undefined; + assert.equal(await callSettle(pi, context), undefined); + assert.equal(readMarker(root), "ran\n", "the still-armed cycle re-runs the gates"); + } finally { + cleanup(root); + } +}); + +test("a custom-triggered run mid-budget does not reset the continuation budget", async () => { + const root = makeTempDir(); + try { + writeGateConfig(root, [ + { name: "red check", command: "exit 1", on_settle: true }, + ]); + const pi = makeAdapter(); + const context = makeContext(root, { hasUI: true }); + + for (let attempt = 1; attempt <= 3; attempt++) { + await startRun(pi, "custom"); + await markSuccessfulTool(pi); + const red = await callSettle(pi, context); + assert.ok(red, `attempt ${attempt} still has budget`); + assert.equal(red.continue, true); + } + + await startRun(pi, "custom"); + await markSuccessfulTool(pi); + assert.equal( + await callSettle(pi, context), + undefined, + "the custom run did not reset the spent budget", + ); + } finally { + cleanup(root); + } +}); + +test("mutation-capable tool ends arm the settle cycle while bash ends do not", async () => { + const cases = [ + { tool: "codemode", armed: true }, + { tool: "subagent", armed: true }, + { tool: "bash", armed: false }, + ]; + for (const { tool, armed } of cases) { + const root = makeTempDir(); + try { + writeGateConfig(root, [ + { + name: "on-settle check", + command: "printf 'ran\\n' > executed.txt", + on_settle: true, + }, + ]); + const pi = makeAdapter(); + const context = makeContext(root); + + await markSuccessfulTool(pi, tool); + assert.equal(await callSettle(pi, context), undefined); + assert.equal( + readMarker(root), + armed ? "ran\n" : "", + `${tool} ${armed ? "arms" : "does not arm"} the settle cycle`, + ); + } finally { + cleanup(root); + } + } +}); + test("settle skips normally for missing configuration, zero On-settle Gates, and untrusted projects", async () => { const cases: Array<{ name: string;