diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bcb42f..bccfa48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ All notable project changes are recorded here. Dates use ISO 8601 (`YYYY-MM-DD`) ### Added - `proofline contract decompose [--out ] [--against a.json,b.json] [--check] [--lint-warn]` turns a scope file (`proofline-scope/1`: an id prefix, tasks with title, acceptance checks, requirement ids, dependencies and an owner placeholder, plus shared defaults and criteria put before or after each task's own) into an unsigned proposal that `contract merge` accepts. The output is byte-stable: fixed key order, criterion ids `-AC01...`, two-space JSON and a final newline, and the command prints its sha256. A duplicate id (in the scope or in an `--against` contract), an unknown dependency, a cycle and a task `contract validate` would refuse are refused and nothing is written. It never writes `proofline.json` or a `.sig`. `--check` exits 1 when the `--out` file differs from what the scope gives. `docs/DECOMPOSITION.md` describes the process from scope file to proposal PR, fold with `merge`, `sign` and `verify-sig`, with a CI job. The toy fixture is `fixtures/decompose/`. +- Contract-mode `proofline receipt ` reruns a task's checks, records revision-bound evidence in a v1 in-toto predicate, signs the envelope with the configured agentkey role, and writes it under `.proofline/receipts/`. Without a usable role key it emits an unsigned L0 receipt, explains the reason on stderr, and preserves the verifier exit code. +- The receipt schema describes contract evidence, subject binding, public/private repository naming, and the distinction between L0 unsigned and L1 agent-signed receipts. The no-task zero-config receipt path remains available. + +### Fixed +- Isolation no longer claims success when the container runtime or pinned image cannot run its Node version probe; unavailable runtimes block the check instead of recording `node=unknown` as isolated. +- Zero-config suite inference tests a toolchain by running its version command, not by checking whether a path exists. Broken launchers, such as a pytest script whose interpreter is missing, are treated as unavailable. ## 0.2.0-next.2 (2026-10-21) diff --git a/README.md b/README.md index 357b8fa..fbf7fa5 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,16 @@ proofline next -> TASK-1: Saves return a durable receipt on the default path Caught five, passed one. ``` +## A receipt for a contract task + +After a task's checks run, create a signed, revision-bound receipt: + +```bash +proofline receipt TASK-1 --role claude-code +``` + +The envelope records the base and head, red-on-base and green-on-head attempts, suite and metric results, scope, forbidden findings, and claim reconciliation. It is signed when the selected agentkey role is available. Without that key, Proofline writes an unsigned L0 receipt, reports why on stderr, and preserves the verifier's exit code. The receipt records which checks ran; it does not prove the acceptance criteria were sufficient or that arbitrary software is correct. See [the receipt format and verification guide](docs/receipt.md). + ## Sixty seconds In the repository the agent works on: diff --git a/bin/proofline.mjs b/bin/proofline.mjs index 59e953c..ae5dda7 100755 --- a/bin/proofline.mjs +++ b/bin/proofline.mjs @@ -77,8 +77,8 @@ const HELP = `proofline: independent V&V and delivery controller evidence record --data '{..}' | evidence verify | evidence log verify-receipt [--keys ] [--sigstore] [--recompute --base ] exit 0 verified, 1 failed or differs, 2 unknown key, 3 usage - receipt [--role ] [--base ] [--vault] - one receipt for the revision; --vault writes the note when a daemon answers + receipt [--role ] [--base ] [--out ] [--vault] + contract receipt for a task; without , infer a zero-config receipt hook pre-commit|pre-push (used by git hooks) hook stop read a Stop hook payload on stdin; one receipt for new commits, or silence connect claude-code merge a Stop hook into ~/.claude/settings.json, after any hook already there @@ -112,7 +112,7 @@ const ACCEPTED_FLAGS = { 'evidence verify': [], 'evidence log': [], 'verify-receipt': ['keys', 'sigstore', 'recompute', 'base'], - receipt: ['base', 'role', 'task', 'vault'], + receipt: ['base', 'role', 'task', 'out', 'vault'], hook: [], watch: [], connect: [], @@ -271,13 +271,17 @@ try { break; } case 'receipt': { + if (flags.task === true || flags.role === true || flags.out === true || flags.base === true) throw new Error('receipt flags need values'); + const task = typeof flags.task === 'string' ? flags.task : sub; const r = await buildReceipt(root, { base: flags.base === true ? undefined : flags.base, role: flags.role === true ? undefined : flags.role, - task: flags.task === true ? undefined : flags.task, + task, + out: flags.out === true ? undefined : flags.out, vault: flags.vault === true, }); print(r); + if (typeof task === 'string' && Number.isInteger(r.exitCode)) process.exitCode = r.exitCode; break; } case 'hook': { diff --git a/docs/receipt.md b/docs/receipt.md index 40bfa05..7158a15 100644 --- a/docs/receipt.md +++ b/docs/receipt.md @@ -1,6 +1,49 @@ # Receipt -Without a contract, `receipt` infers the suite from the manifest at the base revision. A change to that command is reported and is not what runs. +Proofline has two receipt paths. `proofline receipt ` runs the task's contract checks and writes a signed, contract-bound DSSE envelope. Calling `proofline receipt` without a task keeps the earlier zero-config inference path used by the Claude Code Stop hook. + +## Contract receipt + +```sh +proofline receipt TASK-1 [--base ] [--role claude-code] [--out receipt.json] +``` + +The command reruns the task through Proofline's verifier with fresh results. `--base` is optional when `proofline next` pinned the task's base; in a fresh clone, pass the original base explicitly. A receipt is bound to the current committed `HEAD` and its Git tree. Contract-mode receipts require a clean worktree so the subject names the exact revision that was checked. + +The output file defaults to `.proofline/receipts/.json`. `.proofline/` is ignored by default. Use `--out` to choose a different destination. + +### Trust levels + +- **L0 — unsigned:** no role was configured, the role key could not be loaded, the base is unavailable, or the worktree is dirty. The envelope is not authenticated. The reason is written to stderr, and the command preserves the verifier's exit code. +- **L1 — agent-signed:** the task evidence is in a DSSE envelope signed by the configured `agentkey` role. Set `--role ` or `PROOFLINE_AGENT_ROLE`; keep the private key in the agentkey home, never in the repository or receipt. +- **L2 — CI-verified:** reserved for a future CI attestation flow. Contract-mode receipts from this command do not claim L2. + +The statement predicate type is `https://proofline.dev/receipt/v1` and is validated against `schema/receipt-v1.json`. It includes the producer and task contract hash; base and head commit/tree identifiers; changed tests and red-on-base/green-on-head attempts; suite and metric results; scope and forbidden-check results; claim reconciliation; agent role and key id; repository visibility; timestamps; heuristic limitations; and optional memory evidence. + +The in-toto subject digest binds `gitCommit` and `gitTree` to `predicate.head`. Public repository subjects include the sanitized remote URL and commit. Private repository subjects use the commit reference alone; the repository URL is kept in the predicate. Repository visibility defaults to private. Set `PROOFLINE_REPOSITORY_VISIBILITY=public` only for a repository that is public. + +### What a receipt does not claim + +A valid signature proves that the named role signed the recorded bytes. It does not prove the role's key was uncompromised, that acceptance criteria were complete, that a test was sufficient, or that arbitrary software is correct or safe. A receipt records what Proofline ran, the revision and base it used, and the results it observed. `grep`, `wiring`, and the forbidden-pattern scan remain heuristics; they are one layer, not a boundary. + +## Offline verification + +`verify-receipt` checks the DSSE signature offline against PEM files in `--keys` or `$AGENTKEY_HOME/keys`, named `.pem`. + +```sh +proofline verify-receipt .proofline/receipts/.json --keys trusted-keys +proofline verify-receipt receipt.json --keys trusted-keys --recompute --base +``` + +Exit 0 means the envelope verifies; exit 1 means the signature/schema/subject differs; exit 2 means the key is unknown or the receipt is unsigned/unverifiable; exit 3 means usage or a missing required argument. `--sigstore` is the only path that loads the optional Sigstore verifier. + +If the current commit differs but its tree matches the receipt subject, base-relative fields such as red-on-base and scope are reported unverified unless `--recompute` reruns them against the receipt's exact base. A different subject tree does not verify as the same receipt. + +The MCP tools `receipt` and `verify_receipt` return the same JSON as the CLI. Without a `task` argument, the MCP receipt tool uses the zero-config path. + +## Zero-config receipt + +Without ``, `receipt` infers suites from the manifest at the base revision. A changed suite command is reported, and the base command is what runs. | Manifest | Command | | --- | --- | @@ -10,16 +53,12 @@ Without a contract, `receipt` infers the suite from the manifest at the base rev | go.mod | `go test ./...` | | build.gradle, `*.sln` | no default command, status blocked | -Changed tests are paths under `test/` or `tests/`, or names matching `*_test.*`, `*.test.*`, `*.spec.*` or `test_*.py`. Nothing inferable yields an L0 receipt and exit 2. A missing toolchain is blocked, not a pass. - -`verify-receipt` checks the DSSE envelope offline against PEM files in `--keys` (or `$AGENTKEY_HOME/keys`), named `.pem`. Exit 0 is verified, 1 is a bad signature, a schema problem or a `--recompute` difference, 2 is an unknown key, and 3 is usage. `--sigstore` is the only path that loads that verifier. - -The MCP tools `receipt` and `verify_receipt` return that same JSON. `tools/list` shows nine tools. +Changed tests are paths under `test/` or `tests/`, or names matching `*_test.*`, `*.test.*`, `*.spec.*` or `test_*.py`. Nothing inferable yields an L0 receipt and exit 2. A missing or unusable toolchain is blocked, not passed. -`proofline hook stop` reads a Claude Code Stop payload and writes one receipt for the commits that session made. A second run on the same range writes none. `proofline connect claude-code` adds that hook after any Stop hook already in `~/.claude/settings.json`. +## Optional HiveVault note -When `GET /v1/state/digest` answers within 2 seconds, an L1 receipt gains `memory.vault_digest` and `memory.frontier`. An L2 receipt in ci mode gains only `memory_commitment`, the sha256 of the vault id, the digest and the frontier JSON, so a replica id is not in the receipt. No answer leaves the receipt unchanged. `--vault` writes `work/receipts/--.md` with origin `proofline`. +When the local daemon answers `GET /v1/state/digest` within 2 seconds, `--vault` attaches a digest and writes a receipt note. No answer leaves the receipt unchanged. `HIVEVAULT_TOKEN` is used only for the request and is never placed in the receipt. -The weakening check is a warning beside the owner signature. It names a loosened threshold, a removed criterion, or a changed command. Once `guard/owner.pub` is pinned, a missing, altered or wrongly-signed contract is refused with `contract not owner-signed`. +For an L1 receipt the note carries `memory.vault_digest` and `memory.frontier`. A CI/L2 receipt carries only `memory_commitment`, a sha256 commitment over the vault id, digest, and frontier. The Stop hook writes one zero-config receipt for a session that created commits and stays quiet when the same range was already receipted. `proofline connect claude-code` adds the Stop hook after existing hooks in the Claude Code settings file. -grep, wiring and the forbidden scan are marked `heuristic` in the receipt. They are one layer, not a boundary. An isolated run records `isolated` and `env_digest`. A local run records `isolated` false. +The contract weakening check remains alongside the owner signature. Once `guard/owner.pub` is pinned, a missing, altered, or wrongly signed contract is refused. Heuristic checks are labeled and never substitute for a domain-specific acceptance oracle. diff --git a/package.json b/package.json index 631ad82..4b46bd2 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ "files": [ "bin", "src", + "schema", "docs", "AGENTS.md", "README.md", @@ -56,6 +57,9 @@ "self-gate": "node bin/proofline.mjs gate PL-SELF --skip-pushed", "mcp": "node bin/proofline.mjs mcp" }, + "dependencies": { + "@optitransfer/agentkey": "0.1.1" + }, "devDependencies": { "@optitransfer/agentkey": "0.1.1", "hivevault": "0.3.3" diff --git a/schema/receipt-v1.json b/schema/receipt-v1.json index 7aee4ac..c5255d7 100644 --- a/schema/receipt-v1.json +++ b/schema/receipt-v1.json @@ -1,18 +1,194 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://proofline.dev/receipt/v1", - "type": "object", - "properties": { - "isolated": { "type": "boolean" }, - "env_digest": { "type": ["string", "null"] }, - "heuristic": { - "type": "boolean", - "description": "grep, wiring and the forbidden scan are one layer, not a boundary" + "oneOf": [ + { "$ref": "#/$defs/contract" }, + { "$ref": "#/$defs/legacy" } + ], + "$defs": { + "sha": { "type": "string", "pattern": "^[0-9a-f]{40}$" }, + "nullableSha": { "type": ["string", "null"], "pattern": "^[0-9a-f]{40}$" }, + "nullableHash": { "type": ["string", "null"], "pattern": "^[0-9a-f]{64}$" }, + "revision": { + "type": "object", + "required": ["gitCommit", "gitTree", "ref"], + "properties": { + "gitCommit": { "$ref": "#/$defs/nullableSha" }, + "gitTree": { "$ref": "#/$defs/nullableSha" }, + "ref": { "type": ["string", "null"] } + } }, - "coverage_limits": { - "type": "array", - "items": { "type": "string" } + "attempt": { + "type": "object", + "required": ["ran", "failed", "output_sha256"], + "properties": { + "ran": { "type": "boolean" }, + "failed": { "type": ["boolean", "null"] }, + "output_sha256": { "$ref": "#/$defs/nullableHash" } + } + }, + "contract": { + "type": "object", + "required": [ + "level", "producer", "decision", "exitCode", "base", "head", "task", + "tests", "suite", "metrics", "scope", "forbidden", "claims", "agent", + "repository", "timestamps", "heuristic", "heuristic_ran", "coverage_limits" + ], + "properties": { + "level": { "enum": ["L0", "L1", "L2"] }, + "producer": { "type": "string", "minLength": 1 }, + "decision": { "enum": ["PASS", "FAIL", "BLOCKED"] }, + "exitCode": { "type": "integer", "minimum": 0, "maximum": 3 }, + "base": { "$ref": "#/$defs/revision" }, + "head": { "$ref": "#/$defs/revision" }, + "task": { + "type": "object", + "required": ["id", "title", "phase", "contract_hash"], + "properties": { + "id": { "type": "string", "minLength": 1 }, + "title": { "type": "string" }, + "phase": { "type": "string" }, + "contract_hash": { "type": "string", "pattern": "^[0-9a-f]{64}$" } + } + }, + "tests": { + "type": "object", + "required": ["changed", "red_on_base", "green_on_head"], + "properties": { + "changed": { "type": "array", "items": { "type": "string" } }, + "red_on_base": { "$ref": "#/$defs/attempt" }, + "green_on_head": { + "type": "object", + "required": ["ran", "passed", "output_sha256"], + "properties": { + "ran": { "type": "boolean" }, + "passed": { "type": ["boolean", "null"] }, + "output_sha256": { "$ref": "#/$defs/nullableHash" } + } + }, + "attempts": { "type": "array", "items": { "type": "object" } } + } + }, + "suite": { + "type": "object", + "required": ["ran", "command", "exit", "count", "duration_ms", "output_sha256"], + "properties": { + "ran": { "type": "boolean" }, + "command": { "type": ["string", "null"] }, + "exit": { "type": ["integer", "null"] }, + "count": { "type": ["integer", "null"], "minimum": 0 }, + "duration_ms": { "type": ["number", "null"], "minimum": 0 }, + "output_sha256": { "$ref": "#/$defs/nullableHash" }, + "runs": { "type": "array", "items": { "type": "object" } } + } + }, + "metrics": { + "type": "array", + "items": { + "type": "object", + "required": ["name", "ran", "value", "op", "target", "status"], + "properties": { + "name": { "type": "string" }, + "ran": { "type": "boolean" }, + "value": { "type": ["number", "null"] }, + "op": { "type": ["string", "null"] }, + "target": { "type": ["number", "null"] }, + "status": { "type": ["string", "null"] } + } + } + }, + "scope": { + "type": "object", + "required": ["ran", "allowed", "changed", "pass"], + "properties": { + "ran": { "type": "boolean" }, + "allowed": { "type": "array", "items": { "type": "string" } }, + "changed": { "type": "array", "items": { "type": "string" } }, + "pass": { "type": ["boolean", "null"] } + } + }, + "forbidden": { + "type": "object", + "required": ["ran", "findings", "pass"], + "properties": { + "ran": { "type": "boolean" }, + "findings": { "type": "array", "items": { "type": "object" } }, + "pass": { "type": ["boolean", "null"] } + } + }, + "claims": { + "type": "object", + "required": ["ran", "reported", "reconciled"], + "properties": { + "ran": { "type": "boolean" }, + "reported": { "type": "array", "items": { "type": "string" } }, + "reconciled": { "type": ["boolean", "null"] } + } + }, + "agent": { + "type": "object", + "required": ["role", "kid", "run_id", "model", "trace"], + "properties": { + "role": { "type": ["string", "null"] }, + "kid": { "type": ["string", "null"] }, + "run_id": { "type": ["string", "null"] }, + "model": { "type": ["string", "null"] }, + "trace": { "type": ["string", "null"] } + } + }, + "repository": { + "type": "object", + "required": ["url", "visibility"], + "properties": { + "url": { "type": ["string", "null"] }, + "visibility": { "enum": ["public", "private"] } + } + }, + "timestamps": { + "type": "object", + "required": ["started", "finished"], + "properties": { + "started": { "type": "string", "format": "date-time" }, + "finished": { "type": "string", "format": "date-time" } + } + }, + "heuristic": { "type": "boolean" }, + "heuristic_ran": { "type": "boolean" }, + "coverage_limits": { "type": "array", "items": { "type": "string" } }, + "isolation": { + "type": "object", + "required": ["ran", "isolated", "env_digest"], + "properties": { + "ran": { "type": "boolean" }, + "isolated": { "type": ["boolean", "null"] }, + "env_digest": { "type": ["string", "null"] } + } + }, + "memory": { "type": "object" }, + "memory_commitment": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "reason": { "type": ["string", "null"] } + } + }, + "legacy": { + "type": "object", + "required": ["level"], + "not": { "required": ["task", "head", "tests"] }, + "properties": { + "level": { "enum": ["L0", "L1", "L2"] }, + "exitCode": { "type": "integer", "minimum": 0, "maximum": 3 }, + "reason": { "type": "string" }, + "green_on_head": { "type": "boolean" }, + "isolated": { "type": "boolean" }, + "env_digest": { "type": ["string", "null"] }, + "heuristic": { "type": "boolean" }, + "coverage_limits": { "type": "array", "items": { "type": "string" } }, + "suites": { "type": "array", "items": { "type": "object" } }, + "changed": { "type": "array", "items": { "type": "string" } }, + "findings": { "type": "array", "items": { "type": "object" } }, + "agent": { "type": "object" }, + "memory": { "type": "object" }, + "memory_commitment": { "type": "string", "pattern": "^[0-9a-f]{64}$" } + } } - }, - "required": ["isolated", "heuristic"] + } } diff --git a/src/checks.mjs b/src/checks.mjs index 9df08be..003b645 100644 --- a/src/checks.mjs +++ b/src/checks.mjs @@ -4,7 +4,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { run, git, tail, pick, lastJson, matchAny, onRemote } from './util.mjs'; +import { run, git, tail, pick, lastJson, matchAny, onRemote, sha256 } from './util.mjs'; /** The machine a metric runs on: 1-minute load average and CPU count. verifyTask takes a replacement as `machine`. */ export const readMachine = () => ({ load1: os.loadavg()[0], cpus: os.cpus().length }); @@ -95,7 +95,7 @@ export function failingTests(text, cap = FAILING_CAP) { return all.length > cap ? { failing: all.slice(0, cap), failing_total: all.length } : { failing: all }; } -const ev = (r) => ({ cmd: r.cmd, exit: r.exit, ms: r.ms, counts: r.counts, timedOut: r.timedOut, ...failingTests(r.stdout + '\n' + r.stderr), out_tail: tail(r.stdout + (r.stderr ? '\n[stderr]\n' + r.stderr : ''), 1200) }); +const ev = (r) => ({ cmd: r.cmd, exit: r.exit, ms: r.ms, counts: r.counts, timedOut: r.timedOut, output_sha256: sha256(r.stdout + '\n' + r.stderr), ...failingTests(r.stdout + '\n' + r.stderr), out_tail: tail(r.stdout + (r.stderr ? '\n[stderr]\n' + r.stderr : ''), 1200) }); /** "12 tests failed: a, b, ... and 2 more" from a run's evidence (first 10 names), or '' when it names none. */ const named = (e) => { const n = e.failing_total ?? e.failing.length, show = e.failing.slice(0, 10); diff --git a/src/infer.mjs b/src/infer.mjs index aa313b6..e8c3ea9 100644 --- a/src/infer.mjs +++ b/src/infer.mjs @@ -40,8 +40,9 @@ export function nodeCommand(pkg) { function toolchainOk(bin) { if (!bin) return true; - const r = spawnSync('bash', ['-lc', `command -v ${bin}`], { encoding: 'utf8' }); - return r.status === 0; + const args = bin === 'go' ? ['version'] : ['--version']; + const r = spawnSync(bin, args, { encoding: 'utf8', timeout: 5000 }); + return r.status === 0 && !r.error; } function parseJson(text) { diff --git a/src/isolate.mjs b/src/isolate.mjs index 8201f21..c15c5e2 100644 --- a/src/isolate.mjs +++ b/src/isolate.mjs @@ -33,12 +33,20 @@ function hasBin(bin) { } export function runtimeName() { - if (hasBin('docker')) return 'docker'; - if (hasBin('podman')) return 'podman'; + if (hasBin('docker') && runtimeReady('docker')) return 'docker'; + if (hasBin('podman') && runtimeReady('podman')) return 'podman'; if (hasBin('bwrap')) return 'bwrap'; return null; } +function runtimeReady(runtime) { + const args = runtime === 'docker' + ? ['info', '--format', '{{.ServerVersion}}'] + : ['info', '--format', '{{.Host.Version}}']; + const r = spawnSync(runtime, args, { encoding: 'utf8', timeout: 10000 }); + return r.status === 0 && Boolean((r.stdout || '').trim()); +} + function result(cmd, cwd, started, child) { const ms = Math.round(performance.now() - started); const timedOut = child.error?.code === 'ETIMEDOUT'; @@ -118,6 +126,10 @@ export function resolveIsolation(contract, opts = {}) { // The version probe does not need the work tree. Mounting it fails where the desktop runtime cannot see that path. const ver = sandbox('node --version', { timeoutS: 60 }); const nodeVer = (ver.stdout || '').trim().split('\n')[0] || 'unknown'; + if (ver.exit !== 0 || nodeVer === 'unknown') { + const detail = (ver.stderr || ver.stdout || 'no version output').trim().split('\n')[0].slice(0, 240); + return { isolated: false, env_digest: null, block: `isolated runtime probe failed: ${detail}`, sandbox: null }; + } const env_digest = `${image} runtime=${runtime} node=${nodeVer}`; return { isolated: true, env_digest, block: null, sandbox }; } diff --git a/src/mcp.mjs b/src/mcp.mjs index de61e94..6e729b3 100644 --- a/src/mcp.mjs +++ b/src/mcp.mjs @@ -15,7 +15,7 @@ const TOOLS = [ { name: 'gate', description: 'Release decision PASS/FAIL/BLOCKED with Markdown+JSON evidence report.', inputSchema: { type: 'object', properties: { task: { type: 'string' }, claims: { type: 'string' }, base: BASE, fresh: FRESH }, required: ['task'] } }, { name: 'report', description: 'Latest gate report for a task (Markdown).', inputSchema: { type: 'object', properties: { task: { type: 'string' } }, required: ['task'] } }, { name: 'status', description: 'Task and phase status, evidence-chain integrity.', inputSchema: { type: 'object', properties: { owner: OWNER } } }, - { name: 'receipt', description: 'Infer a receipt from the base revision. Returns the same JSON the CLI prints with --json.', inputSchema: { type: 'object', properties: { task: { type: 'string' }, base: { type: 'string', description: 'The revision the receipt is inferred from.' }, role: { type: 'string' }, vault: { type: 'boolean', description: 'Attach a hivevault digest and write the note when the daemon answers.' } } } }, + { name: 'receipt', description: 'Build a signed contract receipt for task when task is supplied; without task, retain zero-config inference. Returns the same JSON the CLI prints with --json.', inputSchema: { type: 'object', properties: { task: { type: 'string' }, base: { type: 'string', description: 'The revision the task started from.' }, role: { type: 'string' }, out: { type: 'string' }, vault: { type: 'boolean', description: 'Attach a hivevault digest and write the note when the daemon answers.' } } } }, { name: 'verify_receipt', description: 'Check a DSSE receipt envelope offline. Returns the same JSON verify-receipt prints with --json.', inputSchema: { type: 'object', properties: { path: { type: 'string' }, recompute: { type: 'boolean' }, base: BASE }, required: ['path'] } }, ]; diff --git a/src/receipt.mjs b/src/receipt.mjs index 4b0a617..7eb6e05 100644 --- a/src/receipt.mjs +++ b/src/receipt.mjs @@ -1,8 +1,185 @@ -// One receipt for a revision range. A missing daemon leaves the receipt unchanged. -import { receiptZeroConfig } from './infer.mjs'; +// Contract receipts bind independently rerun evidence to a committed revision. +// The zero-config path remains for the Stop hook and existing local workflows. +import fs from 'node:fs'; +import path from 'node:path'; +import * as C from './contract.mjs'; +import { verifyTask } from './engine.mjs'; +import { resolveBase } from './checks.mjs'; +import { changedTests, receiptZeroConfig } from './infer.mjs'; import { attachMemory, probeDigest, receiptNote, writeReceiptNote } from './vault.mjs'; +import { git, sha256, writeJson } from './util.mjs'; +import { COVERAGE_LIMITS } from './isolate.mjs'; +import { receiptPredicateProblem } from './verify-receipt.mjs'; -export async function buildReceipt(root, a = {}) { +export const PREDICATE_TYPE = 'https://proofline.dev/receipt/v1'; +const STATEMENT_TYPE = 'https://in-toto.io/Statement/v1'; +const PAYLOAD_TYPE = 'application/vnd.in-toto+json'; + +const commandCode = (decision) => decision === 'PASS' ? 0 : decision === 'FAIL' ? 1 : 2; +const runEvidence = (result) => result?.evidence || null; +const isSha = (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value); + +function safeRemote(root) { + const found = git(['remote', 'get-url', 'origin'], root); + if (!found.ok || !found.out) return null; + const raw = found.out.trim(); + const scp = raw.match(/^(?:[^@/]+@)?([^:/]+):(.+)$/); + if (scp && !raw.includes('://')) return `https://${scp[1]}/${scp[2].replace(/^\/+/, '')}`; + try { + const url = new URL(raw); + url.username = ''; + url.password = ''; + url.search = ''; + url.hash = ''; + return url.toString().replace(/\/$/, ''); + } catch { + return null; + } +} + +function repositoryInfo(root, options) { + const url = safeRemote(root); + const value = options.visibility || process.env.PROOFLINE_REPOSITORY_VISIBILITY; + return { url, visibility: value === 'public' && url ? 'public' : 'private' }; +} + +function changedPaths(root) { + const status = git(['status', '--porcelain', '--untracked-files=all'], root); + if (!status.ok) return ['']; + return status.out.split('\n').filter(Boolean).map((line) => line.slice(3)).filter((file) => file && !file.startsWith('.proofline/')); +} + +function treeAt(root, ref) { + const r = git(['rev-parse', '--verify', '--quiet', `${ref}^{tree}`], root); + return r.ok ? r.out : null; +} + +function makeAttempts(results) { + return results.filter((r) => r.type === 'test_red_green').map((r) => { + const evidence = r.evidence || {}; + const red = evidence.red; + const green = evidence.green; + return { + id: r.id, + red_on_base: { + ran: Boolean(red), + failed: red ? red.exit !== 0 : null, + output_sha256: isSha(red?.output_sha256) ? red.output_sha256 : null, + }, + green_on_head: { + ran: Boolean(green), + passed: green ? green.exit === 0 : null, + output_sha256: isSha(green?.output_sha256) ? green.output_sha256 : null, + }, + }; + }); +} + +function aggregateAttempt(attempts, field, outcome) { + const rows = attempts.map((a) => a[field]).filter((a) => a.ran); + return { + ran: rows.length > 0, + [outcome]: rows.length ? rows.every((a) => a[outcome] === true) : null, + output_sha256: rows.length === 1 ? rows[0].output_sha256 : rows.length ? sha256(JSON.stringify(rows.map((a) => a.output_sha256))) : null, + }; +} + +function suiteEvidence(results) { + const rows = results.filter((r) => r.type === 'command'); + const runs = rows.map((r) => { + const e = runEvidence(r) || {}; + return { + id: r.id, + command: e.cmd || null, + ran: Number.isInteger(e.exit), + exit: Number.isInteger(e.exit) ? e.exit : null, + count: Number.isInteger(e.counts?.tests) ? e.counts.tests : Number.isInteger(e.counts?.pass) ? e.counts.pass : null, + duration_ms: Number.isFinite(e.ms) ? e.ms : null, + output_sha256: isSha(e.output_sha256) ? e.output_sha256 : null, + status: r.status, + }; + }); + const suite = rows.find((r) => /\b(test|suite|pytest|cargo test|go test)\b/i.test(`${r.statement || ''} ${r.evidence?.cmd || ''}`)) || rows[0]; + const selected = runs.find((r) => r.id === suite?.id); + return selected + ? { ...selected, runs } + : { ran: false, command: null, exit: null, count: null, duration_ms: null, output_sha256: null, runs }; +} + +function metricEvidence(results, task) { + return results.filter((r) => r.type === 'metric').map((r) => { + const criterion = task.criteria.find((x) => x.id === r.id); + const evidence = r.evidence || {}; + return { + name: criterion?.verifier?.name || criterion?.verifier?.key || r.id, + ran: Number.isFinite(evidence.measured), + value: Number.isFinite(evidence.measured) ? evidence.measured : null, + op: criterion?.verifier?.op || null, + target: Number.isFinite(criterion?.verifier?.value) ? criterion.verifier.value : null, + status: r.status, + }; + }); +} + +function makePredicate({ root, contract, task, verification, head, base, repository, started, role }) { + const attempts = makeAttempts(verification.results); + const scopeResult = verification.results.find((r) => r.type === 'scope'); + const claims = verification.claims || []; + const hasClaims = claims.length > 0; + const predicate = { + level: 'L1', + producer: `${contract.package?.name || '@optitransfer/proofline'}@${contract.package?.version || '0.2.0-next.2'}`, + decision: verification.decision, + exitCode: commandCode(verification.decision), + base: { gitCommit: base.commit, gitTree: base.tree, ref: verification.base_ref || base.commit }, + head, + task: { id: task.id, title: task.title, phase: task.phase, contract_hash: verification.contract_hash }, + tests: { + changed: base.commit ? changedTests(root, base.commit) : [], + red_on_base: aggregateAttempt(attempts, 'red_on_base', 'failed'), + green_on_head: aggregateAttempt(attempts, 'green_on_head', 'passed'), + attempts, + }, + suite: suiteEvidence(verification.results), + metrics: metricEvidence(verification.results, task), + scope: { + ran: Boolean(scopeResult), + allowed: [...(task.scope?.allow || [])], + changed: [...verification.changed].sort(), + pass: scopeResult ? scopeResult.status === 'pass' : null, + }, + forbidden: { ran: true, findings: verification.forbidden || [], pass: (verification.forbidden || []).length === 0 }, + claims: { + ran: hasClaims, + reported: claims.map((x) => x.claim), + reconciled: hasClaims ? claims.every((x) => x.ok) : null, + }, + agent: { + role, + kid: null, + run_id: process.env.GITHUB_RUN_ID || process.env.PROOFLINE_RUN_ID || null, + model: process.env.PROOFLINE_MODEL || null, + trace: process.env.PROOFLINE_TRACE || null, + }, + repository, + timestamps: { started, finished: new Date().toISOString() }, + heuristic: true, + heuristic_ran: true, + coverage_limits: [...(verification.coverage_limits || COVERAGE_LIMITS)], + isolation: { + ran: true, + isolated: verification.isolated === true, + env_digest: verification.env_digest || null, + }, + }; + return predicate; +} + +function statementFor(subject, predicate) { + return { _type: STATEMENT_TYPE, subject: [subject], predicateType: PREDICATE_TYPE, predicate }; +} + +async function legacyReceipt(root, a) { const receipt = receiptZeroConfig(root, { base: a.base }); if (a.vault !== true) return receipt; const digest = await probeDigest(); @@ -10,8 +187,96 @@ export async function buildReceipt(root, a = {}) { const note = receiptNote({ receipt: attached.receipt, role: typeof a.role === 'string' && a.role ? a.role : 'agent', - subject: typeof a.task === 'string' ? a.task : '', + subject: typeof a.subject === 'string' ? a.subject : '', }); await writeReceiptNote(note, { vault: true }); return attached.receipt; } + +/** Build a contract-bound DSSE receipt, or retain zero-config inference when no task is supplied. */ +export async function buildReceipt(root, a = {}) { + if (typeof a.task !== 'string' || !a.task.trim()) return legacyReceipt(root, a); + + const contract = C.load(root); + const task = contract.tasks.find((t) => t.id === a.task); + if (!task) throw new Error(`unknown task ${a.task}`); + const headCommit = git(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], root); + const headTree = headCommit.ok ? treeAt(root, 'HEAD') : null; + if (!headCommit.ok || !headTree) throw new Error('receipt needs a committed HEAD and Git tree'); + + const started = new Date().toISOString(); + const verification = verifyTask(root, task.id, { base: a.base, claims: a.claims, fresh: true, isolated: a.isolated === true }); + const baseCommit = verification.base; + const base = { commit: baseCommit || null, tree: baseCommit ? treeAt(root, baseCommit) : null }; + const repository = repositoryInfo(root, a); + const role = typeof a.role === 'string' && a.role.trim() + ? a.role.trim() + : typeof process.env.PROOFLINE_AGENT_ROLE === 'string' && process.env.PROOFLINE_AGENT_ROLE.trim() + ? process.env.PROOFLINE_AGENT_ROLE.trim() + : null; + const predicate = makePredicate({ + root, contract: { ...contract, package: JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')) }, + task, verification, head: { gitCommit: headCommit.out, gitTree: headTree, ref: headCommit.out }, base, repository, started, role, + }); + const dirty = changedPaths(root); + let reason = null; + let signingKey = null; + if (dirty.length) reason = `worktree is not clean: ${dirty.join(', ')}`; + else if (!base.commit) reason = 'no base revision; signed receipt cannot bind red/green and scope evidence'; + else if (!role) reason = 'no agent role configured; receipt is unsigned'; + else { + try { + const agentkey = await import('@optitransfer/agentkey'); + signingKey = agentkey.load(role); + predicate.agent.kid = signingKey.kid; + } catch (e) { + reason = e?.message || 'agentkey could not load the configured role'; + } + } + + const signed = Boolean(signingKey) && !dirty.length && Boolean(base.commit); + predicate.level = signed ? 'L1' : 'L0'; + if (reason) predicate.reason = reason; + if (a.vault === true) { + const attached = attachMemory(predicate, await probeDigest()); + Object.assign(predicate, attached.receipt); + } + + const validation = receiptPredicateProblem(predicate); + if (validation) throw new Error(`receipt predicate fails schema/receipt-v1.json: ${validation}`); + const subject = { + name: repository.visibility === 'public' && repository.url + ? `git+${repository.url}@${headCommit.out}` + : headCommit.out, + digest: { gitCommit: headCommit.out, gitTree: headTree }, + }; + const statement = statementFor(subject, predicate); + const payload = Buffer.from(JSON.stringify(statement), 'utf8'); + let envelope; + if (signed) { + const agentkey = await import('@optitransfer/agentkey'); + envelope = agentkey.signDSSE(PAYLOAD_TYPE, payload, signingKey); + } else { + envelope = { payloadType: PAYLOAD_TYPE, payload: payload.toString('base64'), signatures: [] }; + process.stderr.write(`proofline receipt: ${reason || 'agent identity is unavailable'}\n`); + } + + const short = headCommit.out.slice(0, 7); + const destination = typeof a.out === 'string' && a.out.trim() + ? path.resolve(root, a.out) + : path.join(root, '.proofline', 'receipts', `${short}.json`); + writeJson(destination, envelope); + + if (a.vault === true) { + const note = receiptNote({ + receipt: predicate, + role: role || 'agent', + subject: task.id, + envelopeSha: sha256(JSON.stringify(envelope)), + date: predicate.timestamps.finished, + }); + await writeReceiptNote(note, { vault: true }); + } + + return { envelope, path: destination, predicate, level: predicate.level, signed, exitCode: predicate.exitCode, reason }; +} diff --git a/src/verify-receipt.mjs b/src/verify-receipt.mjs index 464862b..79a219a 100644 --- a/src/verify-receipt.mjs +++ b/src/verify-receipt.mjs @@ -2,7 +2,9 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; -import { receiptZeroConfig } from './infer.mjs'; +import { receiptZeroConfig, changedTests } from './infer.mjs'; +import { verifyTask } from './engine.mjs'; +import { git } from './util.mjs'; const STATEMENT = 'https://in-toto.io/Statement/v1'; const PAYLOAD_TYPE = 'application/vnd.in-toto+json'; @@ -30,13 +32,68 @@ function loadKeys(dir) { return out; } +const object = (x) => Boolean(x) && typeof x === 'object' && !Array.isArray(x); +const stringOrNull = (x) => x === null || typeof x === 'string'; +const sha40 = (x) => typeof x === 'string' && /^[0-9a-f]{40}$/.test(x); +const sha64OrNull = (x) => x === null || (typeof x === 'string' && /^[0-9a-f]{64}$/.test(x)); + +/** Keep the dependency-free runtime validator aligned with schema/receipt-v1.json. */ +export function receiptPredicateProblem(p) { + if (!object(p)) return 'predicate'; + if (!['L0', 'L1', 'L2'].includes(p.level)) return 'predicate.level'; + // Receipts inferred without a task contract remain readable as the legacy v1 shape. + if (p.task === undefined) { + if (p.agent != null && !object(p.agent)) return 'predicate.agent'; + return null; + } + if (typeof p.producer !== 'string' || !p.producer) return 'predicate.producer'; + if (!['PASS', 'FAIL', 'BLOCKED'].includes(p.decision)) return 'predicate.decision'; + if (!Number.isInteger(p.exitCode) || ![0, 1, 2, 3].includes(p.exitCode)) return 'predicate.exitCode'; + for (const name of ['base', 'head']) { + const rev = p[name]; + if (!object(rev) || !stringOrNull(rev.gitCommit) || !stringOrNull(rev.gitTree) || !stringOrNull(rev.ref)) return `predicate.${name}`; + if (rev.gitCommit !== null && !sha40(rev.gitCommit)) return `predicate.${name}.gitCommit`; + if (rev.gitTree !== null && !sha40(rev.gitTree)) return `predicate.${name}.gitTree`; + } + if (!object(p.task) || typeof p.task.id !== 'string' || typeof p.task.title !== 'string' || typeof p.task.phase !== 'string' || !/^[0-9a-f]{64}$/.test(p.task.contract_hash || '')) return 'predicate.task'; + if (!object(p.tests) || !Array.isArray(p.tests.changed) || !p.tests.changed.every((x) => typeof x === 'string')) return 'predicate.tests'; + for (const [name, boolName] of [['red_on_base', 'failed'], ['green_on_head', 'passed']]) { + const a = p.tests[name]; + if (!object(a) || typeof a.ran !== 'boolean' || !(typeof a[boolName] === 'boolean' || a[boolName] === null) || !sha64OrNull(a.output_sha256)) return `predicate.tests.${name}`; + } + const suite = p.suite; + if (!object(suite) || typeof suite.ran !== 'boolean' || !stringOrNull(suite.command) || !(Number.isInteger(suite.exit) || suite.exit === null) || !(Number.isInteger(suite.count) || suite.count === null) || !(typeof suite.duration_ms === 'number' || suite.duration_ms === null) || !sha64OrNull(suite.output_sha256)) return 'predicate.suite'; + if (!Array.isArray(p.metrics) || !p.metrics.every((m) => object(m) && typeof m.name === 'string' && typeof m.ran === 'boolean' && (typeof m.value === 'number' || m.value === null) && stringOrNull(m.op) && (typeof m.target === 'number' || m.target === null) && stringOrNull(m.status))) return 'predicate.metrics'; + if (!object(p.scope) || typeof p.scope.ran !== 'boolean' || !Array.isArray(p.scope.allowed) || !p.scope.allowed.every((x) => typeof x === 'string') || !Array.isArray(p.scope.changed) || !p.scope.changed.every((x) => typeof x === 'string') || !(typeof p.scope.pass === 'boolean' || p.scope.pass === null)) return 'predicate.scope'; + if (!object(p.forbidden) || typeof p.forbidden.ran !== 'boolean' || !Array.isArray(p.forbidden.findings) || !(typeof p.forbidden.pass === 'boolean' || p.forbidden.pass === null)) return 'predicate.forbidden'; + if (!object(p.claims) || typeof p.claims.ran !== 'boolean' || !Array.isArray(p.claims.reported) || !p.claims.reported.every((x) => typeof x === 'string') || !(typeof p.claims.reconciled === 'boolean' || p.claims.reconciled === null)) return 'predicate.claims'; + if (!object(p.agent) || !stringOrNull(p.agent.role) || !stringOrNull(p.agent.kid) || !stringOrNull(p.agent.run_id) || !stringOrNull(p.agent.model) || !stringOrNull(p.agent.trace)) return 'predicate.agent'; + if (!object(p.repository) || !stringOrNull(p.repository.url) || !['public', 'private'].includes(p.repository.visibility)) return 'predicate.repository'; + if (!object(p.timestamps) || typeof p.timestamps.started !== 'string' || Number.isNaN(Date.parse(p.timestamps.started)) || typeof p.timestamps.finished !== 'string' || Number.isNaN(Date.parse(p.timestamps.finished))) return 'predicate.timestamps'; + if (typeof p.heuristic !== 'boolean' || typeof p.heuristic_ran !== 'boolean' || !Array.isArray(p.coverage_limits) || !p.coverage_limits.every((x) => typeof x === 'string')) return 'predicate.heuristics'; + if (!object(p.isolation) || typeof p.isolation.ran !== 'boolean' || !(typeof p.isolation.isolated === 'boolean' || p.isolation.isolated === null) || !stringOrNull(p.isolation.env_digest)) return 'predicate.isolation'; + if (p.memory_commitment !== undefined && !/^[0-9a-f]{64}$/.test(p.memory_commitment)) return 'predicate.memory_commitment'; + if (p.reason !== undefined && !stringOrNull(p.reason)) return 'predicate.reason'; + return null; +} + function schemaProblem(statement) { if (!statement || statement._type !== STATEMENT) return 'statement _type'; if (statement.predicateType !== PREDICATE_TYPE) return 'predicateType'; const p = statement.predicate; - if (!p || typeof p !== 'object') return 'predicate'; - if (!['L0', 'L1', 'L2'].includes(p.level)) return 'predicate.level'; - if (p.agent != null && typeof p.agent !== 'object') return 'predicate.agent'; + const problem = receiptPredicateProblem(p); + if (problem) return problem; + if (p.task !== undefined) { + if (!Array.isArray(statement.subject) || statement.subject.length !== 1) return 'statement.subject'; + const subject = statement.subject[0]; + const digest = subject?.digest; + if (!subject || typeof subject.name !== 'string' || !object(digest)) return 'statement.subject'; + if (digest.gitCommit !== p.head.gitCommit || digest.gitTree !== p.head.gitTree) return 'statement.subject.binding'; + const expected = p.repository.visibility === 'public' && p.repository.url + ? `git+${p.repository.url}@${p.head.gitCommit}` + : p.head.gitCommit; + if (subject.name !== expected) return 'statement.subject.name'; + } return null; } @@ -76,6 +133,7 @@ export async function verifyReceipt(envelopePath, opts = {}) { try { raw = JSON.parse(fs.readFileSync(envelopePath, 'utf8')); } catch { return result(1, 'envelope is not JSON'); } if (opts.sigstore) return verifySigstore(raw); + if (Array.isArray(raw?.signatures) && raw.signatures.length === 0) return result(2, 'unsigned L0 receipt; authenticity is not established', { level: 'L0' }); const keys = loadKeys(opts.keys || (process.env.AGENTKEY_HOME ? path.join(process.env.AGENTKEY_HOME, 'keys') : '')); const sig = verifySignatures(raw, keys); if (sig.problem) return result(1, sig.detail); @@ -88,9 +146,42 @@ export async function verifyReceipt(envelopePath, opts = {}) { const schema = schemaProblem(statement); if (schema) return result(1, `schema: ${schema}`); const level = statement.predicate.level; + const predicate = statement.predicate; + const root = opts.root || process.cwd(); + if (predicate.task !== undefined && opts.root) { + const localHead = git(['rev-parse', '--verify', '--quiet', 'HEAD'], root); + const localTree = localHead.ok ? git(['rev-parse', '--verify', '--quiet', 'HEAD^{tree}'], root) : { ok: false, out: '' }; + if (localHead.ok && localHead.out !== predicate.head.gitCommit) { + if (!localTree.ok || localTree.out !== predicate.head.gitTree) return result(1, 'receipt subject does not match the current repository head or tree', { level }); + if (!opts.recompute) return result(2, 'tree matches but the commit differs; base-relative fields tests.red_on_base and scope are unverified without --recompute', { level, unverified: ['tests.red_on_base', 'scope'] }); + } + if (!opts.recompute) return result(0, `verified\nlevel ${level}`, { level }); + if (!opts.base) return result(3, '--recompute needs --base'); + if (opts.base !== predicate.base.gitCommit) return result(1, `base differs: receipt ${predicate.base.gitCommit || 'none'}; supplied ${opts.base}`, { level }); + if (!localHead.ok) return result(2, 'cannot resolve current HEAD for recomputation', { level, unverified: ['tests.red_on_base', 'tests.green_on_head', 'suite', 'scope'] }); + const live = verifyTask(root, predicate.task.id, { base: opts.base, fresh: true }); + const differences = []; + if (live.decision !== predicate.decision) differences.push(`decision: receipt ${predicate.decision} recomputed ${live.decision}`); + if (live.base !== predicate.base.gitCommit) differences.push(`base.gitCommit: receipt ${predicate.base.gitCommit} recomputed ${live.base}`); + const red = live.results.find((x) => x.type === 'test_red_green')?.evidence?.red; + const green = live.results.find((x) => x.type === 'test_red_green')?.evidence?.green; + const redFailed = red ? red.exit !== 0 : null; + const greenPassed = green ? green.exit === 0 : null; + if (redFailed !== predicate.tests.red_on_base.failed) differences.push(`tests.red_on_base.failed: receipt ${predicate.tests.red_on_base.failed} recomputed ${redFailed}`); + if (greenPassed !== predicate.tests.green_on_head.passed) differences.push(`tests.green_on_head.passed: receipt ${predicate.tests.green_on_head.passed} recomputed ${greenPassed}`); + const changed = changedTests(root, opts.base).sort(); + if (JSON.stringify(changed) !== JSON.stringify([...predicate.tests.changed].sort())) differences.push('tests.changed differs from the current base-relative diff'); + const scope = live.results.find((x) => x.type === 'scope'); + if ((scope?.status === 'pass') !== predicate.scope.pass) differences.push(`scope.pass: receipt ${predicate.scope.pass} recomputed ${scope?.status === 'pass'}`); + if (differences.length) { + const detail = [...differences, ...(live.blocked || []).map((x) => `recompute blocked: ${x}`), ...(live.failing || []).map((x) => `recompute failed: ${x}`)]; + return result(1, detail.join('\n'), { level, differences: detail }); + } + return result(0, `verified\nlevel ${level}\nrecomputed against ${opts.base}`, { level, recomputed: true }); + } if (!opts.recompute) return result(0, `verified\nlevel ${level}`, { level }); if (!opts.base) return result(3, '--recompute needs --base'); - const live = receiptZeroConfig(opts.root || process.cwd(), { base: opts.base }); + const live = receiptZeroConfig(root, { base: opts.base }); const recomputed = live.exitCode === 0 && live.level === 'L1' && live.suites.every((s) => s.status === 'pass'); const differences = []; if (Boolean(statement.predicate.green_on_head) !== recomputed) { diff --git a/test/mcp_receipt.test.mjs b/test/mcp_receipt.test.mjs index a5045ef..e64c260 100644 --- a/test/mcp_receipt.test.mjs +++ b/test/mcp_receipt.test.mjs @@ -7,10 +7,38 @@ import path from 'node:path'; import test from 'node:test'; import { receiptZeroConfig } from '../src/infer.mjs'; import { verifyReceipt } from '../src/verify-receipt.mjs'; +import { makeTask, skeleton } from '../src/contract.mjs'; const BIN = path.resolve(import.meta.dirname, '..', 'bin', 'proofline.mjs'); const sh = (cwd, args) => execFileSync('git', args, { cwd, encoding: 'utf8' }); +function receiptEnv(extraEnv = {}) { + const env = { ...process.env, HIVEVAULT_URL: 'http://127.0.0.1:1', HIVEVAULT_TOKEN: '', ...extraEnv }; + if (extraEnv.PROOFLINE_AGENT_ROLE === undefined) delete env.PROOFLINE_AGENT_ROLE; + return env; +} + +function comparableReceipt(receipt) { + // MCP and CLI each rerun verification, so timestamps, durations, and captured-output hashes are run-specific. + const copy = JSON.parse(JSON.stringify(receipt)); + const normalize = (predicate) => { + delete predicate.timestamps; + const visit = (value) => { + if (!value || typeof value !== 'object') return; + for (const key of Object.keys(value)) { + if (key === 'duration_ms' || key === 'output_sha256') delete value[key]; + else visit(value[key]); + } + }; + visit(predicate); + }; + normalize(copy.predicate); + const statement = JSON.parse(Buffer.from(copy.envelope.payload, 'base64').toString('utf8')); + normalize(statement.predicate); + copy.envelope.payload = Buffer.from(JSON.stringify(statement), 'utf8').toString('base64'); + return copy; +} + function fixture() { const r = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-mcp-')); sh(r, ['init', '-q', '-b', 'main']); @@ -26,10 +54,10 @@ function fixture() { return { r, base }; } -function ask(root, messages) { +function ask(root, messages, extraEnv = {}) { return new Promise((resolve, reject) => { const child = spawn(process.execPath, [BIN, 'mcp', '--root', root], { - env: { ...process.env, HIVEVAULT_URL: 'http://127.0.0.1:1', HIVEVAULT_TOKEN: '' }, + env: receiptEnv(extraEnv), stdio: ['pipe', 'pipe', 'pipe'], }); let out = ''; @@ -56,7 +84,7 @@ test('receipt and verify_receipt are listed and answer over stdio', async () => { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05' } }, { jsonrpc: '2.0', method: 'notifications/initialized' }, { jsonrpc: '2.0', id: 2, method: 'tools/list' }, - { jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'receipt', arguments: { task: 'T', base, role: 'claude-code', vault: true } } }, + { jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'receipt', arguments: { base, role: 'claude-code', vault: true } } }, { jsonrpc: '2.0', id: 4, method: 'tools/call', params: { name: 'verify_receipt', arguments: { path: path.join(r, 'not-json.txt') } } }, ]); assert.equal(replies.length, 4); @@ -71,3 +99,66 @@ test('receipt and verify_receipt are listed and answer over stdio', async () => assert.equal(checked.exitCode, 1); assert.equal(checked.message, 'envelope is not JSON'); }); + +// With a task, the MCP receipt tool builds the contract receipt for that task (the CLI's `receipt --json`), +// not the zero-config one: with no role and an empty AGENTKEY_HOME it is an unsigned L0 receipt for that task. +function taskFixture() { + const r = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-mcp-task-')); + sh(r, ['init', '-q', '-b', 'main']); + sh(r, ['config', 'user.email', 't@t']); + sh(r, ['config', 'user.name', 't']); + fs.mkdirSync(path.join(r, 'src')); + fs.writeFileSync(path.join(r, 'package.json'), JSON.stringify({ type: 'module', scripts: { test: 'node --test' } }) + '\n'); + fs.writeFileSync(path.join(r, '.gitignore'), '.proofline/\n'); + fs.writeFileSync(path.join(r, 'src', 'answer.mjs'), 'export const answer = () => 0;\n'); + const contract = skeleton('mcp-task-fixture'); + contract.tasks = [makeTask({ + id: 'TASK-1', + title: 'Return the accepted answer', + scope: ['src/**', 'test/**'], + criteria: [ + { id: 'TASK-1-AC01', statement: 'the test fails on base and passes now', verifier: { type: 'test_red_green', test_file: 'test/answer.test.mjs', cmd: 'node --test {test}' } }, + { id: 'TASK-1-AC02', statement: 'changes stay in scope', verifier: { type: 'scope' } }, + ], + })]; + fs.writeFileSync(path.join(r, 'proofline.json'), JSON.stringify(contract, null, 2) + '\n'); + sh(r, ['add', '.gitignore', 'package.json', 'proofline.json', 'src/answer.mjs']); + sh(r, ['commit', '-q', '-m', 'base']); + const base = sh(r, ['rev-parse', 'HEAD']).trim(); + fs.writeFileSync(path.join(r, 'src', 'answer.mjs'), 'export const answer = () => 42;\n'); + fs.mkdirSync(path.join(r, 'test')); + fs.writeFileSync(path.join(r, 'test', 'answer.test.mjs'), "import assert from 'node:assert/strict';\nimport test from 'node:test';\nimport { answer } from '../src/answer.mjs';\ntest('answer', () => assert.equal(answer(), 42));\n"); + sh(r, ['add', 'src/answer.mjs', 'test/answer.test.mjs']); + sh(r, ['commit', '-q', '-m', 'TASK-1']); + return { r, base }; +} + +test('receipt with a task over MCP is the contract receipt for that task, unsigned L0 without a role', async (t) => { + const { r, base } = taskFixture(); + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-mcp-empty-home-')); + t.after(() => { fs.rmSync(r, { recursive: true, force: true }); fs.rmSync(home, { recursive: true, force: true }); }); + const replies = await ask(r, [ + { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05' } }, + { jsonrpc: '2.0', method: 'notifications/initialized' }, + { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'receipt', arguments: { task: 'TASK-1', base } } }, + ], { AGENTKEY_HOME: home, PROOFLINE_REPOSITORY_VISIBILITY: 'private', PROOFLINE_RUN_ID: 'mcp-task-parity' }); + assert.equal(replies.length, 2); + const receipt = JSON.parse(replies[1].result.content[0].text); + const env = { AGENTKEY_HOME: home, PROOFLINE_REPOSITORY_VISIBILITY: 'private', PROOFLINE_RUN_ID: 'mcp-task-parity' }; + const cliReceipt = JSON.parse(execFileSync(process.execPath, [BIN, '--root', r, 'receipt', 'TASK-1', '--base', base, '--json'], { + cwd: r, + env: receiptEnv(env), + encoding: 'utf8', + })); + assert.equal(receipt.level, 'L0'); + assert.equal(receipt.signed, false); + assert.equal(receipt.exitCode, 0); + assert.equal(receipt.predicate.task.id, 'TASK-1'); + assert.equal(receipt.predicate.base.gitCommit, base); + assert.equal(receipt.predicate.tests.red_on_base.failed, true); + assert.equal(receipt.predicate.tests.green_on_head.passed, true); + assert.equal(receipt.predicate.scope.pass, true); + assert.match(receipt.reason, /no agent role configured/); + assert.deepEqual(comparableReceipt(receipt), comparableReceipt(cliReceipt)); + assert.notDeepEqual(receipt, receiptZeroConfig(r, { base })); +}); diff --git a/test/receipt.test.mjs b/test/receipt.test.mjs new file mode 100644 index 0000000..bf0fa6b --- /dev/null +++ b/test/receipt.test.mjs @@ -0,0 +1,159 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { execFileSync, spawnSync } from 'node:child_process'; +import test from 'node:test'; +import { generate, load, verifyDSSE } from '@optitransfer/agentkey'; +import { verifyReceipt } from '../src/verify-receipt.mjs'; +import { makeTask, skeleton } from '../src/contract.mjs'; + +const BIN = path.resolve(import.meta.dirname, '..', 'bin', 'proofline.mjs'); +const remote = 'https://github.com/example/receipt-fixture.git'; +const git = (cwd, args) => execFileSync('git', args, { cwd, encoding: 'utf8' }).trim(); + +function fixture() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-receipt-')); + git(root, ['init', '-q', '-b', 'main']); + git(root, ['config', 'user.name', 'receipt fixture']); + git(root, ['config', 'user.email', 'receipt@example.test']); + fs.mkdirSync(path.join(root, 'src'), { recursive: true }); + fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ type: 'module', scripts: { test: 'node --test' } }) + '\n'); + fs.writeFileSync(path.join(root, '.gitignore'), '.proofline/\n'); + fs.writeFileSync(path.join(root, 'src', 'answer.mjs'), 'export const answer = () => 0;\n'); + const contract = skeleton('receipt-fixture'); + contract.tasks = [makeTask({ + id: 'TASK-1', + title: 'Return the accepted answer', + scope: ['src/**', 'test/**'], + criteria: [ + { id: 'TASK-1-AC01', statement: 'the test fails on base and passes now', verifier: { type: 'test_red_green', test_file: 'test/answer.test.mjs', cmd: 'node --test {test}' } }, + { id: 'TASK-1-AC02', statement: 'the suite passes', verifier: { type: 'command', cmd: 'npm test' } }, + { id: 'TASK-1-AC03', statement: 'changes stay in scope', verifier: { type: 'scope' } }, + ], + })]; + fs.writeFileSync(path.join(root, 'proofline.json'), JSON.stringify(contract, null, 2) + '\n'); + git(root, ['add', '.gitignore', 'package.json', 'proofline.json', 'src/answer.mjs']); + git(root, ['commit', '-q', '-m', 'fixture base']); + const base = git(root, ['rev-parse', 'HEAD']); + git(root, ['remote', 'add', 'origin', remote]); + fs.writeFileSync(path.join(root, 'src', 'answer.mjs'), 'export const answer = () => 42;\n'); + fs.mkdirSync(path.join(root, 'test'), { recursive: true }); + fs.writeFileSync(path.join(root, 'test', 'answer.test.mjs'), [ + "import assert from 'node:assert/strict';", + "import test from 'node:test';", + "import { answer } from '../src/answer.mjs';", + "test('answer is accepted', () => assert.equal(answer(), 42));", + '', + ].join('\n')); + git(root, ['add', 'src/answer.mjs', 'test/answer.test.mjs']); + git(root, ['commit', '-q', '-m', 'TASK-1 implement accepted answer']); + return { root, base }; +} + +function runReceipt(root, base, env, args = []) { + return spawnSync(process.execPath, [BIN, 'receipt', 'TASK-1', '--root', root, '--base', base, '--json', ...args], { + cwd: root, + env, + encoding: 'utf8', + }); +} + +test('receipt command signs a contract check with bound evidence and a public subject', async (t) => { + const { root, base } = fixture(); + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-agentkey-home-')); + const outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-receipt-out-')); + const trust = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-trusted-keys-')); + t.after(() => { + fs.rmSync(root, { recursive: true, force: true }); + fs.rmSync(home, { recursive: true, force: true }); + fs.rmSync(outputDir, { recursive: true, force: true }); + fs.rmSync(trust, { recursive: true, force: true }); + }); + const env = { ...process.env, AGENTKEY_HOME: home, GITHUB_RUN_ID: 'fixture-run', PROOFLINE_REPOSITORY_VISIBILITY: 'public' }; + delete env.PROOFLINE_AGENT_ROLE; + generate('test-role', { env }); + const signer = load('test-role', { env }); + const outputPath = path.join(outputDir, 'receipt.json'); + const run = runReceipt(root, base, env, ['--role', 'test-role', '--out', outputPath]); + assert.equal(run.status, 0, run.stderr); + const output = JSON.parse(run.stdout); + assert.equal(output.exitCode, 0); + assert.equal(output.signed, true); + assert.equal(output.path, outputPath); + assert.equal(fs.existsSync(outputPath), true); + + const envelope = JSON.parse(fs.readFileSync(outputPath, 'utf8')); + const signed = verifyDSSE(envelope, [signer.publicKey]); + assert.equal(signed.ok, true); + const statement = JSON.parse(signed.payload.toString('utf8')); + assert.equal(statement.predicateType, 'https://proofline.dev/receipt/v1'); + assert.equal(statement.subject[0].name, `git+${remote}@${output.predicate.head.gitCommit}`); + assert.equal(statement.subject[0].digest.gitCommit, output.predicate.head.gitCommit); + assert.equal(statement.subject[0].digest.gitTree, output.predicate.head.gitTree); + assert.equal(output.predicate.base.gitCommit, base); + assert.equal(output.predicate.task.id, 'TASK-1'); + assert.equal(output.predicate.tests.red_on_base.ran, true); + assert.equal(output.predicate.tests.red_on_base.failed, true); + assert.equal(output.predicate.tests.green_on_head.ran, true); + assert.equal(output.predicate.tests.green_on_head.passed, true); + assert.equal(output.predicate.suite.command, 'npm test'); + assert.equal(output.predicate.suite.exit, 0); + assert.ok(output.predicate.suite.count > 0); + assert.ok(output.predicate.suite.duration_ms >= 0); + assert.deepEqual(output.predicate.scope.allowed, ['src/**', 'test/**']); + assert.equal(output.predicate.scope.pass, true); + assert.equal(output.predicate.forbidden.pass, true); + assert.equal(output.predicate.claims.ran, false); + assert.equal(output.predicate.claims.reconciled, null); + assert.equal(output.predicate.agent.role, 'test-role'); + assert.equal(output.predicate.agent.kid, signer.kid); + assert.equal(output.predicate.agent.run_id, 'fixture-run'); + + fs.copyFileSync(path.join(home, 'keys', 'test-role.pub'), path.join(trust, `${signer.kid}.pem`)); + const verified = await verifyReceipt(outputPath, { keys: trust, root }); + assert.equal(verified.exitCode, 0, verified.message); + + const recomputed = await verifyReceipt(outputPath, { keys: trust, root, recompute: true, base }); + assert.equal(recomputed.exitCode, 0, recomputed.message); + git(root, ['commit', '-q', '--allow-empty', '-m', 'same tree, different commit']); + const treeOnly = await verifyReceipt(outputPath, { keys: trust, root }); + assert.equal(treeOnly.exitCode, 2); + assert.match(treeOnly.message, /tree matches but the commit differs/); + const treeRecomputed = await verifyReceipt(outputPath, { keys: trust, root, recompute: true, base }); + assert.equal(treeRecomputed.exitCode, 0, treeRecomputed.message); +}); + +test('receipt without a configured role is unsigned L0 and preserves pass and fail exit statuses', (t) => { + const { root, base } = fixture(); + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-empty-agentkey-home-')); + t.after(() => { + fs.rmSync(root, { recursive: true, force: true }); + fs.rmSync(home, { recursive: true, force: true }); + }); + const env = { ...process.env, AGENTKEY_HOME: home, PROOFLINE_REPOSITORY_VISIBILITY: 'private' }; + delete env.PROOFLINE_AGENT_ROLE; + const outputPath = path.join(root, '.proofline', 'receipts', `${git(root, ['rev-parse', 'HEAD']).slice(0, 7)}.json`); + const run = runReceipt(root, base, env); + assert.equal(run.status, 0, run.stderr); + assert.match(run.stderr, /unsigned|no role|key/i); + const output = JSON.parse(run.stdout); + assert.equal(output.exitCode, 0); + assert.equal(output.level, 'L0'); + assert.equal(output.signed, false); + assert.equal(output.path, outputPath); + assert.equal(fs.existsSync(outputPath), true); + assert.equal(output.envelope.signatures.length, 0); + assert.equal(output.predicate.agent.role, null); + assert.equal(output.predicate.base.gitCommit, base); + const statement = JSON.parse(Buffer.from(output.envelope.payload, 'base64').toString('utf8')); + assert.equal(statement.subject[0].name, output.predicate.head.gitCommit); + assert.equal(output.predicate.repository.url, remote); + + fs.writeFileSync(path.join(root, 'src', 'answer.mjs'), 'export const answer = () => 0;\n'); + const failed = runReceipt(root, base, env); + assert.equal(failed.status, 1, failed.stderr); + assert.match(failed.stderr, /worktree is not clean/); + assert.equal(JSON.parse(failed.stdout).level, 'L0'); + assert.equal(JSON.parse(failed.stdout).exitCode, 1); +}); diff --git a/test/zeroconf_toolchains.test.mjs b/test/zeroconf_toolchains.test.mjs index 1115cf3..2553aa8 100644 --- a/test/zeroconf_toolchains.test.mjs +++ b/test/zeroconf_toolchains.test.mjs @@ -7,7 +7,7 @@ import { execFileSync, spawnSync } from 'node:child_process'; import { receiptZeroConfig } from '../src/infer.mjs'; const sh = (cwd, args) => execFileSync('git', args, { cwd, encoding: 'utf8' }); -const present = (bin) => spawnSync('bash', ['-lc', `command -v ${bin}`], { encoding: 'utf8' }).status === 0; +const present = (bin) => spawnSync(bin, bin === 'go' ? ['version'] : ['--version'], { encoding: 'utf8', timeout: 5000 }).status === 0; function fresh() { const r = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-tc-'));