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.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(approval): preserve setup and reader compatibility [S1,B26,H16]
Corey Olsond3fdad0a14d1
diff --git a/docs/formats.md b/docs/formats.mdindex fae05bc4..08bfc590 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -388,7 +388,7 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap| `release` | builder | — || `submit` | builder | `commit`, `tree`, `policyCommit`, engine-9 `criterionDigest`, engine-38 `submissionProof` || `reserve` | reviewer | `until` |-| `accept` | reviewer | `reason`, `commit`, engine-20 `implies`, engine-33 `review` |+| `accept` | reviewer | `reason`, `commit`, engine-20 `implies`, engine-33 `review`, engine-68 `note` || `reject` | reviewer | `reason`, `commit`, engine-20 `implies`, engine-33 `review` || `reopen` | coordinator | `commit`, `note`, `judgment`, engine-10 `supersedes`, `landingFailure`, engine-30 `cause`, engine-52 `conflict` || `merged` | coordinator | `commit` |diff --git a/src/api.js b/src/api.jsindex c51b5a1d..b0a004cd 100644--- a/src/api.js+++ b/src/api.js@@ -54,7 +54,11 @@ import {projectFlowStats,} from './stats-flow.js';import { projectRowDecisions } from './row-decisions.js';-import { projectSpecApprovals, specApprovalState } from './spec-approval.js';+import {+ projectItemSpecApprovals,+ projectSpecApprovals,+ specApprovalState,+} from './spec-approval.js';import {fitFile,pendingFit,@@ -967,7 +971,8 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =const row = currentBoard.db.prepare('SELECT item_status FROM item WHERE item_id = ?').get(dependency);if (row) status.set(dependency, row.item_status);}- const base = projectItemState(currentBoard, source, status);+ const base = projectItemSpecApprovals(projectItemState(currentBoard, source, status),+ specApprovalState(board.root, { board: currentBoard, config: loadConfig(board.root) }));// Detail reads need no new Git process while the trunk and immutable receipt log hold.const info = repoInfo(board.root);const tip = trunkRevisionReader(info)();diff --git a/src/blueprint-set.js b/src/blueprint-set.jsindex 31e65a38..ced4afef 100644--- a/src/blueprint-set.js+++ b/src/blueprint-set.js@@ -14,7 +14,10 @@ import {bundledBlueprints,readBlueprint,} from './blueprints.js';-import { CONFIG_FILE, configFromSource } from './config.js';+import {+ CONFIG_FILE,+ configFromSource,+} from './config.js';import { Refused } from './refused.js';/**diff --git a/src/cli.js b/src/cli.jsindex d8ab4035..0d7b38f7 100644--- a/src/cli.js+++ b/src/cli.js@@ -213,10 +213,8 @@ import {standings,unmetRows,} from './spec.js';-import {- captureSpecApprovalBaseline,- refuseAgentApprovedRows,-} from './spec-approval.js';+import { refuseAgentApprovedRows } from './spec-approval.js';+import { initialSpecApprovalBaseline } from './spec-approval-bootstrap.js';import {answerQuestion,landBlueprint,@@ -880,8 +878,7 @@ function relayOutboxSetting(root) {}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;+ const initialBaseline = initialSpecApprovalBaseline(ctx, board, operation);// Only a reject or a reopen can open a builder's first-refusal window (#954), so an accept never reads the coordinator's policy.if (operation === 'reopen' || operation === 'verify' && args[1]?.decision === 'REJECT') args = firstRefusalArgs(operation, args, configFromSource(coordinatorFile(ctx.info.root, CONFIG_FILE).stdout));ctx.io.relayOutbox ??= () => relayOutboxSetting(ctx.info.root);diff --git a/src/commands/ledger.js b/src/commands/ledger.jsindex 6842e155..ac822bd0 100644--- a/src/commands/ledger.js+++ b/src/commands/ledger.js@@ -1,6 +1,10 @@/** The pullboard ledger command, in its own module so an item adding another command never edits these lines. */import * as store from '../board.js';-import { agentApprovalLine, itemAgentApprovals, specApprovalState } from '../spec-approval.js';+import {+ agentApprovalLine,+ itemAgentApprovals,+ specApprovalState,+} from '../spec-approval.js';import {agentDisplayName,context,diff --git a/src/commands/resume.js b/src/commands/resume.jsindex f2a7761b..db2aef43 100644--- a/src/commands/resume.js+++ b/src/commands/resume.js@@ -64,6 +64,7 @@ import {import {loadSpec,} from '../spec.js';+import { initialSpecApprovalBaseline } from '../spec-approval-bootstrap.js';import {flowAlertLine,} from '../stats-flow.js';@@ -114,6 +115,15 @@ export async function resumeHere(io, view) {const ctx = context(io);await withBoard(ctx, async board => {const me = whoAmI(ctx, board);+ // Bootstrap is an ordered move: observe health only after it, so the first legacy scan is not stale.+ const initialBaseline = initialSpecApprovalBaseline(ctx, board, 'recordHealthFindings');+ if (initialBaseline) {+ const baselineIo = ctx.io.personRequest || ctx.io.personRequestMoveId+ ? { ...ctx.io, personRequest: undefined, personRequestMoveId: undefined } : ctx.io;+ await ordered({ ...ctx, io: baselineIo }, board, 'recordSpecApprovalBaseline', [{+ agentId: COORDINATOR, baseline: initialBaseline,+ }]);+ }const observation = scanHealthSentinel(ctx.file, { root: ctx.info.root, config: ctx.config, now: ctx.clock.now() });if (observation) {try { await ordered(ctx, board, 'recordHealthFindings', [{ agentId: me.id, ...observation }]); }diff --git a/src/commands/show.js b/src/commands/show.jsindex 5246061e..ff7a7780 100644--- a/src/commands/show.js+++ b/src/commands/show.js@@ -7,7 +7,11 @@ import {barCorrections,} from '../bar-corrections.js';import * as store from '../board.js';-import { agentApprovalLine, itemAgentApprovals, specApprovalState } from '../spec-approval.js';+import {+ agentApprovalLine,+ itemAgentApprovals,+ specApprovalState,+} from '../spec-approval.js';import {sayCheckBaseline,} from '../check-baseline.js';diff --git a/src/commands/status.js b/src/commands/status.jsindex 802e4409..607a6553 100644--- a/src/commands/status.js+++ b/src/commands/status.js@@ -1,6 +1,6 @@/** The pullboard status command, in its own module so an item adding another command never edits these lines. */import * as store from '../board.js';-import { personNeedsState } from '../needs-state.js';+import { personNeedsSummary } from '../needs-state.js';import {reviewQueueLine,} from '../next-steps.js';@@ -32,7 +32,7 @@ export function run(io, { values }) {const summary = withBoard(ctx, (board) => {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 });+ const approvalState = personNeedsSummary(ctx.info.root, { board, config: ctx.config });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) };});diff --git a/src/commands/verify.js b/src/commands/verify.jsindex 1730ec3d..84e50e6d 100644--- a/src/commands/verify.js+++ b/src/commands/verify.js@@ -1,6 +1,10 @@/** The pullboard verify command, in its own module so an item adding another command never edits these lines. */import * as store from '../board.js';-import { agentApprovalLine, itemAgentApprovals, specApprovalState } from '../spec-approval.js';+import {+ agentApprovalLine,+ itemAgentApprovals,+ specApprovalState,+} from '../spec-approval.js';import {checkNeedsBrowser,explicitCheckFiles,diff --git a/src/exchange.js b/src/exchange.jsindex 13c36017..d767a96f 100644--- a/src/exchange.js+++ b/src/exchange.js@@ -8,7 +8,10 @@ import {ENGINE_VERSION,storeTriggers,} from './machine.js';-import { EVENT_LOG_VERSION } from './board.js';+import {+ EVENT_LOG_VERSION,+ specApprovalBaseline,+} from './board.js';const VERSION = 1;@@ -119,22 +122,27 @@ function validateDocument(db, document, names) {}/** Only the generated identity is disposable when restoring a fresh board (A2, A7). */-function hasOnlyIdentity(db) {+function hasOnlyIdentity(db, { baseline = false } = {}) {const rows = db.prepare('SELECT * FROM board_meta').all();const identity = rows.find((row) => row.meta_key === 'board_id');const eventLog = rows.find((row) => row.meta_key === 'event_log_version');return /^[0-9a-f]{32}$/.test(identity?.meta_value ?? '')- && rows.length === (eventLog ? 2 : 1)- && rows.every((row) => row.meta_key === 'board_id' || row.meta_key === 'event_log_version');+ && rows.length === (eventLog ? 2 : 1) + (baseline ? 1 : 0)+ && rows.every((row) => row.meta_key === 'board_id' || row.meta_key === 'event_log_version' || baseline && row.meta_key === 'spec_approval_baseline');}/** True only for the coordinator registration and join event that `pullboard init` creates. */function hasOnlyInitCoordinator(db, names) {- if (!names.includes('sqlite_sequence') || !hasOnlyIdentity(db)) return false;+ let baseline;+ try { baseline = specApprovalBaseline({ db }); }+ catch (error) { if (!(error instanceof Refused)) throw error; return false; }+ if (!names.includes('sqlite_sequence') || !hasOnlyIdentity(db, { baseline: Boolean(baseline) })) return false;const agents = db.prepare('SELECT * FROM agent').all();- const events = db.prepare('SELECT * FROM event').all();+ const events = db.prepare('SELECT * FROM event ORDER BY event_id').all();const sequence = db.prepare('SELECT name, seq FROM sqlite_sequence ORDER BY name').all();- if (agents.length !== 1 || events.length !== 1 || sequence.length !== 1) return false;+ if (agents.length !== 1 || events.length !== (baseline ? 2 : 1) || sequence.length !== 1) return false;+ if (baseline && (events[1].event_id !== 2 || events[1].event_by !== 'coordinator'+ || events[1].event_kind !== 'spec_approval_baseline' || events[1].item_id !== null)) return false;const [agent] = agents;const [event] = events;if (@@ -143,11 +151,12 @@ function hasOnlyInitCoordinator(db, names) {|| agent.agent_route !== 'strong'|| agent.agent_last_shout_id !== 0|| !agent.agent_path+ || event.event_id !== 1|| event.event_by !== 'coordinator'|| event.event_kind !== 'join'|| event.item_id !== null|| sequence[0].name !== 'event'- || sequence[0].seq !== 1+ || sequence[0].seq !== events.length) return false;try {const detail = JSON.parse(event.event_detail);@@ -162,6 +171,11 @@ function hasOnlyInitCoordinator(db, names) {.every((table) => !db.prepare(`SELECT 1 FROM ${identifier(table)} LIMIT 1`).get());}+/** Share the exact disposable init shape with pairing before it consumes a one-use code. */+export function isInitialBoard(board) {+ return hasOnlyInitCoordinator(board.db, tableNames(board.db));+}+/*** Restore a v1 export only into an empty board, atomically, while briefly allowing historical item* states to be inserted before restoring the board's declared lifecycle triggers.@@ -221,7 +235,7 @@ function restoreDocument(board, document, replace = false, expectedNativeDigest} else if (initCoordinator) {db.exec('DELETE FROM event; DELETE FROM agent; DELETE FROM sqlite_sequence');}- if (onlyIdentity && !replace) db.exec('DELETE FROM board_meta');+ if ((onlyIdentity || initCoordinator) && !replace) db.exec('DELETE FROM board_meta');for (const table of names.filter((name) => name !== 'sqlite_sequence')) {const columns = columnsOf(db, table);const sql = `INSERT INTO ${identifier(table)} (${columns.map(identifier).join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`;diff --git a/src/needs-state.js b/src/needs-state.jsindex dd12c68b..6b652f0b 100644--- a/src/needs-state.js+++ b/src/needs-state.js@@ -16,7 +16,11 @@ import {undraftedRigor,} from './rigor-notices.js';import { personNeeds } from './needs.js';-import { projectSpecApprovals, specApprovalState } from './spec-approval.js';+import { displayAgentName } from './agent-names.js';+import {+ projectSpecApprovals,+ specApprovalState,+} from './spec-approval.js';import {sentinelDraftNeeds,sentinels,@@ -40,3 +44,15 @@ export function personNeedsState(root, { board: providedBoard = null, includeRigif (!providedBoard) store.closeBoard(board);}}++/** Keep status's complete obligation list without dashboard history, Git ages, or release notes. */+export function personNeedsSummary(root, { board, config }) {+ const spec = loadSpec(root, config);+ const rows = projectRowDecisions(store.rowDecisions(board), { root, spec: spec.rows, practice: loadDoctrine(root, config).rows });+ const projected = projectSpecApprovals({ ...rows,+ decisions: store.openDecisions(board, store.PERSON), holds: store.laneHolds(board),+ agents: store.listAgents(board).map(agent => ({ ...agent, displayName: displayAgentName(agent, config.agents.names) })),+ rigorDrafts: rigorDraftNeeds(rows), sentinelDrafts: sentinelDraftNeeds(sentinels(board)),+ }, specApprovalState(root, { board, config, spec }));+ return projected;+}diff --git a/src/relay-pairing-client.js b/src/relay-pairing-client.jsindex e6b15598..220fd6e1 100644--- a/src/relay-pairing-client.js+++ b/src/relay-pairing-client.js@@ -18,6 +18,7 @@ import * as store from './board.js';import {exportBoard,importBoard,+ isInitialBoard,} from './exchange.js';import {codeIsFromMain,@@ -200,33 +201,14 @@ export async function relayPair(root, io) {/** Refuse a nonempty target board before spending its one-use code. */function requireFreshTarget(root) {- const local = localSnapshot(root);- const tables = local.snapshot.tables;- const nonempty = Object.entries(tables).filter(([name, rows]) => !['board_meta', 'agent', 'event', 'sqlite_sequence'].includes(name) && rows.length);- const meta = tables.board_meta;- const metadata = new Map(meta.map((row) => [row.meta_key, row.meta_value]));- const agents = tables.agent;- const events = tables.event;- const sequence = tables.sqlite_sequence;- let initialDetail = false;+ const info = repoInfo(root);+ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });try {- const detail = JSON.parse(events[0]?.event_detail);- // Init has no declared model; engine 8 records that absence explicitly.- if (detail.model === undefined || detail.model === 'unknown') {- delete detail.model;- initialDetail = JSON.stringify(detail) === JSON.stringify({ lane: 'coordinator' });+ const eventLog = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('event_log_version');+ if (!isInitialBoard(board) || eventLog?.meta_value !== String(store.EVENT_LOG_VERSION)) {+ throw new Refused('IMPORT_NOT_EMPTY', 'pair into a freshly initialized clone with no board work; preserve this board and use another clone');}- }- catch { /* A non-init history cannot be safely replaced by a paired snapshot. */ }- if (meta.length !== 2 || !BOARD.test(metadata.get('board_id') ?? '') ||- metadata.get('event_log_version') !== String(store.EVENT_LOG_VERSION) ||- agents.length !== 1 || agents[0].agent_id !== 'coordinator' || agents[0].agent_lane !== 'coordinator' ||- agents[0].agent_route !== 'strong' || agents[0].agent_last_shout_id !== 0 || !agents[0].agent_path ||- events.length !== 1 || events[0].event_by !== 'coordinator' || events[0].event_kind !== 'join' ||- events[0].item_id !== null || !initialDetail || sequence.length !== 1 || sequence[0].name !== 'event' ||- sequence[0].seq !== 1 || nonempty.length) {- throw new Refused('IMPORT_NOT_EMPTY', 'pair into a freshly initialized clone with no board work; preserve this board and use another clone');- }+ } finally { store.closeBoard(board); }}/** Refuse to overwrite an unrelated device key under the same persistent board id. */diff --git a/src/relay.js b/src/relay.jsindex c90dbd13..0cb9a8b7 100644--- a/src/relay.js+++ b/src/relay.js@@ -1410,9 +1410,9 @@ export async function relayCommandReceiptReported(root, moveId) {}/** Expose only an unreported operation descriptor so CLI preconditions cannot strand its outcome. */-export function relayRecovered(root) {+export function relayRecovered(root, { includePending = false } = {}) {const state = loadLink(linkFile(root));- return state ? state.recovered?.move ?? null : deletedRecovery(root)?.move ?? null;+ return state ? state.recovered?.move ?? (includePending ? state.pending?.move : null) ?? null : deletedRecovery(root)?.move ?? null;}/** Explicitly refuse one blocked position, replay its valid tail on a private copy, then publish it. */diff --git a/src/spec-approval-baseline.js b/src/spec-approval-baseline.jsindex 8ca5c6cc..2541d2e2 100644--- a/src/spec-approval-baseline.js+++ b/src/spec-approval-baseline.js@@ -1,5 +1,8 @@/** One shared compatibility snapshot, recorded through the board engine, never a person approval. */-import { atomic, logEvent } from './board.js';+import {+ atomic,+ logEvent,+} from './board.js';import { Refused } from './refused.js';import { parseSpec } from './spec.js';import { COORDINATOR } from './config.js';diff --git a/src/spec-approval-bootstrap.js b/src/spec-approval-bootstrap.jsnew file mode 100644index 00000000..527504f4--- /dev/null+++ b/src/spec-approval-bootstrap.js@@ -0,0 +1,15 @@+/** Keep one compatibility setup move recoverable without stealing an interrupted work result [S1,H16]. */+import { specApprovalBaselineExists } from './board.js';+import { loadConfig } from './config.js';+import { relayRecovered } from './relay.js';+import { captureSpecApprovalBaseline } from './spec-approval.js';++/** Reuse the exact interrupted setup payload; only a main-checkout command can establish it. */+export function initialSpecApprovalBaseline(ctx, board, operation) {+ if (!ctx.info.isMain || operation === 'recordSpecApprovalBaseline') return null;+ const recovered = relayRecovered(ctx.info.root, { includePending: true });+ // A pending send or catch-up can retain the original move while its setup reply is still unreported.+ // Repeating that same move consumes its receipt through ordinary relay validation, not a new seed.+ if (recovered?.operation === 'recordSpecApprovalBaseline') return recovered.args[0].baseline;+ return specApprovalBaselineExists(board) ? null : captureSpecApprovalBaseline(ctx.info.root, loadConfig(ctx.info.root));+}diff --git a/src/spec-approval.js b/src/spec-approval.jsindex ab5d0a36..13c0c1d9 100644--- a/src/spec-approval.js+++ b/src/spec-approval.js@@ -5,8 +5,14 @@ import * as store from './board.js';import { tryGit } from './git.js';import { personNeeds } from './needs.js';import { Refused } from './refused.js';-import { loadSpec, readSignoffs } from './spec.js';-import { isVerifiedSignoff, verifyRowDecision } from './signature.js';+import {+ loadSpec,+ readSignoffs,+} from './spec.js';+import {+ isVerifiedSignoff,+ verifyRowDecision,+} from './signature.js';/** Read each line's actual commit and Git author; neither identifies a person approval. */function rowOrigins(root, file) {@@ -102,11 +108,17 @@ export function agentApprovalLine(rows) {return rows.length ? `verified against agent-approved ${rows.map(row => row.id).join(', ')}` : '';}+/** Keep item detail and whole-state approval fields identical without changing compact summaries. */+export function projectItemSpecApprovals(item, approval) {+ const rows = itemAgentApprovals(item, approval);+ return { ...item, agentApproved: rows, approvalQualification: 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, 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)) })) };+ items: state.items?.map(item => projectItemSpecApprovals(item, approval)) };return { ...projected, needs: personNeeds(projected) };}diff --git a/test/api-http.test.js b/test/api-http.test.jsindex 87460bdc..631b47be 100644--- a/test/api-http.test.js+++ b/test/api-http.test.js@@ -723,7 +723,8 @@ test("[A2, N26] the board state sends summaries and an item's detail comes fromassert.equal(acceptedDetail.criterion, 'Every list reads the Zebra marker');assert.equal(acceptedDetail.check, 'true');assert.equal(acceptedDetail.checkBaseline.result, 'green');- assert.equal(acceptedDetail.verdict.note, 'ran the check and read the summary');+ assert.equal(acceptedDetail.verdict.note, 'ran the check and read the summary\nverified against agent-approved G1',+ 'the post-init approved fixture row qualifies the receipt without losing the reviewer note');assert.deepEqual(acceptedDetail.thread.filter((entry) => entry.type === 'fact').map((entry) => entry.text), ['a fact only the thread carries']);/** Search through HTTP and return the matching ids in board order. */diff --git a/test/exchange.test.js b/test/exchange.test.jsindex 6b811a60..c7b48ebb 100644--- a/test/exchange.test.js+++ b/test/exchange.test.js@@ -289,3 +289,48 @@ test('import preserves other metadata and refuses malformed fresh identities [A2rmSync(directory, { recursive: true, force: true });}});+++test('fresh-init approval baselines are disposable only with exact setup history [A2,A7,S1]', () => {+ const directory = tempDirectory();+ const source = populatedBoard(join(directory, 'source.sqlite'));+ const setup = store.openBoard(join(directory, 'setup.sqlite'));+ /** An exact valid source snapshot, deliberately different on the two boards. */+ const baseline = text => ({ version: 1, file: 'SPEC.md', anchor: null,+ rows: [{ id: 'G1', text, source: `- G1 [approved, must] ${text}` }] });+ try {+ store.recordSpecApprovalBaseline(source, { agentId: 'coordinator', baseline: baseline('The imported source governs.') });+ const incoming = exportBoard(source);+ store.register(setup, { lane: 'coordinator', path: '/fresh' });+ store.recordSpecApprovalBaseline(setup, { agentId: 'coordinator', baseline: baseline('Local setup is disposable.') });+ for (let index = 0; index < 6; index += 1) {+ const target = store.openBoard(join(directory, `fresh-${index}.sqlite`));+ try {+ // A trusted restore can carry malformed old state; no append-only guard is bypassed here.+ const initial = exportBoard(setup);+ if (index === 1) initial.tables.board_meta.push({ meta_key: 'retained', meta_value: 'repo setting' });+ if (index === 2) initial.tables.event[1].event_by = 'machine';+ if (index === 3) initial.tables.event[1].item_id = 42;+ if (index === 4) initial.tables.board_meta.find(row => row.meta_key === 'spec_approval_baseline').meta_value = '{}';+ if (index === 5) {+ initial.tables.event.push({ ...initial.tables.event[0], event_id: 3, event_kind: 'unrelated', event_detail: '{}' });+ initial.tables.sqlite_sequence.find(row => row.name === 'event').seq = 3;+ }+ importBoard(target, initial);+ if (index) {+ const before = exportBoard(target);+ assert.throws(() => importBoard(target, incoming), /IMPORT_NOT_EMPTY/u);+ assert.deepEqual(exportBoard(target), before, 'non-setup history and metadata remain untouched');+ } else {+ importBoard(target, incoming);+ assert.deepEqual(exportBoard(target), incoming, 'the source baseline and every source row replace local setup');+ assert.equal(store.specApprovalBaseline(target).rows[0].text, 'The imported source governs.');+ }+ } finally { store.closeBoard(target); }+ }+ } finally {+ store.closeBoard(setup);+ store.closeBoard(source);+ rmSync(directory, { recursive: true, force: true });+ }+});diff --git a/test/needs.test.js b/test/needs.test.jsindex a31a2a29..17fbfda8 100644--- a/test/needs.test.js+++ b/test/needs.test.js@@ -47,7 +47,9 @@ test('one builder lists what needs the person [N26,A9]', async (t) => {const card = JSON.parse(resumed.out);assert.ok(Array.isArray(card.needsYou), 'resume exposes the shared person needs list');const expected = card.needsYou;- assert.deepEqual(expected.map(need => need.kind).sort(), ['decision', 'draft', 'hold', 'pending']);+ assert.deepEqual(expected.map(need => need.kind).sort(), ['agent-approved', 'agent-approved', 'decision', 'draft', 'hold', 'pending']);+ assert.deepEqual(expected.filter(need => need.kind === 'agent-approved').map(need => need.id).sort(), ['G1', 'G2'],+ 'approved source added after init stays visibly unconfirmed');assert.equal(expected.find(need => need.kind === 'pending').id, 'G3');assert.equal(expected.find(need => need.kind === 'draft').count, 1);assert.equal(expected.find(need => need.kind === 'hold').id, 'web');@@ -56,6 +58,9 @@ test('one builder lists what needs the person [N26,A9]', async (t) => {const { personNeedsState } = await import('../src/needs-state.js');const state = personNeedsState(box.repo);assert.deepEqual(personNeeds(state), expected);+ const statusCard = box.run(box.repo, 'status', '--json');+ assert.equal(statusCard.code, 0, statusCard.err || statusCard.out);+ assert.deepEqual(JSON.parse(statusCard.out).needs, expected, 'lightweight status preserves every kind of person obligation');const before = JSON.stringify(state);const browserBuilder = runInNewContext(`(${personNeeds.toString()})`);assert.deepEqual(JSON.parse(JSON.stringify(browserBuilder(state))), expected,diff --git a/test/relay-client.test.js b/test/relay-client.test.jsindex d8e8124a..491f1893 100644--- a/test/relay-client.test.js+++ b/test/relay-client.test.js@@ -28,6 +28,8 @@ import { fetchFresh } from './http-fixture.js';import { relayResetSample } from './relay-reset-fixture.js';import { request as relayRequest } from '../src/relay.js';import { openPagedSnapshot } from '../src/relay-page-layout.js';+import { initialSpecApprovalBaseline } from '../src/spec-approval-bootstrap.js';+import { captureSpecApprovalBaseline } from '../src/spec-approval.js';import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';const SIGN_INS = new Map();@@ -1016,6 +1018,9 @@ async function competingReplicaClaims(fixture, timing) {async function recoverReplicaReplies(fixture, timing) {const { scratch, clones, worktrees, envs, gitAt, commonDir, relay, key, boardId, replicaFiles } = fixture;timing.begin('lost-reply recovery', 'exercise dropped CLI replies, replay recovery, and durable outcome ordering across all replicas');+ // Exercise loss of the add's reply, after the separate one-time legacy migration has completed.+ await timing.wait('establish the legacy approval baseline before the add fault', () => cli(clones[0], envs[0], 'shout', 'all', 'Legacy board ready for add recovery'));+ await timing.wait('sync the migrated baseline to all clones', () => Promise.all(clones.map((root, index) => cli(root, envs[index], 'status'))));const beforeDropped = relay.uploads.length;relay.dropNextReply({ offline: true });const lostAdd = await timing.wait('send clone A add with its reply dropped', () => cliResult(clones[0], envs[0], 'add', 'web', 'Lost clone reply'));@@ -1025,6 +1030,8 @@ async function recoverReplicaReplies(fixture, timing) {await timing.wait('sync all clones before retrying the lost add', () => Promise.all(clones.map((root, index) => cli(root, envs[index], 'status'))));const retriedAdd = await timing.wait('retry the lost clone add', () => cli(clones[0], envs[0], 'add', 'web', 'Lost clone reply'));assert.equal(relay.uploads.length, beforeDropped + 1, 'three-clone recovery never posts a second operation');+ assert.equal(localEvents(replicaFiles[0]).filter(event => event.event_kind === 'spec_approval_baseline').length, 1,+ 'a lost bootstrap reply is consumed through its original receipt, never a second baseline');const retriedId = retriedAdd.item.item_id;for (const file of replicaFiles) {assert.equal(localEvents(file).filter((event) => event.event_kind === 'add' && event.item_id === retriedId).length, 1,@@ -1421,3 +1428,37 @@ test('relay read recovery stays bounded and preserves refusals, invalid bodies aawait assert.rejects(relayRequest({ url: 'http://127.0.0.1:1' }, '/fixture', { signal: {} }, { ignoreRelayEnvironmentToken: true }),error => error.code === 'RELAY_UNAVAILABLE', 'invalid signal setup keeps its existing transport refusal');});+++test('a pending legacy approval baseline keeps its exact source through resume [H16,S1]', { timeout: 60_000 }, async t => { // budget: one lost setup reply and one real resume, bounded fixture cleanup.+ const timing = threeReplicaPhaseCapture(t);+ await timing.run(async () => {+ const fixture = await threeReplicaFixture(t, timing);+ const { clones, envs, relay, replicaFiles } = fixture;+ timing.begin('baseline reply recovery', 'lose one compatibility setup reply, change the spec, and resume');+ relay.dropNextReply({ offline: true });+ const first = await cliResult(clones[0], envs[0], 'add', 'web', 'Work after migration');+ assert.equal(first.status, 1);+ assert.equal(first.document.error.code, 'RELAY_UNAVAILABLE');+ assert.equal(relay.uploads.length, 1, 'only setup reached the relay before the interrupted work');+ const spec = join(clones[0], 'SPEC.md');+ writeFileSync(spec, readFileSync(spec, 'utf8') + '- G99 [approved, must] A later row needs confirmation. | gate: review\n');+ const local = store.openBoard(replicaFiles[0]);+ try {+ assert.equal(store.specApprovalBaselineExists(local), false, 'the offline device has not replayed its pending setup');+ const config = { spec: 'SPEC.md' };+ assert.ok(captureSpecApprovalBaseline(clones[0], config).rows.some(row => row.id === 'G99'));+ const selected = initialSpecApprovalBaseline({ info: { root: clones[0], isMain: true } }, local, 'recordHealthFindings');+ assert.equal(selected.rows.some(row => row.id === 'G99'), false, 'pending setup retains its original source instead of approving the changed file');+ assert.equal(initialSpecApprovalBaseline({ info: { root: clones[0], isMain: false } }, local, 'recordHealthFindings'), null, 'a lane never seeds or consumes setup');+ } finally { store.closeBoard(local); }+ relay.failReads(false);+ const resumed = await cli(clones[0], envs[0], 'resume');+ assert.ok(resumed.needsYou.some(need => need.kind === 'agent-approved' && need.id === 'G99'));+ const events = localEvents(replicaFiles[0]);+ assert.equal(events.filter(event => event.event_kind === 'spec_approval_baseline').length, 1);+ assert.equal(events.filter(event => event.event_kind === 'add' && JSON.parse(event.event_detail).title === 'Work after migration').length, 0,+ 'recovering internal setup never claims the interrupted add was performed');+ timing.finish(['cloning three replicas', 'baseline reply recovery']);+ });+});