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.

chore(core): derive help from command declarations [C3,C7]

Corey Olson7cf3e5997583
diff --cc src/api.js
index 17bcaa5e,25a55281..b89c028d
--- a/src/api.js
+++ b/src/api.js
@@@ -1,59 -1,26 +1,66 @@@
/** The local API v1: the CLI's moves, persistent board identities and live events (A2). */
-import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
+import {
+ createHash,
+ randomBytes,
+ timingSafeEqual,
+} from 'node:crypto';
import { createServer } from 'node:http';
-import { basename, join, resolve } from 'node:path';
-import { existsSync, readFileSync, statSync } from 'node:fs';
+import {
+ basename,
+ join,
+ resolve,
+} from 'node:path';
+import {
+ existsSync,
+ readFileSync,
+ statSync,
+} from 'node:fs';
import { displayAgentName } from './agent-names.js';
import * as store from './board.js';
-import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';
-import { codeIsFromMain, repoInfo, resolveCommit, withGitReadFacts } from './git.js';
+import {
+ CONFIG_FILE,
+ COORDINATOR,
+ loadConfig,
+} from './config.js';
+import {
+ codeIsFromMain,
+ repoInfo,
+ resolveCommit,
+ withGitReadFacts,
+} from './git.js';
import { refusalDocument } from './json.js';
-import { relayLinked, relayOperation, relayRevoke, relayTokens } from './relay.js';
+import {
+ relayLinked,
+ relayOperation,
+ relayRevoke,
+ relayTokens,
+} from './relay.js';
import { laneNames } from './lanes.js';
import { MACHINE } from './machine.js';
-import { listApiProjects, registryFile } from './projects.js';
+import {
+ listApiProjects,
+ registryFile,
+} from './projects.js';
import { milestoneRoadmap } from './roadmap.js';
import { proofStats } from './stats.js';
-import { prepareFlowHistory, projectFlowStats } from './stats-flow.js';
+import {
+ prepareFlowHistory,
+ projectFlowStats,
+} from './stats-flow.js';
import { projectRowDecisions } from './row-decisions.js';
-import { fitFile, pendingFit, projectFit } from './blueprint-fit.js';
++import {
++ fitFile,
++ pendingFit,
++ projectFit,
++} from './blueprint-fit.js';
import { Refused } from './refused.js';
+ import { verdictProjector } from './verdict-freshness.js';
+ import { trunkRevisionReader } from './trunk-revision.js';
-import { codeAt, projectItemState, projectState } from './serve.js';
+import {
+ codeAt,
+ projectItemState,
+ projectState,
+} from './serve.js';
import { relayPresentationShout } from './relay-presentation.js';
import { createApiHandler } from './api-http.js';
import { moveArgs } from './api-moves.js';
diff --cc src/blueprint-fit-command.js
index 00000000,7c6a81fb..6eb17b79
mode 000000,100644..100644
--- a/src/blueprint-fit-command.js
+++ b/src/blueprint-fit-command.js
@@@ -1,0 -1,76 +1,87 @@@
+ /** The blueprint fit verbs: blueprint fit, spec fit, spec fit edit and spec fit approve [S1,E3]. */
+ import { readFileSync } from 'node:fs';
+ import * as store from './board.js';
-import { approveFit, editFit, fitLine, fitSummary, proposeFit, readFitBatch, refuseOwnFit } from './blueprint-fit.js';
++import {
++ approveFit,
++ editFit,
++ fitLine,
++ fitSummary,
++ proposeFit,
++ readFitBatch,
++ refuseOwnFit,
++} from './blueprint-fit.js';
+ import { readBlueprint } from './blueprints.js';
+ import { COORDINATOR } from './config.js';
+ import { headCommit } from './git.js';
-import { agentSessionDigest, requirePersonChannel } from './person.js';
++import {
++ agentSessionDigest,
++ requirePersonChannel,
++} from './person.js';
+ import { Refused } from './refused.js';
+ import { prepareRowDecisions } from './row-decisions.js';
+ import { loadSpec } from './spec.js';
+
+ /**
+ * Blueprint fit (#730): a seat proposes how a blueprint's target fits this repo; the person lists,
+ * edits and approves the waiting batch. The proposer is this seat's own id and agent session, never
+ * a flag. Edit and approve first refuse the session that proposed, then any non-person channel.
+ * The CLI passes its ordered dispatch and its identity lookup, so every board move goes through the
+ * same engine path as any other command.
+ *
+ * @param {any} ctx
+ * @param {any} board
+ * @param {{ id: string } | null} me - The seat, for a proposal; null for the person's verbs.
+ * @param {'list' | 'propose' | 'edit' | 'approve' | string} verb
+ * @param {string[]} args
+ * @param {Record<string, any>} values
+ * @param {{ ordered: Function, whoAmI: Function }} cli
+ * @returns {Promise<number>}
+ */
+ export async function fitCommand(ctx, board, me, verb, args, values, { ordered, whoAmI }) {
+ const { io } = ctx;
+ const [spec, items, at] = [loadSpec(ctx.info.root, ctx.config), store.listItems(board, { all: true }), new Date().toISOString()];
+ const usage = 'pullboard spec fit [approve <batch>] | spec fit edit <row id or #item> keep|adapt|drop|answer [--text "..."] [--reason "why"]';
+ /** List the batch and its code; the person's own listing is their reading of it. */
+ const show = (extra = {}) => {
+ const read = readFitBatch(ctx.info.commonDir, { isMain: ctx.info.isMain, channel: io.personChannel });
+ io.result?.({ ...extra, proposals: read.proposals, batch: read.batch });
+ (read.proposals.length ? fitSummary(read) : ['no blueprint fit proposals wait for the person']).forEach((line) => io.say(line));
+ return 0;
+ };
+ if (verb === 'list') return show();
+ if (verb === 'propose') {
+ const [reference, target, decision, ...extra] = args;
+ if (!reference || !target || !decision || extra.length) throw new Refused('USAGE', 'pullboard blueprint fit <name or file> <row id or #item> keep|adapt|drop|answer [--text "..."] [--reason "why"]');
+ // Only the proposal's own words are flags; who proposed it is this seat, so no flag can name another.
+ const flag = Object.keys(values).find((key) => !['text', 'reason', 'json'].includes(key));
+ if (flag) throw new Refused('FLAG_NOT_ALLOWED', `blueprint fit does not take --${flag}; it records this seat as the proposer and takes only --text and --reason`);
+ const proposal = proposeFit({ commonDir: ctx.info.commonDir, blueprint: readBlueprint(reference, io.cwd), specSource: readFileSync(spec.file, 'utf8'),
+ spec, items, by: me.id, session: agentSessionDigest(), at }, { target, decision, text: values.text, reason: values.reason });
+ io.result?.({ proposals: [proposal] });
+ io.say(`recorded ${fitLine(proposal)}\nnext: nothing applies until the person reads the batch with pullboard spec fit and approves it with pullboard spec fit approve <batch>`);
+ return 0;
+ }
+ if (!['edit', 'approve'].includes(verb) || (verb === 'approve' && args.length !== 1) || (verb === 'edit' && args.length !== 2)) throw new Refused('USAGE', usage);
+ refuseOwnFit(ctx.info.commonDir, agentSessionDigest());
+ requirePersonChannel(io.personChannel);
+ const person = whoAmI(ctx, board);
+ if (!ctx.info.isMain || person.id !== COORDINATOR) throw new Refused('B26_PERSON_APPROVAL', 'only the person, from the main checkout, edits or approves blueprint fit proposals; use pullboard spec fit to read them');
+ if (verb === 'edit') {
+ const proposal = editFit(ctx.info.commonDir, { target: args[0], decision: args[1], text: values.text, reason: values.reason, at });
+ io.say(`edited ${fitLine(proposal)}`);
+ // The whole batch is shown again, so the person reads what they will approve.
+ return show({ edited: proposal });
+ }
+ const commit = headCommit(ctx.info.root) ?? '';
+ const done = await approveFit({ commonDir: ctx.info.commonDir, spec, items, session: agentSessionDigest(), at, code: args[0] }, {
+ decide: async (rows) => await ordered(ctx, board, 'recordRowDecisions', [{ agentId: store.PERSON, channel: io.personChannel ?? 'terminal',
+ decisions: rows.flatMap(({ proposal, note }) => prepareRowDecisions(ctx.info.root, ctx.config, { ids: [proposal.target], decision: proposal.decision === 'drop' ? 'decline' : 'approve',
+ reason: proposal.reason, text: proposal.text ?? undefined, on: at, commit, note })) }]),
+ fact: async (id, text) => await ordered(ctx, board, 'appendFact', [id, { agentId: person.id, kind: 'decision', text }]),
+ criterion: async (id, text) => await ordered(ctx, board, 'editItem', [id, { agentId: person.id, criterion: text }]),
+ withdraw: async (id, reason) => await ordered(ctx, board, 'withdraw', [id, { agentId: person.id, reason }]),
+ });
+ io.result?.(done); done.proposals.forEach((proposal) => io.say(`approved ${fitLine(proposal)}`));
+ if (done.decisions.length) io.say('next: the coordinator runs pullboard spec apply to write the row decisions');
+ return 0;
+ }
diff --cc src/blueprint-fit.js
index 00000000,48f59a64..c8a0876e
mode 000000,100644..100644
--- a/src/blueprint-fit.js
+++ b/src/blueprint-fit.js
@@@ -1,0 -1,508 +1,524 @@@
+ /**
+ * Blueprint fit: after a blueprint lands, a seat proposes how each drafted row, question and
+ * starter item fits this repo, and the person approves every proposal as one batch [S1,E3].
+ *
+ * A proposal is keep, adapt (with the new text), drop (with a reason) or, for a question the repo
+ * already settles, answer (with one of its choices). Proposals wait in one file in the git common
+ * dir, beside the board, so every worktree of this clone records into the same batch and the
+ * person sees them all from the main checkout. Nothing in SPEC.md or on the board changes until
+ * the person approves: then each row proposal becomes the person's own row decision (the usual
+ * pending apply), each starter adaptation becomes the item's new criterion and each starter drop
+ * withdraws it, and every one keeps its reason and its blueprint source.
+ *
+ * The proposer is the seat's own identity, read by the caller from the board, and the seat's agent
+ * session digest; no flag sets either. Any local process can still edit the file, so a proposal is
+ * an unverified draft and is always shown as one, with its recorder named as recorded, never as
+ * authenticated. The durable record is the person's batch approval on the board. Approval is the
+ * person's alone: it refuses an agent session that recorded any proposal in the batch, then every
+ * agent shell, remote shell and worktree, then any difference from what the person last read.
+ *
+ * The person's reading is bound by the person's own hand, not by a file: every listing prints a
+ * batch code, a digest of each proposal's id, target and content, and approve takes that code as
+ * its argument. The reading file beside the batch only lets a refusal name what differs; approve
+ * first checks that the stored reading still hashes to the code the person typed, so a forged or
+ * rewritten reading is refused, and only then compares it with the batch, entry by entry: a
+ * proposal read but now missing, new since the reading, or changed is refused by name. Like a
+ * person's row decision, which is trusted because the person's own channel records it, the
+ * approval rests on input only the person gives; anything an agent can write is only a draft.
+ */
-import { createHash, randomUUID } from 'node:crypto';
-import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import { blueprintMarker, questionText, ruleText } from './blueprints.js';
++import {
++ createHash,
++ randomUUID,
++} from 'node:crypto';
++import {
++ existsSync,
++ mkdirSync,
++ readFileSync,
++ renameSync,
++ writeFileSync,
++} from 'node:fs';
++import {
++ dirname,
++ join,
++} from 'node:path';
++import {
++ blueprintMarker,
++ questionText,
++ ruleText,
++} from './blueprints.js';
+ import { requirePersonChannel } from './person.js';
+ import { Refused } from './refused.js';
+
+ /** What a fit proposal can say about one target. */
+ export const FIT_DECISIONS = Object.freeze(['keep', 'adapt', 'drop', 'answer']);
+
+ /** The proposer a person's own edit records. */
+ const PERSON = 'person';
+
+ /**
+ * Where this clone's fit proposals wait: beside the board in the git common dir, so every worktree
+ * reads and writes the same batch.
+ *
+ * @param {string} commonDir
+ * @returns {string}
+ */
+ export function fitFile(commonDir) {
+ return join(commonDir, 'pullboard', 'blueprint-fit.json');
+ }
+
+ /**
+ * Every fit proposal recorded in this clone, waiting or decided, oldest first. A missing file holds
+ * none; a file that is not a proposal list is refused rather than read as empty, so a damaged batch
+ * is never approved as a smaller one.
+ *
+ * @param {string} commonDir
+ * @returns {any[]}
+ */
+ export function readFit(commonDir) {
+ const file = fitFile(commonDir);
+ if (!existsSync(file)) return [];
+ let value;
+ try { value = JSON.parse(readFileSync(file, 'utf8')); }
+ catch (error) { throw new Refused('FIT_FILE', `${file} is not readable JSON (${error.message.split('\n')[0]})`); }
+ if (!value || value.version !== 1 || !Array.isArray(value.proposals)) throw new Refused('FIT_FILE', `${file} is not a blueprint fit file`);
+ // Every proposal has its own id. Two sharing one could let an unread proposal pass as the read
+ // one, so a batch with any shared id is refused, naming every target that shares it.
+ const seen = new Map();
+ for (const proposal of value.proposals) seen.set(proposal?.id, [...(seen.get(proposal?.id) ?? []), proposal?.target]);
+ const shared = [...seen.values()].filter((targets) => targets.length > 1).flat();
+ if (shared.length) {
+ throw new Refused('FIT_FILE', `${shared.join(', ')} share a proposal id in ${file}, so the blueprint fit batch cannot be read or approved`,
+ `remove ${file} and have the seats record their proposals again with pullboard blueprint fit`);
+ }
+ return value.proposals;
+ }
+
+ /**
+ * Replace the whole proposal list by rename, so a reader never sees half a batch.
+ *
+ * @param {string} commonDir
+ * @param {any[]} proposals
+ */
+ function writeFit(commonDir, proposals) {
+ const file = fitFile(commonDir);
+ mkdirSync(dirname(file), { recursive: true });
+ const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;
+ writeFileSync(temp, `${JSON.stringify({ version: 1, proposals }, null, 2)}\n`);
+ renameSync(temp, file);
+ }
+
+ /**
+ * The proposals that wait for the person.
+ *
+ * @param {string} commonDir
+ * @returns {any[]}
+ */
+ export function pendingFit(commonDir) {
+ return readFit(commonDir).filter((proposal) => proposal.state === 'proposed');
+ }
+
+ /**
+ * The blueprint's drafted rows, questions and open starter items as they sit on this board, by the
+ * name a seat uses for them: a row id such as W3, or #12 for an item. A rule matches its row by
+ * exact text in its own section, or as a unique shared draft from an earlier blueprint; a question
+ * by its ask and choices, whatever default it landed with; a starter by its title and cited rows.
+ * A row or item that has moved on (approved, reworded, claimed) is no longer a target.
+ *
+ * @param {import('./blueprints.js').Blueprint} blueprint
+ * @param {{ rows: any[], sections: { name: string }[] }} spec
+ * @param {any[]} items - The board's items as store.listItems returns them.
+ * @returns {Map<string, { kind: string, key: string, target: string, source: string, current: string, ask?: string, choices?: string[] }>}
+ */
+ export function fitTargets(blueprint, spec, items) {
+ const section = spec.sections.find((entry) => entry.name.replace(/^[A-Z][A-Z0-9]*\s*[·.:-]\s*/u, '') === blueprint.title.trim());
+ const targets = new Map();
+ const ownRows = section ? spec.rows.filter((row) => row.section === section.name) : [];
+ /** Prefer this blueprint's section; otherwise accept only a unique shared row on the board. */
+ const findDraft = (matches) => {
+ const inRows = (rows) => rows.filter((row) => row.status === matches.status && matches.test(row));
+ const own = inRows(ownRows);
+ if (own.length === 1) return own[0];
+ if (own.length > 1) return undefined;
+ const shared = inRows(spec.rows);
+ return shared.length === 1 ? shared[0] : undefined;
+ };
+ const ids = {};
+ for (const rule of blueprint.rules) {
+ const text = ruleText(rule);
+ const row = findDraft({ status: 'draft', test: (entry) => entry.text === text });
+ if (!row) continue;
+ ids[rule.key] = row.id;
+ targets.set(row.id, { kind: 'rule', key: rule.key, target: row.id, source: ruleText(rule), current: row.text });
+ }
+ for (const question of blueprint.questions) {
+ const choices = question.choices.map((choice) => choice.trim());
+ const row = findDraft({ status: 'pending', test: (entry) => entry.text.startsWith(`${question.ask.trim()}: `)
+ && entry.text.endsWith(`. Choices: ${choices.join(', ')}.`) });
+ if (!row) continue;
+ ids[question.key] = row.id;
+ targets.set(row.id, { kind: 'question', key: question.key, target: row.id, source: questionText(question), current: row.text, ask: question.ask.trim(), choices });
+ }
+ for (const starter of blueprint.items) {
+ const cites = starter.cites.map((key) => ids[key]).filter(Boolean).join(',');
+ const item = items.find((entry) => entry.item_status === 'open' && entry.item_title === starter.title.trim() && (entry.item_spec_ids ?? '') === cites);
+ if (!item) continue;
+ const source = `${starter.title.trim()}${starter.criterion ? `; criterion: ${starter.criterion}` : ''}`;
+ targets.set(`#${item.item_id}`, { kind: 'item', key: starter.key, target: `#${item.item_id}`, source, current: item.item_criterion ?? '' });
+ }
+ return targets;
+ }
+
+ /**
+ * Check one proposal against its target and give the text it would apply: the new row text, the
+ * answered question's row text or the item's new criterion, or null for keep and drop.
+ *
+ * @param {{ kind: string, target: string, ask?: string, choices?: string[] }} target
+ * @param {{ decision?: string, text?: string, reason?: string }} proposal
+ * @returns {{ decision: string, text: string | null, reason: string }}
+ */
+ function checkProposal(target, { decision, text, reason }) {
+ const line = (value) => typeof value === 'string' && value.trim() && !/[\r\n|]/u.test(value);
+ if (!FIT_DECISIONS.includes(decision)) throw new Refused('USAGE', `say how ${target.target} fits: keep, adapt, drop or answer`);
+ if (reason !== undefined && !line(reason)) throw new Refused('FIT_PROPOSAL', 'a reason is one nonempty line without a | character');
+ if (['adapt', 'drop', 'answer'].includes(decision) && reason === undefined) {
+ throw new Refused('FIT_PROPOSAL', `a ${decision} proposal keeps its reason; add --reason "why it fits this repo that way"`);
+ }
+ if (['keep', 'drop'].includes(decision)) {
+ if (text !== undefined) throw new Refused('FIT_PROPOSAL', `a ${decision} proposal takes no --text; use adapt to change the wording`);
+ return { decision, text: null, reason: reason?.trim() ?? '' };
+ }
+ if (!line(text)) throw new Refused('FIT_PROPOSAL', `an ${decision} proposal needs --text, one nonempty line without a | character`);
+ if (decision === 'adapt') return { decision, text: text.trim(), reason: reason.trim() };
+ if (target.kind !== 'question') throw new Refused('FIT_PROPOSAL', `${target.target} is no question; only a question takes an answer, so use keep, adapt or drop`);
+ if (!target.choices.includes(text.trim())) throw new Refused('FIT_PROPOSAL', `${text.trim()} is not one of ${target.target}'s choices (${target.choices.join(', ')})`);
+ return { decision, text: questionText({ ask: target.ask, choices: target.choices, default: text.trim() }), reason: reason.trim() };
+ }
+
+ /**
+ * Record a seat's fit proposal for one target of a blueprint this board has fully added. A later
+ * proposal for the same target replaces the waiting one; nothing else changes.
+ *
+ * @param {{ commonDir: string, blueprint: import('./blueprints.js').Blueprint, specSource: string, spec: any, items: any[], by: string, session: string | null, at: string }} where
+ * @param {{ target?: string, decision?: string, text?: string, reason?: string }} proposal
+ * @returns {any} the recorded proposal
+ */
+ export function proposeFit({ commonDir, blueprint, specSource, spec, items, by, session, at }, { target, decision, text, reason }) {
+ if (!specSource.split(/\r?\n/u).some((line) => line.trim() === blueprintMarker(blueprint))) {
+ throw new Refused('BLUEPRINT_NOT_ADDED', `${blueprint.name} version ${blueprint.version} is not fully added to this board`);
+ }
+ const targets = fitTargets(blueprint, spec, items);
+ const found = targets.get(String(target ?? '').trim());
+ if (!found) {
+ throw new Refused('FIT_TARGET', `${target ?? 'nothing'} is no drafted row, question or open starter of ${blueprint.name} here; targets: ${[...targets.keys()].join(', ') || 'none left'}`);
+ }
+ const checked = checkProposal(found, { decision, text, reason });
+ return saveProposal(commonDir, { id: randomUUID(), blueprint: { name: blueprint.name, version: blueprint.version }, ...found, ...checked, by, session, at, state: 'proposed' });
+ }
+
+ /**
+ * The person's edit of a waiting proposal: the same target and blueprint source, a new decision,
+ * text or reason, recorded as the person's own proposal.
+ *
+ * @param {string} commonDir
+ * @param {{ target?: string, decision?: string, text?: string, reason?: string, at: string }} edit
+ * @returns {any} the edited proposal
+ */
+ export function editFit(commonDir, { target, decision, text, reason, at }) {
+ const waiting = pendingFit(commonDir).find((proposal) => proposal.target === String(target ?? '').trim());
+ if (!waiting) throw new Refused('FIT_TARGET', `no fit proposal waits for ${target ?? 'that target'}; read the batch with pullboard spec fit`);
+ const checked = checkProposal(waiting, { decision, text, reason });
+ // The caller shows the whole batch again after an edit, so the person reads what they approve.
+ return saveProposal(commonDir, { ...waiting, id: randomUUID(), ...checked, by: PERSON, session: null, at, editedFrom: waiting.id });
+ }
+
+ /**
+ * Put one waiting proposal in the file, replacing any proposal still waiting for its target.
+ *
+ * @param {string} commonDir
+ * @param {any} proposal
+ * @returns {any}
+ */
+ function saveProposal(commonDir, proposal) {
+ const all = readFit(commonDir).map((entry) => (entry.state === 'proposed' && entry.target === proposal.target ? { ...entry, state: 'replaced', replacedBy: proposal.id } : entry));
+ writeFit(commonDir, [...all, proposal]);
+ return proposal;
+ }
+
+ /**
+ * Where a proposal came from, as one line: the blueprint, its version, its key and its text.
+ *
+ * @param {any} proposal
+ * @returns {string}
+ */
+ export function fitSource(proposal) {
+ return `${proposal.blueprint.name} v${proposal.blueprint.version} ${proposal.kind === 'item' ? 'starter' : proposal.kind} ${proposal.key}: ${proposal.source}`;
+ }
+
+ /**
+ * One proposal as the person reads it: target, decision, proposer, new text, reason and source.
+ *
+ * @param {any} proposal
+ * @returns {string}
+ */
+ export function fitLine(proposal) {
+ return `${proposal.target} ${proposal.decision} (unverified draft, recorded as ${proposal.by})${proposal.text ? `: ${proposal.text}` : ''}`
+ + `${proposal.reason ? `; reason: ${proposal.reason}` : ''}; blueprint source: ${fitSource(proposal)}`;
+ }
+
+ /**
+ * The lines pullboard spec prints for the waiting batch, or none: every proposal, then the batch
+ * code the person approves this exact batch with.
+ *
+ * @param {{ proposals: any[], batch: string }} read - From readFitBatch.
+ * @returns {string[]}
+ */
+ export function fitSummary({ proposals, batch }) {
+ if (!proposals.length) return [];
+ return [`blueprint fit: ${proposals.length} unverified draft ${proposals.length === 1 ? 'proposal waits' : 'proposals wait'} for the person; nothing applies until the person approves the batch`,
+ ...proposals.map((proposal) => ` ${fitLine(proposal)}`),
+ `the person edits one with pullboard spec fit edit <target> keep|adapt|drop|answer, or approves exactly this batch with pullboard spec fit approve ${batch}`];
+ }
+
+ /**
+ * The note a decision keeps: what the person approved, why, and where it came from.
+ *
+ * @param {any} proposal
+ * @returns {string}
+ */
+ function fitNote(proposal) {
+ return `blueprint fit ${proposal.decision}${proposal.reason ? `: ${proposal.reason}` : ''}; recorded as ${proposal.by}, unverified; blueprint source: ${fitSource(proposal)}`;
+ }
+
+ /**
+ * The person approves every waiting proposal as one batch. Each target must still read as it did
+ * when proposed. Row proposals become one set of the person's row decisions (keep and adapt and
+ * answer approve, drop declines with its reason), each with a note keeping the reason and the
+ * blueprint source; then starter adaptations set the item's criterion and starter drops withdraw
+ * it, each after a fact on the item keeping the same note. The batch is marked approved last.
+ *
+ * @param {{ commonDir: string, spec: any, items: any[], session: string | null, at: string, code: string }} where - code is the batch code the person typed
+ * @param {{ decide: (rows: { proposal: any, note: string }[]) => Promise<any[]>, fact: (id: number, text: string) => Promise<any>, criterion: (id: number, text: string) => Promise<any>, withdraw: (id: number, reason: string) => Promise<any> }} moves
+ * @returns {Promise<{ proposals: any[], decisions: any[], items: { id: number, decision: string }[] }>}
+ */
+ export async function approveFit({ commonDir, spec, items, session, at, code }, moves) {
+ const batch = refuseOwnFit(commonDir, session);
+ refuseUnreadFit(commonDir, batch, code);
+ if (!batch.length) throw new Refused('NO_FIT_PROPOSALS', 'no blueprint fit proposals wait for the person');
+ return await approveBatch({ commonDir, spec, items, at, batch }, moves);
+ }
+
+ /**
+ * Refuse an agent session that recorded any waiting proposal, before any other check reads the
+ * caller: a seat never approves or edits its own proposal, whatever channel it comes through.
+ * Returns the waiting batch.
+ *
+ * @param {string} commonDir
+ * @param {string | null} session - The caller's agent session digest, or null outside an agent shell.
+ * @returns {any[]}
+ */
+ export function refuseOwnFit(commonDir, session) {
+ const batch = pendingFit(commonDir);
+ const own = session && batch.find((proposal) => proposal.session === session);
+ if (own) throw new Refused('FIT_OWN_PROPOSAL', `this agent session recorded ${own.target}'s fit proposal as ${own.by}; a seat never approves its own proposal`);
+ return batch;
+ }
+
+ /**
+ * Apply an already-authorized batch; see approveFit.
+ *
+ * @param {{ commonDir: string, spec: any, items: any[], at: string, batch: any[] }} where
+ * @param {any} moves
+ * @returns {Promise<{ proposals: any[], decisions: any[], items: { id: number, decision: string }[] }>}
+ */
+ async function approveBatch({ commonDir, spec, items, at, batch }, moves) {
+ const stale = batch.filter((proposal) => {
+ const item = proposal.kind === 'item' && items.find((entry) => `#${entry.item_id}` === proposal.target && entry.item_status === 'open');
+ const now = proposal.kind === 'item'
+ ? (item ? item.item_criterion ?? '' : null)
+ : spec.rows.find((row) => row.id === proposal.target && ['draft', 'pending'].includes(row.status))?.text ?? null;
+ return now !== proposal.current;
+ });
+ if (stale.length) {
+ // The batch no longer matches the board, so none of it applies; the stale proposals leave the
+ // batch, so the person can read what is left and approve that.
+ const ids = new Set(stale.map((proposal) => proposal.id));
+ writeFit(commonDir, readFit(commonDir).map((entry) => (ids.has(entry.id) ? { ...entry, state: 'stale', staleAt: at } : entry)));
+ throw new Refused('FIT_STALE', `${stale.map((proposal) => proposal.target).join(', ')} changed after its fit proposal, so nothing in the batch was applied and those proposals left it`,
+ 'read what is left with pullboard spec fit, then approve it with the batch code it prints: pullboard spec fit approve <batch>');
+ }
+ const rows = batch.filter((proposal) => proposal.kind !== 'item');
+ const decisions = rows.length ? await moves.decide(rows.map((proposal) => ({ proposal, note: fitNote(proposal) }))) : [];
+ const changed = [];
+ for (const proposal of batch.filter((entry) => entry.kind === 'item' && entry.decision !== 'keep')) {
+ const id = Number(proposal.target.slice(1));
+ await moves.fact(id, `The person approved this blueprint fit: ${fitNote(proposal)}`);
+ if (proposal.decision === 'adapt') await moves.criterion(id, proposal.text);
+ else await moves.withdraw(id, `blueprint fit drop: ${proposal.reason}`);
+ changed.push({ id, decision: proposal.decision });
+ }
+ const approved = new Set(batch.map((proposal) => proposal.id));
+ const events = new Map(decisions.map((record) => [record.id, record.event]));
+ const after = readFit(commonDir).map((entry) => (approved.has(entry.id)
+ ? { ...entry, state: 'approved', approvedBy: PERSON, approvedAt: at, ...(events.has(entry.target) ? { decisionEvent: events.get(entry.target) } : {}) }
+ : entry));
+ writeFit(commonDir, after);
+ return { proposals: after.filter((entry) => approved.has(entry.id)), decisions, items: changed };
+ }
+
+ /**
+ * Show the waiting batch in the shared view state: each row a proposal names carries it and a
+ * stage saying it waits for the person, unless the person already decided that row; each starter
+ * carries its proposal; and the state lists the whole batch as fit.
+ *
+ * @param {any[]} proposals - From pendingFit.
+ * @param {any} state - The API state, after row decisions are projected.
+ * @returns {any}
+ */
+ export function projectFit(proposals, state) {
+ if (!proposals.length) return state;
+ // A recorder is shown only as recorded, never as an authenticated author, and no session digest leaves.
+ const drafts = proposals.map(({ by, session, ...proposal }) => ({ ...proposal, recordedAs: by, verified: false }));
+ const byTarget = new Map(drafts.map((proposal) => [proposal.target, proposal]));
+ return { ...state,
+ fit: drafts,
+ spec: state.spec.map((row) => (byTarget.has(row.id) && !row.decision
+ ? { ...row, fit: byTarget.get(row.id), stage: `fit draft, unverified: ${byTarget.get(row.id).decision}, waits for the person` } : row)),
+ items: state.items.map((item) => (byTarget.has(`#${item.id}`) ? { ...item, fit: byTarget.get(`#${item.id}`) } : item)),
+ };
+ }
+
+ /**
+ * The digest of what a proposal says, so a reading can tell later whether it changed.
+ *
+ * @param {any} proposal
+ * @returns {string}
+ */
+ export function fitDigest(proposal) {
+ const { id, blueprint, kind, key, target, source, current, decision, text, reason, by } = proposal;
+ return createHash('sha256').update(JSON.stringify({ id, blueprint, kind, key, target, source, current, decision, text, reason, by })).digest('hex');
+ }
+
+ /**
+ * Where the person's last reading is kept, so a refusal can name what differs from it. It is no
+ * proof of anything by itself: approve checks it against the batch code the person typed.
+ *
+ * @param {string} commonDir
+ * @returns {string}
+ */
+ function viewedFile(commonDir) {
+ return join(commonDir, 'pullboard', 'blueprint-fit-viewed.json');
+ }
+
+ /**
+ * Each proposal of a batch as a reading holds it, one entry per proposal and never merged by id:
+ * its id, its target and its digest, in id then digest order.
+ *
+ * @param {any[]} proposals
+ * @returns {{ id: string, target: string, digest: string }[]}
+ */
+ function readingOf(proposals) {
+ const entries = proposals.map((proposal) => ({ id: String(proposal.id), target: String(proposal.target), digest: fitDigest(proposal) }));
+ return entries.sort((a, b) => (a.id === b.id ? (a.digest < b.digest ? -1 : a.digest > b.digest ? 1 : 0) : a.id < b.id ? -1 : 1));
+ }
+
+ /**
+ * The batch code of a reading: a short digest of every entry's id, target and proposal digest, each
+ * entry on its own. The person approves by typing it, which binds the approval to exactly what
+ * they read.
+ *
+ * @param {{ id: string, target: string, digest: string }[]} reading
+ * @returns {string}
+ */
+ export function batchCode(reading) {
+ const entries = reading.map((entry) => [entry?.id, entry?.target, entry?.digest]);
+ return createHash('sha256').update(JSON.stringify(entries)).digest('hex').slice(0, 12);
+ }
+
+ /**
+ * The person's last reading, or null when there is none or it cannot be read.
+ *
+ * @param {string} commonDir
+ * @returns {{ id: string, target: string, digest: string }[] | null}
+ */
+ function readViewed(commonDir) {
+ const file = viewedFile(commonDir);
+ if (!existsSync(file)) return null;
+ let value;
+ try { value = JSON.parse(readFileSync(file, 'utf8')); }
+ catch (error) {
+ if (!(error instanceof SyntaxError)) throw error;
+ // A damaged reading is no reading; approve refuses it and the person reads the batch again.
+ return null;
+ }
+ const reading = value?.reading;
+ const entry = (item) => item && ['id', 'target', 'digest'].every((key) => typeof item[key] === 'string');
+ return Array.isArray(reading) && reading.every(entry) ? reading : null;
+ }
+
+ /**
+ * The waiting batch for a reader, with its batch code. When the reader is the person, in the main
+ * checkout's own terminal, this listing is the person's reading and replaces the last one. An
+ * agent, a remote shell or a worktree sees the batch and its code without it counting as read.
+ *
+ * @param {string} commonDir
+ * @param {{ isMain: boolean, channel?: string, at?: string }} reader
+ * @returns {{ proposals: any[], batch: string }}
+ */
+ export function readFitBatch(commonDir, { isMain, channel, at = new Date().toISOString() }) {
+ const proposals = pendingFit(commonDir);
+ const reading = readingOf(proposals);
+ if (isMain && isPersonTerminal(channel)) {
+ const file = viewedFile(commonDir);
+ mkdirSync(dirname(file), { recursive: true });
+ const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;
+ writeFileSync(temp, `${JSON.stringify({ version: 1, at, reading }, null, 2)}\n`);
+ renameSync(temp, file);
+ }
+ return { proposals, batch: batchCode(reading) };
+ }
+
+ /**
+ * True when this terminal is the person's own, by the same rule person moves use.
+ *
+ * @param {string | undefined} channel
+ * @returns {boolean}
+ */
+ function isPersonTerminal(channel) {
+ try { requirePersonChannel(channel ?? 'terminal'); return channel !== 'view'; }
+ catch (error) {
+ if (error instanceof Refused) return false;
+ throw error;
+ }
+ }
+
+ /**
+ * Refuse unless the batch is exactly what the person last read. The stored reading must hash to
+ * the code the person typed, or it was rewritten after the reading (FIT_READING). Then every id
+ * the person read must still wait with the same digest, and nothing may wait that they did not
+ * read (FIT_CHANGED, naming each). Nothing is written on either refusal.
+ *
+ * @param {string} commonDir
+ * @param {any[]} batch
+ * @param {string} code
+ */
+ function refuseUnreadFit(commonDir, batch, code) {
+ const reading = readViewed(commonDir);
+ if (!reading || batchCode(reading) !== String(code ?? '').trim()) {
+ throw new Refused('FIT_READING', `${code ?? 'no batch code'} is not the batch code of your last reading of the blueprint fit batch, or that reading was changed since; nothing was approved`,
+ 'read the batch again with pullboard spec fit, then approve it with the batch code it prints: pullboard spec fit approve <batch>');
+ }
+ const now = readingOf(batch);
+ // Compared entry by entry, never merged by id: a shared id, on either side, is itself a difference.
+ const count = (entries) => entries.reduce((ids, entry) => ids.set(entry.id, (ids.get(entry.id) ?? 0) + 1), new Map());
+ const [readIds, nowIds] = [count(reading), count(now)];
+ const named = [
+ ...reading.filter((entry) => !nowIds.has(entry.id)).map((entry) => `${entry.target} (gone)`),
+ ...now.filter((entry) => !readIds.has(entry.id)).map((entry) => `${entry.target} (new)`),
+ ...now.filter((entry) => readIds.has(entry.id) && !reading.some((read) => read.id === entry.id && read.digest === entry.digest)).map((entry) => `${entry.target} (changed)`),
+ ...[...reading, ...now].filter((entry) => readIds.get(entry.id) > 1 || nowIds.get(entry.id) > 1).map((entry) => `${entry.target} (shared id)`),
+ ];
+ if (named.length) {
+ throw new Refused('FIT_CHANGED', `${named.join(', ')} differ from your last reading of the blueprint fit batch, so nothing was approved`,
+ 'read the batch again with pullboard spec fit, then approve it with the batch code it prints: pullboard spec fit approve <batch>');
+ }
+ }
diff --cc src/board.js
index 64bccd1a,38f376bc..650abc34
--- a/src/board.js
+++ b/src/board.js
@@@ -6,47 -6,24 +6,61 @@@
* every move lands in an append-only event log (R2). The caller supplies what only git and the
* spec know: the commit, the verifier's checkout, the frozen criterion.
*/
-import { verdictReviewProblem, verdictsFor, acceptedVerdict, checkedLandingCommit } from './verdict-reviews.js';
++import {
++ verdictReviewProblem,
++ verdictsFor,
++ acceptedVerdict,
++ checkedLandingCommit,
++} from './verdict-reviews.js';
+ export { verdictReviewProblem, verdictsFor, acceptedVerdict, checkedLandingCommit };
-import { randomBytes, randomUUID } from 'node:crypto';
-import { existsSync, mkdirSync } from 'node:fs';
+import {
+ randomBytes,
+ randomUUID,
+} from 'node:crypto';
+import {
+ existsSync,
+ mkdirSync,
+} from 'node:fs';
import { dirname } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { boardNotWritable } from './board-access.js';
-import { briefFiles, briefSections } from './brief.js';
+import {
+ briefFiles,
- checkRouted,
++ briefSections,
+} from './brief.js';
import { COORDINATOR } from './config.js';
-import { ENGINE_VERSION, VERDICT_REVIEW_ENGINE, GUARDS, IN_STATE, MOVES, STATES, UNKNOWN_MOVE, effectiveGuards, storeTriggers } from './machine.js';
+import {
+ ENGINE_VERSION,
++ VERDICT_REVIEW_ENGINE,
+ GUARDS,
+ IN_STATE,
+ MOVES,
+ STATES,
+ UNKNOWN_MOVE,
+ effectiveGuards,
+ storeTriggers,
+} from './machine.js';
import { Refused } from './refused.js';
-import { causeProblem, requireNeverAgain } from './rigor.js';
+import {
+ causeProblem,
+ requireNeverAgain,
+} from './rigor.js';
import { barCorrectionFields } from './bar-corrections.js';
import { factReference } from './fact-reference.js';
-import { factFromEvent, requestAnswerRefusal, tellAnswerImplications, tellFactImplications, tellVerdictImplications } from './implies.js';
-import { landingFlakes, landingWaiverCovers, landingWaiverKind } from './landing-exceptions.js';
+import {
+ factFromEvent,
+ requestAnswerRefusal,
+ tellAnswerImplications,
+ tellFactImplications,
+ tellVerdictImplications,
+} from './implies.js';
++import {
++ landingFlakes,
++ landingWaiverCovers,
++ landingWaiverKind,
++} from './landing-exceptions.js';
import { parseSpec } from './spec.js';
+ export { landingFlakes, landingWaiverCovers, landingWaiverKind };
export { acceptCheck } from './check-accept.js';
export const ACCEPT_REASON = 'CRITERION_MET';
diff --cc src/browser-slot-guard.js
index c5d33822,187ce970..5567f4cb
--- a/src/browser-slot-guard.js
+++ b/src/browser-slot-guard.js
@@@ -14,23 -14,13 +14,22 @@@
* Without the marker, importing this module changes nothing.
*/
import childProcess from 'node:child_process';
-import { statSync, realpathSync } from 'node:fs';
+import {
+ statSync,
+ realpathSync,
+} from 'node:fs';
import { syncBuiltinESMExports } from 'node:module';
-import { basename, delimiter, isAbsolute, relative, resolve } from 'node:path';
+import {
+ basename,
+ delimiter,
+ isAbsolute,
+ relative,
+ resolve,
+} from 'node:path';
import { Refused } from './refused.js';
- // The util ESM facade evaluates lazy exports, including diff, which opens stderr on Node 24.
- // A child may share that descriptor with stdout; keep its pipe mode unchanged when preloading us.
- const { promisify } = process.getBuiltinModule('node:util');
+ // Node registers this symbol globally; looking it up needs no util facade or dynamic loader.
+ const PROMISIFY_CUSTOM = Symbol.for('nodejs.util.promisify.custom');
/** The marker the runner sets in a test file's process: held, none, or unset when the setting is off. */
export const BROWSER_SLOT_ENV = 'PULLBOARD_TEST_BROWSER_SLOT';
diff --cc src/cli.js
index 4a086e2c,ea3ef3aa..60a902a5
--- a/src/cli.js
+++ b/src/cli.js
@@@ -2,117 -2,27 +2,120 @@@
* The pullboard command line: every command, bound to who is asking (B3, R3). The main checkout is the
* coordinator; every other worktree is the agent that joined from it.
*/
-import { createHash, randomUUID } from 'node:crypto';
-import { spawn, spawnSync } from 'node:child_process';
-import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
-import { hostname, loadavg } from 'node:os';
-import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
+import {
+ createHash,
+ randomUUID,
+} from 'node:crypto';
+import {
+ spawn,
+ spawnSync,
+} from 'node:child_process';
+import {
+ appendFileSync,
+ existsSync,
+ mkdirSync,
++ readdirSync,
+ readFileSync,
+ realpathSync,
++ renameSync,
+ writeFileSync,
+} from 'node:fs';
- import { loadavg } from 'node:os';
++import {
++ hostname,
++ loadavg,
++} from 'node:os';
+import {
+ basename,
+ dirname,
+ isAbsolute,
+ join,
+ relative,
+ resolve,
+} from 'node:path';
import { performance } from 'node:perf_hooks';
- import {
- fileURLToPath,
- pathToFileURL,
- } from 'node:url';
+ import { pathToFileURL } from 'node:url';
import { parseArgs } from 'node:util';
import * as store from './board.js';
-import { CONFIG_FILE, COORDINATOR, DOCTRINE_FILE, LEGACY_DOCTRINE_FILE, loadConfig } from './config.js';
+import {
+ CONFIG_FILE,
+ COORDINATOR,
+ DOCTRINE_FILE,
+ LEGACY_DOCTRINE_FILE,
+ loadConfig,
+} from './config.js';
import { displayAgentName } from './agent-names.js';
-import { doctrineHistory, loadDoctrine } from './doctrine.js';
-import { agentDoctrine, proposeDoctrine, resumeDoctrineNotes, staleDoctrineRows } from './doctrine-rulings.js';
-import { checkRulesAt, doctrineReport, hasSubmitRules, holdDoctrine, ruleLine } from './doctrine-checks.js';
-import { AGENT_SESSION_IDS, agentSessionDigest, requirePersonChannel } from './person.js';
-import { bindLocalSession, localSessionMatches, localSessionSeats } from './agent-session.js';
-import { decisionAnswer, decisionProjection, handAnsweredQuestions, pendingAnswers, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';
-import { digestOf, gateReport, refuseSandboxBlocked, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';
+import {
+ doctrineHistory,
+ loadDoctrine,
+} from './doctrine.js';
+import {
+ agentDoctrine,
+ proposeDoctrine,
+ resumeDoctrineNotes,
+ staleDoctrineRows,
+} from './doctrine-rulings.js';
+import {
+ checkRulesAt,
+ doctrineReport,
+ hasSubmitRules,
+ holdDoctrine,
+ ruleLine,
+} from './doctrine-checks.js';
+import {
+ AGENT_SESSION_IDS,
+ agentSessionDigest,
+ requirePersonChannel,
+} from './person.js';
+import {
+ bindLocalSession,
+ localSessionMatches,
+ localSessionSeats,
+} from './agent-session.js';
+import {
+ decisionAnswer,
+ decisionProjection,
+ handAnsweredQuestions,
+ pendingAnswers,
+ planRowApply,
+ prepareRowDecisions,
+ restoreRowApply,
+ writeRowApply,
+} from './row-decisions.js';
+import {
+ digestOf,
+ gateReport,
+ refuseSandboxBlocked,
+ runGate,
+ runProfiledShell,
+ runSubmitGate,
+ submitGateReport,
+ timingDigest,
+ withGateSlot,
+} from './gate.js';
+ import { gateWaitReporter } from './gate-wait.js';
-import { checkNeedsBrowser, explicitCheckFiles } from './browser-admission.js';
-import { bareWorktreeFinding, codeIsFromMain, contains, differFromHead, git, gitChildEnv, headCommit, headTree, invalidateGitFacts, isClean, mainCheckout, patchId, repoInfo, resolveCommit, tryGit, untracked, withGitFacts } from './git.js';
+import {
+ checkNeedsBrowser,
+ explicitCheckFiles,
+} from './browser-admission.js';
+import {
+ bareWorktreeFinding,
+ codeIsFromMain,
+ contains,
+ differFromHead,
+ git,
+ gitChildEnv,
+ headCommit,
+ headTree,
+ invalidateGitFacts,
+ isClean,
+ mainCheckout,
+ patchId,
+ repoInfo,
+ resolveCommit,
+ tryGit,
+ untracked,
+ withGitFacts,
+} from './git.js';
import {
FIX_NOTE,
applyFixers,
@@@ -124,44 -34,15 +127,45 @@@
pushesTrunk,
unwiredHookProblems,
} from './hooks.js';
-import { askedLaneNotes, detectGate, initRepo, proposeLanes, starterLane, starterLaneNotes } from './init.js';
+import {
+ askedLaneNotes,
++ detectGate,
+ initRepo,
+ proposeLanes,
+ starterLane,
+ starterLaneNotes,
+} from './init.js';
import { lifecycleMarkdown } from './machine.js';
-import { HELP, VERSION } from './help.js';
-import { barCorrectionLine, barCorrections, barStatsLines } from './bar-corrections.js';
-import { checkImplies, decisionsImplying, parseImplies, takeDecisionNotices, whyLine } from './implies.js';
+import {
+ buildHelp,
+ VERSION,
+} from './help.js';
+import {
+ barCorrectionLine,
+ barCorrections,
+ barStatsLines,
+} from './bar-corrections.js';
+import {
+ checkImplies,
+ decisionsImplying,
+ parseImplies,
+ takeDecisionNotices,
+ whyLine,
+} from './implies.js';
import { defaultViewPort } from './view-port.js';
-export { HELP, VERSION };
-import { productLine, productProblems, productSummaries } from './products.js';
-import { addLane, isLane, laneNames, laneOf, outOfLane } from './lanes.js';
+export { VERSION };
+import {
+ productLine,
+ productProblems,
+ productSummaries,
+} from './products.js';
+import {
+ addLane,
+ isLane,
+ laneNames,
+ laneOf,
+ outOfLane,
+} from './lanes.js';
import { Refused } from './refused.js';
import { personNeeds } from './needs.js';
import { personNeedsState } from './needs-state.js';
@@@ -189,209 -63,54 +193,212 @@@ import
standings,
unmetRows,
} from './spec.js';
-import { answerQuestion, bundledBlueprints, landBlueprint, planBlueprint, readBlueprint, repoAnswers, saveBlueprint } from './blueprints.js';
+import {
+ answerQuestion,
+ bundledBlueprints,
+ landBlueprint,
+ planBlueprint,
+ readBlueprint,
+ repoAnswers,
+ saveBlueprint,
+} from './blueprints.js';
+ import { fitCommand } from './blueprint-fit-command.js';
-import { fitSummary, readFitBatch } from './blueprint-fit.js';
-import { blueprintStarterNote, combinedSummary, initBlueprintLines, initBlueprintResult, installedBlueprints, landEach, readBlueprints, sharedRowLines } from './blueprint-set.js';
++import {
++ fitSummary,
++ readFitBatch,
++} from './blueprint-fit.js';
+import {
+ blueprintStarterNote,
+ combinedSummary,
+ initBlueprintLines,
+ initBlueprintResult,
+ installedBlueprints,
+ landEach,
+ readBlueprints,
+ sharedRowLines,
+} from './blueprint-set.js';
import { briefFiles } from './brief.js';
-import { commitFirst, commitOwnerLines, commitOwners, coordinatorInbox, coordinatorInboxLines, inboxFirst } from './resume.js';
-import { checkBaseline, prepareCheckBaseline, refuseCheckSyntax, sayCheckBaseline } from './check-baseline.js';
-import { checkAcceptCommand, refuseClaimProvesNothing, refuseProvesNothing } from './check-accept.js';
-import { retryCheckBaselines, startCheckBaseline } from './check-baseline-worker.js';
-import { compareMainFailures, mainRedMessage, mainRedReworkItems } from './main-red.js';
+import {
+ commitFirst,
+ commitOwnerLines,
+ commitOwners,
+ coordinatorInbox,
+ coordinatorInboxLines,
+ inboxFirst,
+} from './resume.js';
+import {
+ checkBaseline,
+ prepareCheckBaseline,
+ refuseCheckSyntax,
+ sayCheckBaseline,
+} from './check-baseline.js';
+import {
+ checkAcceptCommand,
+ refuseClaimProvesNothing,
+ refuseProvesNothing,
+} from './check-accept.js';
+import {
+ retryCheckBaselines,
+ startCheckBaseline,
+} from './check-baseline-worker.js';
+import {
+ compareMainFailures,
+ mainRedMessage,
+ mainRedReworkItems,
+} from './main-red.js';
import { runItems } from './run.js';
-import { parseProblems, sweepItems } from './sweep.js';
+import {
+ parseProblems,
+ sweepItems,
+} from './sweep.js';
import { renderSpecView } from './view.js';
import { tour } from './tour.js';
-import { commandOutput, refusalDocument } from './json.js';
-import { forgetProject, listApiProjects, registerProjectAndLink, registeredProjectRootsSnapshot } from './projects.js';
+import {
+ commandOutput,
+ refusalDocument,
+} from './json.js';
+import {
+ forgetProject,
+ listApiProjects,
+ registerProjectAndLink,
+ registeredProjectRootsSnapshot,
+} from './projects.js';
import { milestoneRoadmap } from './roadmap.js';
-import { rigorLines, rigorReport } from './rigor.js';
-import { listResources, memoryVerdict, readMachineMemory, runnerResourceStatus } from './resources.js';
-import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';
-import { exportView, serveView } from './serve.js';
-import { forgetView, portHolder, rememberView, runningView } from './view-session.js';
-import { backgroundViewLine, keepViewRunning, launchBackgroundView, reportView } from './background-view.js';
+import {
+ rigorLines,
+ rigorReport,
+} from './rigor.js';
+import {
+ listResources,
+ memoryVerdict,
+ readMachineMemory,
+ runnerResourceStatus,
+} from './resources.js';
+import {
+ citedTestFiles,
+ rowEvidence,
+ rowStage,
+} from './evidence.js';
+import {
+ exportView,
+ serveView,
+} from './serve.js';
+import {
+ forgetView,
+ portHolder,
+ rememberView,
+ runningView,
+} from './view-session.js';
+import {
+ backgroundViewLine,
+ keepViewRunning,
+ launchBackgroundView,
+ reportView,
+} from './background-view.js';
import { serveApi } from './api.js';
import { watchCommand } from './watch.js';
import { serveMcp } from './mcp.js';
-import { doctorProblems, doctrineProblems } from './doctor.js';
-import { boardHealth, healthLines } from './health.js';
-import { staleFrozenItems, staleItemFinding } from './approved-rows.js';
-import { mainPolicy, policyAt, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots, requireTrunkMerge, trunkRef } from './trusted-policy.js';
-import { captureVerdictReview, staleVerdictRefusal, verdictProjector, verdictTrunk } from './verdict-freshness.js';
+import {
+ doctorProblems,
+ doctrineProblems,
+} from './doctor.js';
+import {
+ boardHealth,
+ healthLines,
+} from './health.js';
+import {
+ staleFrozenItems,
+ staleItemFinding,
+} from './approved-rows.js';
+import {
+ mainPolicy,
+ policyAt,
+ itemPolicy,
+ submissionPaths,
+ frozenCheck,
+ checkAtCommit,
+ dependencySnapshots,
+ requireTrunkMerge,
+ trunkRef,
+} from './trusted-policy.js';
++import {
++ captureVerdictReview,
++ staleVerdictRefusal,
++ verdictProjector,
++ verdictTrunk,
++} from './verdict-freshness.js';
import { proofStats } from './stats.js';
-import { flowLines, flowAlertLine } from './stats-flow.js';
+import {
+ flowLines,
+ flowAlertLine,
+} from './stats-flow.js';
import { releaseHeadlinesBetween } from './changelog.js';
-import { exportBoard, importBoard } from './exchange.js';
+import {
+ exportBoard,
+ importBoard,
+} from './exchange.js';
+ import { digestCommand } from './digest.js';
-import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';
-import { addRunner, browserFreeChecksEnabled, gateQueueSettings, gateShortSlots, loadMachineSettings, memoryFloorMB, relayOfferEnabled, setBrowserSlots, setGateShortSlots, setGateSlots } from './settings.js';
-import { formatSnapshotLimit, pendingSnapshotSize, pendingCheckpointProblem, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecover, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';
-import { autoLinkProject, offerRelayAtInit, relayOnAllCommand, revokeRelayDevice, unlinkedRelayProjects } from './relay-setup.js';
+import {
+ addSigner,
+ assertRequiredSigners,
+ defaultPrincipal,
+ hasSignerFile,
+} from './signature.js';
+import {
++ addRunner,
+ browserFreeChecksEnabled,
+ gateQueueSettings,
+ gateShortSlots,
+ loadMachineSettings,
+ memoryFloorMB,
++ relayOfferEnabled,
++ setBrowserSlots,
++ setGateShortSlots,
++ setGateSlots,
+} from './settings.js';
+import {
++ formatSnapshotLimit,
+ pendingSnapshotSize,
+ pendingCheckpointProblem,
+ relayCommandReceipt,
+ relayCommandReceiptReported,
+ relayLinked,
+ relayOff,
+ relayOn,
+ relayOperation,
+ relayRecover,
+ relayRecovered,
+ relayRevoke,
+ relayStatus,
+ relayTokens,
+ syncRelay,
+} from './relay.js';
+import {
+ autoLinkProject,
+ offerRelayAtInit,
+ relayOnAllCommand,
+ revokeRelayDevice,
+ unlinkedRelayProjects,
+} from './relay-setup.js';
- import { digestCommand } from './digest.js';
import { readRelayMachine } from './relay-machine.js';
-import { relayJoin, relayPair } from './relay-pairing-client.js';
+import {
+ relayJoin,
+ relayPair,
+} from './relay-pairing-client.js';
import { executePersonRequests } from './relay-request-execution.js';
+ import { engineReceipt } from './engine.js';
-import { accountedFailures, land, landingRemote, landingSubject, liveWaiverProjection, waivedFailures, waiverLine } from './land.js';
+import {
- boardSetup,
- recordSetupState,
- recordViewBind,
- recordViewReuse,
- setupIdentity,
- viewSetupComplete,
- } from './setup-card.js';
- import { formatSnapshotLimit } from './relay-messages.js';
- import { privateNames } from './private-names.js';
- import {
- runnerCommand,
- settingsCommand,
- } from './machine-commands.js';
- import {
- filesSince,
- recordedRecovery,
- refuseUnverifiedStack,
- reportSubmission,
- } from './submission.js';
- import {
++ accountedFailures,
+ land,
+ landingRemote,
+ landingSubject,
++ liveWaiverProjection,
++ waivedFailures,
++ waiverLine,
+} from './land.js';
import { installStep } from './worktree.js';
+ export { gateWaitReporter };
const CHECKOUT_LEASES = new WeakMap();
const CHECKOUT_BOARD_ONLY = new WeakMap();
let startupMainTraced = false;
@@@ -4258,9 -4292,6 +4580,9 @@@ export function resultCommands()
])].sort();
}
- /** The actual command maps supply help names, so adding a handler needs no parallel help-name edit. */
++/** Command help follows the same dispatch declarations as execution. */
+export const HELP = buildHelp(resultCommands());
+
// This marker is emitted once when the actual CLI entrypoint finishes evaluating.
if (process.env.PULLBOARD_STARTUP_TRACE_ENTRY
&& resolve(process.argv[1] ?? '') === resolve(process.env.PULLBOARD_STARTUP_TRACE_ENTRY)) {
diff --cc src/engine.js
index 4df28078,a88943bd..a53b631a
--- a/src/engine.js
+++ b/src/engine.js
@@@ -1,33 -1,14 +1,34 @@@
/** Versioned, deterministic replay through the CLI's existing board engine [H3,H16]. */
-import { createHash, randomUUID } from 'node:crypto';
+import {
+ createHash,
+ randomUUID,
+} from 'node:crypto';
import * as store from './board.js';
import { recordedRefusal } from './recorded-refusal.js';
-import { BAR_ENGINE, carriesBarReason } from './bar-corrections.js';
-import { carriesImplies, IMPLIES_ENGINE } from './implies.js';
+import {
+ BAR_ENGINE,
+ carriesBarReason,
+} from './bar-corrections.js';
+import {
+ carriesImplies,
+ IMPLIES_ENGINE,
+} from './implies.js';
import { CHECK_ACCEPT_ENGINE } from './check-accept.js';
-import { CAUSE_ENGINE, ENGINE_VERSION, VERDICT_REVIEW_ENGINE } from './machine.js';
+import {
+ CAUSE_ENGINE,
+ ENGINE_VERSION,
++ VERDICT_REVIEW_ENGINE,
+} from './machine.js';
import { Refused } from './refused.js';
-import { requestMoveProblem, recordRequestMove } from './relay-requests.js';
-import { relayMoveActor, relaySenderProblem, validRelaySender } from './relay-sender.js';
+import {
+ requestMoveProblem,
+ recordRequestMove,
+} from './relay-requests.js';
+import {
+ relayMoveActor,
+ relaySenderProblem,
+ validRelaySender,
+} from './relay-sender.js';
const ITEM_ID_FIRST_ARGUMENT = new Set(['acceptCheck', 'editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze', 'reopen', 'appendFact']);
diff --cc src/gate-stages.js
index 00000000,1cfcbbc5..eb1d1784
mode 000000,100644..100644
--- a/src/gate-stages.js
+++ b/src/gate-stages.js
@@@ -1,0 -1,130 +1,134 @@@
+ /** Shared local and registered-runner gate accounting [B3,R3,C7]. */
-import { existsSync, readFileSync, statSync } from 'node:fs';
++import {
++ existsSync,
++ readFileSync,
++ statSync,
++} from 'node:fs';
+ import { join } from 'node:path';
+
+ /**
+ * Split a gate command into its top-level stages, the commands joined by `&&`, `||`, `;` or a newline,
+ * and each stage into its pipeline components, the commands joined by `|`. Anything the split cannot
+ * read for certain (a subshell, a group, command substitution, a heredoc, a comment, a background job,
+ * `|&` or an open quote) returns null, so no stage or component is ever guessed [B3,R3].
+ *
+ * @param {string} command
+ * @returns {Array<{ text: string, op: string, pipeline: string[] }> | null}
+ */
+ export function gateStages(command) {
+ const source = String(command).trim();
+ const stages = [];
+ let current = '';
+ let segment = '';
+ let pipeline = [];
+ let quote = null;
+ let variable = 0;
+ /** Append text to both the stage and its current pipeline component. */
+ const add = (text) => { current += text; segment += text; };
+ /** Close the current pipeline component; an empty or line-continued component is unreadable. */
+ const pipe = () => {
+ if (!segment.trim() || /\\$/u.test(segment.trim())) return false;
+ pipeline.push(segment.trim());
+ segment = '';
+ return true;
+ };
+ /** Close the current stage with the operator that follows it; an empty stage is unreadable. */
+ const close = (op) => {
+ if (!current.trim() || /\\$/u.test(current.trim()) || !pipe()) return false;
+ stages.push({ text: current.trim(), op, pipeline });
+ current = '';
+ pipeline = [];
+ return true;
+ };
+ for (let at = 0; at < source.length; at += 1) {
+ const char = source[at];
+ const next = source[at + 1];
+ if (quote === "'") { add(char); if (char === "'") quote = null; continue; }
+ if (char === '\\') { add(next === '\n' ? ' ' : char + (next ?? '')); at += 1; continue; }
+ if (char === '`' || (char === '$' && next === '(')) return null;
+ if (quote === '"') { add(char); if (char === '"') quote = null; continue; }
+ if (char === "'" || char === '"') { quote = char; add(char); continue; }
+ if (char === '$' && next === '{') { variable += 1; add('${'); at += 1; continue; }
+ if (char === '}' && variable) { variable -= 1; add(char); continue; }
+ if ('(){}#'.includes(char) || (char === '<' && (next === '<' || next === '('))) return null;
+ if (char === '&') {
+ if (next === '&') { if (!close('&&')) return null; at += 1; continue; }
+ if (next === '>' || source[at - 1] === '>' || source[at - 1] === '<') { add(char); continue; }
+ return null;
+ }
+ if (char === '|' && next === '|') { if (!close('||')) return null; at += 1; continue; }
+ if (char === '|') {
+ if (source[at - 1] === '>') { add(char); continue; }
+ if (next === '&' || variable || !pipe()) return null;
+ current += char;
+ continue;
+ }
+ if (char === ';') { if (next === ';' || !close(';')) return null; continue; }
+ if (char === '\n') { if (current.trim() && !close(';')) return null; continue; }
+ add(char);
+ }
+ if (quote || variable || !current.trim() || /\\$/u.test(current.trim()) || !close('')) return null;
+ return stages;
+ }
+
+ /**
+ * Wrap each stage so the shell prints its start and its exit status between private marker lines.
+ * Control flow is unchanged: each wrapper exits with its stage's status, and an `exit` inside a
+ * stage still ends the run, which leaves that stage without an end marker and so unaccounted.
+ * A pipeline's components each keep their own exit status and their own standard output in
+ * private files instead of the run's output, since a marker written into a pipe would land in the
+ * next component's input. A failure is then credited only to the component that printed it [B3,R3].
+ */
+ export function stagedScript(stages, marker, pipes) {
+ /** Quote one private file of a component for the shell. */
+ const file = (index, at, kind) => `'${join(String(pipes), `${index}-${at}.${kind}`).replaceAll("'", "'\\''")}'`;
+ /** One component that records its own status and output, then exits with that status. */
+ const component = (text, index, at) => `{ { {\n${text}\n}; printf '%s\\n' "$?" >> ${file(index, at, 'status')}; } | tee ${file(index, at, 'out')}; `
+ + `pullboard_pipe_status=$(tail -n 1 ${file(index, at, 'status')} 2>/dev/null); (exit "\${pullboard_pipe_status:-125}"); }`;
+ return stages.map((stage, index) => {
+ const body = stage.pipeline.length > 1 ? stage.pipeline.map((text, at) => component(text, index, at)).join(' | ') : stage.text;
+ return `{ printf '\\n${marker} begin ${index}\\n'; {\n${body}\n}; pullboard_stage_status=$?; `
+ + `printf '\\n${marker} end ${index} %s\\n' "$pullboard_stage_status"; (exit "$pullboard_stage_status"); } ${stage.op}`;
+ }).join('\n');
+ }
+
+ /**
+ * Read each pipeline component's own status and, when it failed, its own output. A component that
+ * recorded no status, or more than one, has a null status, so a line forged into its private file
+ * can only make its stage unaccounted [B3,R3].
+ */
+ export function readPipes(split, pipes, limit = Infinity) {
+ /** Read one private component file, or null when the component never wrote it. */
+ const read = (index, at, kind) => {
+ const path = join(pipes, `${index}-${at}.${kind}`);
+ return existsSync(path) && statSync(path).size <= limit ? readFileSync(path, 'utf8') : null;
+ };
+ return split.map((stage, index) => (stage.pipeline.length > 1 ? stage.pipeline.map((_, at) => {
+ const lines = (read(index, at, 'status') ?? '').split('\n').filter(Boolean);
+ const status = lines.length === 1 && /^\d+$/u.test(lines[0]) ? Number(lines[0]) : null;
+ return { status, output: status ? read(index, at, 'out') : null };
+ }) : null));
+ }
+
+ /** Cut a staged run's output back to the command's own lines and each stage's lines and status. */
+ export function readStages(output, marker, count) {
+ const stages = Array.from({ length: count }, () => ({ status: null, lines: [], began: false }));
+ const kept = [];
+ let open = null;
+ const lines = output.split('\n');
+ for (const [index, line] of lines.entries()) {
+ const found = line.startsWith(`${marker} `) ? /^(?:\S+) (begin|end) (\d+)(?: (\d+))?$/u.exec(line) : null;
+ if (found) {
+ if (kept.length && kept.at(-1) === '' && lines[index - 1] === '') kept.pop();
+ const stage = stages[Number(found[2])];
+ if (!stage) { open = null; continue; }
+ if (found[1] === 'begin') { stage.began = true; open = stage; }
+ else { stage.status = found[3] === undefined ? null : Number(found[3]); open = null; }
+ continue;
+ }
+ kept.push(line);
+ if (open) open.lines.push(line);
+ }
+ return { output: kept.join('\n'), stages: stages.map(({ status, lines: own, began }) => ({ status: began ? status : null, output: own.join('\n') })) };
+ }
+
diff --cc src/gate.js
index 9c48bdd1,f70bfcf0..af7b3006
--- a/src/gate.js
+++ b/src/gate.js
@@@ -4,72 -4,25 +4,86 @@@
* tree's id in the git dir, so the same tree is never checked twice. An agent sees a digest of the
* run, not the run (V10): a passing suite's output costs tokens and says nothing.
*/
-import { spawn, spawnSync } from 'node:child_process';
+import {
+ spawn,
+ spawnSync,
+} from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
-import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
-import { availableParallelism, tmpdir } from 'node:os';
+import {
+ existsSync,
+ mkdirSync,
++ mkdtempSync,
+ readFileSync,
++ realpathSync,
++ rmSync,
+ statSync,
+ writeFileSync,
+} from 'node:fs';
+import {
+ dirname,
+ isAbsolute,
+ join,
+ relative,
++ resolve,
+ sep,
+} from 'node:path';
- import { availableParallelism } from 'node:os';
++import {
++ availableParallelism,
++ tmpdir,
++} from 'node:os';
import { fileURLToPath } from 'node:url';
-import { gitChildEnv, gitPath, headTree, invalidateGitFacts, isClean, untracked } from './git.js';
+import {
+ gitChildEnv,
+ gitPath,
+ headTree,
+ invalidateGitFacts,
+ isClean,
+ untracked,
+} from './git.js';
import { secretsIn } from './hooks.js';
import { Refused } from './refused.js';
-import { GATE_SLOT_HELD_ENV, gateSlotEnvironment, inheritedGateSlot, memoryAdmission, readMachineMemory, takeResource } from './resources.js';
-import { browserFreeChecksEnabled, gateQueueSettings, gateShortSlots, loadMachineSettings, memoryFloorMB } from './settings.js';
+import {
+ GATE_SLOT_HELD_ENV,
+ gateSlotEnvironment,
+ inheritedGateSlot,
+ memoryAdmission,
+ readMachineMemory,
+ takeResource,
+} from './resources.js';
+import {
+ browserFreeChecksEnabled,
+ gateQueueSettings,
+ gateShortSlots,
+ loadMachineSettings,
+ memoryFloorMB,
+} from './settings.js';
import { selectAffectedTests } from './affected-tests.js';
-import { checkNeedsBrowser, testsNeedBrowser } from './browser-admission.js';
-import { timingFromOutput, timingRunner } from './timing.js';
+import {
+ checkNeedsBrowser,
+ testsNeedBrowser,
+} from './browser-admission.js';
+import {
+ timingFromOutput,
+ timingRunner,
+} from './timing.js';
import { landingShardProfile } from './landing-shards.js';
-import { gateStages, stagedScript, readPipes, readStages } from './gate-stages.js';
++import {
++ gateStages,
++ stagedScript,
++ readPipes,
++ readStages,
++} from './gate-stages.js';
+ export { gateStages } from './gate-stages.js';
-import { RunnerDropped, runOnRunner, runOnRunnerAsync, runnerSource } from './runners.js';
-import { sandboxBlockedOperation, sandboxBlockedScanner } from './sandbox-denial.js';
+import {
+ RunnerDropped,
+ runOnRunner,
+ runOnRunnerAsync,
+ runnerSource,
+} from './runners.js';
+import {
+ sandboxBlockedOperation,
+ sandboxBlockedScanner,
+} from './sandbox-denial.js';
// Callers keep importing the classifier from the gate; the runner worker imports it directly.
export { sandboxBlockedOperation, sandboxBlockedScanner };
diff --cc src/help.js
index b6eac727,eac08d1c..e56cac6e
--- a/src/help.js
+++ b/src/help.js
@@@ -260,6 -272,6 +262,8 @@@ const HELP_EXAMPLES =
};
const HELP_ALIASES = {
++ help: { usage: 'pullboard help', source: null },
++ version: { usage: 'pullboard version', source: null },
whoami: { usage: 'pullboard whoami', source: 'whoami' },
lanes: { usage: 'pullboard lanes', source: 'whoami' },
lane: { usage: 'pullboard lane add <name> --owns <path>[,<path>]', source: 'lane add' },
@@@ -325,10 -336,7 +328,13 @@@ function commandHelpRows(fullHelp, comm
for (let next = index + 1; next < lines.length && lines[next].startsWith(' ') && lines[next].trim() && !lines[next].startsWith(' pullboard '); next += 1) details.push(lines[next].trim());
rows.push({ usage: lines[index].trim().slice('pullboard '.length).split(/\s{2,}/, 1)[0].trim(), details });
}
- return Object.fromEntries(HELP_NAMES.map((name) => {
+ const phrases = rows.flatMap((row) => usagePhrases(row.usage));
- const names = [...new Set([...commandNames, ...Object.keys(HELP_ALIASES),
- ...phrases.flatMap((name) => [name.split(' ')[0], name])])];
++ const names = [...new Set([
++ ...commandNames,
++ ...Object.keys(HELP_ALIASES),
++ ...phrases.flatMap((name) => [name.split(' ')[0], name]),
++ ])];
+ return Object.fromEntries(names.map((name) => {
const parts = name.split(' ');
const alias = HELP_ALIASES[name];
const matches = alias?.source ? rows.filter((row) => row.usage === alias.source || row.usage.startsWith(`${alias.source} `)) : alias ? [] : rows.filter((row) => {
@@@ -367,19 -375,14 +373,19 @@@ function overviewHelp(groups, firstRun
return lines.join('\n');
}
- /** Derive help names from live command declarations and the existing usage and alias declarations. */
-/** The one help declaration feeds the overview, command detail, JSON result and unchanged full list. */
-export const HELP = Object.freeze({
- overview: overviewHelp(HELP_GROUPS),
- firstRun: overviewHelp(HELP_GROUPS, true),
- all: ALL_HELP,
- groups: HELP_GROUPS,
- commands: Object.freeze(commandHelpRows(ALL_HELP)),
-});
++/** Build help from the actual command declarations, preserving the printed overview and full list. */
+export function buildHelp(commandNames = []) {
+ return Object.freeze({
+ overview: overviewHelp(HELP_GROUPS),
+ firstRun: overviewHelp(HELP_GROUPS, true),
+ all: ALL_HELP,
+ groups: HELP_GROUPS,
+ commands: Object.freeze(commandHelpRows(ALL_HELP, commandNames)),
+ });
+}
+
- /** Browser command phrases use the same pure declarations without initializing the CLI or server. */
++/** Browser consumers read pure help declarations without initializing the CLI or server. */
+export const HELP = buildHelp();
/** Replace help placeholders with ordinary values so every command receives a usable example. */
function exampleFor(name, usage) {
diff --cc src/land.js
index 5e01af74,c60844b5..09021d27
--- a/src/land.js
+++ b/src/land.js
@@@ -1,41 -1,13 +1,45 @@@
/** Coordinator landing batches retain exact Git and gate receipts across interruptions [B3,R3]. */
-import { createHash, randomUUID } from 'node:crypto';
-import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync } from 'node:fs';
-import { dirname, isAbsolute, join, relative } from 'node:path';
+import {
+ createHash,
+ randomUUID,
+} from 'node:crypto';
+import {
+ closeSync,
+ copyFileSync,
+ existsSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ readSync,
+} from 'node:fs';
+import {
+ dirname,
+ isAbsolute,
+ join,
+ relative,
+} from 'node:path';
import * as store from './board.js';
-import { git, headCommit, headTree, isClean, mainCheckout, repoInfo, tryGit, untracked } from './git.js';
-import { runGate, runProfiledShell, withGateSlot } from './gate.js';
+import {
+ git,
+ headCommit,
+ headTree,
+ isClean,
+ mainCheckout,
+ repoInfo,
+ tryGit,
+ untracked,
+} from './git.js';
+import {
+ runGate,
+ runProfiledShell,
+ withGateSlot,
+} from './gate.js';
import { laneOf } from './lanes.js';
import { Refused } from './refused.js';
-import { staleVerdictRefusal, verdictProjector } from './verdict-freshness.js';
++import {
++ staleVerdictRefusal,
++ verdictProjector,
++} from './verdict-freshness.js';
/** Quote a command argument without allowing shell interpolation. */
function quote(value) { return `'${String(value).replaceAll("'", "'\\''")}'`; }
diff --cc src/needs-state.js
index 3095adec,659656b8..18b55884
--- a/src/needs-state.js
+++ b/src/needs-state.js
@@@ -3,6 -3,7 +3,10 @@@ import { join } from 'node:path'
import * as store from './board.js';
import { repoInfo } from './git.js';
import { projectRowDecisions } from './row-decisions.js';
-import { pendingFit, projectFit } from './blueprint-fit.js';
++import {
++ pendingFit,
++ projectFit,
++} from './blueprint-fit.js';
import { projectState } from './serve.js';
/** Borrow an existing connection or open a read-only one; retain exact row-decision matching. */
diff --cc src/relay-presentation.js
index 154aee83,4f3f1924..edbc7ad2
--- a/src/relay-presentation.js
+++ b/src/relay-presentation.js
@@@ -3,14 -3,13 +3,20 @@@ import { createHash } from 'node:crypto
import { join } from 'node:path';
import * as store from './board.js';
import { exportBoard } from './exchange.js';
-import { codeIsFromMain, repoInfo, withGitReadFacts } from './git.js';
+import {
+ codeIsFromMain,
+ repoInfo,
++ withGitReadFacts,
+} from './git.js';
import { Refused } from './refused.js';
import { loadConfig } from './config.js';
import { projectState } from './serve.js';
import { personRequestStatuses } from './relay-requests.js';
-import { cachedVerdictStates, verdictProjector } from './verdict-freshness.js';
++import {
++ cachedVerdictStates,
++ verdictProjector,
++} from './verdict-freshness.js';
+ import { trunkRevisionReader } from './trunk-revision.js';
/** Capture spec, doctrine, config and board presentation without sending plaintext to a relay. */
export function relayPresentation(root, { board: providedBoard = null } = {}) {
diff --cc src/relay.js
index de864334,f8900245..f7131721
--- a/src/relay.js
+++ b/src/relay.js
@@@ -1,103 -1,26 +1,94 @@@
/** Opt-in, sealed relay ordering, with crash-safe migration from the older mirror [H1,H3,H5,H16,H17,P5]. */
-import { createHash, randomUUID } from 'node:crypto';
-import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import {
+ createHash,
+ randomUUID,
+} from 'node:crypto';
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
import { hostname } from 'node:os';
-import { basename, dirname, join } from 'node:path';
-import { gunzipSync, gzipSync } from 'node:zlib';
+import {
+ basename,
+ dirname,
+ join,
+} from 'node:path';
+import {
+ gunzipSync,
+ gzipSync,
+} from 'node:zlib';
import * as store from './board.js';
-import { exportBoard, importBoard, restoreRelaySnapshot, semanticBoardDigest } from './exchange.js';
-import { appliedSequence, applyEngineMove, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, refuseRelayMove, requireSupportedEngine, startRelayEpoch } from './engine.js';
+import {
+ exportBoard,
+ importBoard,
+ restoreRelaySnapshot,
+ semanticBoardDigest,
+} from './exchange.js';
+import {
+ appliedSequence,
+ applyEngineMove,
+ applyRelayMove,
+ checkpointSequence,
+ engineReceipt,
+ prepareEngineMove,
+ refuseRelayMove,
+ requireSupportedEngine,
+ startRelayEpoch,
+} from './engine.js';
import { relayMoveActor } from './relay-sender.js';
import { ENGINE_VERSION } from './machine.js';
-import { presentationDigest, relayPresentation, relaySnapshot } from './relay-presentation.js';
-import { codeIsFromMain, repoInfo, tryGit } from './git.js';
-import { forgetBoardKey, readBoardKey, storeBoardKey } from './relay-key.js';
-import { encodeBoardKey, generateBoardKey, seal, unseal } from './seal.js';
+import {
+ presentationDigest,
+ relayPresentation,
+ relaySnapshot,
+} from './relay-presentation.js';
+import {
+ codeIsFromMain,
+ repoInfo,
+ tryGit,
+} from './git.js';
+import {
+ forgetBoardKey,
+ readBoardKey,
+ storeBoardKey,
+} from './relay-key.js';
+import {
+ encodeBoardKey,
+ generateBoardKey,
+ seal,
+ unseal,
+} from './seal.js';
import { terminalQr } from './qr.js';
import { Refused } from './refused.js';
- import {
- baselinePauseLine,
- expiredSignInMoveRefusal,
- formatSnapshotLimit,
- permanentBaselineRefusal,
- safePauseCode,
- safePauseMessage,
- transportFailure,
- } from './relay-messages.js';
import { refusalFromReceipt } from './recorded-refusal.js';
import { relaySenderProblem } from './relay-sender.js';
-import { readRelayMachine, removeRecordedDevice, updateRelayMachine, wrapForRecordedDevice } from './relay-machine.js';
-import { receivePersonRequest, requestMoveProblem } from './relay-requests.js';
-import { nativePhoneAction, phoneProposal, publishPhoneApproval, warnPhoneApproval } from './relay-phone.js';
-import { remoteShell as isRemoteShell, requirePersonChannel, requireRelayOnChannel } from './person.js';
+import {
+ readRelayMachine,
+ removeRecordedDevice,
+ updateRelayMachine,
+ wrapForRecordedDevice,
+} from './relay-machine.js';
+import {
+ receivePersonRequest,
+ requestMoveProblem,
+} from './relay-requests.js';
+import {
+ nativePhoneAction,
+ phoneProposal,
+ publishPhoneApproval,
+ warnPhoneApproval,
+} from './relay-phone.js';
+import {
+ remoteShell as isRemoteShell,
+ requirePersonChannel,
+ requireRelayOnChannel,
+} from './person.js';
import { listApiProjects } from './projects.js';
export const DEFAULT_RELAY = 'https://app.pullboard.dev';
diff --cc src/runner-worker.js
index ccb98cee,0b707e06..9cecf8d9
--- a/src/runner-worker.js
+++ b/src/runner-worker.js
@@@ -1,39 -1,13 +1,44 @@@
/** SSH runner entry point in a pinned capsule with a static trusted resource graph. */
-import { spawn, spawnSync } from 'node:child_process';
+import {
+ spawn,
+ spawnSync,
+} from 'node:child_process';
import { createHash } from 'node:crypto';
-import { chmodSync, closeSync, createReadStream, createWriteStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import {
+ chmodSync,
+ closeSync,
+ createReadStream,
+ createWriteStream,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ openSync,
+ readFileSync,
+ readdirSync,
+ readSync,
+ renameSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from 'node:fs';
import { userInfo } from 'node:os';
-import { delimiter, dirname, isAbsolute, join } from 'node:path';
-import { fileURLToPath, pathToFileURL } from 'node:url';
+import {
+ delimiter,
+ dirname,
+ isAbsolute,
+ join,
+} from 'node:path';
+import {
+ fileURLToPath,
+ pathToFileURL,
+} from 'node:url';
import * as resourceApi from './resources.js';
import { parseProcessCensus } from './process-census.js';
-import { gateStages, stagedScript, readPipes } from './gate-stages.js';
++import {
++ gateStages,
++ stagedScript,
++ readPipes,
++} from './gate-stages.js';
import { fileDenialWatcher } from './sandbox-denial.js';
import { once } from 'node:events';
import { pipeline } from 'node:stream/promises';
diff --cc src/runners.js
index d3060ad9,b2d1812e..74e5be77
--- a/src/runners.js
+++ b/src/runners.js
@@@ -1,56 -1,17 +1,60 @@@
/** Exact committed source and bounded, credential-free SSH execution for machine runners [C7]. */
-import { spawn, spawnSync } from 'node:child_process';
-import { createHash, randomUUID } from 'node:crypto';
-import { chmodSync, closeSync, createReadStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import {
+ spawn,
+ spawnSync,
+} from 'node:child_process';
+import {
+ createHash,
+ randomUUID,
+} from 'node:crypto';
+import {
+ chmodSync,
+ closeSync,
+ createReadStream,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ openSync,
+ readFileSync,
+ readSync,
+ realpathSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
-import { dirname, isAbsolute, join } from 'node:path';
+import {
+ dirname,
+ isAbsolute,
+ join,
+} from 'node:path';
import { fileURLToPath } from 'node:url';
import { pipeline } from 'node:stream/promises';
-import { gunzipSync, gzipSync } from 'node:zlib';
-import { configFromSource, defaults } from './config.js';
-import { blockedPaths, secretsIn } from './hooks.js';
-import { cleanGitEnvironment, headCommit, headTree, isClean, repoInfo, untracked } from './git.js';
+import {
+ gunzipSync,
+ gzipSync,
+} from 'node:zlib';
+import {
+ configFromSource,
+ defaults,
+} from './config.js';
+import {
+ blockedPaths,
+ secretsIn,
+} from './hooks.js';
+import {
+ cleanGitEnvironment,
+ headCommit,
+ headTree,
+ isClean,
+ repoInfo,
+ untracked,
+} from './git.js';
import { Refused } from './refused.js';
-import { gateStages, readStages } from './gate-stages.js';
++import {
++ gateStages,
++ readStages,
++} from './gate-stages.js';
import { remoteFileDenial } from './sandbox-denial.js';
// Budget: 64 MiB bounds worst-case JSON bridge escaping below Node string limits.
diff --cc src/trunk-revision.js
index 00000000,1ea4330c..d794b5bd
mode 000000,100644..100644
--- a/src/trunk-revision.js
+++ b/src/trunk-revision.js
@@@ -1,0 -1,46 +1,49 @@@
+ /** Cheap filesystem observation of the primary or retained trunk [E8,A2]. */
-import { readFileSync, statSync } from 'node:fs';
++import {
++ readFileSync,
++ statSync,
++} from 'node:fs';
+ import { join } from 'node:path';
+ import { trunkRef } from './trusted-policy.js';
+
+ /** Invalidate a retained branch lookup only when its local configuration changes. */
+ function fileMarkerForPath(path) {
+ try {
+ const stat = statSync(path);
+ return JSON.stringify([stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs]);
+ } catch (error) {
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return 'missing';
+ throw error;
+ }
+ }
+
+ const TRUNK_REVISION_READERS = new Map();
+
+ /** Watch the primary trunk ref even when this served worktree's HEAD remains fixed [E8]. */
+ export function trunkRevisionReader(info) {
+ const cached = TRUNK_REVISION_READERS.get(info.commonDir);
+ if (cached) return cached;
+ let retainedMarker = null;
+ let retained = null;
+ /** Read loose or packed refs without spawning Git in every event-stream poll. */
+ const read = () => {
+ const head = readFileSync(join(info.commonDir, 'HEAD'), 'utf8').trim();
+ let ref = /^ref: (refs\/heads\/.+)$/u.exec(head)?.[1];
+ if (!ref) {
+ const marker = fileMarkerForPath(join(info.commonDir, 'config'));
+ if (marker !== retainedMarker) { retained = trunkRef(info.root); retainedMarker = marker; }
+ ref = retained;
+ }
+ if (!ref?.startsWith('refs/heads/') || ref.includes('\\') || ref.split('/').some(part => !part || part === '.' || part === '..')) return null;
+ try { return readFileSync(join(info.commonDir, ref), 'utf8').trim(); }
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
+ try {
+ return readFileSync(join(info.commonDir, 'packed-refs'), 'utf8').split('\n')
+ .find(line => line.endsWith(' ' + ref))?.split(' ')[0] ?? null;
+ } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
+ };
+ TRUNK_REVISION_READERS.set(info.commonDir, read);
+ while (TRUNK_REVISION_READERS.size > 32) TRUNK_REVISION_READERS.delete(TRUNK_REVISION_READERS.keys().next().value);
+ return read;
+ }
+
diff --cc src/verdict-freshness.js
index 00000000,da472814..cc2aecf1
mode 000000,100644..100644
--- a/src/verdict-freshness.js
+++ b/src/verdict-freshness.js
@@@ -1,0 -1,182 +1,185 @@@
+ /** Acceptance stays append-only; freshness is derived from the known Git trunk [E8,V8]. */
+ import { spawnSync } from 'node:child_process';
+ import * as store from './board.js';
-import { cleanGitEnvironment, mainCheckout } from './git.js';
++import {
++ cleanGitEnvironment,
++ mainCheckout,
++} from './git.js';
+ import { trunkRef } from './trusted-policy.js';
+ import { Refused } from './refused.js';
+ import { trunkRevisionReader } from './trunk-revision.js';
+
+ /** Read exact Git objects without inherited selectors, replacements, or filename quoting. */
+ function readGit(root, args) {
+ const result = spawnSync('git', ['--no-replace-objects', ...args], {
+ cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,
+ });
+ if (result.status !== 0) throw new Error('Git history is unavailable');
+ return result.stdout;
+ }
+
+ /** Read the actual retained trunk tip, rather than a cached checkout HEAD used during review. */
+ export function verdictTrunk(root) {
+ try {
+ const ref = mainCheckout(root)?.branch ?? trunkRef(root);
+ if (!ref?.startsWith('refs/heads/')) throw new Error('The retained trunk is unavailable');
+ return readGit(root, ['rev-parse', '--verify', `${ref}^{commit}`]).trim();
+ } catch {
+ throw new Refused('BAD_VERDICT_REVIEW', 'the retained trunk cannot be read; restore its branch and Git objects before reviewing');
+ }
+ }
+
+ /** Capture the exact checked commit, review trunk and candidate delta against its submitted coordinator snapshot. */
+ export function captureVerdictReview(root, board, item, trunk = verdictTrunk(root), head = item.item_commit) {
+ const receipt = store.events(board, { itemId: item.item_id }).findLast(event => {
+ if (event.event_kind !== 'submit') return false;
+ return JSON.parse(event.event_detail).commit === item.item_commit;
+ });
+ const submittedMain = receipt ? JSON.parse(receipt.event_detail).policyCommit : null;
+ const base = submittedMain ?? item.item_claim_head;
+ if (!base) throw new Refused('BAD_VERDICT_REVIEW', 'the submitted base is unavailable; restore its Git objects before reviewing');
+ try {
+ const ancestor = readGit(root, ['merge-base', base, item.item_commit]).trim();
+ let paths = readGit(root, ['diff', '--no-renames', '--name-only', '-z', ancestor, item.item_commit, '--'])
+ .split('\0').filter(Boolean).sort();
+ if (head !== item.item_commit) {
+ readGit(root, ['merge-base', '--is-ancestor', trunk, head]);
+ const repairs = readGit(root, ['diff', '--no-renames', '--name-only', '-z', trunk, head, '--']).split('\0').filter(Boolean);
+ paths = [...new Set([...paths, ...repairs])].sort();
+ }
+ return { commit: item.item_commit, head, trunk, paths };
+ } catch {
+ throw new Refused('BAD_VERDICT_REVIEW', 'the submitted paths cannot be read; restore the submitted commit and base objects before reviewing');
+ }
+ }
+
+ /** Name the concrete stale proof and the required re-review without changing the original verdict. */
+ export function staleVerdictRefusal(item, state) {
+ if (state.landingCode === 'LAND_ITEM_MOVED') return new Refused('STALE_VERDICT',
+ `item #${item.item_id}: ${state.reason}; keep its landing receipt and ask the coordinator to create a correction item, then have another agent verify that correction before landing it`);
+ const changed = state.file && state.commit
+ ? `${JSON.stringify(state.file)} changed on main in ${state.commit}`
+ : state.reason ?? 'the reviewed Git history is unavailable';
+ return new Refused('STALE_VERDICT', `item #${item.item_id}: ${changed}; merge current main into the submitted commit, commit a clean composition, then another agent runs pullboard verify ${item.item_id} accept --note "what was re-reviewed" before landing`);
+ }
+
+ /** Create one read's projector, sharing Git history lookups across its unlanded acceptances. */
+ export function verdictProjector(root, board, { main } = {}) {
+ let tip = main;
+ let resolved = main !== undefined;
+ const histories = new Map();
+ const validatedBaselines = new Set();
+ const changes = new Map();
+ /** Query only first-parent commits touching these literal paths, retaining merges and reverts. */
+ const history = (baseline, paths) => {
+ if (!validatedBaselines.has(baseline)) {
+ readGit(root, ['merge-base', '--is-ancestor', baseline, tip]);
+ validatedBaselines.add(baseline);
+ }
+ const key = JSON.stringify([baseline, [...paths]]);
+ if (!histories.has(key)) {
+ const commits = paths.size ? readGit(root, ['--literal-pathspecs', 'log', '--first-parent', '--full-history',
+ '--diff-merges=first-parent', '--no-renames', '--reverse', '--format=%H', `${baseline}..${tip}`, '--', ...paths])
+ .trim().split('\n').filter(Boolean) : [];
+ histories.set(key, commits);
+ }
+ return histories.get(key);
+ };
+ /** Compare every commit with its first parent, so a merge's files and a revert both count. */
+ const changedFiles = commit => {
+ if (!changes.has(commit)) changes.set(commit,
+ readGit(root, ['diff', '--no-renames', '--name-only', '-z', `${commit}^1`, commit, '--']).split('\0').filter(Boolean));
+ return changes.get(commit);
+ };
+ /** Derive pending proof freshness and an older landing's explicitly recorded review mismatch. */
+ const state = item => {
+ if (item.item_status !== 'verified') return null;
+ const accepted = store.acceptedVerdict(board, item);
+ const mismatch = item.item_merged_commit && store.events(board, { itemId: item.item_id }).findLast(event => {
+ if (event.event_kind !== 'landing-review-moved') return false;
+ const detail = JSON.parse(event.event_detail);
+ return detail.verdict === accepted?.verdict_id && detail.landed === item.item_merged_commit;
+ });
+ if (item.item_merged_commit && !mismatch) return null;
+ let review = accepted?.review;
+ try {
+ if (!resolved) {
+ resolved = true;
+ tip = verdictTrunk(root);
+ }
+ if (!tip) throw new Error('The known trunk is unavailable');
+ review = accepted?.review;
+ if (review && store.verdictReviewProblem(review, item.item_commit)) throw new Error('The sealed review is invalid');
+ const checked = review?.head ?? item.item_commit;
+ // A physical landing is final only when it includes the checked composition.
+ const landed = spawnSync('git', ['--no-replace-objects', 'merge-base', '--is-ancestor', checked, tip],
+ { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8' });
+ if (landed.status === 0) return null;
+ if (landed.status !== 1) throw new Error('The checked commit is unavailable');
+ if (mismatch) return { code: 'STALE_VERDICT', file: null, commit: item.item_merged_commit,
+ reviewedTrunk: review.trunk, main: tip, landingCode: 'LAND_ITEM_MOVED', checked: review.head,
+ reason: `the older landing recorded ${item.item_merged_commit}, which does not contain checked composition ${review.head}` };
+ if (review && !review.head) return { code: 'STALE_VERDICT', file: null, commit: null,
+ reviewedTrunk: review.trunk, main: tip, reason: 'this acceptance predates checked-commit binding; re-review the clean composition with current Pullboard' };
+ if (review?.head && review.head !== item.item_commit) {
+ readGit(root, ['merge-base', '--is-ancestor', item.item_commit, review.head]);
+ readGit(root, ['merge-base', '--is-ancestor', review.trunk, review.head]);
+ }
+ if (!review) {
+ // Legacy receipts did not seal a reviewed trunk. Use a conservative claim-base bound,
+ // never invent a capture time or rewrite those immutable receipts.
+ const baseline = readGit(root, ['merge-base', item.item_claim_head, tip]).trim();
+ review = { trunk: baseline,
+ paths: readGit(root, ['diff', '--no-renames', '--name-only', '-z', baseline, item.item_commit, '--']).split('\0').filter(Boolean), legacy: true };
+ }
+ if (!review.legacy && store.verdictReviewProblem(review, item.item_commit)) throw new Error('The sealed review is invalid');
+ const paths = new Set(review.paths);
+ for (const commit of history(review.trunk, paths)) {
+ const file = changedFiles(commit).find(path => paths.has(path));
+ if (file) return { code: 'STALE_VERDICT', file, commit, reviewedTrunk: review.trunk, main: tip,
+ ...(review.legacy ? { legacy: true } : {}) };
+ }
+ return null;
+ } catch {
+ return { code: 'STALE_VERDICT', file: null, commit: null, reviewedTrunk: review?.trunk ?? null,
+ main: tip ?? null, ...(mismatch ? { landingCode: 'LAND_ITEM_MOVED', checked: review?.head,
+ reason: `the older landing recorded ${item.item_merged_commit}; checked composition ${review?.head} is unavailable on this replica` }
+ : { reason: 'the reviewed Git history is unavailable; restore its objects and re-review' }) };
+ }
+ };
+ /** Decorate a public item read while preserving every stored proof field. */
+ const project = item => {
+ const freshness = state(item);
+ return freshness ? { ...item, item_verdict_state: freshness } : item;
+ };
+ return { state, project, main: tip ?? null };
+ }
+
+
+ const PRESENTATION_VERDICTS = new Map();
+
+ /** Reuse derived presentation values, never a closed board connection or mutable native row. */
+ export function cachedVerdictStates(root, board, info) {
+ const tip = trunkRevisionReader(info)();
+ const event = board.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id;
+ const key = JSON.stringify([info.commonDir, store.boardId(board)]);
+ const revision = JSON.stringify([tip, event]);
+ let cached = PRESENTATION_VERDICTS.get(key);
+ if (cached?.revision !== revision) {
+ cached = { revision, states: new Map() };
+ PRESENTATION_VERDICTS.delete(key);
+ PRESENTATION_VERDICTS.set(key, cached);
+ while (PRESENTATION_VERDICTS.size > 32) PRESENTATION_VERDICTS.delete(PRESENTATION_VERDICTS.keys().next().value);
+ }
+ const projector = verdictProjector(root, board, { main: tip });
+ /** Refresh only a changed item; unchanged sealed presentations start no new Git process. */
+ return item => {
+ const raw = JSON.stringify(item);
+ const prior = cached.states.get(item.item_id);
+ if (prior?.raw === raw) return prior.state;
+ const state = projector.state(item);
+ // A fetched review pin can resolve missing objects without changing this revision.
+ if (!state?.reason) cached.states.set(item.item_id, { raw, state });
+ return state;
+ };
+ }
diff --cc test/boundary.test.js
index 8e522e73,8e522e73..2e7010ab
--- a/test/boundary.test.js
+++ b/test/boundary.test.js
@@@ -131,7 -131,7 +131,7 @@@ assert.deepEqual(globalThis.__localFetc
assert.match(serve, /export const LOOPBACK = '127\.0\.0\.1';/);
assert.match(serve, /server\.listen\(port, LOOPBACK, /);
const viewSession = readFileSync(join(ROOT, 'src', 'view-session.js'), 'utf8');
-- assert.match(viewSession, /import \{ LOOPBACK, lastPort \} from '\.\/serve\.js';/);
++ assert.match(viewSession, /import\s*\{\s*LOOPBACK\s*,\s*lastPort\s*,?\s*\}\s*from '\.\/serve\.js';/);
assert.match(viewSession, /redirect: 'manual'/, 'the local reuse probe cannot follow a remote redirect');
const api = readFileSync(join(ROOT, 'src', 'api.js'), 'utf8');
assert.match(api, /const ADDRESS = '127\.0\.0\.1';/);
diff --cc test/cli-help.test.js
index 8b40aec4,c72c00aa..6256dfe0
--- a/test/cli-help.test.js
+++ b/test/cli-help.test.js
@@@ -1,15 -1,6 +1,7 @@@
+/** @pullboard-test-input source-tree */
/** The layered CLI help stays short, command-specific, and in parity with its declaration [N37,I1]. */
import assert from 'node:assert/strict';
- import {
- chmodSync,
- mkdirSync,
- mkdtempSync,
- readdirSync,
- readFileSync,
- rmSync,
- writeFileSync,
- } from 'node:fs';
-import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
++import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { runFixtureChild, runFixtureGit } from './fixture-child.js';