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.

feat(core): stamp native proof receipts [C7,H16]

Corey Olson0680cdbd57f6
diff --git a/src/board.js b/src/board.js
index 0887bd87..ccdb3eb6 100644
--- a/src/board.js
+++ b/src/board.js
@@ -146,6 +146,9 @@ export { declareJob, recordJobRun } from './recurring-jobs.js';
export { proposeSentinel, decideSentinel, beginSentinelRun, finishSentinelRun } from './sentinels.js';
export { flakeLedger, recordFlakeObservation } from './flakes.js';
export { flakeQuarantines, gateRuns, recordGateRun } from './quarantine.js';
+export { proofReceipts, recordProofRun } from './proof-receipts.js';
+import { refuseLongShout } from './proof-receipts.js';
+import { PROOF_RUN_ENGINE } from './proof-run-engine.js';
/** The seat readers live in seats.js; the board re-exports them so `store.*` callers keep one import. */
export { agentAt, agentById, agentCreator, coordinatorHolder, listAgents, nextSeatId, seatEnrolled, seatLineage, takeCoordinator, withVerifierStanding } from './seats.js';
@@ -1936,6 +1939,7 @@ function persistShout(board, { from, to, text, decision = false, answers = null,
* @returns {number}
*/
export function shout(board, message) {
+ if ((board.executionEngineVersion ?? ENGINE_VERSION) >= PROOF_RUN_ENGINE) refuseLongShout(message.text);
return atomic(board, () => insertShout(board, message));
}
diff --git a/src/commands/show.js b/src/commands/show.js
index 1bded843..0baf158a 100644
--- a/src/commands/show.js
+++ b/src/commands/show.js
@@ -39,7 +39,7 @@ import { relayStatus } from '../relay.js';
export function run(io, { first, values }) {
const ctx = context(io);
const id = idArg(first);
- const { item, verdicts, moves, thread, related, reviewer, agents, mainMerge, infra, approval } = withBoardRead(ctx, (board) => ({
+ const { item, verdicts, moves, thread, related, reviewer, agents, mainMerge, infra, approval, proofReceipts } = withBoardRead(ctx, (board) => ({
item: verdictProjector(ctx.info.root, board).project(store.getItem(board, id)),
verdicts: store.verdictsFor(board, id),
moves: store.events(board, { itemId: id }).filter((event) => ['attempt', 'escalate'].includes(event.event_kind)),
@@ -48,6 +48,7 @@ export function run(io, { first, values }) {
reviewer: store.reviewHolder(board, store.getItem(board, id)),
agents: store.listAgents(board), mainMerge: mainMergeFor(board, id), infra: infraNotes.infraNoteOf(store.events(board, { itemId: id })),
approval: specApprovalState(ctx.info.root, { board, config: ctx.config }),
+ proofReceipts: store.proofReceipts(board, id),
}));
const agentName = (id) => displayAgentName(agents.find((agent) => agent.agent_id === id) ?? { agent_id: id }, ctx.config.agents.names);
const agentApproved = itemAgentApprovals(item, approval);
@@ -55,7 +56,7 @@ export function run(io, { first, values }) {
// #922: moves on this item made while the relay was down wait in this machine's relay outbox until it answers.
const relayPending = (relayStatus(ctx.info.root).outbox ?? []).filter((move) => move.item === id);
if (values.json) {
- io.result({ ...item, verdicts, thread, agentApproved, approvalQualification, ...(relayPending.length ? { relayPending } : {}) });
+ io.result({ ...item, verdicts, thread, proofReceipts, agentApproved, approvalQualification, ...(relayPending.length ? { relayPending } : {}) });
return 0;
}
io.say(itemLine(item, agentName, Boolean(mainMerge)));
@@ -63,6 +64,12 @@ export function run(io, { first, values }) {
if (item.item_verdict_state) io.say(staleVerdictRefusal(item, item.item_verdict_state).message);
if (item.item_criterion) io.say(`criterion: ${item.item_criterion}`);
if (item.item_check) io.say(`check: ${item.item_check}`);
+ for (const receipt of proofReceipts) {
+ const runtime = receipt.environment ? `Node ${receipt.environment.node} ${receipt.environment.platform}/${receipt.environment.arch}` : 'runtime unknown';
+ const counts = Object.values(receipt.counts).some(value => value === null) ? 'test counts unknown'
+ : `${receipt.counts.passed} pass, ${receipt.counts.failed} fail, ${receipt.counts.skipped} skip`;
+ io.say(`receipt ${receipt.id}: ${receipt.kind}, ${receipt.commit?.slice(0, 12) ?? 'commit unknown'}, ${runtime}, runner ${receipt.runner ?? 'unknown'}, seat ${receipt.seat}, parent ${receipt.parentSession ?? 'unknown'}, exit ${receipt.exitCode ?? 'unknown'}, ${counts}, ${receipt.durationMs}ms${receipt.sourceClean ? '' : ', source unproven'}`);
+ }
sayCheckBaseline(io, item);
sayBrief(io, item.item_brief);
for (const move of relayPending) io.say(`pending in the relay outbox: ${move.operation}${move.actor ? ` by ${move.actor}` : ''} (made ${move.queuedAt}); it goes up in order when the relay answers`);
@@ -98,6 +105,7 @@ export function run(io, { first, values }) {
if (item.item_withdrawn_reason) io.say(`withdrawn: ${item.item_withdrawn_reason}`);
io.say('thread:');
for (const entry of thread) {
+ if (entry.kind === 'proof-run') continue;
const stamp = ` ${entry.at} ${agentDisplayName(agents, ctx.config, entry.by)} `;
if (entry.type === 'fact') {
io.say(`${stamp}fact ${entry.kind} ${entry.id}${entry.supersedes ? ' (supersedes ' + entry.supersedes + ')' : ''}: ${entry.text}`);
diff --git a/src/commands/submit.js b/src/commands/submit.js
index 06362df2..fafff292 100644
--- a/src/commands/submit.js
+++ b/src/commands/submit.js
@@ -12,6 +12,7 @@ import {
ruleLine,
} from '../doctrine-checks.js';
import * as gateReceipt from '../gate-receipt.js';
+import { recordNativeProof } from '../proof-cli.js';
import {
gateWaitReporter,
} from '../gate-wait.js';
@@ -168,7 +169,11 @@ export async function submitHere(ctx, id, infra) {
// The accepted project runner interprets its current invariant files; candidate config cannot replace it.
...(acceptedMain.config.submitInvariants.length ? { affectedTests: acceptedMain.config.affectedTests } : {}) };
const gate = await runSubmitGate(root, submitConfig, { base: claimHead, trunk: acceptedMain.commit, check: frozenCheck(held), agent: me.id, item: String(id), onWait: queuedItemLease(ctx, held, me.id, 'build'), onBrowserFallback: browserAdmissionReporter(ctx.io, ctx.io.relayJson),
+ proofContext: { item: id, frozenDigest: held.item_frozen_digest ?? null, seat: me.id },
onFailure: nativeFlakes.observer(ctx, { kind: 'submit', main: acceptedMain.commit, config: submitConfig }, { ordered, withBoard, resourceAgent }) });
+ for (const proofReceiptId of gate.proofReceiptIds ?? []) {
+ await recordNativeProof(ctx, held, { proofReceiptId }, { ordered, withBoard, resourceAgent });
+ }
// Only the person's live waivers can pass a red proof, failure by failure; the item's own check is never waived [B3].
const waived = !gate.isGreen && gate.check?.green ? withBoard(ctx, (board) => waivedFailures(board, accountedFailures(gate, root))) : null;
if (!gate.isGreen && !waived) {
diff --git a/src/engine.js b/src/engine.js
index eb8926ac..51e133df 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -41,6 +41,8 @@ import {
canonicalMilestoneTarget,
} from './milestones.js';
import { Refused } from './refused.js';
+import { boundProofReceipt } from './proof-receipts.js';
+import { PROOF_RUN_ENGINE } from './proof-run-engine.js';
import { firstRefusal } from './claims.js';
import {
requestMoveProblem,
@@ -79,7 +81,7 @@ export const ENGINE_OPERATIONS = Object.freeze([
'recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'appendFact', 'recordSpecApprovalBaseline',
'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch', 'acceptCheck',
'recordHealthFindings', 'proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun',
- 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove',
+ 'recordFlakeObservation', 'recordGateRun', 'recordProofRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove',
]);
/** Engine version at which each ordered operation first has stable replay semantics. */
@@ -99,6 +101,7 @@ function minimumOperationEngine(operation, args, board, at) {
if (['proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun'].includes(operation) || typeof args[1]?.cause === 'string' && args[1].cause.startsWith('sentinel:')) return BOARD_SENTINEL_ENGINE;
if (['declareJob', 'recordJobRun'].includes(operation)) return RECURRING_JOB_ENGINE;
if (operation === 'recordGateRun') return GATE_RUN_ENGINE;
+ if (operation === 'recordProofRun') return PROOF_RUN_ENGINE;
if (operation === 'recordHealthFindings') return HEALTH_SENTINEL_ENGINE;
if (operation === 'reserveNextReview' && Array.isArray(args[0]?.skipIds) && args[0].skipIds.length) return REVIEW_SKIP_ENGINE;
const options = args[1];
@@ -165,6 +168,10 @@ export function prepareEngineMove(board, operation, args, { id = randomUUID(), a
// A gate run is sealed only as its gate's own receipt; a run made up by hand is refused before it reaches any replica.
if (operation === 'recordGateRun') requireBound(board, args[0]?.receipt);
const values = args.map((value) => value && typeof value === 'object' ? { ...value } : value);
+ if (operation === 'recordProofRun') {
+ const receipt = boundProofReceipt(board, args[0]);
+ values[0] = { agentId: args[0].agentId, itemId: args[0].itemId, receipt };
+ }
if (operation === 'release') {
const problem = store.reviewReleaseNoteProblem(board, values[0], values[1], values[2]);
if (problem) throw problem;
diff --git a/src/gate-run-receipt.js b/src/gate-run-receipt.js
index 76dbbbf9..4f2d8fe9 100644
--- a/src/gate-run-receipt.js
+++ b/src/gate-run-receipt.js
@@ -11,6 +11,7 @@ import {
join,
} from 'node:path';
import { tryGit } from './git.js';
+import { proofFields } from './proof-provenance.js';
/** The folder beside the board that holds gate run receipts. */
export const RECEIPT_FOLDER = 'gate-receipts';
@@ -54,7 +55,7 @@ function line(value, limit) {
* must not fail a run over its receipt, and the board names its own refusal.
*
* @param {any} value
- * @returns {{ version: 1, id: string, kind: string, tree: string, head: string, main: string | null, command: string, green: boolean, failures: Array<{ file: string, name: string }>, load: { average: number[], cpus: number, freeMB: number }, at: string } | null}
+ * @returns {object | null} A canonical legacy gate or native proof receipt.
*/
export function receiptFields(value) {
try { return checkedFields(value); } catch { return null; }
@@ -63,8 +64,13 @@ export function receiptFields(value) {
/** The checks behind receiptFields; each malformed field throws, and receiptFields turns that into null. */
function checkedFields(value) {
const bad = () => new TypeError('malformed gate receipt');
- if (!value || value.version !== 1 || !ID.test(value.id ?? '') || !['gate', 'land', 'submit'].includes(value.kind) || !SHA.test(value.tree ?? '')
- || !SHA.test(value.head ?? '') || value.main !== null && !SHA.test(value.main ?? '') || !DIGEST.test(value.command ?? '')
+ const proof = value?.version === 2 ? proofFields(value.proof) : null;
+ const version = value?.version;
+ const kinds = version === 2 ? ['check', 'submit', 'verdict'] : ['gate', 'land', 'submit'];
+ if (!value || ![1, 2].includes(version) || version === 2 && !proof || !ID.test(value.id ?? '') || !kinds.includes(value.kind)
+ || !(version === 2 && value.tree === null) && !SHA.test(value.tree ?? '')
+ || !(version === 2 && value.head === null) && !SHA.test(value.head ?? '')
+ || value.main !== null && !SHA.test(value.main ?? '') || !DIGEST.test(value.command ?? '')
|| typeof value.green !== 'boolean' || !Array.isArray(value.failures) || value.failures.length > MOST_FAILURES
|| value.green && value.failures.length > 0 || !line(value.at, 40) || !Number.isFinite(Date.parse(value.at))) throw bad();
const failures = value.failures.map((entry) => {
@@ -73,10 +79,11 @@ function checkedFields(value) {
return { file, name };
});
const load = value.load;
- if (!load || !Array.isArray(load.average) || load.average.length !== 3 || load.average.some((number) => !Number.isFinite(number) || number < 0)
- || !Number.isSafeInteger(load.cpus) || load.cpus < 1 || !Number.isSafeInteger(load.freeMB) || load.freeMB < 0) throw bad();
- return { version: 1, id: value.id, kind: value.kind, tree: value.tree, head: value.head, main: value.main, command: value.command,
- green: value.green, failures, load: { average: [...load.average], cpus: load.cpus, freeMB: load.freeMB }, at: value.at };
+ if (!(version === 2 && load === null) && (!load || !Array.isArray(load.average) || load.average.length !== 3 || load.average.some((number) => !Number.isFinite(number) || number < 0)
+ || !Number.isSafeInteger(load.cpus) || load.cpus < 1 || !Number.isSafeInteger(load.freeMB) || load.freeMB < 0)) throw bad();
+ return { version, id: value.id, kind: value.kind, tree: value.tree, head: value.head, main: value.main, command: value.command,
+ green: value.green, failures, load: load === null ? null : { average: [...load.average], cpus: load.cpus, freeMB: load.freeMB }, at: value.at,
+ ...(proof ? { proof } : {}) };
}
/**
diff --git a/src/gate.js b/src/gate.js
index 83c179ac..05ba1712 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -44,6 +44,7 @@ import {
headTree,
invalidateGitFacts,
isClean,
+ tryGit,
untracked,
} from './git.js';
import { recordGateRun } from './gate-control.js';
@@ -56,7 +57,13 @@ import {
committedTest,
tapTests,
} from './tap-tests.js';
-import { mainPolicy } from './trusted-policy.js';
+import {
+ checkAtCommit,
+ frozenCheck,
+ mainPolicy,
+} from './trusted-policy.js';
+import { proofCounts } from './proof-provenance.js';
+import { logLines } from './timing.js';
import { secretsIn } from './hooks.js';
import { Refused } from './refused.js';
import { missingGate } from './gate-config.js';
@@ -296,12 +303,12 @@ export function runShell(root, command, { pipefail = false, env = {}, stages = f
const raw = `${result.stdout ?? ''}${result.stderr ?? ''}`;
const seconds = Math.round((Date.now() - started) / 1000);
const blocked = (output) => (result.status === 0 ? null : sandboxBlockedOperation(root, output));
- if (!stages) return { isGreen: result.status === 0, output: raw, seconds, ...(timed ? { timedOut: result.timedOut } : {}), sandboxBlocked: blocked(raw) };
- if (!split) return { isGreen: result.status === 0, output: raw, seconds, stages: null, ...(timed ? { timedOut: result.timedOut } : {}), sandboxBlocked: blocked(raw) };
+ if (!stages) return { isGreen: result.status === 0, exitCode: result.status, output: raw, seconds, ...(timed ? { timedOut: result.timedOut } : {}), sandboxBlocked: blocked(raw) };
+ if (!split) return { isGreen: result.status === 0, exitCode: result.status, output: raw, seconds, stages: null, ...(timed ? { timedOut: result.timedOut } : {}), sandboxBlocked: blocked(raw) };
const staged = readStages(raw, marker, split.length);
// Each pipeline component's own status rides on its stage, so no failing producer hides behind a later one.
const withPipes = staged.stages.map((stage, index) => (pipeStatuses?.[index] ? { ...stage, pipeline: pipeStatuses[index] } : stage));
- return { isGreen: result.status === 0, seconds, ...(timed ? { timedOut: result.timedOut } : {}), ...staged, stages: withPipes, sandboxBlocked: blocked(staged.output) };
+ return { isGreen: result.status === 0, exitCode: result.status, seconds, ...(timed ? { timedOut: result.timedOut } : {}), ...staged, stages: withPipes, sandboxBlocked: blocked(staged.output) };
}
/** Refuse an environment-blocked proof after its ordinary raw logs and timings are persisted. */
@@ -325,6 +332,7 @@ function safeLog(output) {
* @param {{ waitMs?: number, artifactDirectory?: string, artifactPrefix?: string, persistLog?: boolean, profileFile?: string, pipefail?: boolean, gateSlotHeld?: boolean, gateLease?: object, landing?: boolean, stages?: boolean, timeoutMs?: number, waivers?: Array<{ kind: string, test: string }> }} [options]
*/
export function runProfiledShell(root, command, { waitMs = 0, artifactDirectory, artifactPrefix = 'pullboard-gate', persistLog = false, profileFile, pipefail = false, gateSlotHeld = false, gateLease, landing = false, stages = false, waivers = [], timeoutMs } = {}) {
+ const proofSource = gateLease?.proof ? proofSourceAt(root) : null;
const directory = artifactDirectory ?? dirname(gitPath(root, LOG));
mkdirSync(directory, { recursive: true, mode: 0o700 });
const id = randomUUID();
@@ -354,7 +362,58 @@ export function runProfiledShell(root, command, { waitMs = 0, artifactDirectory,
...runTiming(profiledRun, command),
waitMs: Math.max(0, Math.round(waitMs)), wallMs: Math.max(0, Date.now() - started), receipt: settleReceipt(gateLease),
});
- return { ...profiledRun, profile, profilePath, logPath };
+ const result = { ...profiledRun, profile, profilePath, logPath };
+ const proofReceiptId = gateLease?.proof && leaveProofReceipt(root, command, result, proofSource, gateLease.proof, gateLease);
+ return { ...result, ...(proofReceiptId ? { proofReceiptId } : {}) };
+}
+
+/** Capture source identifiers before execution; a dirty tree remains explicitly unproven. */
+function proofSourceAt(root, commit = null) {
+ invalidateGitFacts(); // The child may have changed Git facts outside this command context.
+ const head = commit ?? headCommit(root);
+ const tree = head ? tryGit(root, ['rev-parse', '--verify', `${head}^{tree}`], { env: gitChildEnv(root) }) : null;
+ return { head, tree: tree?.status === 0 ? tree.stdout : null, clean: commit !== null || committedTree(root) !== null };
+}
+
+/** The private gate writer records process results, never provenance supplied by a CLI argument. */
+function leaveProofReceipt(root, command, run, before, context, lease) {
+ try {
+ if (!before || run.sandboxBlocked || run.exitCode === undefined) return null;
+ const store = receiptStore(root);
+ if (!store) return null;
+ const after = context.commit ? before : proofSourceAt(root);
+ const source = run.executionSource ?? run.profile?.executionSource;
+ const sourceClean = before.clean && after.clean && before.head === after.head && before.tree === after.tree
+ && run.executionSourceUnchanged !== false && (!source || source.commit === before.head && source.tree === before.tree)
+ && (!lease?.runner || Boolean(source));
+ const environment = run.environment ?? run.profile?.environment ?? null;
+ const remote = run.executionRunner ?? run.profile?.executionRunner;
+ const localLoad = { average: loadavg(), cpus: availableParallelism(), freeMB: Math.floor(freemem() / 1048576) };
+ let main = null;
+ try { main = mainPolicy(root).commit; } catch { /* An unavailable policy remains unknown in this execution record. */ }
+ const receipt = receiptFields({ version: 2, id: randomUUID(), kind: context.kind,
+ tree: before.tree, head: before.head, main, command: createHash('sha256').update(command).digest('hex'),
+ green: run.isGreen ?? run.state === 'pass', failures: [],
+ load: run.executionLoad ?? (remote || lease?.runner ? null : localLoad), at: new Date().toISOString(),
+ proof: { item: context.item, frozenDigest: context.frozenDigest ?? null, seat: context.seat,
+ environment, runner: remote ?? (lease?.runner ? null : 'local'), exitCode: run.exitCode,
+ counts: proofCounts(run.outputPath ? logLines(run.outputPath) : run.output ?? ''),
+ durationMs: Math.max(0, Math.round(run.remoteWallMs ?? run.profile?.wallMs ?? run.seconds * 1000)), sourceClean } });
+ if (!receipt) return null;
+ mkdirSync(store, { recursive: true, mode: 0o700 });
+ writeFileSync(join(store, `${receipt.id}.json`), receiptBody(receipt), { flag: 'wx', mode: 0o600 });
+ return receipt.id;
+ } catch { return null; /* A missing receipt is refused by the CLI before it records a verdict. */ }
+}
+
+/** Execute a private immutable check before the gate writes its provenance. */
+export function runFrozenProof(root, item, { gateLease, waitMs = 0 } = {}) {
+ const context = { item: item.item_id, frozenDigest: item.item_frozen_digest ?? null,
+ seat: gateLease?.proof?.seat, kind: 'verdict', commit: item.item_commit };
+ const before = proofSourceAt(root, item.item_commit);
+ const result = checkAtCommit(root, item, { gateLease, waitMs });
+ const id = result.executed ? leaveProofReceipt(root, frozenCheck(item), result, before, context, gateLease) : null;
+ return { ...result, ...(id ? { proofReceiptId: id } : {}) };
}
/** Run an independent focused comparison without blocking other holders of the machine pool.
@@ -689,7 +748,8 @@ function fullGateRun(root, config, trustStamp = false, { waitMs = 0, log = gitPa
const receiptId = run.sandboxBlocked ? null : leaveRunReceipt(root, config, run, { before, kind });
refuseSandboxBlocked(run);
if (isGreen && before !== null && committedTree(root) === before) writeFileSync(gitPath(root, STAMP), `${before}\n`);
- return { isGreen, isCached: false, output, seconds, log, profile, profilePath, receiptId, ...(run.timedOut ? { timedOut: true } : {}), ...(run.executionRoot ? { executionRoot: run.executionRoot } : {}),
+ return { isGreen, isCached: false, output, seconds, log, profile, profilePath, receiptId,
+ ...(run.proofReceiptId ? { proofReceiptId: run.proofReceiptId } : {}), ...(run.timedOut ? { timedOut: true } : {}), ...(run.executionRoot ? { executionRoot: run.executionRoot } : {}),
// A remote run's host load and pinned main reach the flake diagnostics with it (#925).
...(run.executionRunner ? { executionRunner: run.executionRunner, executionMain: run.executionMain ?? null, executionLoad: run.executionLoad ?? null } : {}), ...(stages ? { stages: run.stages } : {}) };
}
@@ -743,7 +803,7 @@ export async function runStaticChecks(root, config, { agent, item = '', onWait,
* @param {{base:string|null, trunk?:string, changed?:string[], check:string, agent?:string, item?:string|number, kind?:string, onWait?:(state:object)=>void, onBrowserFallback?:(decision:{file:string,reason:string})=>void}} options
* @returns {Promise<any>}
*/
-export async function runSubmitGate(root, config, { base, trunk, changed, check, agent, item = '', kind = 'submit', onWait, onBrowserFallback, onFailure }) {
+export async function runSubmitGate(root, config, { base, trunk, changed, check, agent, item = '', kind = 'submit', onWait, onBrowserFallback, onFailure, proofContext }) {
if (!config.gate.trim()) throw missingGate(root);
await runStaticChecks(root, config, { agent, item, onWait, onBrowserFallback });
const selection = config.affectedTests
@@ -770,6 +830,7 @@ export async function runSubmitGate(root, config, { base, trunk, changed, check,
: (selection.full || !allowBrowserFreeChecks || await testsNeedBrowser(root, proofFiles, { onFallback: onBrowserFallback }));
const browser = checkUsesBrowser || proofUsesBrowser;
return await withGateSlot(root, async (lease) => {
+ if (proofContext) lease.proof = { ...proofContext, kind: 'submit' };
pinRunMain(lease, onFailure);
const startedAt = Date.now();
const log = gitPath(root, 'pullboard-submit.log');
@@ -797,7 +858,9 @@ export async function runSubmitGate(root, config, { base, trunk, changed, check,
refuseSandboxBlocked(proof);
return { ...proof, log, seconds: criterion.seconds + proof.seconds, ...selection, ...(deferred ? { files: proofFiles, submitInvariants: invariants } : {}),
...(deferSelection ? { deferredFiles: selection.files, deferAbove: config.submitDeferAbove } : {}), deferred, deferFullFallback, check: receipt,
- profile, profilePath, proofProfilePath: proof.profilePath, proofLog: proof.log };
+ profile, profilePath, proofProfilePath: proof.profilePath, proofLog: proof.log,
+ proofReceiptIds: [...(check ? [criterion.proofReceiptId ?? null] : []),
+ ...(proof.profile ? [proof.proofReceiptId ?? null] : [])] };
};
if (!criterion.isGreen) {
writeFileSync(log, criterion.output);
diff --git a/src/machine.js b/src/machine.js
index e8f4c714..b65e35bf 100644
--- a/src/machine.js
+++ b/src/machine.js
@@ -185,6 +185,7 @@ export const GUARDS = [
{ id: 'checkProvesSomething', refuse: 'CRITERION_PROVES_NOTHING', rule: "the item's check does not already pass on main, or the person accepted that exact check", next: 'set a check that fails before the work, or the person runs pullboard check accept <id>', source: 'cli', when: 'only when accepted main sets checks.provesNothing to "hold"' },
{ id: 'gateGreen', refuse: 'GATE_RED', alsoRefuses: [{ code: 'LAND_TIMEOUT_CUSTODY', next: 'inspect the saved timed gate cleanup state and stop only its proven owned processes before starting another landing' }, { code: 'LAND_GATE_OUTPUT', next: 'inspect the retained timed gate output directory and free disk space, then start another landing' }, { code: 'SLOT_DB_LOCKED', next: 'the run never started, so it is not a red; rerun the same command once the named process releases the slot database' }, { code: 'RUNNER_BROWSER_SLOT_REQUIRED', next: 'nothing to do: the run reruns on a local gate slot; if it repeats, set gate.browserByLaunch the same on this machine and that runner' }, { code: 'PIPEFAIL_UNAVAILABLE', next: 'rewrite the gate without a pipe' }], rule: 'the gate, which submit runs itself every time, is green at HEAD', next: 'fix what the digest names, commit, submit again', source: 'cli' },
{ id: 'queuedItemLease', refuse: 'ITEM_LEASE_LOST', alsoRefuses: [{ code: 'A5_GRAMMAR_VERSION', next: 'upgrade Pullboard or restore a spec written for grammar 1, then retry' }, { code: 'SPEC_BEHIND_MAIN', next: 'merge main into this worktree, then renew the claim and retry' }, { code: 'NOT_A_REPO', next: 'restore the worktree Git metadata, then retry the command' }, { code: 'NO_CONFIG', next: 'restore pullboard.json in this worktree, then retry the command' }], rule: 'the caller still owns the same live item claim or review and can renew it against the frozen criterion', next: 'claim or reserve the item again before retrying the command', source: 'cli', when: 'while submit or an accept waits for a machine slot, and once immediately before admission' },
+ { id: 'proofRecorded', refuse: 'PROOF_RUN_UNAVAILABLE', alsoRefuses: [{ code: 'PROOF_RUN_UNBOUND', next: 'restore the native gate receipt; do not supply provenance by hand' }, { code: 'PROOF_RUN_ACTOR', next: 'use the receipt from your own seat' }, { code: 'PROOF_RUN_STALE', next: 'read the changed criterion before running a new proof' }, { code: 'PROOF_RUN_CHANGED', next: 'keep the original receipt and run a new proof' }], rule: 'every executed proof is recorded from its native gate receipt before the item outcome', next: 'restore receipt storage and read pullboard show <id>', source: 'cli' },
{ id: 'treeStillDuringGate', refuse: 'MOVED_DURING_GATE', rule: 'when the gate ends, HEAD and every tracked file are as they were when it started', next: 'leave the worktree alone until the gate finishes, then submit again', source: 'cli' },
{ id: 'childrenDone', refuse: 'CHILDREN_OPEN', rule: 'every child item is verified or withdrawn', next: 'finish the child items, or the coordinator withdraws them', source: 'board' },
{ id: 'headIsNew', refuse: 'HEAD_NOT_NEW', rule: 'a verifier has not rejected this commit at this bar; after a no-verdict reopen, the bar was refrozen', next: 'commit the rework, or refreeze the bar after a no-verdict reopen before resubmitting the same commit', source: 'board' },
@@ -223,7 +224,7 @@ export const MOVES = [
{ verb: 'lapse', from: ['claimed'], to: 'open', by: ['clock'], guards: [], when: 'its lease runs out' },
{
verb: 'submit', from: ['claimed'], to: 'submitted', by: ['agent', 'coordinator'], refuse: 'NOT_YOURS',
- guards: ['joined', 'itemExists', IN_STATE, 'isHolder', 'correctionRefrozen', 'checkProvesSomething', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'noUnverifiedStack', 'infraExplained', 'doctrineHolds', 'gateConfigured', 'queuedItemLease', 'gateGreen', 'treeStillDuringGate', 'submissionProofValid', 'childrenDone', 'headIsNew'],
+ guards: ['joined', 'itemExists', IN_STATE, 'isHolder', 'correctionRefrozen', 'checkProvesSomething', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'noUnverifiedStack', 'infraExplained', 'doctrineHolds', 'gateConfigured', 'queuedItemLease', 'gateGreen', 'proofRecorded', 'treeStillDuringGate', 'submissionProofValid', 'childrenDone', 'headIsNew'],
sets: ['item_built_by', 'item_commit'], command: 'pullboard submit <id>',
},
{
@@ -233,7 +234,7 @@ export const MOVES = [
},
{
verb: 'accept', from: ['submitted', 'verified'], to: 'verified', by: ['agent', 'coordinator'], refuse: 'NOT_SUBMITTED',
- guards: ['coordinatorSaysAs', 'joined', 'itemExists', IN_STATE, 'atSubmittedCommit', 'notMerged', 'verdictReviewRecorded', 'reviewTreeCurrent', 'notBuilder', 'routeAllows', 'policyAllows', 'familyAllows', 'reviewFree', 'criterionUnchanged', 'reasonIsMet', 'trunkMergeClean', 'noUnverifiedStack', 'queuedItemLease', 'itemCheckGreen', 'proofNoted'],
+ guards: ['coordinatorSaysAs', 'joined', 'itemExists', IN_STATE, 'atSubmittedCommit', 'notMerged', 'verdictReviewRecorded', 'reviewTreeCurrent', 'notBuilder', 'routeAllows', 'policyAllows', 'familyAllows', 'reviewFree', 'criterionUnchanged', 'reasonIsMet', 'trunkMergeClean', 'noUnverifiedStack', 'queuedItemLease', 'itemCheckGreen', 'proofRecorded', 'proofNoted'],
alsoRefuses: [{ code: 'LAND_HEADER', rule: 'a displayed merge command fits the commit-header limit', next: 'shorten the item title or cited rows so the merge header fits' }, { code: 'ENGINE_VERSION', rule: 'a verdict that implies items replays only under engine 20 or later', next: 'upgrade Pullboard on every linked device before using --implies' }],
sets: ['item_verified_by'], command: 'pullboard verify <id> accept --note "..."',
},
diff --git a/src/native-flake-cli.js b/src/native-flake-cli.js
index 1c7dddb6..ef1e5aaa 100644
--- a/src/native-flake-cli.js
+++ b/src/native-flake-cli.js
@@ -3,7 +3,6 @@ import { readFileSync } from 'node:fs';
import { COORDINATOR } from './config.js';
import { laneOf } from './lanes.js';
import {
- checkAtCommit,
mainPolicy,
policyAt,
} from './trusted-policy.js';
@@ -13,6 +12,8 @@ import {
receiptStore,
} from './gate-run-receipt.js';
import { runProfiledShell } from './gate.js';
+import { runFrozenProof } from './gate.js';
+import { recordNativeProof } from './proof-cli.js';
import {
diagnosticUnavailable,
flakeSource,
@@ -62,7 +63,9 @@ export function check(ctx, item, command, services) {
const observe = observer(ctx, { kind: 'check' }, services);
return async lease => {
pinRunMain(lease, observe);
+ lease.proof = { item: item.item_id, frozenDigest: item.item_frozen_digest ?? null, seat: services.resourceAgent(ctx), kind: 'check' };
const run = runProfiledShell(ctx.info.root, command, { waitMs: lease.waitMs, artifactPrefix: `pullboard-check-${item.item_id}`, persistLog: true, gateLease: lease });
+ await recordNativeProof(ctx, item, run, services);
if (!run.isGreen) await observe(run, { command, lease });
return run;
};
@@ -73,7 +76,9 @@ export function verify(ctx, item, command, options, services) {
const observe = observer(ctx, { ...options, kind: 'verify', privateCheck: true }, services);
return async lease => {
pinRunMain(lease, observe);
- const result = checkAtCommit(ctx.info.root, item, { waitMs: lease.waitMs, gateLease: lease });
+ lease.proof = { seat: services.resourceAgent(ctx) };
+ const result = runFrozenProof(ctx.info.root, item, { waitMs: lease.waitMs, gateLease: lease });
+ await recordNativeProof(ctx, item, result, services, options.board);
if (result.state === 'red') await observe({ isGreen: false, output: result.outputPath ? readFileSync(result.outputPath, 'utf8') : result.output,
log: result.outputPath, profilePath: result.profilePath, executionRoot: result.executionRoot, executionSourceUnchanged: result.executionSourceUnchanged }, { root: ctx.info.root, command, lease });
return result;
diff --git a/src/private-check-worker.js b/src/private-check-worker.js
index bddbb006..84aad995 100644
--- a/src/private-check-worker.js
+++ b/src/private-check-worker.js
@@ -62,7 +62,7 @@ child.once('close', (status, signal) => {
sent = true;
const marker = bytes > LIMIT ? '\n[output capped at 8 MiB; middle omitted]\n' : '';
const output = head.toString('utf8') + marker + tail.toString('utf8');
- process.stdout.write(JSON.stringify({ status, signal, error: timedOut ? { code: 'ETIMEDOUT' } : error, logError, output }));
+ process.stdout.write(JSON.stringify({ status, signal, executed: Boolean(child.pid), error: timedOut ? { code: 'ETIMEDOUT' } : error, logError, output }));
};
log.once('close', finish);
if (log.closed) finish();
diff --git a/src/proof-cli.js b/src/proof-cli.js
new file mode 100644
index 00000000..21683343
--- /dev/null
+++ b/src/proof-cli.js
@@ -0,0 +1,10 @@
+/** Native command adapters record execution ids, never agent-written provenance [C7,H16]. */
+import { Refused } from './refused.js';
+
+/** Bind an actual run to its native caller before the command can publish its outcome. */
+export async function recordNativeProof(ctx, item, run, { ordered, withBoard, resourceAgent }, board = null) {
+ if (run.executed === false || run.checked === false) return;
+ if (!run.proofReceiptId) throw new Refused('PROOF_RUN_UNAVAILABLE', 'the executed check has no native receipt; restore receipt storage and read pullboard show <id> before trying again');
+ const write = target => ordered(ctx, target, 'recordProofRun', [{ agentId: resourceAgent(ctx), itemId: item.item_id, receiptId: run.proofReceiptId }]);
+ return board ? write(board) : withBoard(ctx, write);
+}
diff --git a/src/proof-provenance.js b/src/proof-provenance.js
new file mode 100644
index 00000000..62a02b33
--- /dev/null
+++ b/src/proof-provenance.js
@@ -0,0 +1,47 @@
+/** Normalize execution facts without inventing missing runtime identities or test counts [C7,H16]. */
+
+/** A bounded identity from the executor, never a command or an agent's narrative. */
+function identity(value, limit = 512) {
+ return typeof value === 'string' && value.length > 0 && value.length <= limit && !/[\r\n\0]/u.test(value);
+}
+
+/** Validate the native facts attached to a version-two gate receipt. */
+export function proofFields(value) {
+ if (!value || !Number.isSafeInteger(value.item) || value.item < 1
+ || value.frozenDigest !== null && !/^[a-f0-9]{64}$/u.test(value.frozenDigest ?? '')
+ || !identity(value.seat, 256) || value.runner !== null && !identity(value.runner)
+ || value.exitCode !== null && !Number.isSafeInteger(value.exitCode)
+ || !Number.isSafeInteger(value.durationMs) || value.durationMs < 0 || typeof value.sourceClean !== 'boolean') return null;
+ const environment = value.environment;
+ if (environment !== null && (!environment || !identity(environment.node, 80)
+ || !identity(environment.platform, 80) || !identity(environment.arch, 80))) return null;
+ const names = ['passed', 'failed', 'skipped'];
+ if (!value.counts || !names.every(name => value.counts[name] === null
+ || Number.isSafeInteger(value.counts[name]) && value.counts[name] >= 0)) return null;
+ return { item: value.item, frozenDigest: value.frozenDigest,
+ environment: environment === null ? null : { node: environment.node, platform: environment.platform, arch: environment.arch },
+ seat: value.seat, runner: value.runner, exitCode: value.exitCode,
+ counts: Object.fromEntries(names.map(name => [name, value.counts[name]])), durationMs: value.durationMs, sourceClean: value.sourceClean };
+}
+
+/** Read explicit TAP or Node reporter totals; absent counters stay unknown rather than becoming zero. */
+export function proofCounts(lines) {
+ const names = { pass: 'passed', fail: 'failed', skipped: 'skipped' };
+ let pending = {};
+ let totals = null;
+ for (const line of typeof lines === 'string' ? lines.split(/\r?\n/u) : lines) {
+ const match = /^(?:#|ℹ)\s+(pass|fail|skipped)\s+(\d+)$/u.exec(line);
+ if (!match) continue;
+ const count = Number(match[2]);
+ if (!Number.isSafeInteger(count)) return { passed: null, failed: null, skipped: null };
+ pending[names[match[1]]] = count;
+ if (Object.keys(pending).length === 3) {
+ totals ??= { passed: 0, failed: 0, skipped: 0 };
+ for (const name of Object.values(names)) totals[name] += pending[name];
+ if (!Object.values(totals).every(Number.isSafeInteger)) return { passed: null, failed: null, skipped: null };
+ pending = {};
+ }
+ }
+ return Object.keys(pending).length ? { passed: null, failed: null, skipped: null }
+ : totals ?? { passed: null, failed: null, skipped: null };
+}
diff --git a/src/proof-receipts.js b/src/proof-receipts.js
new file mode 100644
index 00000000..fce39d52
--- /dev/null
+++ b/src/proof-receipts.js
@@ -0,0 +1,70 @@
+/** Stamp the gate's own immutable receipt with the board's seat and recorded parent [C7,H16]. */
+import {
+ atomic,
+ getItem,
+ listAgents,
+ logEvent,
+} from './board.js';
+import {
+ boardReceiptStore,
+ readGateReceipt,
+ receiptBody,
+ receiptFields,
+} from './gate-run-receipt.js';
+import { ENGINE_VERSION } from './machine.js';
+import { PROOF_RUN_ENGINE } from './proof-run-engine.js';
+import { Refused } from './refused.js';
+import * as seats from './seats.js';
+
+/** Read the native gate's file before sealing a replayable move; caller-supplied fields are not evidence. */
+export function boundProofReceipt(board, request) {
+ const id = request?.receiptId ?? request?.receipt?.id;
+ const stored = readGateReceipt(boardReceiptStore(board), id);
+ if (!stored || stored.version !== 2 || request?.receipt && receiptBody(request.receipt) !== receiptBody(stored)) {
+ throw new Refused('PROOF_RUN_UNBOUND', 'proof provenance comes from the gate receipt it stored; run the check, then read pullboard show <id>');
+ }
+ return stored;
+}
+
+/** Every stamped receipt for one item, in recorded order. */
+export function proofReceipts(board, itemId) {
+ return board.db.prepare("SELECT event_id, event_detail FROM event WHERE item_id = ? AND event_kind = 'proof-run' ORDER BY event_id").all(itemId)
+ .map(row => ({ eventId: row.event_id, ...JSON.parse(row.event_detail).receipt }));
+}
+
+/** Record only native facts, resolving the actor and its parent from board-owned registration. */
+export function recordProofRun(board, request) {
+ if ((board.executionEngineVersion ?? ENGINE_VERSION) < PROOF_RUN_ENGINE) {
+ throw new Refused('ENGINE_VERSION', `proof receipts require engine ${PROOF_RUN_ENGINE}; upgrade Pullboard`);
+ }
+ const { agentId, itemId } = request;
+ if (!listAgents(board).some(agent => agent.agent_id === agentId)) throw new Refused('NOT_JOINED', 'join before recording a proof run');
+ const run = board.executionEngineVersion === undefined ? boundProofReceipt(board, request) : receiptFields(request.receipt);
+ if (!run || run.version !== 2 || run.proof.item !== itemId) throw new Refused('PROOF_RUN_UNBOUND', 'the native receipt must name this item; run its check and read pullboard show <id>');
+ if (run.proof.seat !== agentId) throw new Refused('PROOF_RUN_ACTOR', 'the native receipt belongs to another seat; use the receipts from your own check');
+ return atomic(board, () => {
+ const item = getItem(board, itemId);
+ if (run.proof.frozenDigest !== (item.item_frozen_digest ?? null)) throw new Refused('PROOF_RUN_STALE', 'the criterion changed during this proof; read pullboard show <id> before checking again');
+ const receipt = { id: run.id, kind: run.kind, item: itemId, commit: run.head, tree: run.tree,
+ frozenDigest: run.proof.frozenDigest, environment: run.proof.environment, runner: run.proof.runner,
+ seat: agentId, parentSession: seats.agentParent?.(board, agentId) ?? null, exitCode: run.proof.exitCode,
+ counts: run.proof.counts, durationMs: run.proof.durationMs, sourceClean: run.proof.sourceClean, at: run.at };
+ const existing = proofReceipts(board, itemId).find(value => value.id === receipt.id);
+ if (existing) {
+ const { eventId, ...fields } = existing;
+ // Later registration cannot retroactively upgrade an originally unknown parent.
+ receipt.parentSession = existing.parentSession;
+ if (JSON.stringify(fields) !== JSON.stringify(receipt)) throw new Refused('PROOF_RUN_CHANGED', 'that receipt id already binds different facts; keep the original and run a new check');
+ return existing;
+ }
+ logEvent(board, agentId, 'proof-run', itemId, { engine: PROOF_RUN_ENGINE, receipt });
+ return receipt;
+ });
+}
+
+/** A short pointer replaces repeated provenance narratives in shouts. */
+export function refuseLongShout(text) {
+ if (Array.from(String(text)).length > 400) {
+ throw new Refused('SHOUT_TOO_LONG', 'a shout is at most 400 characters; cite proof receipt ids and use pullboard show <id> for the chain');
+ }
+}
diff --git a/src/proof-run-engine.js b/src/proof-run-engine.js
new file mode 100644
index 00000000..287806e7
--- /dev/null
+++ b/src/proof-run-engine.js
@@ -0,0 +1,2 @@
+/** Native proof receipts and bounded shouts retain their replay meaning [C7,H16]. */
+export const PROOF_RUN_ENGINE = 92;
diff --git a/src/quarantine.js b/src/quarantine.js
index 0132bfd8..a858708d 100644
--- a/src/quarantine.js
+++ b/src/quarantine.js
@@ -86,7 +86,7 @@ function existingRepair(board, file, name) {
*/
export function runReceipt(receipt) {
const fields = receiptFields(receipt);
- if (!fields) throw new Refused('GATE_RUN_EVIDENCE', 'a gate run needs its receipt: id, tree, command digest, result, failing tests and host load; run the gate again from a clean checkout');
+ if (!fields || fields.version !== 1) throw new Refused('GATE_RUN_EVIDENCE', 'a gate run needs its receipt: id, tree, command digest, result, failing tests and host load; run the gate again from a clean checkout');
return fields;
}
diff --git a/src/relay-outbox.js b/src/relay-outbox.js
index 187d7d6b..63f5ff23 100644
--- a/src/relay-outbox.js
+++ b/src/relay-outbox.js
@@ -163,7 +163,7 @@ export const ITEM_SLOTS = Object.freeze({
recordRowDecisions: [], applyRowDecisions: [], draftSpecRow: [], recordSpecApprovalBaseline: [],
recordLandingBatch: [], recordLandingWaiver: [], recordLandingFlake: [], finishLandingBatch: [],
recordHealthFindings: [], decideSentinel: [], beginSentinelRun: [], finishSentinelRun: [],
- recordFlakeObservation: [], recordGateRun: [], declareJob: [], recordJobRun: [], takeCoordinator: [], landingLeaseMove: [],
+ recordFlakeObservation: [], recordGateRun: [], recordProofRun: [[0, 'itemId']], declareJob: [], recordJobRun: [], takeCoordinator: [], landingLeaseMove: [],
...Object.fromEntries(FIRST_ITEM.map((operation) => [operation, [[0]]])),
addItem: [[0, 'parentId'], [0, 'after', '*']],
editItem: [[0], [1, 'after', '*']],
diff --git a/src/relay-sender.js b/src/relay-sender.js
index bdca0eab..3cbd4cc5 100644
--- a/src/relay-sender.js
+++ b/src/relay-sender.js
@@ -10,7 +10,7 @@ export function relayMoveActor(move) {
if (move.operation === 'addItem') return args[0]?.by ?? null;
if (move.operation === 'shout') return args[0]?.from ?? null;
if (['proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun'].includes(move.operation)) return args[0]?.agentId ?? null;
- if (['recordHealthFindings', 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove'].includes(move.operation)) return args[0]?.agentId ?? null;
+ if (['recordHealthFindings', 'recordFlakeObservation', 'recordGateRun', 'recordProofRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove'].includes(move.operation)) return args[0]?.agentId ?? null;
if (['holdLane', 'releaseLane'].includes(move.operation) && args[1]?.asPerson) return 'person';
if (move.operation === 'release') return args[1] ?? null;
if (['reserveNextReview', 'addMilestone', 'recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'recordSpecApprovalBaseline', 'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch'].includes(move.operation)) return args[0]?.agentId ?? null;
diff --git a/src/timing.js b/src/timing.js
index cf5ec658..17516a92 100644
--- a/src/timing.js
+++ b/src/timing.js
@@ -118,7 +118,7 @@ export function timingFromOutput(output, runner = 'shell') {
}
/** Iterate a complete log in bounded chunks, discarding only oversized diagnostic lines. */
-function* logLines(path) {
+export function* logLines(path) {
const fd = openSync(path, 'r');
const decoder = new StringDecoder('utf8');
const chunk = Buffer.alloc(32 * 1024);
diff --git a/src/trusted-policy.js b/src/trusted-policy.js
index 5fc1da6c..21b89cfe 100644
--- a/src/trusted-policy.js
+++ b/src/trusted-policy.js
@@ -215,13 +215,15 @@ export function checkAtCommit(root, item, { waitMs = 0, gateSlotHeld = false, ga
let checkLogPath = '';
let timingProfile = { files: [], tests: [] };
let checkedSourceReady = false;
+ let executed = false;
+ let exitCode = null;
/** Format one completed check phase with the private captures and durable artifact locations. */
const finish = (state, stage) => {
const runner = timingRunner(command);
const events = checkLogPath && existsSync(checkLogPath) ? timingFromLog(checkLogPath, runner) : timingFromOutput(checkOutput, runner);
timingProfile = { ...events, wallMs: Math.max(0, Date.now() - checkStartedAt) };
return checkResult(state, stage, installOutput, checkOutput, { root, item, commandRoot: copy, installLogPath, checkLogPath, timingProfile, waitMs,
- executionSourceUnchanged: checkedSourceReady && privateSourceUnchanged(copy, item.item_commit, env) });
+ executed, exitCode, executionSourceUnchanged: checkedSourceReady && privateSourceUnchanged(copy, item.item_commit, env) });
};
try {
const common = policyGit(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']).trim();
@@ -266,6 +268,8 @@ export function checkAtCommit(root, item, { waitMs = 0, gateSlotHeld = false, ga
if (remaining <= 0) return finish('unverified', 'check timed out');
checkLogPath = join(scratch, 'check.log');
const run = runPrivateCommand(copy, env, command, remaining, checkLogPath);
+ executed = run.executed === true;
+ exitCode = run.status ?? null;
checkOutput = run.output;
if (run.error?.code === 'ETIMEDOUT') return finish('unverified', 'check timed out');
if (run.error) return finish('unverified', `check could not start (${run.error.code})`);
@@ -423,7 +427,7 @@ function privateSourceUnchanged(root, commit, env) {
}
/** Persist a sanitized full diagnostic outside the temporary checkout so a refusal can name it. */
-function checkResult(state, stage, installCapture, checkCapture, { root = '', item = {}, commandRoot = root, installLogPath = '', checkLogPath = '', timingProfile = null, waitMs = 0, executionSourceUnchanged } = {}) {
+function checkResult(state, stage, installCapture, checkCapture, { root = '', item = {}, commandRoot = root, installLogPath = '', checkLogPath = '', timingProfile = null, waitMs = 0, executed = false, exitCode = null, executionSourceUnchanged } = {}) {
const boundedInstall = secretScanned(installCapture, 'check install capture');
const boundedCheck = secretScanned(checkCapture, 'frozen check capture');
const install = digestOf(boundedInstall) || '(no output)';
@@ -499,6 +503,6 @@ function checkResult(state, stage, installCapture, checkCapture, { root = '', it
: /could not start/u.test(stage) ? "couldn't start" : state === 'unverified' ? 'could not be verified' : 'passed';
const output = `install output:\n${boundedInstall || '(no output)'}\ncheck output:\n${boundedCheck || '(not run or no output)'}`;
return { sandboxBlocked, state, green: state === 'pass', checked: true, stage, failure, report, output, outputTail, outputPath, outputError, profilePath,
- executionRoot: commandRoot, ...(executionSourceUnchanged === undefined ? {} : { executionSourceUnchanged }),
+ executionRoot: commandRoot, executed, exitCode, ...(executionSourceUnchanged === undefined ? {} : { executionSourceUnchanged }),
profile: timingProfile ? { ...timingProfile, profilePath } : null };
}
diff --git a/test/proof-provenance.test.js b/test/proof-provenance.test.js
new file mode 100644
index 00000000..7dc80873
--- /dev/null
+++ b/test/proof-provenance.test.js
@@ -0,0 +1,72 @@
+/** Native provenance rejects borrowed evidence and keeps unknown facts explicit [C7,H16]. */
+import assert from 'node:assert/strict';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import * as store from '../src/board.js';
+import { prepareEngineMove, applyEngineMove } from '../src/engine.js';
+import { boardReceiptStore, receiptBody, receiptFields } from '../src/gate-run-receipt.js';
+import { proofCounts } from '../src/proof-provenance.js';
+import { recordNativeProof } from '../src/proof-cli.js';
+
+test('proof counters retain explicit totals and do not invent success from missing output [C7,H16]', () => {
+ const unknown = { passed: null, failed: null, skipped: null };
+ assert.deepEqual(proofCounts('no test reporter\n'), unknown);
+ assert.deepEqual(proofCounts('# pass 1\n# fail 0\n'), unknown);
+ assert.deepEqual(proofCounts(' # pass 9\n # fail 0\n # skipped 0'), unknown, 'nested child summaries are not added twice');
+ assert.deepEqual(proofCounts('# pass 2\n# fail 1\n# skipped 3\nℹ pass 4\nℹ fail 0\nℹ skipped 1'),
+ { passed: 6, failed: 1, skipped: 4 });
+ assert.deepEqual(proofCounts('# pass 1\n# fail 0\n# skipped 0\n# pass 8'), unknown,
+ 'an incomplete later summary cannot turn the whole run into a known total');
+});
+
+test('an executed run without its receipt cannot publish an outcome [C7,H16]', async () => {
+ let moves = 0;
+ const services = { ordered: () => { moves += 1; }, withBoard: () => { moves += 1; }, resourceAgent: () => 'web-1' };
+ await assert.rejects(recordNativeProof({}, { item_id: 1 }, { proofReceiptId: null }, services),
+ error => error.code === 'PROOF_RUN_UNAVAILABLE');
+ await recordNativeProof({}, { item_id: 1 }, { executed: false }, services);
+ assert.equal(moves, 0, 'a zero-execution refusal creates no proof receipt');
+});
+
+test('proof receipts bind the native actor and replay without the origin filesystem [C7,H16]', (t) => {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-proof-receipts-'));
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
+ const board = store.openBoard(join(directory, 'board.sqlite'));
+ const replica = store.openBoard(':memory:');
+ t.after(() => { store.closeBoard(replica); store.closeBoard(board); });
+ let item;
+ for (const target of [board, replica]) {
+ store.register(target, { lane: 'coordinator', path: '/proof-coordinator' });
+ store.register(target, { lane: 'web', path: '/proof-builder' });
+ store.register(target, { lane: 'web', path: '/proof-peer' });
+ item = store.addItem(target, { by: 'coordinator', lane: 'web', title: 'A synthetic receipt boundary' });
+ }
+ // This is synthetic storage-boundary evidence, not a claim that this fixture ran a gate.
+ const receipt = { version: 2, id: '00000000-0000-4000-8000-00000000c0de', kind: 'check',
+ head: 'a'.repeat(40), tree: 'b'.repeat(40), main: null, command: 'c'.repeat(64), green: false,
+ failures: [], load: null, at: '2026-10-23T00:00:00.000Z',
+ proof: { item, frozenDigest: null, seat: 'web-1', environment: null, runner: null, exitCode: 7,
+ counts: { passed: null, failed: null, skipped: null }, durationMs: 37, sourceClean: false } };
+ mkdirSync(boardReceiptStore(board));
+ writeFileSync(join(boardReceiptStore(board), `${receipt.id}.json`), receiptBody(receipt));
+ assert.throws(() => store.recordProofRun(board, { agentId: 'web-2', itemId: item, receiptId: receipt.id }),
+ error => error.code === 'PROOF_RUN_ACTOR', 'a peer cannot appropriate a real native receipt');
+ assert.throws(() => prepareEngineMove(board, 'recordProofRun', [{ agentId: 'web-1', itemId: item,
+ receipt: { ...receipt, proof: { ...receipt.proof, exitCode: 0 } } }]), error => error.code === 'PROOF_RUN_UNBOUND');
+ const args = [{ agentId: 'web-1', itemId: item, receiptId: receipt.id }];
+ const move = prepareEngineMove(board, 'recordProofRun', args, { actor: 'web-1' });
+ const recorded = store.recordProofRun(board, args[0]);
+ assert.equal(recorded.exitCode, 7);
+ assert.equal(recorded.environment, null, 'missing executor identity never becomes controller identity');
+ assert.equal(recorded.parentSession, null, 'a legacy seat never becomes recorded-parent assurance');
+ assert.deepEqual(recorded.counts, receipt.proof.counts);
+ applyEngineMove(replica, move, { sequence: 1, at: receipt.at });
+ const [{ eventId, ...replayed }] = store.proofReceipts(replica, item);
+ assert.deepEqual(replayed, recorded);
+ assert.equal(store.proofReceipts(board, item).length, 1);
+ store.recordProofRun(board, args[0]);
+ assert.equal(store.proofReceipts(board, item).length, 1, 'retrying the same receipt is idempotent');
+ assert.equal(receiptFields({ ...receipt, proof: { ...receipt.proof, environment: { node: '22', platform: 'darwin' } } }), null);
+});
diff --git a/test/relay-credential.test.js b/test/relay-credential.test.js
index e3deff20..afbe6e4e 100644
--- a/test/relay-credential.test.js
+++ b/test/relay-credential.test.js
@@ -29,6 +29,7 @@ test('every current operation selects its native actor credential without a seco
if (operation === 'recordFlakeObservation') args = [{ agentId: actor, lane: box.lane, observation: syntheticFlakeObservation('credential-fixture') }];
if (operation === 'recordGateRun') args = [{ agentId: actor, lane: box.lane, receipt: { version: 1, id: '00000000-0000-4000-8000-00000000c0de', kind: 'gate', tree: 'b'.repeat(40), head: 'a'.repeat(40),
main: 'a'.repeat(40), command: 'c'.repeat(64), green: true, failures: [], load: { average: [0, 0, 0], cpus: 1, freeMB: 100 }, at: '2026-10-20T00:00:00.000Z' } }];
+ if (operation === 'recordProofRun') args = [{ agentId: actor, itemId: 999999, receiptId: '00000000-0000-4000-8000-00000000c0de' }];
if (operation === 'declareJob') args = [{ agentId: actor, name: 'credential-job', every: '10m', owner: actor }];
if (operation === 'recordJobRun') args = [{ agentId: actor, name: 'credential-job' }];
if (operation === 'takeCoordinator') args = [{ agentId: actor, machine: 'credential-machine' }];
@@ -56,6 +57,7 @@ test('every current operation selects its native actor credential without a seco
if (operation === 'draftSpecRow') args = [{ agentId: actor, row: { id: 'G9', text: 'A credential fixture row.', gate: 'review', tier: 'must', section: 'G · Goals' } }];
if (operation === 'recordRowDecisions') { args = [{ agentId: 'person', channel: 'terminal', decisions: [] }]; kind = 'person'; }
// A gate run with no receipt from this machine's own gate is refused before it reaches transport.
+ if (operation === 'recordProofRun') return { operation, args, kind, sent: false, expected: 'PROOF_RUN_UNBOUND' };
if (operation === 'recordGateRun') return { operation, args, kind, sent: false, expected: 'GATE_RUN_UNBOUND' };
return { operation, args, kind, ...(kind === 'person' ? { sent: false } : {}) };
});