Skip to content

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

fix(spec): preserve approval origins across bootstrap [S1,P6]

Corey Olson15164db7afd8
diff --git a/docs/api.md b/docs/api.md
index 4863004f..2dc8a3f9 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -589,10 +589,10 @@ An approved watch runs when due on `resume` and through the background view’s
## Approval provenance
-An `approved` status written directly into the Spec is reported as `agent-approved` until the exact row is backed by a person decision or a verified signed row-decision receipt. Git blame supplies the row's commit and author, labelled “Git author, seat unknown”; it never establishes person approval. `pullboard spec approve <id>` confirms the row and `spec decline <id> --reason "why"` declines it through the existing person channel. File application remains a coordinator step.
+A row approved after the board’s compatibility baseline is reported as `agent-approved` until its exact source is backed by a person decision or a verified signed row-decision receipt. The initial approved set is recorded during `init`, before the setup commit. An older board records its existing approved rows on its first coordinator or person command from the main checkout with this version; earlier reads report the baseline as pending and flag nothing. The snapshot is a compatibility boundary, not evidence of historical person approval. Git blame supplies the row's commit and author, labelled “Git author, seat unknown”; it never establishes person approval. `pullboard spec approve <id>` confirms the row and `spec decline <id> --reason "why"` declines it through the existing person channel. File application remains a coordinator step.
`pullboard.json` accepts the existing `"spec": "SPEC.md"` form, or `"spec": {"file": "SPEC.md", "agentApproval": "flag"}`. `flag` is the default and keeps work moving; `allow` suppresses the outstanding approval call; explicit `refuse` prevents a new frozen citation of an unconfirmed row with `AGENT_APPROVAL_REQUIRED`.
-Board state adds `spec[].agentApproval` (or `null`), item `agentApproved` and `approvalQualification`, and `agent-approved` Needs-you calls carrying the available author and commit. Invalid receipt evidence remains unconfirmed and appears in `specApprovalEvidenceErrors`; it is never treated as an approval. The state cache and live watcher include receipt and signer-trust file bytes. Status JSON exposes the same calls and diagnostics.
+Board state and status expose `specApprovalBaseline: {pending: boolean, invalid: boolean}`. Read-only status/API calls do not establish a pending baseline. A present but unreadable baseline is invalid, never pending: current approved rows require their own confirmation evidence, flag-mode work remains available, and no command automatically resets the marker. Restore a known-good board export to recover it. Board state adds `spec[].agentApproval` (or `null`), item `agentApproved` and `approvalQualification`, and `agent-approved` Needs-you calls carrying the available author and commit. Invalid receipt evidence remains unconfirmed and appears in `specApprovalEvidenceErrors`; it is never treated as an approval. The state cache and live watcher include receipt and signer-trust file bytes. Status JSON exposes the same calls and diagnostics.
Verification output, current item detail and the ledger qualify affected accepted work as “verified against agent-approved <ids>”. A later confirmation clears the current qualification; it does not rewrite earlier acceptance receipts.
diff --git a/docs/formats.md b/docs/formats.md
index 83f4fe3b..f0665bfa 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -489,8 +489,10 @@ Engine 54 replaces the automatic strong-to-strong ceiling escalation with one co
## Approval provenance
-An `approved` status written directly into the Spec is reported as `agent-approved` until the exact row is backed by a person decision or a verified signed row-decision receipt. Git blame supplies the row's commit and author, labelled “Git author, seat unknown”; it never establishes person approval. `pullboard spec approve <id>` confirms the row and `spec decline <id> --reason "why"` declines it through the existing person channel. File application remains a coordinator step.
+A row approved after the board’s compatibility baseline is reported as `agent-approved` until its exact source is backed by a person decision or a verified signed row-decision receipt. The initial approved set is recorded during `init`, before the setup commit. An older board records its existing approved rows on its first ordered command with this version; earlier reads report the baseline as pending and flag nothing. The snapshot is a compatibility boundary, not evidence of historical person approval. Git blame supplies the row's commit and author, labelled “Git author, seat unknown”; it never establishes person approval. `pullboard spec approve <id>` confirms the row and `spec decline <id> --reason "why"` declines it through the existing person channel. File application remains a coordinator step.
`pullboard.json` accepts the existing `"spec": "SPEC.md"` form, or `"spec": {"file": "SPEC.md", "agentApproval": "flag"}`. `flag` is the default and keeps work moving; `allow` suppresses the outstanding approval call; explicit `refuse` prevents a new frozen citation of an unconfirmed row with `AGENT_APPROVAL_REQUIRED`.
Engine 68 retains the existing validated verifier note in new acceptance-event detail. Earlier engines retain their original receipt shape; later person confirmations project current approval state beside that immutable history. No new row status or approval authority is inferred from a Git author or an unsigned receipt.
+
+The engine-68 `recordSpecApprovalBaseline` move carries `{agentId, baseline: {version: 1, file, anchor, rows: [{id, text, source}]}}`. `anchor` is the current commit or `null` before the first commit; exact source rows also cover uncommitted initial requirements. Only the authenticated coordinator may establish the snapshot; a person uses the main checkout’s coordinator path. Lane commands never seed or replace it. The first snapshot is indexed under `board_meta.spec_approval_baseline` with a `spec_approval_baseline` event. Replay writes metadata only, never checkout files. Sender attribution is authenticated normally, older engines refuse the new move, and later bootstrap attempts cannot replace or expand the original snapshot. No local sidecar establishes shared approval authority. The metadata snapshot must agree with its single original coordinator event; a partial restore with either half missing or changed is invalid. A malformed stored marker remains in place with an invalid-baseline diagnostic; it is not treated as an absent migration baseline or reseeded by later commands. Board imports remain trusted recovery operations; agreement of these records is a consistency check, not cryptographic authentication of an imported history.
diff --git a/src/board.js b/src/board.js
index 0d8764d0..cf7df181 100644
--- a/src/board.js
+++ b/src/board.js
@@ -2574,6 +2574,7 @@ export function milestones(board) {
// A lane agent's drafted rows live in row-drafts.js (#878); exported here so the engine dispatches them.
export { draftSpecRow, rowDrafts } from './row-drafts.js';
+export { recordSpecApprovalBaseline, specApprovalBaseline, specApprovalBaselineExists } from './spec-approval-baseline.js';
// The roadmap's moves live in milestones.js; the board keeps exporting them so the engine replays them.
export { addMilestone, canonicalMilestoneTarget, editMilestone, editMilestoneItems, orderMilestoneItems, moveMilestone, removeMilestone, roadmap, shipMilestone } from './milestones.js';
diff --git a/src/cli.js b/src/cli.js
index d760b96e..874ffe26 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -213,7 +213,7 @@ import {
standings,
unmetRows,
} from './spec.js';
-import { refuseAgentApprovedRows } from './spec-approval.js';
+import { captureSpecApprovalBaseline, refuseAgentApprovedRows } from './spec-approval.js';
import {
answerQuestion,
landBlueprint,
@@ -866,6 +866,8 @@ export async function reserveRow(ctx, row, written) {
async function withItemSession(info, operation, args, move) { const noted = operation === 'claim' || operation === 'submit'; if (noted) itemSessions.requireLedger(info); const result = await move(); if (noted) itemSessions.recordItemSession(info, args[0], operation); return result; }
export async function ordered(ctx, board, operation, args) {
+ const baselineRoot = ctx.info.isMain && operation !== 'recordSpecApprovalBaseline' && !store.specApprovalBaselineExists(board) ? primaryCheckoutRoot(ctx.info) : null;
+ const initialBaseline = baselineRoot ? captureSpecApprovalBaseline(baselineRoot, loadConfig(baselineRoot)) : null;
if (['verify', 'reopen'].includes(operation)) args = firstRefusalArgs(operation, args, configFromSource(coordinatorFile(ctx.info.root, CONFIG_FILE).stdout));
// Every engine-27 registration records the seat that made it: the coordinator from the main
// checkout, the joined agent from its worktree, or `machine` for a join no seat made (#579).
@@ -875,8 +877,23 @@ export async function ordered(ctx, board, operation, args) {
}
const command = ['add', 'edit', 'merged'].includes(ctx.io.relayCommand?.cliOperation) ? ctx.io.relayCommand : undefined;
/** Dispatch while this session holds the checkout, including long-running next/run loops. */
- const execute = () => withItemSession(ctx.info, operation, args, () => relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)
- ? relayOperation(ctx.info.root, operation, args, ctx.io, command, () => store[operation](board, ...args)) : store[operation](board, ...args));
+ const execute = async () => {
+ /** Keep bootstrap in the same authenticated seat, without borrowing a person's action receipt. */
+ const recordBaseline = async (agentId) => {
+ const values = [{ agentId, baseline: initialBaseline }];
+ const baselineIo = ctx.io.personRequest || ctx.io.personRequestMoveId
+ ? { ...ctx.io, personRequest: undefined, personRequestMoveId: undefined } : ctx.io;
+ return relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)
+ ? relayOperation(ctx.info.root, 'recordSpecApprovalBaseline', values, baselineIo, undefined,
+ () => store.recordSpecApprovalBaseline(board, ...values))
+ : store.recordSpecApprovalBaseline(board, ...values);
+ };
+ const actor = ctx.info.isMain ? COORDINATOR : store.agentAt(board, ctx.info.root)?.agent_id;
+ if (initialBaseline && actor) await recordBaseline(actor);
+ const result = await withItemSession(ctx.info, operation, args, () => relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)
+ ? relayOperation(ctx.info.root, operation, args, ctx.io, command, () => store[operation](board, ...args)) : store[operation](board, ...args));
+ return result;
+ };
const digest = agentSessionDigest();
const boardOnly = CHECKOUT_BOARD_ONLY.get(ctx.io);
const boardOnlyOperation = (boardOnly === 'shout' && operation === 'shout') || (boardOnly === 'fact' && operation === 'appendFact');
diff --git a/src/commands/init.js b/src/commands/init.js
index 46c3c619..178b592b 100644
--- a/src/commands/init.js
+++ b/src/commands/init.js
@@ -26,6 +26,7 @@ import {
import {
initRepo,
} from '../init.js';
+import { captureSpecApprovalBaseline } from '../spec-approval.js';
import {
agentSessionDigest,
} from '../person.js';
@@ -77,6 +78,9 @@ export async function run(io, { values }) {
if (!linked) {
const existing = board.db.prepare('SELECT 1 FROM agent WHERE agent_id=?').get(COORDINATOR);
const registered = store.register(board, options);
+ if (!store.specApprovalBaselineExists(board)) store.recordSpecApprovalBaseline(board, {
+ agentId: COORDINATOR, baseline: captureSpecApprovalBaseline(info.root, loadConfig(info.root)),
+ });
if (!existing) recordSetupState({ info }, setupIdentity(board), 'started');
return registered;
}
diff --git a/src/commands/status.js b/src/commands/status.js
index 9081c0ac..802e4409 100644
--- a/src/commands/status.js
+++ b/src/commands/status.js
@@ -33,7 +33,7 @@ export function run(io, { values }) {
const me = whoAmI(ctx, board);
const mine = store.listItems(board).filter((item) => item.item_status === 'claimed' && item.item_owner === me.id);
const approvalState = personNeedsState(ctx.info.root, { board });
- return { me, mine, needs: approvalState.needs, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relayStatus(ctx.info.root),
+ return { me, mine, needs: approvalState.needs, specApprovalBaseline: approvalState.specApprovalBaseline, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relayStatus(ctx.info.root),
submitInvariantProposals: submitInvariantProposals(store.events(board), ctx.config) };
});
if (values.json) {
@@ -45,6 +45,8 @@ export function run(io, { values }) {
io.say(`${summary.me.displayName}: ${summary.unread} unread shouts; holding ${summary.mine.map((item) => `#${item.item_id}`).join(', ') || 'nothing'}`);
io.say(`board: ${items.open} open, ${items.claimed} claimed, ${items.submitted} awaiting verification, ${items.verified} verified, ${items.withdrawn} withdrawn`);
io.say(`verdicts: ${accepted} accepted, ${rejected} rejected`);
+ if (summary.specApprovalBaseline?.pending) io.say('approval baseline pending: the next coordinator or person command in the main checkout records the existing approved rows; lane work may continue and none are flagged until then');
+ if (summary.specApprovalBaseline?.invalid) io.say('approval baseline unreadable: existing rows need approval evidence; restore a known-good board export to recover the original baseline');
io.say(reviewQueueLine(ctx, summary.reviewQueue, span));
for (const proposal of summary.submitInvariantProposals) io.say(submitInvariantLine(proposal));
for (const need of summary.needs.filter(need => need.kind === 'agent-approved')) io.say(`${need.text}; ${need.what}`);
diff --git a/src/engine.js b/src/engine.js
index 39814a95..6e25d583 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -22,6 +22,7 @@ import { CHECK_ACCEPT_ENGINE } from './check-accept.js';
import { HEALTH_SENTINEL_ENGINE } from './health-receipts.js';
import { BOARD_SENTINEL_ENGINE } from './sentinels.js';
import { RECURRING_JOB_ENGINE } from './job-engine.js';
+import { SPEC_APPROVAL_ENGINE } from './spec-approval-engine.js';
import {
REOPEN_FIRST_REFUSAL_ENGINE,
CAUSE_ENGINE,
@@ -66,7 +67,7 @@ export const ENGINE_OPERATIONS = Object.freeze([
'claim', 'release', 'submit', 'reserveReview', 'reserveNextReview', 'verify', 'merged',
'withdraw', 'refreeze', 'reopen', 'shout', 'passDecision', 'answerDecision', 'holdLane', 'releaseLane', 'holdItem', 'releaseItemHold',
'addMilestone', 'editMilestoneItems', 'orderMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone', 'shipMilestone',
- 'recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'appendFact',
+ 'recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'appendFact', 'recordSpecApprovalBaseline',
'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch', 'acceptCheck',
'recordHealthFindings', 'proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun',
'recordFlakeObservation', 'declareJob', 'recordJobRun',
@@ -74,7 +75,7 @@ export const ENGINE_OPERATIONS = Object.freeze([
/** Engine version at which each ordered operation first has stable replay semantics. */
const OPERATION_ENGINE = Object.freeze({ draftSpecRow: ROW_DRAFT_ENGINE, orderMilestoneItems: MILESTONE_RANK_ENGINE, reopen: 8, recordLandingBatch: 8, recordLandingWaiver: 8, recordLandingFlake: 8, finishLandingBatch: 8, acceptCheck: CHECK_ACCEPT_ENGINE,
- shipMilestone: MILESTONE_SHIP_ENGINE });
+ shipMilestone: MILESTONE_SHIP_ENGINE, recordSpecApprovalBaseline: SPEC_APPROVAL_ENGINE });
/** Dependency edits, causes, sealed reviews, submission proofs, trunk conflicts, health observations and milestone targets retain distinct recorded engine meanings. */
function minimumOperationEngine(operation, args, board, at) {
diff --git a/src/relay-sender.js b/src/relay-sender.js
index 15015ae3..7cec68a5 100644
--- a/src/relay-sender.js
+++ b/src/relay-sender.js
@@ -13,7 +13,7 @@ export function relayMoveActor(move) {
if (['recordHealthFindings', 'recordFlakeObservation', 'declareJob', 'recordJobRun'].includes(move.operation)) return args[0]?.agentId ?? null;
if (['holdLane', 'releaseLane'].includes(move.operation) && args[1]?.asPerson) return 'person';
if (move.operation === 'release') return args[1] ?? null;
- if (['reserveNextReview', 'addMilestone', 'recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch'].includes(move.operation)) return args[0]?.agentId ?? null;
+ if (['reserveNextReview', 'addMilestone', 'recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'recordSpecApprovalBaseline', 'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'finishLandingBatch'].includes(move.operation)) return args[0]?.agentId ?? null;
if (['acceptCheck', 'completeCheckBaseline', 'appendFact', 'editItem', 'escalate', 'recordAttempt', 'claim', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze',
'passDecision', 'answerDecision', 'holdLane', 'releaseLane', 'holdItem', 'releaseItemHold', 'reopen', 'editMilestoneItems', 'orderMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone', 'shipMilestone'].includes(move.operation)) return args[1]?.agentId ?? null;
return null;
diff --git a/src/signature.js b/src/signature.js
index b10fb49c..058050e7 100644
--- a/src/signature.js
+++ b/src/signature.js
@@ -342,11 +342,16 @@ function writeAtomic(file, text) {
}
/** Read raw sign-off records without applying signer verification recursively. */
-function readRawRecords(root) {
+export function readRawRecords(root) {
const file = join(root, '.pullboard/signoffs.jsonl');
if (!existsSync(file)) return [];
return readFileSync(file, 'utf8').split('\n').filter((line) => line.trim()).map((line, index) => {
- try { return JSON.parse(line); } catch { throw new Refused('BAD_SIGNOFFS', `.pullboard/signoffs.jsonl line ${index + 1} is not JSON`); }
+ let record;
+ try { record = JSON.parse(line); } catch { throw new Refused('BAD_SIGNOFFS', `.pullboard/signoffs.jsonl line ${index + 1} is not JSON`); }
+ if (!record || typeof record !== 'object' || Array.isArray(record)) {
+ throw new Refused('BAD_SIGNOFFS', `.pullboard/signoffs.jsonl line ${index + 1} is not a record object; restore the complete sign-off record`);
+ }
+ return record;
});
}
diff --git a/src/spec-approval-baseline.js b/src/spec-approval-baseline.js
new file mode 100644
index 00000000..8ca5c6cc
--- /dev/null
+++ b/src/spec-approval-baseline.js
@@ -0,0 +1,70 @@
+/** One shared compatibility snapshot, recorded through the board engine, never a person approval. */
+import { atomic, logEvent } from './board.js';
+import { Refused } from './refused.js';
+import { parseSpec } from './spec.js';
+import { COORDINATOR } from './config.js';
+
+const KEY = 'spec_approval_baseline';
+
+/** Distinguish a missing migration marker from an unreadable one without replacing either. */
+export function specApprovalBaselineExists(board) {
+ return Boolean(board.db.prepare('SELECT 1 FROM board_meta WHERE meta_key=?').get(KEY)
+ || board.db.prepare('SELECT 1 FROM event WHERE event_kind=? LIMIT 1').get(KEY));
+}
+
+/** Validate the exact source carried by an ordered snapshot, including the empty initial set. */
+function validBaseline(value) {
+ if (!value || value.version !== 1 || typeof value.file !== 'string' || !value.file
+ || !(value.anchor === null || /^[a-f0-9]{40,64}$/u.test(value.anchor)) || !Array.isArray(value.rows)) return false;
+ const seen = new Set();
+ return value.rows.every(row => {
+ if (!row || typeof row.id !== 'string' || typeof row.text !== 'string' || typeof row.source !== 'string'
+ || /[\r\n]/u.test(row.source) || seen.has(row.id)) return false;
+ const parsed = parseSpec(`## Baseline\n${row.source}\n`).rows;
+ seen.add(row.id);
+ return parsed.length === 1 && parsed[0].id === row.id && parsed[0].text === row.text && parsed[0].status === 'approved';
+ });
+}
+
+/** Compare the snapshot payload without incidental event attribution or JSON property order. */
+function canonicalBaseline(baseline) {
+ return { version: 1, file: baseline.file, anchor: baseline.anchor,
+ rows: baseline.rows.map(({ id, text, source }) => ({ id, text, source })) };
+}
+
+/** Read the original snapshot without interpreting it as authenticated approval or reseeding it. */
+export function specApprovalBaseline(board) {
+ const stored = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(KEY);
+ const events = board.db.prepare('SELECT event_by,event_detail FROM event WHERE event_kind=?').all(KEY);
+ if (!stored && !events.length) return null;
+ let value;
+ let recorded;
+ try {
+ value = stored && JSON.parse(stored.meta_value);
+ recorded = events.length === 1 && events[0].event_by === COORDINATOR && JSON.parse(events[0].event_detail);
+ } catch { /* The same typed recovery covers malformed and incompatible records. */ }
+ if (!validBaseline(value) || !validBaseline(recorded)
+ || JSON.stringify(canonicalBaseline(value)) !== JSON.stringify(canonicalBaseline(recorded))) {
+ throw new Refused('SPEC_APPROVAL_BASELINE', 'the approval baseline is unreadable or disagrees with its original event; restore it from a known-good board export');
+ }
+ return value;
+}
+
+/** Persist the first ordered snapshot once; later setup or competing replicas cannot expand it. */
+export function recordSpecApprovalBaseline(board, { agentId, baseline }) {
+ return atomic(board, () => {
+ if (agentId !== COORDINATOR) {
+ throw new Refused('COORDINATOR_ONLY', 'only the coordinator or person establishes the approval baseline from the main checkout; lane work may continue while it is pending');
+ }
+ if (!board.db.prepare('SELECT 1 FROM agent WHERE agent_id=?').get(agentId)) {
+ throw new Refused('NOT_JOINED', 'join a lane before recording the board approval baseline');
+ }
+ const existing = specApprovalBaseline(board);
+ if (existing) return existing;
+ if (!validBaseline(baseline)) throw new Refused('SPEC_APPROVAL_BASELINE', 'an approval baseline needs its exact approved source rows; retry from the coordinator checkout');
+ const value = canonicalBaseline(baseline);
+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?)').run(KEY, JSON.stringify(value));
+ logEvent(board, agentId, 'spec_approval_baseline', null, value);
+ return value;
+ });
+}
diff --git a/src/spec-approval.js b/src/spec-approval.js
index e1c136f1..ab5d0a36 100644
--- a/src/spec-approval.js
+++ b/src/spec-approval.js
@@ -50,15 +50,35 @@ function confirmedDecision(root, decision, evidenceErrors) {
}
}
+/** Capture the current approved source before setup commits or a legacy board's first ordered move. */
+export function captureSpecApprovalBaseline(root, config) {
+ const spec = loadSpec(root, config);
+ const source = spec.exists === false ? [] : readFileSync(join(root, config.spec), 'utf8').split(/\r?\n/u);
+ const head = tryGit(root, ['rev-parse', '--verify', 'HEAD']);
+ return { version: 1, file: config.spec, anchor: head.status === 0 ? head.stdout.trim() : null,
+ rows: spec.rows.filter(row => row.status === 'approved').map(row => ({ id: row.id, text: row.text, source: source[row.line - 1] })) };
+}
+
/** Load one provenance view for a command; no observation here manufactures an approval event. */
export function specApprovalState(root, { board, config, spec = loadSpec(root, config) }) {
- if (spec.exists === false) return { mode: config.specAgentApproval ?? 'flag', rows: [] };
+ const mode = config.specAgentApproval ?? 'flag';
+ let baseline;
+ let baselineInvalid = false;
+ const evidenceErrors = [];
+ try { baseline = store.specApprovalBaseline(board); }
+ catch (error) {
+ if (!(error instanceof Refused)) throw error;
+ evidenceErrors.push({ code: error.code, message: error.message });
+ baselineInvalid = true;
+ }
+ if (!baseline && !baselineInvalid) return { mode, baselinePending: true, evidenceErrors, rows: [] };
+ if (spec.exists === false) return { mode, baselinePending: false, baselineInvalid, evidenceErrors, rows: [] };
const source = readFileSync(join(root, config.spec), 'utf8').split(/\r?\n/u);
const decisions = store.rowDecisions(board).filter(record => record.kind === 'spec' && record.file === config.spec);
- const evidenceErrors = [];
const signed = approvalEvidence(root, evidenceErrors);
const unconfirmed = spec.rows.filter(row => row.status === 'approved').filter(row => {
const current = { row, file: config.spec, source: source[row.line - 1] };
+ if (baseline?.file === current.file && baseline.rows.some(old => old.id === row.id && old.text === row.text && old.source === current.source)) return false;
const decision = decisions.findLast(record => record.id === row.id);
if (decision) {
if (!matchesApproval(decision, current)) return true;
@@ -67,7 +87,7 @@ export function specApprovalState(root, { board, config, spec = loadSpec(root, c
return !matchesApproval(signed.findLast(record => record.kind === 'spec' && record.file === config.spec && record.id === row.id), current);
});
const origins = unconfirmed.length ? rowOrigins(root, config.spec) : new Map();
- return { mode: config.specAgentApproval ?? 'flag', evidenceErrors, rows: unconfirmed.map(row => ({ id: row.id, text: row.text, gate: row.gate,
+ return { mode, baselinePending: false, baselineInvalid, evidenceErrors, rows: unconfirmed.map(row => ({ id: row.id, text: row.text, gate: row.gate,
status: 'agent-approved', ...(origins.get(row.line) ?? { commit: null, agent: 'unknown', attribution: 'Git author, seat unknown' }) })) };
}
@@ -85,7 +105,7 @@ export function agentApprovalLine(rows) {
/** Project current confirmation beside immutable items and their historical receipts. */
export function projectSpecApprovals(state, approval) {
const byId = new Map(approval.rows.map(row => [row.id, row]));
- const projected = { ...state, specApprovalEvidenceErrors: approval.evidenceErrors ?? [], spec: state.spec.map(row => ({ ...row, agentApproval: byId.has(row.id) ? { ...byId.get(row.id), mode: approval.mode } : null })),
+ const projected = { ...state, specApprovalBaseline: { pending: approval.baselinePending === true, invalid: approval.baselineInvalid === true }, specApprovalEvidenceErrors: approval.evidenceErrors ?? [], spec: state.spec.map(row => ({ ...row, agentApproval: byId.has(row.id) ? { ...byId.get(row.id), mode: approval.mode } : null })),
items: state.items?.map(item => ({ ...item, agentApproved: itemAgentApprovals(item, approval), approvalQualification: agentApprovalLine(itemAgentApprovals(item, approval)) })) };
return { ...projected, needs: personNeeds(projected) };
}
diff --git a/src/spec.js b/src/spec.js
index 16defe71..b81dc61a 100644
--- a/src/spec.js
+++ b/src/spec.js
@@ -28,6 +28,7 @@ import { Refused } from './refused.js';
import {
hasSignerFile,
isVerifiedSignoff,
+ readRawRecords,
signRows,
verifySignedRecords,
} from './signature.js';
@@ -406,18 +407,7 @@ export function frozenCriterion(spec, item, doctrine = null) {
* @returns {{ id: string, by: string, on: string, text: string }[]}
*/
export function readSignoffs(root) {
- const file = join(root, SIGNOFFS_FILE);
- const records = !existsSync(file) ? [] : readFileSync(file, 'utf8')
- .split('\n')
- .filter((line) => line.trim())
- .map((line, index) => {
- try {
- return JSON.parse(line);
- } catch {
- throw new Refused('BAD_SIGNOFFS', `${SIGNOFFS_FILE} line ${index + 1} is not JSON`);
- }
- });
- return verifySignedRecords(root, records);
+ return verifySignedRecords(root, readRawRecords(root));
}
/**
diff --git a/test/spec-approval.test.js b/test/spec-approval.test.js
index 4a6f3d7d..0ac6bc3b 100644
--- a/test/spec-approval.test.js
+++ b/test/spec-approval.test.js
@@ -1,14 +1,18 @@
/** Hand-written approval is visible without becoming a person's decision [S1,B26,P6]. */
import assert from 'node:assert/strict';
-import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { tmpdir } from 'node:os';
import { test } from 'node:test';
import { createE2eHelpers } from './e2e-helpers.js';
import { runFixtureChild } from './fixture-child.js';
import { configFromSource } from '../src/config.js';
import * as store from '../src/board.js';
+import { captureSpecApprovalBaseline, specApprovalState } from '../src/spec-approval.js';
import { SPEC_APPROVAL_ENGINE } from '../src/spec-approval-engine.js';
import { submitFixture } from './board-submit-fixture.js';
+import { exportBoard, importBoard } from '../src/exchange.js';
+import { applyEngineMove, applyRelayMove, prepareEngineMove } from '../src/engine.js';
/** Run the private project's real CLI and require its structured successful response. */
function document(box, root, ...args) {
@@ -163,7 +167,10 @@ test('a clone recognizes an exact signed approval without borrowing another boar
box.git(box.repo, 'commit', '-q', '-m', 'chore(spec): preserve the signed approval');
const clone = join(box.dir, 'signed-clone');
box.git(box.repo, 'clone', '-q', box.repo, clone);
+ const cloneSpec = readFileSync(join(clone, 'SPEC.md'), 'utf8');
+ writeFileSync(join(clone, 'SPEC.md'), '# Clone setup\n\n## G · Goals\n');
document(box, clone, 'init');
+ writeFileSync(join(clone, 'SPEC.md'), cloneSpec);
assert.equal(document(box, clone, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'), false,
'a separate local board verifies the committed signed receipt');
const view = await helpers.startView(box, clone);
@@ -257,3 +264,288 @@ test('malformed approval evidence stays unconfirmed without blocking default fla
// The malformed ledger is in the coordinator checkout; the builder independently sees an unconfirmed row.
assert.equal(box.run(box.web, 'claim', String(id)).code, 0);
});
+
+
+test('malformed JSONL record shapes stay unconfirmed in status and the API [A9,S1,S19,P6]', async t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ for (const signed of [false, true]) {
+ const box = helpers.project('true');
+ if (signed) {
+ const key = join(box.dir, 'private-shape-signing-key');
+ const made = runFixtureChild('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-f', key], { env: box.env, encoding: 'utf8' });
+ assert.equal(made.status, 0, made.failure ?? made.stderr);
+ box.git(box.repo, 'config', 'user.signingkey', key);
+ document(box, box.repo, 'spec', 'signers', 'add', '--key', key + '.pub', '--by', 'fixture-person');
+ }
+ document(box, box.repo, 'spec', 'approve', 'G1', ...(signed ? ['--by', 'fixture-person'] : []));
+ const view = await helpers.startView(box, box.repo);
+ t.after(view.stop);
+ assert.equal((await view.state(box.repo)).project.spec.find(row => row.id === 'G1').agentApproval, null);
+ mkdirSync(join(box.repo, '.pullboard'), { recursive: true });
+ for (const value of [null, [], true, 0, 'not a record']) {
+ writeFileSync(join(box.repo, '.pullboard/signoffs.jsonl'), JSON.stringify(value) + '\n');
+ const status = document(box, box.repo, 'status');
+ assert.ok(status.needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'),
+ `invalid receipt shape stays unconfirmed, signed=${signed}, value=${JSON.stringify(value)}`);
+ assert.ok(status.specApprovalEvidenceErrors.some(error => error.code === 'BAD_SIGNOFFS'));
+ const state = (await view.state(box.repo)).project;
+ assert.ok(state.needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'));
+ assert.ok(state.specApprovalEvidenceErrors.some(error => error.code === 'BAD_SIGNOFFS'));
+ }
+ const id = document(box, box.repo, 'add', 'web', 'A malformed receipt does not opt into refusal',
+ '--specs', 'G1', '--criterion', 'A real fixture.').item.item_id;
+ mkdirSync(join(box.web, '.pullboard'), { recursive: true });
+ writeFileSync(join(box.web, '.pullboard/signoffs.jsonl'), 'null\n');
+ assert.equal(box.run(box.web, 'claim', String(id)).code, 0, 'default flag leaves engineering claims usable even in the malformed checkout');
+ }
+});
+
+test("a board's approval baseline is taken once and never blesses later edits [I10,A9,S1,P6]", async t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ const sandbox = helpers.sandbox();
+ const repo = join(sandbox.dir, 'existing-project');
+ mkdirSync(repo);
+ sandbox.git(repo, 'init', '-q', '-b', 'main');
+ const initial = '# Existing requirements\n\n## G · Goals\n- G7 [approved, must] The existing requirement. | gate: review\n';
+ writeFileSync(join(repo, 'SPEC.md'), initial);
+ const box = { ...sandbox, repo };
+ document(box, repo, 'init');
+ const first = document(box, repo, 'status');
+ assert.equal(first.needs.some(need => need.kind === 'agent-approved' && need.id === 'G7'), false,
+ 'the existing approved row is a first-open compatibility baseline, not a new person decision');
+ box.git(repo, 'add', '-A');
+ box.git(repo, 'commit', '-q', '-m', 'chore: preserve the initial project');
+ writeFileSync(join(repo, 'SPEC.md'), initial + '- G8 [approved, must] A later approval needs the person. | gate: review\n');
+ assert.ok(document(box, repo, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G8'));
+ document(box, repo, 'init');
+ assert.ok(document(box, repo, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G8'),
+ 'repeating setup cannot replace or expand the original baseline');
+ const view = await helpers.startView(box, repo);
+ t.after(view.stop);
+ assert.ok((await view.state(repo)).project.needs.some(need => need.kind === 'agent-approved' && need.id === 'G8'),
+ 'another process and the actual API retain the original baseline');
+ writeFileSync(join(repo, 'SPEC.md'), initial.replace('existing requirement.', 'changed requirement.'));
+ assert.ok(document(box, repo, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G7'),
+ 'an existing id cannot borrow its baseline approval for different source bytes');
+ document(box, repo, 'spec', 'approve', 'G7');
+ assert.equal(document(box, repo, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G7'), false,
+ 'one exact person decision confirms a changed baseline row');
+});
+
+test('an upgraded board stays pending until a coordinator command in the main checkout [I10,A9,H16,S1]', async t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ const box = helpers.project('true');
+ const legacy = document(box, box.repo, 'export');
+ // A public legacy-format snapshot has neither the new metadata nor its new event.
+ legacy.tables.board_meta = legacy.tables.board_meta.filter(row => row.meta_key !== 'spec_approval_baseline');
+ legacy.tables.event = legacy.tables.event.filter(row => row.event_kind !== 'spec_approval_baseline');
+ const root = join(box.dir, 'legacy-clone');
+ // Model an already located legacy checkout; view startup need not repair its coordinator path.
+ legacy.tables.agent.find(agent => agent.agent_id === 'coordinator').agent_path = root;
+ box.git(box.repo, 'clone', '-q', box.repo, root);
+ const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'));
+ try { importBoard(board, legacy); } finally { store.closeBoard(board); }
+ const lane = join(box.dir, 'legacy-lane');
+ box.git(root, 'worktree', 'add', '-q', '-b', 'web/legacy', lane);
+ document(box, lane, 'join', 'web');
+ document(box, lane, 'shout', 'all', 'A lane command cannot establish the compatibility baseline');
+ const before = document(box, root, 'export');
+ const first = document(box, root, 'status');
+ assert.equal(first.specApprovalBaseline.pending, true);
+ assert.equal(first.needs.some(need => need.kind === 'agent-approved'), false);
+ // The imported clone shares the source board id; expose only this clone to the API fixture.
+ const registryFile = join(box.env.PULLBOARD_HOME, 'projects.json');
+ const registry = JSON.parse(readFileSync(registryFile, 'utf8'));
+ writeFileSync(registryFile, JSON.stringify({ ...registry, projects: registry.projects.filter(project => project.root === root) }) + '\n');
+ const view = await helpers.startView(box, root);
+ t.after(view.stop);
+ const state = (await view.state(root)).project;
+ assert.equal(state.specApprovalBaseline.pending, true);
+ assert.equal(state.needs.some(need => need.kind === 'agent-approved'), false);
+ assert.deepEqual(document(box, root, 'export').tables, before.tables, 'status/API reads cannot seed or rewrite the legacy board');
+ document(box, root, 'shout', 'all', 'First coordinator command establishes the compatibility baseline');
+ const ready = document(box, root, 'status');
+ assert.equal(ready.specApprovalBaseline.pending, false);
+ assert.equal(ready.needs.some(need => need.kind === 'agent-approved'), false);
+ const specFile = join(root, 'SPEC.md');
+ writeFileSync(specFile, readFileSync(specFile, 'utf8') + '- G3 [approved, must] Later agent approval. | gate: review\n');
+ const later = document(box, root, 'status');
+ assert.ok(later.needs.some(need => need.kind === 'agent-approved' && need.id === 'G3'));
+ document(box, root, 'shout', 'all', 'A later ordered command cannot expand the baseline');
+ assert.ok((await view.state(root)).project.needs.some(need => need.kind === 'agent-approved' && need.id === 'G3'));
+ const after = document(box, root, 'export');
+ assert.equal(after.tables.event.filter(row => row.event_kind === 'spec_approval_baseline').length, 1);
+});
+
+test('an approval baseline is ordered once with authenticated engine68 replay [H16,S1,P6]', t => {
+ const first = store.openBoard(':memory:');
+ const replica = store.openBoard(':memory:');
+ t.after(() => { store.closeBoard(first); store.closeBoard(replica); });
+ store.register(first, { lane: 'coordinator', path: '/private-baseline-coordinator' });
+ const agent = store.register(first, { lane: 'core', path: '/private-baseline-agent' });
+ importBoard(replica, exportBoard(first));
+ const baseline = { version: 1, file: 'SPEC.md', anchor: null,
+ rows: [{ id: 'G1', text: 'An existing row.', source: '- G1 [approved, must] An existing row. | gate: review' }] };
+ const deniedLane = prepareEngineMove(first, 'recordSpecApprovalBaseline', [{ agentId: agent, baseline }]);
+ const laneMeta = { sequence: 1, at: '2026-10-21T11:59:59Z', kind: 'move', sender: { kind: 'agent', userId: 'fixture', agent } };
+ const laneRefusal = applyRelayMove(first, deniedLane, laneMeta);
+ assert.equal(laneRefusal.error.code, 'COORDINATOR_ONLY');
+ assert.deepEqual(applyRelayMove(replica, deniedLane, laneMeta), laneRefusal);
+ assert.equal(store.specApprovalBaseline(first), null, 'a lane cannot seed the first snapshot');
+ const move = prepareEngineMove(first, 'recordSpecApprovalBaseline', [{ agentId: 'coordinator', baseline }]);
+ assert.throws(() => applyEngineMove(first, { ...move, engine: SPEC_APPROVAL_ENGINE - 1 },
+ { sequence: 2, at: '2026-10-21T12:00:00Z' }), { code: 'RELAY_MOVE' });
+ const meta = { sequence: 2, at: '2026-10-21T12:00:00Z', kind: 'move', sender: { kind: 'agent', userId: 'fixture', agent: 'coordinator' } };
+ const result = applyRelayMove(first, move, meta);
+ assert.equal(result.error, undefined, JSON.stringify(result));
+ assert.deepEqual(applyRelayMove(replica, move, meta), result);
+ assert.deepEqual(store.specApprovalBaseline(first), baseline);
+ assert.deepEqual(store.specApprovalBaseline(replica), baseline);
+ assert.deepEqual(applyRelayMove(first, move, meta), result, 'repeated delivery returns the original receipt');
+ const second = prepareEngineMove(first, 'recordSpecApprovalBaseline', [{ agentId: 'coordinator', baseline: { ...baseline, rows: [] } }]);
+ const repeated = applyRelayMove(first, second, { ...meta, sequence: 3 });
+ assert.equal(repeated.error, undefined, JSON.stringify(repeated));
+ assert.deepEqual(store.specApprovalBaseline(first), baseline, 'later snapshots cannot replace the original set');
+ const denied = applyRelayMove(replica, second, { ...meta, sequence: 3,
+ sender: { kind: 'agent', userId: 'fixture', agent: 'unrelated-seat' } });
+ assert.equal(denied.error.code, 'RELAY_SENDER_MISMATCH');
+ assert.deepEqual(store.specApprovalBaseline(replica), baseline);
+});
+
+
+for (const change of ['metadata changed', 'metadata missing']) {
+ test(`a partial baseline restore stays invalid instead of blessing later rows: ${change} [H16,S1,P6]`, t => {
+ const original = store.openBoard(':memory:');
+ const restored = store.openBoard(':memory:');
+ t.after(() => { store.closeBoard(original); store.closeBoard(restored); });
+ store.register(original, { lane: 'coordinator', path: '/private-baseline-restore' });
+ const baseline = { version: 1, file: 'SPEC.md', anchor: null, rows: [] };
+ store.recordSpecApprovalBaseline(original, { agentId: 'coordinator', baseline });
+ const snapshot = exportBoard(original);
+ if (change === 'metadata missing') {
+ snapshot.tables.board_meta = snapshot.tables.board_meta.filter(row => row.meta_key !== 'spec_approval_baseline');
+ } else {
+ snapshot.tables.board_meta.find(row => row.meta_key === 'spec_approval_baseline').meta_value = JSON.stringify({ ...baseline,
+ rows: [{ id: 'G99', text: 'Later row.', source: '- G99 [approved, must] Later row. | gate: review' }] });
+ }
+ importBoard(restored, snapshot);
+ assert.throws(() => store.specApprovalBaseline(restored), { code: 'SPEC_APPROVAL_BASELINE' },
+ 'one changed or missing half must not silently establish a different trusted snapshot');
+ assert.equal(store.specApprovalBaselineExists(restored), true, 'an existing event prevents automatic reseeding');
+ assert.throws(() => store.recordSpecApprovalBaseline(restored, { agentId: 'coordinator', baseline }),
+ { code: 'SPEC_APPROVAL_BASELINE' }, 'a later bootstrap cannot reset the invalid marker');
+ assert.deepEqual(exportBoard(restored).tables, snapshot.tables);
+ });
+}
+
+test('an invalid baseline stays diagnostic while flag work remains usable and refuse stays strict [A9,H16,S1,P6]', async t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ const box = helpers.project('true');
+ const item = document(box, box.repo, 'add', 'web', 'Corrupt baseline policy fixture',
+ '--specs', 'G1', '--criterion', 'The private fixture stays unconfirmed.').item.item_id;
+ const exported = document(box, box.repo, 'export');
+ const baseline = exported.tables.board_meta.find(row => row.meta_key === 'spec_approval_baseline');
+ assert.ok(baseline);
+ baseline.meta_value = '{broken-baseline';
+ const file = join(box.dir, 'corrupt-export.json');
+ writeFileSync(file, JSON.stringify(exported));
+ const root = join(box.dir, 'flag-clone');
+ box.git(box.repo, 'clone', '-q', box.repo, root);
+ document(box, root, 'import', file);
+ const state = document(box, root, 'status');
+ assert.equal(state.specApprovalBaseline.pending, false, 'invalid is not an absent legacy baseline');
+ assert.equal(state.specApprovalBaseline.invalid, true);
+ assert.ok(state.specApprovalEvidenceErrors.some(error => error.code === 'SPEC_APPROVAL_BASELINE'));
+ assert.ok(state.needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'));
+ // A public view must address only this imported clone, not its same-id source project.
+ writeFileSync(join(box.env.PULLBOARD_HOME, 'projects.json'), JSON.stringify({ projects: [] }));
+ const view = await helpers.startView(box, root);
+ t.after(view.stop);
+ const api = (await view.state(root)).project;
+ assert.equal(api.specApprovalBaseline.pending, false);
+ assert.equal(api.specApprovalBaseline.invalid, true);
+ assert.ok(api.specApprovalEvidenceErrors.some(error => error.code === 'SPEC_APPROVAL_BASELINE'));
+ assert.ok(api.needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'));
+ document(box, root, 'shout', 'all', 'Flag mode still permits ordinary work with a diagnostic');
+ const after = document(box, root, 'export');
+ assert.equal(after.tables.board_meta.find(row => row.meta_key === 'spec_approval_baseline').meta_value, '{broken-baseline');
+ assert.deepEqual(after.tables.event.filter(row => row.event_kind === 'spec_approval_baseline'),
+ exported.tables.event.filter(row => row.event_kind === 'spec_approval_baseline'), 'no reset or invented baseline event');
+
+ const strict = join(box.dir, 'refuse-clone');
+ box.git(box.repo, 'clone', '-q', box.repo, strict);
+ const configFile = join(strict, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configFile, 'utf8'));
+ writeFileSync(configFile, JSON.stringify({ ...config, spec: { file: 'SPEC.md', agentApproval: 'refuse' } }));
+ box.git(strict, 'add', 'pullboard.json');
+ box.git(strict, 'commit', '-q', '-m', 'chore: choose explicit refusal in private fixture');
+ document(box, strict, 'import', file);
+ const web = join(box.dir, 'strict-web');
+ box.git(strict, 'worktree', 'add', '-q', '-b', 'web/strict', web);
+ document(box, web, 'join', 'web');
+ const claimed = box.run(web, 'claim', String(item), '--json');
+ assert.equal(claimed.code, 1);
+ assert.equal(JSON.parse(claimed.out).error.code, 'AGENT_APPROVAL_REQUIRED',
+ 'the actual claim reaches and enforces the explicit policy instead of trusting invalid metadata');
+});
+
+test('an authenticated first baseline cannot grandfather an absent future row [H16,S1,P6]', t => {
+ const root = mkdtempSync(join(tmpdir(), 'pullboard-baseline-forgery-'));
+ const board = store.openBoard(':memory:');
+ const replica = store.openBoard(':memory:');
+ t.after(() => {
+ store.closeBoard(board);
+ store.closeBoard(replica);
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ const coordinator = store.register(board, { lane: 'coordinator', path: '/private-baseline-control/coordinator' });
+ const agent = store.register(board, { lane: 'core', path: '/private-baseline-control/agent' });
+ assert.ok(coordinator);
+ importBoard(replica, exportBoard(board));
+
+ const initialSource = [
+ '# Private spec fixture',
+ '',
+ '## Existing',
+ '- G1 [approved, must] Existing requirement. | gate: review',
+ '',
+ ].join('\n');
+ writeFileSync(join(root, 'SPEC.md'), initialSource);
+ const config = configFromSource('{"spec":"SPEC.md"}');
+
+ const futureRow = '- G99 [approved, must] Future requirement. | gate: review';
+ const baseline = {
+ version: 1,
+ file: 'SPEC.md',
+ anchor: 'a'.repeat(40),
+ rows: [{ id: 'G99', text: 'Future requirement.', source: futureRow }],
+ };
+ const move = prepareEngineMove(board, 'recordSpecApprovalBaseline', [{ agentId: agent, baseline }]);
+ const sender = { kind: 'agent', userId: 'private-control-user', agent };
+ const receipt = { sequence: 1, at: '2026-10-21T12:00:00.000Z', kind: 'move', sender };
+ const outcome = applyRelayMove(board, move, receipt);
+ assert.equal(outcome.error?.code, 'COORDINATOR_ONLY', JSON.stringify(outcome));
+ assert.deepEqual(applyRelayMove(replica, move, receipt), outcome,
+ 'a second replica refuses the same authenticated lane snapshot');
+ assert.equal(store.specApprovalBaseline(board), null);
+ assert.equal(store.specApprovalBaseline(replica), null);
+ assert.equal(specApprovalState(root, { board, config }).baselinePending, true);
+ const captured = captureSpecApprovalBaseline(root, config);
+ const authorized = prepareEngineMove(board, 'recordSpecApprovalBaseline', [{ agentId: coordinator, baseline: captured }]);
+ const authorizedReceipt = { ...receipt, sequence: 2, sender: { ...sender, agent: coordinator } };
+ const accepted = applyRelayMove(board, authorized, authorizedReceipt);
+ assert.equal(accepted.error, undefined, JSON.stringify(accepted));
+ assert.deepEqual(applyRelayMove(replica, authorized, authorizedReceipt), accepted);
+ assert.deepEqual(store.specApprovalBaseline(board), captured);
+
+ // The row was absent from the source at the time the baseline move was created.
+ writeFileSync(join(root, 'SPEC.md'), initialSource + `${futureRow}\n`);
+ const projected = specApprovalState(root, { board, config });
+ assert.ok(projected.rows.some(row => row.id === 'G99'),
+ 'a later approved row absent from the captured source must remain agent-approved until a person confirms it');
+});