Package the verify extension as pi-verification v1.0.0
Turn the loose ~/.pi/agent/extensions/verify/ extension into an installable pi package: conventional extensions/ layout, explicit pi manifest, pi-package keyword, host packages as peerDependencies, and a vendored tla2tools.jar (TLA+ Tools 2.0) so the TLA+ tools work out of the box. Jar resolution gains the package vendor/ and ~/.pi/agent/vendor/ candidates; a local-path install replaces the old auto-discovered extension.
This commit is contained in:
commit
42de6c6931
13 files changed
+2554
No files matched your search
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
*.log
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"gates": [
|
||||
{
|
||||
"name": "typecheck",
|
||||
"command": "npm run check",
|
||||
"on_settle": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
## Agent skills
|
||||
|
||||
### Issue tracker
|
||||
|
||||
Issues are tracked as markdown files under `.scratch/<feature-slug>/` in this repo. See `docs/agents/issue-tracker.md`.
|
||||
|
||||
### Triage labels
|
||||
|
||||
The five canonical triage roles, using their default strings: `needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`. See `docs/agents/triage-labels.md`.
|
||||
|
||||
### Domain docs
|
||||
|
||||
Single-context: one `GLOSSARY.md` at the repo root, ADRs in `docs/adr/`. See `docs/agents/domain.md`.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Changelog
|
||||
|
||||
## [1.0.0] - 2026-11-23
|
||||
|
||||
First release as a pi package (previously a loose extension at `~/.pi/agent/extensions/verify/`).
|
||||
|
||||
- Ship `tla2tools.jar` (TLA+ Tools 2.0, 2024-08-08) in `vendor/` — the TLA+ tools work out of the box; no manual jar download needed.
|
||||
- Tools: `tla_check` (SANY parse check with PlusCal re-translation), `tlc` (TLC model check with counterexample traces), `run_gates` (deterministic gates from `.pi/verify.json`).
|
||||
- Hooks: auto-SANY after `.tla` edits, on-settle gates with red-gate continuation, test/spec deletion guard.
|
||||
- Command: `/verify [filter]`.
|
||||
- New jar resolution candidates: package `vendor/` and `~/.pi/agent/vendor/` (survives package updates), in addition to `.pi/verify.json` `tla2toolsJar`, `TLA2_TOOLS_JAR`, and project `vendor/`/`tools/`.
|
||||
@@ -0,0 +1,90 @@
|
||||
# pi-verification
|
||||
|
||||
A [pi](https://github.com/earendil-works/pi-coding-agent) package that folds verification into the agent loop: deterministic project gates that run themselves, and TLA+ tooling for design-level model checking.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pi install git:github.com/alex/pi-verification # from git (adjust URL)
|
||||
pi install npm:pi-verification # from npm
|
||||
pi install ./path/to/pi-verification # from a local path
|
||||
```
|
||||
|
||||
Requires Java 11+ for the TLA+ tools (the `tla2tools.jar` ships with the package):
|
||||
|
||||
```bash
|
||||
sudo apt-get install default-jre
|
||||
```
|
||||
|
||||
Then `/reload` (or restart pi).
|
||||
|
||||
## What you get
|
||||
|
||||
### Tools (callable by the agent)
|
||||
|
||||
- **`tla_check`** — SANY parse check for a `.tla` spec (fast; re-translates PlusCal algorithms).
|
||||
- **`tlc`** — model-check a spec with TLC. Needs a `<Spec>.cfg` with the finite model (`INIT`, `NEXT`, `INVARIANT`s). Returns PASS with statistics or FAIL with the counterexample state trace.
|
||||
- **`run_gates`** — run the project's gates from `.pi/verify.json`, per-gate pass/fail with output tails.
|
||||
|
||||
### 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.
|
||||
- **Gate-before-idle** (`agent_before_settle`): when the agent finishes a run that edited files, gates marked `"on_settle": true` run automatically. 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.
|
||||
- **Test/spec deletion guard** (`tool_call`): `rm` / `git rm` / `git clean` targeting test- or spec-looking paths asks for confirmation first (TUI mode only; headless allows).
|
||||
|
||||
### Command
|
||||
|
||||
- **`/verify [filter]`** — run gates on demand, report a green/red summary.
|
||||
|
||||
## Config: `.pi/verify.json` (project root)
|
||||
|
||||
```json
|
||||
{
|
||||
"gates": [
|
||||
{ "name": "typecheck", "command": "tsc --noEmit", "on_settle": true },
|
||||
{ "name": "lint", "command": "npm run lint", "on_settle": true },
|
||||
{ "name": "tests", "command": "npm test" },
|
||||
{ "name": "kani", "command": "cargo kani --output-format terse" }
|
||||
],
|
||||
"tla2toolsJar": "vendor/tla2tools.jar",
|
||||
"tlcTimeoutMs": 300000
|
||||
}
|
||||
```
|
||||
|
||||
- `on_settle: true` gates run automatically at agent-settle — they must be fast (seconds).
|
||||
- `tla2toolsJar` — path to `tla2tools.jar`; relative resolves against the project root.
|
||||
- `tlcTimeoutMs` — TLC timeout (default 300000); the `tlc` tool's `timeout_sec` param takes precedence when given.
|
||||
|
||||
### tla2tools.jar resolution order
|
||||
|
||||
1. `tla2toolsJar` in `.pi/verify.json`
|
||||
2. `TLA2_TOOLS_JAR` env var
|
||||
3. `vendor/tla2tools.jar` shipped inside this package
|
||||
4. `~/.pi/agent/vendor/tla2tools.jar` (user-level; survives package updates)
|
||||
5. `vendor/tla2tools.jar` and `tools/tla2tools.jar` in the project root
|
||||
|
||||
Without a jar, `tla_check`/`tlc` return setup instructions; everything else still works.
|
||||
|
||||
### Updating the vendored jar
|
||||
|
||||
```bash
|
||||
curl -L -o vendor/tla2tools.jar \
|
||||
https://github.com/tlaplus/tlaplus/releases/latest/download/tla2tools.jar
|
||||
```
|
||||
|
||||
Currently vendored: TLA+ Tools 2.0 (2024-08-08). The jar is MIT-licensed ([tlaplus/tlaplus](https://github.com/tlaplus/tlaplus)).
|
||||
|
||||
## Design notes
|
||||
|
||||
Enforcement belongs in the deterministic layer, never in prose: agents must iterate on red gates before handoff, and deleting tests to get green is the classic agent failure mode — so the hooks enforce both instead of asking nicely. Gates are plain shell commands; TLA+ specs are checked exhaustively by TLC over all interleavings of a small instance, the failure mode example tests cannot enumerate.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
npm install # devDependencies for typechecking
|
||||
npm run check # tsc --noEmit
|
||||
```
|
||||
|
||||
This repo dogfoods itself: `.pi/verify.json` runs the typecheck gate on settle.
|
||||
|
||||
Companion skills (kept separate, user-level): `verification-doctrine` and `tla-plus`.
|
||||
@@ -0,0 +1,51 @@
|
||||
# Domain Docs
|
||||
|
||||
How the engineering skills should consume this repo's domain documentation when exploring the codebase.
|
||||
|
||||
## Before exploring, read these
|
||||
|
||||
- **`GLOSSARY.md`** at the repo root, or
|
||||
- **`GLOSSARY-MAP.md`** at the repo root if it exists: it points at one `GLOSSARY.md` per context. Read each one relevant to the topic.
|
||||
- **`docs/adr/`**: read ADRs that touch the area you're about to work in. In multi-context repos, also check `src/<context>/docs/adr/` for context-scoped decisions.
|
||||
|
||||
If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/skill:domain-modeling` skill (reached via `/skill:grill-with-docs` and `/skill:improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved.
|
||||
|
||||
## File structure
|
||||
|
||||
Single-context repo (most repos):
|
||||
|
||||
```
|
||||
/
|
||||
├── GLOSSARY.md
|
||||
├── docs/adr/
|
||||
│ ├── 0001-event-sourced-orders.md
|
||||
│ └── 0002-postgres-for-write-model.md
|
||||
└── src/
|
||||
```
|
||||
|
||||
Multi-context repo (presence of `GLOSSARY-MAP.md` at the root):
|
||||
|
||||
```
|
||||
/
|
||||
├── GLOSSARY-MAP.md
|
||||
├── docs/adr/ ← system-wide decisions
|
||||
└── src/
|
||||
├── ordering/
|
||||
│ ├── GLOSSARY.md
|
||||
│ └── docs/adr/ ← context-specific decisions
|
||||
└── billing/
|
||||
├── GLOSSARY.md
|
||||
└── docs/adr/
|
||||
```
|
||||
|
||||
## Use the glossary's vocabulary
|
||||
|
||||
When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `GLOSSARY.md`. Don't drift to synonyms the glossary explicitly avoids.
|
||||
|
||||
If the concept you need isn't in the glossary yet, that's a signal: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/skill:domain-modeling`).
|
||||
|
||||
## Flag ADR conflicts
|
||||
|
||||
If your output contradicts an existing ADR, surface it explicitly rather than silently overriding:
|
||||
|
||||
> _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_
|
||||
@@ -0,0 +1,30 @@
|
||||
# Issue tracker: Local Markdown
|
||||
|
||||
Issues and specs for this repo live as markdown files in `.scratch/`.
|
||||
|
||||
## Conventions
|
||||
|
||||
- One feature per directory: `.scratch/<feature-slug>/`
|
||||
- The spec is `.scratch/<feature-slug>/spec.md`
|
||||
- Implementation issues are one file per ticket at `.scratch/<feature-slug>/issues/<NN>-<slug>.md`, numbered from `01`, never a single combined tickets file
|
||||
- Triage state is recorded as a `Status:` line near the top of each issue file (see `triage-labels.md` for the role strings)
|
||||
- Comments and conversation history append to the bottom of the file under a `## Comments` heading
|
||||
|
||||
## When a skill says "publish to the issue tracker"
|
||||
|
||||
Create a new file under `.scratch/<feature-slug>/` (creating the directory if needed).
|
||||
|
||||
## When a skill says "fetch the relevant ticket"
|
||||
|
||||
Read the file at the referenced path. The user will normally pass the path or the issue number directly.
|
||||
|
||||
## Wayfinding operations
|
||||
|
||||
Used by `/skill:wayfinder`. The **map** is a file with one **child** file per ticket.
|
||||
|
||||
- **Map**: `.scratch/<effort>/map.md` (the Notes / Decisions-so-far / Fog body).
|
||||
- **Child ticket**: `.scratch/<effort>/issues/NN-<slug>.md`, numbered from `01`, with the question in the body. A `Type:` line records the ticket type (`research`/`prototype`/`grilling`/`task`); a `Status:` line records `claimed`/`resolved`.
|
||||
- **Blocking**: a `Blocked by: NN, NN` line near the top. A ticket is unblocked when every file it lists is `resolved`.
|
||||
- **Frontier**: scan `.scratch/<effort>/issues/` for files that are open, unblocked, and unclaimed; first by number wins.
|
||||
- **Claim**: set `Status: claimed` and save before any work.
|
||||
- **Resolve**: append the answer under an `## Answer` heading, set `Status: resolved`, then append a context pointer (gist + link) to the map's Decisions-so-far in `map.md`.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Triage Labels
|
||||
|
||||
The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker.
|
||||
|
||||
| Label in mattpocock/skills | Label in our tracker | Meaning |
|
||||
| -------------------------- | -------------------- | ---------------------------------------- |
|
||||
| `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue |
|
||||
| `needs-info` | `needs-info` | Waiting on reporter for more information |
|
||||
| `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent |
|
||||
| `ready-for-human` | `ready-for-human` | Requires human implementation |
|
||||
| `wontfix` | `wontfix` | Will not be actioned |
|
||||
|
||||
When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table.
|
||||
|
||||
Edit the "Label in our tracker" column to match whatever vocabulary you actually use.
|
||||
@@ -0,0 +1,581 @@
|
||||
/**
|
||||
* Verify Extension — fold verification into the agent loop.
|
||||
*
|
||||
* Tools:
|
||||
* - tla_check: SANY parse check for TLA+ specs (fast; translates PlusCal)
|
||||
* - tlc: TLC model check with counterexample traces
|
||||
* - run_gates: run the project's deterministic gates from .pi/verify.json
|
||||
*
|
||||
* Hooks:
|
||||
* - tool_result on edit/write of *.tla: auto-run SANY, append the verdict to
|
||||
* the tool result so the agent sees parse errors immediately
|
||||
* - agent_before_settle: run gates marked "on_settle": true; if any is red,
|
||||
* inject the failures and request one continuation (bounded per prompt)
|
||||
* - tool_call (bash): confirm before deleting test/spec files (rm, git rm)
|
||||
*
|
||||
* Command:
|
||||
* - /verify [filter]: run gates on demand and report
|
||||
*
|
||||
* Config: .pi/verify.json in the project root — see README.md.
|
||||
*
|
||||
* The package ships tla2tools.jar in vendor/ (TLA+ Tools, MIT license); jar
|
||||
* resolution order: .pi/verify.json `tla2toolsJar`, TLA2_TOOLS_JAR env var,
|
||||
* this package's vendor/, ~/.pi/agent/vendor/, then project vendor/ and
|
||||
* tools/ directories.
|
||||
*
|
||||
* Hardened by exhaustive live testing: JVM tools run via execFile directly
|
||||
* (kills hit the JVM, no bash orphans), each TLC run gets an isolated metadir
|
||||
* (parallel runs can't collide), PlusCal is re-translated whenever an
|
||||
* algorithm is present (no stale translations), and pcal.trans runs with
|
||||
* -nocfg so it never mutates the user's .cfg files.
|
||||
*/
|
||||
|
||||
import { execFile } from "node:child_process";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
||||
import { Type } from "typebox";
|
||||
|
||||
const EXT_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const GATE_TIMEOUT_MS = 120_000;
|
||||
const TLC_TIMEOUT_MS = 300_000;
|
||||
const SANY_TIMEOUT_MS = 60_000;
|
||||
const MAX_SETTLE_CONTINUATIONS = 3;
|
||||
|
||||
const SETUP_TEXT = [
|
||||
"TLA+ toolchain not found. To set it up:",
|
||||
" 1. Install Java 11+ (e.g. `sudo apt-get install default-jre`)",
|
||||
" 2. Download tla2tools.jar:",
|
||||
" curl -L --create-dirs -o ~/.pi/agent/vendor/tla2tools.jar \\",
|
||||
" https://github.com/tlaplus/tlaplus/releases/latest/download/tla2tools.jar",
|
||||
" Or set `tla2toolsJar` in .pi/verify.json, or the TLA2_TOOLS_JAR env var.",
|
||||
].join("\n");
|
||||
|
||||
const NO_GATES_TEXT = [
|
||||
"No gates configured. Add a `.pi/verify.json` in the project root:",
|
||||
"",
|
||||
" {",
|
||||
' "gates": [',
|
||||
' { "name": "typecheck", "command": "tsc --noEmit", "on_settle": true },',
|
||||
' { "name": "lint", "command": "npm run lint", "on_settle": true },',
|
||||
' { "name": "tests", "command": "npm test" }',
|
||||
" ]",
|
||||
" }",
|
||||
"",
|
||||
"Gates with \"on_settle\": true also run automatically when the agent finishes",
|
||||
"its run; they must be fast (seconds, not minutes). `tlc`/`kani`-style gates",
|
||||
"belong in the list without on_settle, run via run_gates or CI.",
|
||||
].join("\n");
|
||||
|
||||
interface Gate {
|
||||
name: string;
|
||||
command: string;
|
||||
/** Also run automatically on agent_before_settle. Must be fast. Default false. */
|
||||
on_settle?: boolean;
|
||||
/** Per-gate timeout in ms. Default 120000. */
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
interface VerifyConfig {
|
||||
gates?: Gate[];
|
||||
/** Path to tla2tools.jar (relative paths resolve against the project root). */
|
||||
tla2toolsJar?: string;
|
||||
/** TLC timeout in ms. Default 300000. */
|
||||
tlcTimeoutMs?: number;
|
||||
}
|
||||
|
||||
interface ConfigResult {
|
||||
config: VerifyConfig;
|
||||
/** Set when .pi/verify.json exists but doesn't parse. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface RunResult {
|
||||
code: number;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
timedOut: boolean;
|
||||
}
|
||||
|
||||
interface GateResult {
|
||||
name: string;
|
||||
ok: boolean;
|
||||
code: number;
|
||||
timedOut: boolean;
|
||||
ms: number;
|
||||
output: string;
|
||||
}
|
||||
|
||||
function loadConfig(root: string): ConfigResult {
|
||||
const file = path.join(root, ".pi", "verify.json");
|
||||
let raw: string;
|
||||
try {
|
||||
raw = fs.readFileSync(file, "utf8");
|
||||
} catch {
|
||||
return { config: {} };
|
||||
}
|
||||
try {
|
||||
return { config: JSON.parse(raw) as VerifyConfig };
|
||||
} catch (e) {
|
||||
return { config: {}, error: `Malformed .pi/verify.json (${(e as Error).message}). Fix it before gates can run.` };
|
||||
}
|
||||
}
|
||||
|
||||
function tail(s: string, max: number): string {
|
||||
const cleaned = s.replace(/[\b\r]/g, "");
|
||||
if (cleaned.length <= max) return cleaned;
|
||||
return "…\n" + cleaned.slice(cleaned.length - max);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shell command runner (gates). Node's timeout error message text varies by
|
||||
* version, so timeouts are detected via the `killed` flag, not the message.
|
||||
*/
|
||||
function run(command: string, cwd: string, timeoutMs: number, signal?: AbortSignal): Promise<RunResult> {
|
||||
return new Promise((resolve) => {
|
||||
execFile(
|
||||
"bash",
|
||||
["-c", command],
|
||||
{ cwd, timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 20_000_000, signal },
|
||||
(err, stdout, stderr) => {
|
||||
const e = err as (Error & { code?: number | string; killed?: boolean }) | null;
|
||||
const aborted = signal?.aborted === true;
|
||||
const timedOut = !!e && e.killed === true && !aborted;
|
||||
const code = e ? (typeof e.code === "number" ? e.code : 1) : 0;
|
||||
resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), timedOut });
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* JVM tool runner (SANY, pcal.trans, TLC). Runs java directly — no shell
|
||||
* wrapper — so a timeout kill terminates the JVM itself, and argument
|
||||
* quoting can never break.
|
||||
*/
|
||||
function runJava(jar: string, mainArgs: string[], cwd: string, timeoutMs: number, signal?: AbortSignal): Promise<RunResult> {
|
||||
return new Promise((resolve) => {
|
||||
const args = ["-XX:+UseParallelGC", "-cp", jar, ...mainArgs];
|
||||
execFile(
|
||||
"java",
|
||||
args,
|
||||
{ cwd, timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 20_000_000, signal },
|
||||
(err, stdout, stderr) => {
|
||||
const e = err as (Error & { code?: number | string; killed?: boolean }) | null;
|
||||
const aborted = signal?.aborted === true;
|
||||
const timedOut = !!e && e.killed === true && !aborted;
|
||||
const code = e ? (typeof e.code === "number" ? e.code : 1) : 0;
|
||||
resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), timedOut });
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let javaOk: boolean | null = null;
|
||||
async function hasJava(): Promise<boolean> {
|
||||
if (javaOk === null) {
|
||||
const r = await run("java -version", process.cwd(), 15_000);
|
||||
javaOk = r.code === 0 && !r.timedOut;
|
||||
}
|
||||
return javaOk;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nearest enclosing package root for this module — the package's own
|
||||
* vendor/ (with the shipped jar) lives there. Null when the extension runs
|
||||
* loose, outside any package.
|
||||
*/
|
||||
function findPackageRoot(): string | null {
|
||||
let dir = EXT_DIR;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const pkg = path.join(dir, "package.json");
|
||||
if (fs.existsSync(pkg)) return dir;
|
||||
const parent = path.dirname(dir);
|
||||
if (parent === dir) break;
|
||||
dir = parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveJar(root: string, cfg: VerifyConfig): string | null {
|
||||
const pkgRoot = findPackageRoot();
|
||||
const candidates = [
|
||||
cfg.tla2toolsJar,
|
||||
process.env.TLA2_TOOLS_JAR,
|
||||
// The jar shipped inside this package (vendor/ next to package.json).
|
||||
pkgRoot ? path.join(pkgRoot, "vendor", "tla2tools.jar") : undefined,
|
||||
// Loose-layout fallback: vendor/ next to the extension file.
|
||||
path.join(EXT_DIR, "vendor", "tla2tools.jar"),
|
||||
// User-level shared jar, survives package updates.
|
||||
path.join(os.homedir(), ".pi", "agent", "vendor", "tla2tools.jar"),
|
||||
path.join(root, "vendor", "tla2tools.jar"),
|
||||
path.join(root, "tools", "tla2tools.jar"),
|
||||
].filter((c): c is string => typeof c === "string" && c.length > 0);
|
||||
for (const c of candidates) {
|
||||
const abs = path.isAbsolute(c) ? c : path.resolve(root, c);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** True when the spec contains a PlusCal algorithm (translated or not). */
|
||||
function hasPlusCalAlgorithm(specPath: string): boolean {
|
||||
try {
|
||||
return /--(fair )?algorithm/.test(fs.readFileSync(specPath, "utf8"));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-translate PlusCal whenever an algorithm is present. pcal.trans replaces
|
||||
* prior translations, so this is safe on already-translated files — and
|
||||
* required, otherwise algorithm edits check a stale translation. -nocfg keeps
|
||||
* the translator from prepending `SPECIFICATION Spec` into the user's cfg.
|
||||
*/
|
||||
function translatePlusCal(jar: string, specAbs: string, signal?: AbortSignal): Promise<RunResult> {
|
||||
return runJava(jar, ["pcal.trans", "-nocfg", specAbs], path.dirname(specAbs), SANY_TIMEOUT_MS, signal);
|
||||
}
|
||||
|
||||
/** SANY parse of a single spec file. */
|
||||
function sany(jar: string, specAbs: string, signal?: AbortSignal): Promise<RunResult> {
|
||||
return runJava(jar, ["tla2sany.SANY", specAbs], path.dirname(specAbs), SANY_TIMEOUT_MS, signal);
|
||||
}
|
||||
|
||||
function okResult(text: string) {
|
||||
return { content: [{ type: "text" as const, text }], details: {} };
|
||||
}
|
||||
|
||||
function errResult(text: string) {
|
||||
return { content: [{ type: "text" as const, text }], details: {}, isError: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract TLC's error report. Semantic/parsing errors print their detail
|
||||
* *before* the `Error:` summary line, so include preceding context too.
|
||||
*/
|
||||
function extractTlcErrors(out: string): string {
|
||||
const idx = out.search(/(^|\n)Error:/);
|
||||
if (idx >= 0) {
|
||||
const start = Math.max(0, idx - 800);
|
||||
return tail(out.slice(start), 8000);
|
||||
}
|
||||
return tail(out, 4000);
|
||||
}
|
||||
|
||||
async function runGates(root: string, filter?: string, signal?: AbortSignal, onlyOnSettle = false): Promise<GateResult[]> {
|
||||
const { config } = loadConfig(root);
|
||||
const gates = (config.gates ?? [])
|
||||
.filter((g) => (onlyOnSettle ? g.on_settle === true : true))
|
||||
.filter((g) => !filter || g.name.toLowerCase().includes(filter.toLowerCase()));
|
||||
const results: GateResult[] = [];
|
||||
for (const g of gates) {
|
||||
if (typeof g.name !== "string" || typeof g.command !== "string" || !g.name || !g.command) {
|
||||
results.push({
|
||||
name: String(g.name ?? "(unnamed)"),
|
||||
ok: false,
|
||||
code: -1,
|
||||
timedOut: false,
|
||||
ms: 0,
|
||||
output: "Invalid gate: needs string `name` and `command`.",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const started = Date.now();
|
||||
const r = await run(g.command, root, g.timeoutMs ?? GATE_TIMEOUT_MS, signal);
|
||||
results.push({
|
||||
name: g.name,
|
||||
ok: r.code === 0 && !r.timedOut,
|
||||
code: r.code,
|
||||
timedOut: r.timedOut,
|
||||
ms: Date.now() - started,
|
||||
output: tail((r.stdout + (r.stderr ? `\n${r.stderr}` : "")).trim(), 3000),
|
||||
});
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
function formatGateResults(results: GateResult[], ms: number): string {
|
||||
const green = results.filter((r) => r.ok).length;
|
||||
const header = `Gates: ${green}/${results.length} green (${(ms / 1000).toFixed(1)}s total)`;
|
||||
const lines = results.map((r) => {
|
||||
const status = r.ok ? "✓" : r.timedOut ? "⏱" : "✗";
|
||||
const line = `${status} ${r.name} (${(r.ms / 1000).toFixed(1)}s)`;
|
||||
return r.ok ? line : `${line}${r.timedOut ? " — timed out" : ""}\n${r.output}`;
|
||||
});
|
||||
return [header, "", ...lines].join("\n");
|
||||
}
|
||||
|
||||
export default function verifyExtension(pi: ExtensionAPI) {
|
||||
// ------------------------------------------------------------------ tools
|
||||
|
||||
pi.registerTool({
|
||||
name: "tla_check",
|
||||
label: "TLA+ parse check",
|
||||
description:
|
||||
"Parse a TLA+ spec with SANY — fast syntax and basic semantic checks, no model checking. Runs automatically after .tla edits; call it directly to re-check or see error details. Re-translates PlusCal algorithms when present (so SANY OK ≠ model-checkable; only tlc checks the full semantics).",
|
||||
parameters: Type.Object({
|
||||
spec: Type.String({ description: "Path to the .tla file, relative to the working directory" }),
|
||||
}),
|
||||
async execute(_toolCallId, params, signal) {
|
||||
const root = process.cwd();
|
||||
const file = path.resolve(root, params.spec);
|
||||
if (!fs.existsSync(file)) return errResult(`File not found: ${params.spec}`);
|
||||
const { config } = loadConfig(root);
|
||||
const jar = resolveJar(root, config);
|
||||
if (!jar) return errResult(SETUP_TEXT);
|
||||
if (!(await hasJava())) return errResult("Java not found on PATH. Install Java 11+ (e.g. `sudo apt-get install default-jre`).");
|
||||
if (hasPlusCalAlgorithm(file)) {
|
||||
const t = await translatePlusCal(jar, file, signal);
|
||||
if (t.code !== 0) return errResult(`PlusCal translation failed:\n${tail(t.stdout + t.stderr, 4000)}`);
|
||||
}
|
||||
const r = await sany(jar, file, signal);
|
||||
if (r.timedOut) return errResult("SANY timed out.");
|
||||
if (r.code === 0) return okResult(`SANY: ${path.basename(file)} parsed OK (no syntax/semantic errors).`);
|
||||
return errResult(`SANY found parse errors in ${path.basename(file)}:\n\n${tail(r.stdout + r.stderr, 4000)}`);
|
||||
},
|
||||
});
|
||||
|
||||
pi.registerTool({
|
||||
name: "tlc",
|
||||
label: "TLC model check",
|
||||
description:
|
||||
"Model-check a TLA+ spec with TLC: exhaustively explores the finite model in the .cfg and checks every invariant/property. Returns PASS with statistics, or FAIL with the counterexample state trace. Check designs before implementing them.",
|
||||
parameters: Type.Object({
|
||||
spec: Type.String({ description: "Path to the .tla file" }),
|
||||
cfg: Type.Optional(Type.String({ description: "Model config path (default: <spec>.cfg next to the spec; relative paths resolve against the spec's directory)" })),
|
||||
ignore_deadlock: Type.Optional(Type.Boolean({ description: "Don't report deadlocked states as errors (default false)" })),
|
||||
timeout_sec: Type.Optional(Type.Number({ description: "Timeout in seconds, default 300, max 900" })),
|
||||
}),
|
||||
async execute(_toolCallId, params, signal) {
|
||||
const root = process.cwd();
|
||||
const spec = path.resolve(root, params.spec);
|
||||
if (!fs.existsSync(spec)) return errResult(`Spec not found: ${params.spec}`);
|
||||
const specDir = path.dirname(spec);
|
||||
const cfgFile = params.cfg ? path.resolve(specDir, params.cfg) : spec.replace(/\.tla$/, ".cfg");
|
||||
if (!fs.existsSync(cfgFile)) {
|
||||
return errResult(
|
||||
`Model config not found: ${path.relative(root, cfgFile)}.\nTLC needs a .cfg defining the finite model (INIT, NEXT, INVARIANT, PROPERTY — or SPECIFICATION Spec for translated PlusCal). Keep it small: 3 nodes, 2 clients, values {0,1,2}.`,
|
||||
);
|
||||
}
|
||||
const { config } = loadConfig(root);
|
||||
const jar = resolveJar(root, config);
|
||||
if (!jar) return errResult(SETUP_TEXT);
|
||||
if (!(await hasJava())) return errResult("Java not found on PATH. Install Java 11+ (e.g. `sudo apt-get install default-jre`).");
|
||||
if (hasPlusCalAlgorithm(spec)) {
|
||||
const t = await translatePlusCal(jar, spec, signal);
|
||||
if (t.code !== 0) return errResult(`PlusCal translation failed:\n${tail(t.stdout + t.stderr, 4000)}`);
|
||||
}
|
||||
const requestedSec = Math.min(Math.max(params.timeout_sec ?? 300, 10), 900);
|
||||
const effectiveTimeout = params.timeout_sec
|
||||
? requestedSec * 1000 + 15_000
|
||||
: (config.tlcTimeoutMs ?? TLC_TIMEOUT_MS);
|
||||
// Isolated metadir per run: parallel TLC invocations can never
|
||||
// collide on TLC's timestamp-based states directories.
|
||||
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), "tlc-"));
|
||||
try {
|
||||
const args = ["tlc2.TLC"];
|
||||
if (params.ignore_deadlock) args.push("-deadlock");
|
||||
args.push("-config", path.relative(specDir, cfgFile), "-workers", "auto", "-metadir", workDir, path.basename(spec));
|
||||
const r = await runJava(jar, args, specDir, effectiveTimeout, signal);
|
||||
if (r.timedOut) {
|
||||
return errResult(
|
||||
`TLC exceeded its ${requestedSec}s budget. Shrink the model (fewer nodes/values) or raise timeout_sec.`,
|
||||
);
|
||||
}
|
||||
const out = r.stdout + (r.stderr ? `\n${r.stderr}` : "");
|
||||
const violated = /(^|\n)Error:|is violated|Deadlock (reached|detected)|Temporal properties were violated/i.test(out);
|
||||
if (!violated && (/No errors? (?:have|has) been found/i.test(out) || /Model checking completed/i.test(out))) {
|
||||
return okResult(`TLC: PASS — model checking completed, all invariants hold.\n\n${tail(out, 1200)}`);
|
||||
}
|
||||
return errResult(
|
||||
`TLC: FAIL — the model violates a checked property. Read the state trace: fix the design (or the spec if the model is wrong), then re-run.\n\n${extractTlcErrors(out)}`,
|
||||
);
|
||||
} finally {
|
||||
try {
|
||||
fs.rmSync(workDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// best-effort cleanup of the temp metadir
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
pi.registerTool({
|
||||
name: "run_gates",
|
||||
label: "Run verification gates",
|
||||
description:
|
||||
"Run the project's deterministic verification gates from .pi/verify.json (typecheck, lint, tests, proof harnesses). Per-gate pass/fail with output. Run after changes and before claiming done — done means gates green. Use the filter param for a subset.",
|
||||
parameters: Type.Object({
|
||||
filter: Type.Optional(Type.String({ description: "Only run gates whose name contains this substring" })),
|
||||
}),
|
||||
async execute(_toolCallId, params, signal) {
|
||||
const root = process.cwd();
|
||||
const { config, error } = loadConfig(root);
|
||||
if (error) return errResult(error);
|
||||
if (!config.gates || config.gates.length === 0) return errResult(NO_GATES_TEXT);
|
||||
const started = Date.now();
|
||||
const results = await runGates(root, params.filter, signal);
|
||||
if (results.length === 0) return errResult(`No gates match filter "${params.filter}".`);
|
||||
const text = formatGateResults(results, Date.now() - started);
|
||||
return results.every((r) => r.ok)
|
||||
? okResult(text)
|
||||
: { content: [{ type: "text" as const, text }], details: {}, isError: true };
|
||||
},
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ hooks
|
||||
|
||||
// Auto-SANY: after any edit/write of a .tla file, parse it and append the verdict.
|
||||
pi.on("tool_result", async (event) => {
|
||||
if (event.isError) return;
|
||||
if (event.toolName !== "edit" && event.toolName !== "write") return;
|
||||
const file = String((event.input as { path?: string } | undefined)?.path ?? "");
|
||||
if (!file.endsWith(".tla")) return;
|
||||
const root = process.cwd();
|
||||
const abs = path.resolve(root, file);
|
||||
if (!fs.existsSync(abs)) return;
|
||||
const { config } = loadConfig(root);
|
||||
const jar = resolveJar(root, config);
|
||||
if (!jar || !(await hasJava())) return; // silent: tla_check reports setup guidance
|
||||
let note: string;
|
||||
if (hasPlusCalAlgorithm(abs)) {
|
||||
const t = await translatePlusCal(jar, abs);
|
||||
if (t.code !== 0) {
|
||||
note = `tla_check (auto): PlusCal translation failed — call tla_check for details:\n${tail(t.stdout + t.stderr, 1500)}`;
|
||||
} else {
|
||||
const r = await sany(jar, abs);
|
||||
note =
|
||||
r.timedOut || r.code === 0
|
||||
? "tla_check (auto): PlusCal re-translated; SANY parsed OK."
|
||||
: `tla_check (auto): PlusCal re-translated; SANY found parse errors — fix before model checking:\n${tail(r.stdout + r.stderr, 2000)}`;
|
||||
}
|
||||
} else {
|
||||
const r = await sany(jar, abs);
|
||||
if (r.timedOut) return;
|
||||
note =
|
||||
r.code === 0
|
||||
? "tla_check (auto): SANY parsed OK."
|
||||
: `tla_check (auto): SANY found parse errors — fix before model checking:\n${tail(r.stdout + r.stderr, 2000)}`;
|
||||
}
|
||||
const content = Array.isArray(event.content)
|
||||
? [...event.content, { type: "text" as const, text: note }]
|
||||
: [{ type: "text" as const, text: String(event.content ?? "") }, { type: "text" as const, text: note }];
|
||||
return { content };
|
||||
});
|
||||
|
||||
// Confirm before deleting test/spec files via bash.
|
||||
pi.on("tool_call", async (event, ctx) => {
|
||||
if (event.toolName !== "bash") return;
|
||||
const command = String((event.input as { command?: string } | undefined)?.command ?? "");
|
||||
if (!/(^|\s)(rm|git rm|git clean)\b/.test(command)) return;
|
||||
const tokens = command.split(/\s+/).map((t) => t.replace(/^["']+|["']+$/g, ""));
|
||||
const testish = /(^|[\/\\])(tests?|__tests__|spec)([\/\\]|$)|[\/\\._-](test|spec|_test|_spec)\.[a-z]+$/i;
|
||||
const targets = tokens.filter((t) => testish.test(t) && /[\/\\]/.test(t));
|
||||
if (targets.length === 0) return;
|
||||
if (!ctx.hasUI) return; // headless: cannot confirm, allow
|
||||
const allowed = await ctx.ui.confirm(
|
||||
"Test/spec deletion",
|
||||
`The agent wants to delete test or spec files:\n${targets.join("\n")}\n\nAllow this deletion?`,
|
||||
);
|
||||
if (allowed) return;
|
||||
return {
|
||||
block: true,
|
||||
reason:
|
||||
"Blocked: deleting tests/specs to get green is not allowed without explicit approval. Fix the code, or fix the test. If the file is genuinely obsolete, ask the user to remove it directly.",
|
||||
};
|
||||
});
|
||||
|
||||
// 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;
|
||||
});
|
||||
|
||||
pi.on("before_agent_start", (event) => {
|
||||
if (event.messageType === "user") {
|
||||
dirty = false;
|
||||
settleContinuations = 0;
|
||||
}
|
||||
});
|
||||
|
||||
pi.on("tool_execution_end", (event) => {
|
||||
if ((event.toolName === "edit" || event.toolName === "write") && !event.isError) dirty = true;
|
||||
});
|
||||
|
||||
pi.on("agent_before_settle", async (event, ctx) => {
|
||||
if (!dirty || settleContinuations >= MAX_SETTLE_CONTINUATIONS) return;
|
||||
const root = process.cwd();
|
||||
const { config, error } = loadConfig(root);
|
||||
if (error) return; // run_gates and /verify surface the error; don't nag on settle
|
||||
const settleGates = (config.gates ?? []).filter((g) => g.on_settle === true);
|
||||
if (settleGates.length === 0) return;
|
||||
dirty = false; // this cycle re-arms only when new edits land
|
||||
const signal = (ctx as { signal?: AbortSignal }).signal;
|
||||
const results = await runGates(root, undefined, signal, true);
|
||||
if (signal?.aborted) return;
|
||||
const failed = results.filter((r) => !r.ok);
|
||||
if (failed.length === 0) {
|
||||
if (ctx.hasUI) ctx.ui.setStatus("verify", "");
|
||||
return;
|
||||
}
|
||||
settleContinuations++;
|
||||
const report = failed
|
||||
.map((r) => `### ${r.name} — ${r.timedOut ? "TIMED OUT" : `FAILED (exit ${r.code})`}\n${r.output}`)
|
||||
.join("\n\n");
|
||||
const msg = [
|
||||
"The verification gates are red. Fix the failures below, then re-run run_gates (or the failing commands) and confirm green before reporting done.",
|
||||
"Do not weaken or delete gates, tests, or specs to get green.",
|
||||
"",
|
||||
report,
|
||||
].join("\n");
|
||||
if (ctx.hasUI) ctx.ui.setStatus("verify", `gates red: ${failed.map((f) => f.name).join(", ")}`);
|
||||
return {
|
||||
entries: [
|
||||
...event.entries,
|
||||
{ type: "custom_message" as const, customType: "verify-gates", content: msg, display: true },
|
||||
],
|
||||
continue: true,
|
||||
};
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ command
|
||||
|
||||
pi.registerCommand("verify", {
|
||||
description: "Run the project's verification gates (.pi/verify.json) and report",
|
||||
handler: async (args, ctx) => {
|
||||
const root = process.cwd();
|
||||
const { config, error } = loadConfig(root);
|
||||
if (error) {
|
||||
if (ctx.hasUI) ctx.ui.notify(error, "error");
|
||||
else console.log(error);
|
||||
return;
|
||||
}
|
||||
if (!config.gates || config.gates.length === 0) {
|
||||
if (ctx.hasUI) ctx.ui.notify("No gates configured in .pi/verify.json", "error");
|
||||
else console.log(NO_GATES_TEXT);
|
||||
return;
|
||||
}
|
||||
if (ctx.hasUI) ctx.ui.setStatus("verify", "running gates…");
|
||||
const started = Date.now();
|
||||
const results = await runGates(root, args || undefined);
|
||||
if (ctx.hasUI) ctx.ui.setStatus("verify", "");
|
||||
const summary = results.map((r) => `${r.ok ? "✓" : "✗"} ${r.name}`).join(" ");
|
||||
const green = results.every((r) => r.ok);
|
||||
if (ctx.hasUI) {
|
||||
ctx.ui.notify(
|
||||
green ? `Gates green (${((Date.now() - started) / 1000).toFixed(1)}s): ${summary}` : `Gates RED: ${summary} — use run_gates for output`,
|
||||
green ? "info" : "error",
|
||||
);
|
||||
} else {
|
||||
console.log(formatGateResults(results, Date.now() - started));
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
Generated
+1701
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "pi-verification",
|
||||
"version": "1.0.0",
|
||||
"description": "Verification gates and TLA+ tooling for pi — fold verification into the agent loop.",
|
||||
"type": "module",
|
||||
"keywords": [
|
||||
"pi-package",
|
||||
"pi-extension",
|
||||
"tla-plus",
|
||||
"model-checking",
|
||||
"verification"
|
||||
],
|
||||
"files": [
|
||||
"extensions",
|
||||
"vendor",
|
||||
"CHANGELOG.md",
|
||||
"README.md"
|
||||
],
|
||||
"pi": {
|
||||
"extensions": [
|
||||
"./extensions/verify.ts"
|
||||
]
|
||||
},
|
||||
"scripts": {
|
||||
"check": "tsc --noEmit"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@earendil-works/pi-coding-agent": "*",
|
||||
"typebox": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@earendil-works/pi-coding-agent": "1.6.0",
|
||||
"@types/node": "^26.1.2",
|
||||
"typebox": "^1.4.7",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"lib": ["ES2022"],
|
||||
"types": ["node"],
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["extensions/**/*.ts"]
|
||||
}
|
||||
Vendored
BIN
Binary file not shown.
Reference in new issue
Block a user