Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

fix(rigor): bind drafts to observed failure proof [D1,D3,S1]

Corey Olsonc43dffb40e66
diff --git a/docs/api.md b/docs/api.md
index 888e1e02..8ca01a77 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -230,7 +230,10 @@ Rigor is how errors become doctrine or specs. It starts by noticing a failure ca
The person can mark a cause never-again from the main checkout's terminal: `pullboard fact <id> root-cause "<why>" --cause <key> --never-again --as person`. The fact is recorded as the person's, carries `cause` and `neverAgain: true`, and `rigor` lists its cause at once. An agent or a fact without `--as person` is refused with `RIGOR_PERSON_ONLY`. Over the relay, a fact move with person mode, a never-again or a cause key is accepted only from an authenticated person sender; an agent, a coordinator seat or the machine credential is refused with `RELAY_PERSON_ONLY` whatever channel the move names, and nothing is recorded. A move that carries a cause key needs move engine 30; moves without one replay as before.
-`pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit> [--section <letter>]` turns a cause that `rigor` lists into a draft row. The key must be listed now, or it is refused with `RIGOR_UNNOTICED`. First it proves the check: it runs `--check` with `sh -c` in a throwaway detached worktree at each commit. A work check counts problems: it exits 0 or 1 and prints one nonblank line per problem, at least one at `--red` and none at `--green`. A product check is a test: it exits nonzero at `--red` and 0 at `--green`. A cause that reads as both needs both. A missing `--check`, `--red` or `--green`, an unknown commit, a timeout, or a check that is not red then green is refused with `RIGOR_UNPROVEN`, naming what failed. Then it writes the rows through the same writer as `spec draft`, as `[draft, must]`: a work cause becomes a doctrine row `- <id> [draft, must] <rule> Why: rigor <key> failed on #a, #b; red at <sha>, green at <sha>. | gate: check <command> | count: 0`, a product cause a spec row with the same text and `gate: <command>`, and a cause that reads as both one of each. `--section` picks the section prefix; the default is the doctrine file's first section and the spec's G. Nothing is approved or applied: the person approves the rows in Pullboard View or with `spec approve`, and from then on the row's own gate holds it. The JSON result is `{version, key, reads, evidence: {items, occurrences, neverAgain}, proof: {check, red, green}, drafts: [{id, file, line, row}]}`, where `red` and `green` are `{commit, exit, problems, timedOut}`.
+`pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit> [--section <letter>]` turns a currently noticed cause into a draft row. `--red` must resolve to one of that exact cause's failure-receipt commits; an unrelated red commit is refused with `RIGOR_UNPROVEN`, naming the noticed commits. A work check exits 0 or 1 and prints problems at red and none at green. A product check fails at red and passes at green. For a `test:<file>::<title>` cause, the first supported proof format is a literal `node --test <file>` command, optionally with `--test-name-pattern`: the exact file must be regular in both commits, and complete real Node TAP must fail that named test at red and pass it at green without skipping it. Shell wrappers, other runners and unrelated files or selectors are refused rather than inferred to execute the named test. Node preload options are not carried into named-test proof. Ordinary board checks keep their existing runner support.
+
+The proof holds a real local machine gate while it runs on throwaway detached worktrees. Its owned child group is drained before each worktree is removed; an uncertain drain retains the worktree and refuses proof. Missing references, a timeout, incomplete test accounting or a check that is not red then green is `RIGOR_UNPROVEN`. Work causes draft doctrine with `gate: check <command> | count: 0`; product causes draft spec with the test gate; unclear test causes draft both, deriving a portable doctrine scanner that prints only a failed test run so a passing test has count zero. Each row's Why retains the evidence and both full commit hashes. Rows remain `[draft, must]`; only the person approves, and ordinary `spec apply` applies that decision with no extra proof-building item. The JSON result is `{version, key, reads, evidence: {items, occurrences, neverAgain}, proof: {check, red, green}, drafts: [{id, file, line, row}]}`; `red` and `green` retain `{commit, exit, problems, timedOut}`. `--section` selects the existing target section, defaulting to doctrine's first section or spec's G.
+
## Refusals
diff --git a/src/browser-admission.js b/src/browser-admission.js
index 4f842e95..d4e4aac3 100644
--- a/src/browser-admission.js
+++ b/src/browser-admission.js
@@ -34,7 +34,7 @@ const SAFE_CHILD_PROCESS_MODULES = new Map([
]);
/** Split a literal shell command into words, refusing expansion, operators, and incomplete quoting. */
-function literalShellWords(command) {
+export function literalShellWords(command) {
if (typeof command !== 'string' || !command.trim()) return null;
const words = [];
let word = '';
@@ -95,7 +95,7 @@ function explicitRunnerFiles(args) {
* @param {string | undefined} pathValue
* @returns {string | null}
*/
-function resolveExecutable(command, pathValue = process.env.PATH) {
+export function resolveExecutable(command, pathValue = process.env.PATH) {
if (command.includes('/')) return resolve(command);
const suffixes = process.platform === 'win32' ? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : [''];
for (const directory of (pathValue ?? '').split(process.platform === 'win32' ? ';' : ':')) {
diff --git a/src/cli.js b/src/cli.js
index 6390e4be..57001094 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -2259,13 +2259,13 @@ function readCommands(io, { first, second, rest, values }) {
*
* @param {any} io
* @param {{ second?: string, rest: string[], values: any }} args
- * @returns {number}
+ * @returns {Promise<number>}
*/
-function rigorDraftHere(io, { second, rest, values }) {
+async function rigorDraftHere(io, { second, rest, values }) {
if (rest.length > 1) throw new Refused('USAGE', 'pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit> [--section <letter>]');
const ctx = context(io);
- const events = withBoard(ctx, (board) => store.events(board));
- const result = rigorDraft({ root: ctx.info.root, config: ctx.config, events, person: store.PERSON },
+ const { events, actor } = withBoard(ctx, (board) => ({ events: store.events(board), actor: whoAmI(ctx, board).id }));
+ const result = await rigorDraft({ root: ctx.info.root, config: ctx.config, events, person: store.PERSON, agent: actor },
{ key: second, text: rest[0], check: values.check, red: values.red, green: values.green, section: values.section });
io.result?.(result);
io.say(`proved ${result.key}: red at ${result.proof.red.commit.slice(0, 12)} (${result.proof.red.problems} problem lines, exit ${result.proof.red.exit}), green at ${result.proof.green.commit.slice(0, 12)} (exit ${result.proof.green.exit})`);
diff --git a/src/help.js b/src/help.js
index 84d0451a..db87c2b0 100644
--- a/src/help.js
+++ b/src/help.js
@@ -177,8 +177,9 @@ Receipts
pullboard rigor failure causes that repeated: on 2 items, or 1 item at 2 commits;
each with its items and whether it reads as work, product or both
pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit> [--section <letter>]
- prove the check red at --red and green at --green, then draft a
- Doctrine row (work), a spec row (product) or both; only the person approves
+ --red is a noticed failure commit; prove its check red, then green at --green
+ draft Doctrine (work), spec (product) or both; only the person approves
+ test: causes need literal node --test <file> and the named test actually failing, then passing
Spec
pullboard spec --json parsed SPEC.md and doctrine rows as JSON
diff --git a/src/rigor-draft.js b/src/rigor-draft.js
index 90fc6b8c..ce65b672 100644
--- a/src/rigor-draft.js
+++ b/src/rigor-draft.js
@@ -5,74 +5,10 @@
* proof is the check run on real commits: red on the bad one, green on the fix. Nothing here
* approves or applies a row.
*/
-import { spawnSync } from 'node:child_process';
-import { mkdtempSync, rmSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { cleanGitEnvironment, resolveCommit, tryGit } from './git.js';
import { Refused } from './refused.js';
import { causeProblem, rigorReport } from './rigor.js';
import { draftRow } from './spec-draft.js';
-
-// budget: one proof run of a check at one commit; a check slower than this cannot gate a row.
-const CHECK_TIMEOUT_MS = 10 * 60_000;
-
-/** The refusal for a draft without a proof, naming what is missing and the full command shape. */
-function unproven(why, key) {
- return new Refused('RIGOR_UNPROVEN', `${why}; a draft needs its proof: pullboard rigor draft "${key}" "<rule>" --check "<command>" --red <commit where it fails> --green <commit where it passes>`);
-}
-
-/**
- * Run a check in a throwaway detached worktree at one commit and report its exit status and the
- * problem lines it printed (one nonblank stdout line per problem).
- *
- * @param {string} root
- * @param {string} commit
- * @param {string} check
- * @returns {{ commit: string, exit: number | null, problems: number, timedOut: boolean }}
- */
-export function runCheckAt(root, commit, check) {
- const dir = mkdtempSync(join(tmpdir(), 'pullboard-rigor-proof-'));
- const tree = join(dir, 'tree');
- const added = tryGit(root, ['worktree', 'add', '--detach', '--quiet', tree, commit]);
- try {
- if (added.status !== 0) throw new Refused('RIGOR_UNPROVEN', `cannot check out ${commit.slice(0, 12)} to prove the check: ${added.stderr || 'git worktree add failed'}; fetch the commit and retry`);
- const run = spawnSync('sh', ['-c', check], { cwd: tree, env: cleanGitEnvironment(), encoding: 'utf8', timeout: CHECK_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 });
- const problems = String(run.stdout ?? '').split(/\r?\n/u).filter((line) => line.trim()).length;
- return { commit, exit: run.status, problems, timedOut: Boolean(run.error) };
- } finally {
- if (added.status === 0) tryGit(root, ['worktree', 'remove', '--force', tree]);
- rmSync(dir, { recursive: true, force: true });
- }
-}
-
-/**
- * Prove a check red on the bad commit and green on the fix. A work check counts problems: it exits
- * 0 or 1 and prints at least one problem line at red and none at green. A product check is a test:
- * it exits nonzero at red and 0 at green. A cause that reads as both needs both.
- *
- * @param {string} root
- * @param {{ key: string, reads: string, check?: string, red?: string, green?: string }} request
- * @returns {{ check: string, red: object, green: object }}
- */
-export function proveCheck(root, { key, reads, check, red, green }) {
- if (!check?.trim()) throw unproven('no --check names the command that proves it', key);
- if (!red || !green) throw unproven(`no ${!red ? '--red' : '--green'} names the commit where the check ${!red ? 'fails' : 'passes'}`, key);
- const commits = [red, green].map((ref) => {
- const commit = resolveCommit(root, ref);
- if (!commit) throw unproven(`${ref} is not a commit in this repository`, key);
- return commit;
- });
- const [atRed, atGreen] = commits.map((commit) => runCheckAt(root, commit, check));
- for (const run of [atRed, atGreen]) if (run.timedOut) throw unproven(`the check did not finish at ${run.commit.slice(0, 12)}`, key);
- const work = reads !== 'product';
- const product = reads !== 'work';
- const counted = (run) => run.exit === 0 || run.exit === 1;
- if (work && (!counted(atRed) || !counted(atGreen))) throw unproven(`a work check exits 0 or 1 and prints one line per problem; it exited ${atRed.exit} at red and ${atGreen.exit} at green`, key);
- if (work && (atRed.problems < 1 || atGreen.problems > 0)) throw unproven(`the check printed ${atRed.problems} problems at red ${atRed.commit.slice(0, 12)} and ${atGreen.problems} at green ${atGreen.commit.slice(0, 12)}; red needs at least 1 and green none`, key);
- if (product && (atRed.exit === 0 || atGreen.exit !== 0)) throw unproven(`the test exited ${atRed.exit} at red ${atRed.commit.slice(0, 12)} and ${atGreen.exit} at green ${atGreen.commit.slice(0, 12)}; red needs a failure and green a pass`, key);
- return { check: check.trim(), red: atRed, green: atGreen };
-}
+import { proveCauseCheck } from './rigor-proof.js';
/**
* Draft the rows for a repeated cause, after proving its check. Refused when the key is malformed,
@@ -81,21 +17,21 @@ export function proveCheck(root, { key, reads, check, red, green }) {
*
* @param {{ root: string, config: any, events: any[], person: string }} board
* @param {{ key: string, text: string, check?: string, red?: string, green?: string, section?: string }} request
- * @returns {{ key: string, reads: string, evidence: { items: { id: number, commits: string[] }[], occurrences: number, neverAgain: boolean }, proof: object, drafts: object[] }}
+ * @returns {Promise<{ key: string, reads: string, evidence: { items: { id: number, commits: string[] }[], occurrences: number, neverAgain: boolean }, proof: object, drafts: object[] }>}
*/
-export function rigorDraft({ root, config, events, person }, { key, text, check, red, green, section }) {
+export async function rigorDraft({ root, config, events, person, agent }, { key, text, check, red, green, section }) {
const malformed = causeProblem(key ?? '');
if (malformed) throw malformed;
const cause = rigorReport(events, { person }).causes.find((entry) => entry.key === key);
if (!cause) throw new Refused('RIGOR_UNNOTICED', `${key} has not repeated, so there is nothing to draft yet; pullboard rigor lists the causes that can become rules`);
if (!text?.trim() || /[\r\n|]/u.test(text)) throw new Refused('USAGE', 'give the rule as one nonempty line without a field separator: pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit>');
if (cause.reads !== 'work' && / \| /u.test(check ?? '')) throw new Refused('USAGE', 'a spec row gate cannot hold " | "; put the pipeline in a script and name the script in --check');
- const proof = proveCheck(root, { key, reads: cause.reads, check, red, green });
+ const proof = await proveCauseCheck(root, cause, { check, red, green }, { agent });
const items = cause.items.map((item) => `#${item.id}`).join(', ');
- const why = `Why: rigor ${key.replaceAll('|', '/')} ${cause.neverAgain ? 'was marked never again by the person' : `failed on ${items}`}; red at ${proof.red.commit.slice(0, 12)}, green at ${proof.green.commit.slice(0, 12)}.`;
+ const why = `Why: rigor ${key.replaceAll('|', '/')} ${cause.neverAgain ? 'was marked never again by the person' : `failed on ${items}`}; red at ${proof.red.commit}, green at ${proof.green.commit}.`;
const rowText = `${text.trim()} ${why}`;
const drafts = [];
- if (cause.reads !== 'product') drafts.push(draftRow(root, config, { target: 'doctrine', text: rowText, gate: `check ${proof.check}`, fields: ['count: 0'], section }));
+ if (cause.reads !== 'product') drafts.push(draftRow(root, config, { target: 'doctrine', text: rowText, gate: `check ${proof.countCheck}`, fields: ['count: 0'], section }));
if (cause.reads !== 'work') drafts.push(draftRow(root, config, { target: 'spec', text: rowText, gate: proof.check, section }));
return { key, reads: cause.reads, evidence: { items: cause.items, occurrences: cause.occurrences, neverAgain: cause.neverAgain },
proof: { check: proof.check, red: proof.red, green: proof.green }, drafts };
diff --git a/src/rigor-proof.js b/src/rigor-proof.js
new file mode 100644
index 00000000..f0e43d6c
--- /dev/null
+++ b/src/rigor-proof.js
@@ -0,0 +1,251 @@
+/** Commit-bound, observed proof for a noticed failure cause; uncertain execution proves no rule [D1,D3,S1]. */
+import { spawn, spawnSync } from 'node:child_process';
+import { mkdtempSync, realpathSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { isAbsolute, join, posix } from 'node:path';
+import { literalShellWords, resolveExecutable } from './browser-admission.js';
+import { cleanGitEnvironment, resolveCommit, tryGit } from './git.js';
+import { parseProcessCensus } from './process-census.js';
+import { withGateSlot } from './gate.js';
+import { gateSlotEnvironment } from './resources.js';
+import { Refused } from './refused.js';
+
+const CHECK_TIMEOUT_MS = 10 * 60_000;
+const OUTPUT_LIMIT = 64 * 1024 * 1024;
+
+/** Name what a proof lacks and the noticed commits it must use, without interpreting failure prose. */
+export function unproven(why, key, receipts = []) {
+ return new Refused('RIGOR_UNPROVEN', `${why}; noticed failure commits: ${receipts.join(', ') || 'none'}; a draft needs its proof: pullboard rigor draft "${key}" "<rule>" --check "<command>" --red <noticed failure commit> --green <fix commit>`);
+}
+
+/** Quote a literal command word for the derived count check; no text becomes a shell expansion. */
+function quote(word) { return `'${word.replaceAll("'", "'\\''")}'`; }
+
+/** Resolve the caller's red to an exact failure receipt of this key before running any command. */
+export async function prepareCauseProof(root, cause, { check, red, green }) {
+ const receipts = [...new Set(cause.items.flatMap(item => item.commits))];
+ const refuse = why => { throw unproven(why, cause.key, receipts); };
+ if (!check?.trim()) refuse('no --check names the command that proves it');
+ if (!red || !green) refuse(`no ${!red ? '--red' : '--green'} names the commit where the check ${!red ? 'fails' : 'passes'}`);
+ const commits = [red, green].map(ref => resolveCommit(root, ref));
+ if (!commits[0] || !commits[1]) refuse('both proof references must resolve to commits in this repository');
+ if (!receipts.includes(commits[0])) refuse(`${commits[0]} is not a noticed failure receipt for ${cause.key}`);
+ const match = /^test:([^:]+)::(.+)$/u.exec(cause.key);
+ let runner = null;
+ if (match) {
+ const [, file, title] = match;
+ if (isAbsolute(file) || posix.normalize(file) !== file || file.startsWith('../') || file.includes('\\') || /[\0*?\[\]{}]/u.test(file)) refuse('the failing test must name a repository-relative regular file');
+ const words = literalShellWords(check);
+ const executable = words && resolveExecutable(words[0]);
+ let exactNode = false;
+ try { exactNode = Boolean(executable) && realpathSync(executable) === realpathSync(process.execPath); } catch { /* No verified executable. */ }
+ if (!exactNode || words[1] !== '--test') refuse(`the check for ${file}::${title} must be a literal Node test command: node --test ${quote(file)}; other runners cannot yet provide bound named-test proof`);
+ const args = words.slice(2);
+ let pattern = null;
+ const files = [];
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+ if (arg === '--test-name-pattern') {
+ if (pattern !== null || index + 1 === args.length) refuse('the named-test selector is missing or repeated');
+ pattern = args[++index];
+ } else if (arg.startsWith('--test-name-pattern=')) {
+ if (pattern !== null) refuse('the named-test selector is repeated');
+ pattern = arg.slice('--test-name-pattern='.length);
+ } else if (arg.startsWith('-')) refuse(`the proof does not accept the test option ${arg}; use the exact failing file and optional --test-name-pattern`);
+ else files.push(arg);
+ }
+ if (files.length !== 1 || files[0] !== file) refuse(`the check must execute exactly the noticed test file ${file}`);
+ if (pattern !== null) {
+ let selected = false;
+ try { selected = new RegExp(pattern).test(title); } catch { /* Invalid selectors cannot prove execution. */ }
+ if (!selected) refuse(`the check's selector excludes the noticed test ${title}`);
+ }
+ for (const commit of commits) {
+ const entry = tryGit(root, ['--literal-pathspecs', 'ls-tree', '-z', commit, '--', file]);
+ const records = entry.stdout.split('\0').filter(Boolean);
+ if (entry.status !== 0 || records.length !== 1 || !/^(?:100644|100755) blob [0-9a-f]+\t/u.test(records[0]) || records[0].slice(records[0].indexOf('\t') + 1) !== file) refuse(`${file} is not a regular committed test at ${commit}`);
+ }
+ // Force the real runner's machine-readable report; the caller cannot substitute a shell echo.
+ runner = { executable, command: words[0], args: ['--test', '--test-reporter=tap', ...args], file, title };
+ }
+ return { key: cause.key, receipts, check: check.trim(), commits, runner };
+}
+
+/** Read one positively owned detached process group; an unavailable census is never empty. */
+function processCensus() {
+ const read = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], { encoding: 'utf8', timeout: 3000, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, LC_ALL: 'C' } });
+ const rows = read.status === 0 ? parseProcessCensus(read.stdout) : null;
+ if (!rows) throw new Refused('RIGOR_UNPROVEN', 'the proof process census is unavailable; preserve its worktree and check the owned process before retrying');
+ return rows;
+}
+
+/** Read live members of one detached group from a locale-stable, validated census. */
+function groupMembers(pgid) {
+ return [...processCensus().values()].filter(row => row.pgid === pgid && !row.state.startsWith('Z'));
+}
+
+/** Stop and drain only a group whose leader still matches the identity captured at spawn. */
+async function drainGroup(pgid, anchor) {
+ if (!pgid || process.platform === 'win32') {
+ if (pgid) throw new Refused('RIGOR_UNPROVEN', 'owned proof process-group drain is unavailable on this platform; the worktree is retained');
+ return;
+ }
+ for (const signal of ['SIGTERM', 'SIGKILL']) {
+ const members = groupMembers(pgid);
+ if (!members.length) return;
+ if (!anchor) {
+ throw new Refused('RIGOR_UNPROVEN', `owned proof group ${pgid} remains without a captured leader identity; preserve the worktree and recover only after ownership is re-established`);
+ }
+ const current = processCensus().get(anchor.pid);
+ if (!current || current.pgid !== pgid || current.started !== anchor.started || current.processSha256 !== anchor.processSha256) {
+ throw new Refused('RIGOR_UNPROVEN', `owned proof group ${pgid} remains but its captured leader identity changed; preserve the worktree and recover only after ownership is re-established`);
+ }
+ try { process.kill(-pgid, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; }
+ const deadline = Date.now() + 2000;
+ do {
+ if (!groupMembers(pgid).length) return;
+ await new Promise(resolve => setTimeout(resolve, 25));
+ } while (Date.now() < deadline);
+ }
+ throw new Refused('RIGOR_UNPROVEN', 'the owned proof process group did not drain; its worktree is retained for recovery');
+}
+
+/** Run one bounded direct child (or a work scanner shell), retaining full output for proof evaluation. */
+async function runOwnedCheck(tree, check, runner, timeoutMs, gateEnvironment, recoveryPath) {
+ if (process.platform === 'win32') throw new Refused('RIGOR_UNPROVEN', 'this proof runner needs POSIX process-group ownership; no proof command was started');
+ const environment = { ...cleanGitEnvironment(), ...gateEnvironment };
+ // Proof of a named test uses the verified Node executable without externally injected preload code.
+ if (runner) delete environment.NODE_OPTIONS;
+ // The Node harness marker would silently skip a nested test command.
+ delete environment.NODE_TEST_CONTEXT;
+ const child = spawn(runner?.executable ?? '/bin/sh', runner?.args ?? ['-c', check], {
+ cwd: tree, env: environment, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ const stdout = [], stderr = [];
+ let anchor = null;
+ try { anchor = processCensus().get(child.pid) ?? null; } catch { /* Without a validated identity, cleanup fails closed and retains the worktree. */ }
+ let bytes = 0, failure = null, stopped = null;
+ let resolveInterrupted;
+ const interrupted = new Promise(resolve => { resolveInterrupted = resolve; });
+ /** Stop this owned group once and wake the runner when the bounded drain settles. */
+ const stop = reason => {
+ failure ??= new Error(reason);
+ if (!stopped) {
+ stopped = drainGroup(child.pid, anchor);
+ stopped.then(() => resolveInterrupted({ stopped: true }), error => resolveInterrupted({ cleanupError: error }));
+ }
+ };
+ /** Retain output within the proof's explicit byte bound; overflow proves nothing. */
+ const retain = chunks => part => {
+ bytes += part.length;
+ if (bytes > OUTPUT_LIMIT) stop('proof output exceeds its bound');
+ else chunks.push(part);
+ };
+ child.stdout.on('data', retain(stdout)); child.stderr.on('data', retain(stderr));
+ let closeResolve;
+ const closed = new Promise(resolve => { closeResolve = resolve; });
+ child.once('error', error => { failure = error; closeResolve({ exit: null }); });
+ child.once('close', (exit, signal) => closeResolve({ exit, signal }));
+ const timer = setTimeout(() => stop('proof deadline expired'), timeoutMs);
+ let result;
+ try {
+ result = await Promise.race([closed, interrupted]);
+ } finally {
+ clearTimeout(timer);
+ try {
+ // A close event may beat the interruption; still finish the drain before worktree removal.
+ if (stopped) await stopped;
+ else await drainGroup(child.pid, anchor);
+ } catch (error) {
+ // Preserve captured output, then release only our own pipes/handle so refusal cannot hang the CLI.
+ child.stdout.destroy(); child.stderr.destroy(); child.unref();
+ const identity = anchor ? `${anchor.pid}/${anchor.pgid}/${anchor.started}/${anchor.processSha256}` : 'unavailable';
+ const refused = new Refused('RIGOR_UNPROVEN', `proof process ${child.pid ?? 'unavailable'} could not be safely drained; preserve worktree ${recoveryPath}; captured leader identity ${identity}`);
+ refused.cause = error;
+ throw refused;
+ }
+ }
+ if (result.stopped) {
+ child.stdout.destroy(); child.stderr.destroy(); child.unref();
+ result = { exit: child.exitCode, signal: child.signalCode };
+ }
+ return { ...result, stdout: Buffer.concat(stdout).toString('utf8'), stderr: Buffer.concat(stderr).toString('utf8'), timedOut: Boolean(failure) };
+}
+
+/** Run an immutable commit's check, draining its child group before removing only this owned worktree. */
+export async function runCheckAt(root, commit, check, runner = null, { timeoutMs = CHECK_TIMEOUT_MS, gateEnvironment = {} } = {}) {
+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-rigor-proof-'));
+ const tree = join(dir, 'tree');
+ const added = tryGit(root, ['worktree', 'add', '--detach', '--quiet', tree, commit]);
+ let drained = added.status !== 0;
+ try {
+ if (added.status !== 0) throw unproven(`cannot check out ${commit}`, 'unknown');
+ const run = await runOwnedCheck(tree, check, runner, timeoutMs, gateEnvironment, tree);
+ drained = true;
+ return { commit, ...run, problems: run.stdout.split(/\r?\n/u).filter(line => line.trim()).length };
+ } catch (error) {
+ if (!drained) {
+ const message = `proof worktree retained for recovery: ${tree}; captured process recovery context: ${error instanceof Refused ? error.message : 'owned process state unavailable'}`;
+ throw new Refused('RIGOR_UNPROVEN', message);
+ }
+ throw error;
+ } finally {
+ if (drained) {
+ if (added.status === 0) {
+ const removed = tryGit(root, ['worktree', 'remove', '--force', tree]);
+ if (removed.status !== 0) throw new Refused('RIGOR_UNPROVEN', `the owned proof worktree at ${tree} could not be removed; clean it before retrying`);
+ }
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}
+
+/** Require complete real Node TAP accounting and one non-skipped result for the exact noticed title. */
+function observedTest(run, title, expected) {
+ const fields = ['tests', 'pass', 'fail', 'cancelled', 'skipped', 'todo'];
+ const summaries = [...run.stdout.matchAll(/^# (tests|pass|fail|cancelled|skipped|todo) (\d+)$/gmu)];
+ if (summaries.length !== fields.length || fields.some(key => summaries.filter(match => match[1] === key).length !== 1)) return false;
+ const counts = Object.fromEntries(summaries.map(match => [match[1], Number(match[2])]));
+ const records = [...run.stdout.matchAll(/^\s*(not ok|ok) \d+ - (.+)$/gmu)];
+ const plans = [...run.stdout.matchAll(/^1\.\.(\d+)$/gmu)];
+ const named = records.filter(match => match[2] === title);
+ const skipOrTodo = records.some(match => / # (?:SKIP|TODO)(?: |$)/u.test(match[2]));
+ const passed = records.filter(match => match[1] === 'ok').length;
+ const failed = records.filter(match => match[1] === 'not ok').length;
+ const complete = plans.length === 1 && Number(plans[0][1]) > 0
+ && counts.tests === records.length && counts.pass === passed && counts.fail === failed
+ && passed + failed === counts.tests && !skipOrTodo;
+ return complete && named.length === 1 && named[0][1] === expected && counts.cancelled === 0 && counts.skipped === 0 && counts.todo === 0;
+}
+
+/** Prove this key's exact noticed failure, retaining only summaries in the returned public draft result. */
+export async function proveCauseCheck(root, cause, request, { agent } = {}) {
+ const prepared = await prepareCauseProof(root, cause, request);
+ return await withGateSlot(root, lease => provePreparedCheck(root, cause, prepared, gateSlotEnvironment(lease)),
+ { browser: true, remote: false, agent, kind: 'rigor-proof' });
+}
+
+/** Run only an already validated cause proof while its real machine lease remains held. */
+async function provePreparedCheck(root, cause, prepared, gateEnvironment) {
+ const refuse = why => { throw unproven(why, cause.key, prepared.receipts); };
+ const runs = [];
+ for (const commit of prepared.commits) runs.push(await runCheckAt(root, commit, prepared.check, prepared.runner, { gateEnvironment }));
+ const [red, green] = runs;
+ if (runs.some(run => run.timedOut || run.exit === null)) refuse('the check did not complete at both commits');
+ if (prepared.runner) {
+ if (red.exit === 0 || green.exit !== 0 || !observedTest(red, prepared.runner.title, 'not ok') || !observedTest(green, prepared.runner.title, 'ok')) refuse(`the complete report must fail ${prepared.runner.file}::${prepared.runner.title} at red and pass it at green, without skips`);
+ } else {
+ const work = cause.reads !== 'product';
+ if (work && (![0, 1].includes(red.exit) || ![0, 1].includes(green.exit) || red.problems < 1 || green.problems > 0)) refuse('a work check exits 0 or 1, prints problems at red and none at green');
+ if (!work && (red.exit === 0 || green.exit !== 0)) refuse('the test must fail at red and pass at green');
+ }
+ const summary = ({ commit, exit, problems, timedOut }) => ({ commit, exit,
+ problems: prepared.runner ? Number(exit !== 0) : problems, timedOut });
+ // The complete original command proved the target red then green. Count just that same target in doctrine,
+ // with one line on failure and none on success, independently of TAP verbosity or unrelated tests in its file.
+ const exact = prepared.runner?.title.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
+ const countCheck = prepared.runner
+ ? `unset NODE_TEST_CONTEXT; ${[prepared.runner.command, '--test', '--test-reporter=tap', '--test-name-pattern', '^' + exact + '$', prepared.runner.file].map(quote).join(' ')} >/dev/null 2>&1; status=$?; if [ "$status" -ne 0 ]; then printf '%s\\n' 'The noticed test failed.'; fi; exit "$status"`
+ : prepared.check;
+ return { check: prepared.check, red: summary(red), green: summary(green), countCheck };
+}
diff --git a/test/api.test.js b/test/api.test.js
index 82375819..e714ee23 100644
--- a/test/api.test.js
+++ b/test/api.test.js
@@ -1033,8 +1033,8 @@ test('[A1] every catalog command and subcommand has a real CLI exercise', () =>
assert.equal(drafted.drafts.length, 1);
json(source, source.repo, 'spec', ['approve', 'G1'], 'approve');
json(source, source.repo, 'spec', ['decline', 'G1', '--reason', 'Catalog decline'], 'decline');
- writeFileSync(join(source.repo, 'SPEC.md'), `${readFileSync(join(source.repo, 'SPEC.md'), 'utf8')}- G2 [pending, must] Which store holds the catalog: SQLite. Choices: SQLite, Postgres. | gate: review\n`);
- json(source, source.repo, 'spec', ['answer', 'G2', 'Postgres'], 'answer');
+ writeFileSync(join(source.repo, 'SPEC.md'), `${readFileSync(join(source.repo, 'SPEC.md'), 'utf8')}- G3 [pending, must] Which store holds the catalog: SQLite. Choices: SQLite, Postgres. | gate: review\n`);
+ json(source, source.repo, 'spec', ['answer', 'G3', 'Postgres'], 'answer');
json(source, source.repo, 'spec', ['apply'], 'apply');
/** Exercise the agent-only takeover with a private explicit session, leaving later terminal calls markerless. */
diff --git a/test/rigor.test.js b/test/rigor.test.js
index 788823fb..8d250077 100644
--- a/test/rigor.test.js
+++ b/test/rigor.test.js
@@ -1,6 +1,7 @@
/** Rigor: a repeated failure cause is noticed from structured fields, never from notes [D1,V1]. */
import assert from 'node:assert/strict';
-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, watch, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
@@ -83,9 +84,9 @@ function history(file) {
/** A fresh 40-character commit id for each submission. */
const commit = () => (++next).toString(16).padStart(40, '0');
/** Claim and submit an item at a new commit, returning that commit. */
- const submit = (id) => {
+ const submit = (id, at = null) => {
store.claim(board, id, { agentId: builder, lane: 'app', leaseMs: 2 * HOUR, freeze });
- const sha = commit();
+ const sha = at ?? commit();
store.submit(board, id, { agentId: builder, commit: sha, tree: `tree-${sha}` });
return sha;
};
@@ -298,21 +299,36 @@ test('a repeated cause becomes a draft row with its proof [D1,D3,S1,P6]', async
// Two real commits: the bad one has a TODO and no fixed file; the fix removes the TODO and adds it.
mkdirSync(join(box.repo, 'src'), { recursive: true });
writeFileSync(join(box.repo, 'src', 'page.js'), '// TODO: escape the title\nexport const page = 1;\n');
- box.git('add', 'src/page.js');
+ mkdirSync(join(box.repo, 'test'), { recursive: true });
+ writeFileSync(join(box.repo, 'test', 'page.test.js'), "import { test } from 'node:test';\nimport assert from 'node:assert/strict';\nimport { page } from '../src/page.js';\ntest('[G1] the page::title is escaped', () => assert.equal(page, 2));\n");
+ box.git('add', 'src/page.js', 'test/page.test.js');
box.git('commit', '-q', '-m', 'chore: add the page');
const bad = box.git('rev-parse', 'HEAD');
- writeFileSync(join(box.repo, 'src', 'page.js'), 'export const page = 1;\n');
+ writeFileSync(join(box.repo, 'unrelated-note.txt'), 'An unrelated commit still has the same failure.\n');
+ box.git('add', 'unrelated-note.txt');
+ box.git('commit', '-q', '-m', 'chore: record an unrelated note');
+ const unrelatedBad = box.git('rev-parse', 'HEAD');
+ writeFileSync(join(box.repo, 'src', 'page.js'), 'export const page = 2;\n');
writeFileSync(join(box.repo, 'fixed.txt'), 'fixed\n');
box.git('add', 'src/page.js', 'fixed.txt');
box.git('commit', '-q', '-m', 'chore: escape the title');
const fix = box.git('rev-parse', 'HEAD');
+ const testFile = join(box.repo, 'test', 'page.test.js');
+ const testSource = readFileSync(testFile, 'utf8');
+ writeFileSync(testFile, testSource.replace("', () =>", "', { skip: true }, () =>"));
+ box.git('add', 'test/page.test.js');
+ box.git('commit', '-q', '-m', 'chore: record a skipped green test');
+ const skippedGreen = box.git('rev-parse', 'HEAD');
+ writeFileSync(testFile, testSource);
+ box.git('add', 'test/page.test.js');
+ box.git('commit', '-q', '-m', 'chore: restore the executed test');
const board = history(box.file);
const items = ['Work one', 'Work two', 'Product one', 'Product two', 'Both one', 'Both two', 'Lonely'].map(board.add);
const [workA, workB, productA, productB, bothA, bothB, lonely] = items;
- const bothKey = 'test:test/page.test.js::[G1] the page title is escaped';
+ const bothKey = 'test:test/page.test.js::[G1] the page::title is escaped';
for (const [id, cause] of [[workA, 'doctrine:C3'], [workB, 'doctrine:C3'], [productA, 'row:G1'], [productB, 'row:G1'], [bothA, bothKey], [bothB, bothKey], [lonely, 'refusal:LONELY']]) {
- board.submit(id); board.reject(id, cause);
+ board.submit(id, bad); board.reject(id, cause);
}
board.close();
const specBefore = readFileSync(join(box.repo, 'SPEC.md'), 'utf8');
@@ -320,6 +336,14 @@ test('a repeated cause becomes a draft row with its proof [D1,D3,S1,P6]', async
// Without proof, or with a proof that is not red then green, nothing is drafted.
const flags = (check, red, green) => ['--check', check, '--red', red, '--green', green];
+ const unrelatedRed = box.run('rigor', 'draft', 'doctrine:C3', 'No TODO markers in shipped source', ...flags('grep -rn TODO src', unrelatedBad, fix), '--json');
+ refused(unrelatedRed, 'RIGOR_UNPROVEN', 'a red commit outside the noticed failure receipts cannot prove this cause');
+ assert.ok(JSON.parse(unrelatedRed.stdout).error.message.includes(bad), 'the refusal names the actual noticed receipt commit');
+ const unrelatedCheck = box.run('rigor', 'draft', bothKey, 'Page titles are escaped', ...flags('! grep -rn TODO src', bad, fix), '--json');
+ refused(unrelatedCheck, 'RIGOR_UNPROVEN', 'an unrelated check cannot prove the named failing test');
+ assert.ok(JSON.parse(unrelatedCheck.stdout).error.message.includes(bad), 'an unrelated check refusal names the noticed receipt commit');
+ refused(box.run('rigor', 'draft', bothKey, 'Page titles are escaped', ...flags('node --test test/page.test.js', bad, skippedGreen), '--json'), 'RIGOR_UNPROVEN', 'a skipped green test is no passing proof');
+ refused(box.run('rigor', 'draft', bothKey, 'Page titles are escaped', ...flags("node --test --test-name-pattern 'a different test' test/page.test.js", bad, fix), '--json'), 'RIGOR_UNPROVEN', 'a selector that excludes the noticed test is no proof');
const unchecked = box.run('rigor', 'draft', 'doctrine:C3', 'No TODO markers in shipped source', '--json');
refused(unchecked, 'RIGOR_UNPROVEN', 'a draft without a check is unproven');
assert.match(JSON.parse(unchecked.stdout).error.message, /no --check names the command that proves it/u, 'the refusal names the missing check');
@@ -341,7 +365,7 @@ test('a repeated cause becomes a draft row with its proof [D1,D3,S1,P6]', async
assert.equal(work.drafts.length, 1);
const [doctrineRow] = work.drafts;
assert.equal(doctrineRow.file, 'DOCTRINE.md');
- assert.equal(doctrineRow.line, `- ${doctrineRow.id} [draft, must] No TODO markers in shipped source Why: rigor doctrine:C3 failed on #${workA}, #${workB}; red at ${bad.slice(0, 12)}, green at ${fix.slice(0, 12)}. | gate: check grep -rn TODO src | count: 0`);
+ assert.equal(doctrineRow.line, `- ${doctrineRow.id} [draft, must] No TODO markers in shipped source Why: rigor doctrine:C3 failed on #${workA}, #${workB}; red at ${bad}, green at ${fix}. | gate: check grep -rn TODO src | count: 0`);
assert.ok(readFileSync(join(box.repo, 'DOCTRINE.md'), 'utf8').includes(doctrineRow.line), 'the row is written into DOCTRINE.md');
assert.equal(readFileSync(join(box.repo, 'SPEC.md'), 'utf8'), specBefore, 'a work cause writes no spec row');
@@ -352,12 +376,23 @@ test('a repeated cause becomes a draft row with its proof [D1,D3,S1,P6]', async
assert.equal(product.drafts.length, 1);
const [specRow] = product.drafts;
assert.equal(specRow.file, 'SPEC.md');
- assert.equal(specRow.line, `- ${specRow.id} [draft, must] The fixed file exists Why: rigor row:G1 failed on #${productA}, #${productB}; red at ${bad.slice(0, 12)}, green at ${fix.slice(0, 12)}. | gate: test -f fixed.txt`);
+ assert.equal(specRow.line, `- ${specRow.id} [draft, must] The fixed file exists Why: rigor row:G1 failed on #${productA}, #${productB}; red at ${bad}, green at ${fix}. | gate: test -f fixed.txt`);
// An unclear cause drafts both, and the person picks.
- const both = json(box, 'rigor', 'draft', bothKey, 'Page titles are escaped', ...flags('! grep -rn TODO src', bad, fix));
+ const both = json(box, 'rigor', 'draft', bothKey, 'Page titles are escaped', ...flags("node --test test/page.test.js", bad, fix));
assert.equal(both.reads, 'both');
assert.deepEqual(both.drafts.map((draft) => draft.file), ['DOCTRINE.md', 'SPEC.md']);
+ const scanner = both.drafts.find(draft => draft.file === 'DOCTRINE.md').row.gate.slice('check '.length);
+ const scanned = runFixtureChild('/bin/sh', ['-c', scanner], { cwd: box.repo, env: box.env, encoding: 'utf8' });
+ assert.equal(scanned.status, 0, 'the derived count scanner succeeds on the fixed test');
+ assert.equal(scanned.stdout, '', 'a passing test really has zero problem lines in its doctrine scanner');
+ writeFileSync(join(box.repo, 'src', 'page.js'), 'export const page = 1;\n');
+ try {
+ const redScan = runFixtureChild('/bin/sh', ['-c', scanner], { cwd: box.repo, env: box.env, encoding: 'utf8' });
+ assert.equal(redScan.status, 1, 'the derived scanner really executes the failing target instead of inheriting a recursive-test skip');
+ assert.equal(redScan.stdout, 'The noticed test failed.\n', 'a failing target produces exactly one doctrine problem line');
+ } finally { writeFileSync(join(box.repo, 'src', 'page.js'), 'export const page = 2;\n'); }
+ assert.equal(both.drafts.find(draft => draft.file === 'SPEC.md').row.gate, 'node --test test/page.test.js', 'the product row keeps the actual test command');
// Drafting is any agent's; approving stays the person's, however an agent tries to reach it (P6).
const drafted = [doctrineRow.id, specRow.id];
@@ -392,3 +427,88 @@ test('a repeated cause becomes a draft row with its proof [D1,D3,S1,P6]', async
assert.deepEqual(applied.map((row) => row.status), ['approved', 'approved'], 'the person approved both rows and spec apply applied them');
assert.equal(json(box, 'list', '--all').items.length, itemsBefore, 'approval files no proof-building item; the draft already carries its proof');
});
+
+
+test('a timed-out proof drains only its captured process group before removing its worktree [D1,D3,S1]', async () => {
+ const { runCheckAt } = await import('../src/rigor-proof.js');
+ const { parseProcessCensus } = await import('../src/process-census.js');
+ const box = freshBoard();
+ const helper = join(box.repo, 'hold-proof.mjs');
+ const identities = join(box.dir, 'owned-processes.json');
+ const parserUrl = new URL('../src/process-census.js', import.meta.url).href;
+ const timeoutMs = 1000;
+ writeFileSync(helper, `
+ import { spawn, spawnSync } from 'node:child_process';
+ import { renameSync, writeFileSync } from 'node:fs';
+ import { parseProcessCensus } from ${JSON.stringify(parserUrl)};
+ const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)']);
+ await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });
+ const ps = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], { encoding: 'utf8', timeout: 2000, env: { ...process.env, LC_ALL: 'C' } });
+ const rows = ps.status === 0 ? parseProcessCensus(ps.stdout) : null;
+ const owned = rows && [process.pid, child.pid].map(pid => rows.get(pid));
+ if (!owned?.every(Boolean) || owned[0].pgid !== owned[1].pgid) process.exit(32);
+ writeFileSync(${JSON.stringify(identities + '.writing')}, JSON.stringify({ capturedAt: Date.now(), rows: owned }));
+ renameSync(${JSON.stringify(identities + '.writing')}, ${JSON.stringify(identities)});
+ setInterval(() => {}, 1000);
+ `);
+ box.git('add', 'hold-proof.mjs');
+ box.git('commit', '-q', '-m', 'test: add bounded proof process fixture');
+ const before = box.git('worktree', 'list', '--porcelain').split(/\n\n/u).filter(Boolean).length;
+ const startedAt = Date.now();
+ let watcher;
+ let watchdog;
+ const marker = new Promise((resolveMarker, rejectMarker) => {
+ watcher = watch(box.dir, (_event, name) => {
+ if (name?.toString() === 'owned-processes.json' && existsSync(identities)) resolveMarker();
+ });
+ watcher.once('error', rejectMarker);
+ watchdog = setTimeout(() => rejectMarker(new Error('timed-out process fixture did not record its identities')), 5000);
+ if (existsSync(identities)) resolveMarker();
+ });
+ const runOutcome = runCheckAt(box.repo, box.git('rev-parse', 'HEAD'), 'unused', {
+ executable: process.execPath, args: ['hold-proof.mjs', identities],
+ }, { timeoutMs }).then(value => ({ value }), error => ({ error }));
+ let result;
+ let failure;
+ try {
+ await marker;
+ const recorded = JSON.parse(readFileSync(identities, 'utf8'));
+ assert.ok(recorded.capturedAt - startedAt < timeoutMs, 'the fixture recorded identities before the configured timeout');
+ const preTimeoutResult = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], { encoding: 'utf8', timeout: 2000, env: { ...process.env, LC_ALL: 'C' } });
+ assert.equal(preTimeoutResult.status, 0, 'the pre-timeout census completed');
+ const preTimeout = parseProcessCensus(preTimeoutResult.stdout);
+ assert.ok(preTimeout, 'the pre-timeout census is parseable');
+ assert.equal(recorded.rows[0].pgid, recorded.rows[1].pgid, 'both captured processes belong to one group');
+ for (const identity of recorded.rows) {
+ const current = preTimeout.get(identity.pid);
+ assert.ok(current && current.pgid === identity.pgid && current.started === identity.started
+ && current.processSha256 === identity.processSha256 && !current.state.startsWith('Z'),
+ 'each real process identity is still present before timeout');
+ }
+ const outcome = await runOutcome;
+ if (outcome.error) throw outcome.error;
+ result = outcome.value;
+ assert.equal(result.timedOut, true, 'the owned proof reports its configured timeout');
+ const postTimeoutResult = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], { encoding: 'utf8', timeout: 2000, env: { ...process.env, LC_ALL: 'C' } });
+ assert.equal(postTimeoutResult.status, 0, 'the post-timeout process census completed');
+ const postTimeout = parseProcessCensus(postTimeoutResult.stdout);
+ assert.ok(postTimeout, 'the post-timeout process census is parseable');
+ for (const identity of recorded.rows) {
+ const current = postTimeout.get(identity.pid);
+ assert.ok(!current || current.state.startsWith('Z') || current.pgid !== identity.pgid
+ || current.started !== identity.started || current.processSha256 !== identity.processSha256,
+ 'each captured process is absent, a zombie, or a different process');
+ }
+ const after = box.git('worktree', 'list', '--porcelain').split(/\n\n/u).filter(Boolean).length;
+ assert.equal(after, before, 'the temporary proof worktree was removed after its group drained');
+ } catch (error) {
+ failure = error;
+ } finally {
+ clearTimeout(watchdog);
+ watcher?.close();
+ // Do not let fixture teardown remove files until the proof runner has completed cleanup.
+ const outcome = await runOutcome;
+ if (!failure && outcome.error) failure = outcome.error;
+ }
+ if (failure) throw failure;
+});