From 0c02caf86767102d1a8a851c921c9378e05e4008 Mon Sep 17 00:00:00 2001 From: McHerpes Date: Fri, 13 Nov 2026 03:13:52 +0000 Subject: [PATCH 1/7] fix(relay): reconstruct interrupted outbox rebuilds without resending receipts --- src/relay-ordering.js | 36 +++++- src/relay-outbox.js | 30 ++++- src/relay.js | 5 +- test/relay-outbox-rebuild-recovery.test.js | 126 +++++++++++++++++++++ 4 files changed, 186 insertions(+), 11 deletions(-) create mode 100644 test/relay-outbox-rebuild-recovery.test.js diff --git a/src/relay-ordering.js b/src/relay-ordering.js index eae80e271b..09bef15df0 100644 --- a/src/relay-ordering.js +++ b/src/relay-ordering.js @@ -10,7 +10,8 @@ import { appliedSequence, engineReceipt, } from './engine.js'; -import { restoreRelaySnapshot } from './exchange.js'; +import { exportBoard, importBoard, restoreRelaySnapshot } from './exchange.js'; +import { ENGINE_VERSION } from './machine.js'; import { codeIsFromMain, repoInfo, @@ -39,7 +40,7 @@ import { * * @param {{ request: Function, localRecords: Function, decoded: Function, replayRelayRecord: Function, * reportRecoveredReply: Function, saveLink: Function, sealedRecord: Function, flush: Function }} relay - * @returns {{ applyRecords: Function, fetchCheckpoint: Function, catchUp: Function, postPending: Function, sendPending: Function }} + * @returns {{ applyRecords: Function, advanceCheckpoint: Function, fetchCheckpoint: Function, catchUp: Function, postPending: Function, sendPending: Function }} */ export function relayOrdering({ request, localRecords, decoded, replayRelayRecord, reportRecoveredReply, saveLink, sealedRecord, flush }) { /** Apply authenticated relay records in order, each in its own board transaction with a durable receipt. */ @@ -52,6 +53,35 @@ export function relayOrdering({ request, localRecords, decoded, replayRelayRecor return outcomes; } + /** Reconstruct a covering checkpoint in isolation; never roll the live board back or send a move. */ + async function advanceCheckpoint(key, state, checkpoint, records, minimum) { + const meta = new Map((checkpoint.native?.tables?.board_meta ?? []).map(row => [row.meta_key, row.meta_value])); + if (meta.get('board_id') !== state.board || !Number.isSafeInteger(checkpoint.sequence) + || checkpoint.sequence < 0 || String(checkpoint.sequence) !== meta.get('relay_applied_sequence')) { + throw new Refused('RELAY_SNAPSHOT', 'the checkpoint does not identify this board and prefix; keep the local board and fetch a consistent checkpoint'); + } + const engine = Number(meta.get('relay_engine_version')); + if (!Number.isSafeInteger(engine) || engine < 1 || engine > ENGINE_VERSION) { + throw new Refused('ENGINE_VERSION', 'the checkpoint needs another supported engine; keep the local board and use that engine before recovery'); + } + if (!Number.isSafeInteger(minimum) || minimum < checkpoint.sequence || !Array.isArray(records) + || records.some((record, index) => record?.event_id !== checkpoint.sequence + index + 1) + || (records.at(-1)?.event_id ?? checkpoint.sequence) < minimum) { + throw new Refused('RELAY_OUTBOX', 'the authenticated checkpoint history does not cover the current prefix; keep the local board and obtain its missing ordered records'); + } + const board = store.openBoard(':memory:'); + try { + importBoard(board, checkpoint.native); + for (const record of records) { + await replayRelayRecord(board, key, state, record); + if (appliedSequence(board) !== record.event_id) { + throw new Refused('RELAY_RESPONSE', 'checkpoint replay did not advance to its ordered record; keep the local board and inspect that record'); + } + } + return { native: exportBoard(board), sequence: appliedSequence(board), reconstructed: true }; + } finally { store.closeBoard(board); } + } + /** Read and authenticate the relay's checkpoint without touching the board; the caller restores it. */ async function fetchCheckpoint(state, io, key) { const document = await request(state, '/api/v1/boards/' + state.board + '/state', {}, io); @@ -191,5 +221,5 @@ export function relayOrdering({ request, localRecords, decoded, replayRelayRecor if (state.pending) throw new Refused('RELAY_BUSY', 'the relay order stayed busy; retry this command after other clients finish'); } - return { applyRecords, fetchCheckpoint, catchUp, postPending, sendPending }; + return { applyRecords, advanceCheckpoint, fetchCheckpoint, catchUp, postPending, sendPending }; } diff --git a/src/relay-outbox.js b/src/relay-outbox.js index d3687ff8d9..2ccb2b4393 100644 --- a/src/relay-outbox.js +++ b/src/relay-outbox.js @@ -530,10 +530,21 @@ async function pullSinceBase(link, key, { fromCheckpoint = false } = {}) { return remote.events; }; if (fromCheckpoint) { - const checkpoint = await link.fetchCheckpoint(key); - // A checkpoint older than the moves' base cannot stand in for it: the board would go back past what it shows. - if (checkpoint.sequence < outbox.baseSequence) throw new Refused('RELAY_OUTBOX', `this machine cannot take its queued moves back, and the relay checkpoint (sequence ${checkpoint.sequence}) is older than the board they sit on (sequence ${outbox.baseSequence}); keep the board as it is and ask the person to publish a newer checkpoint from another machine`); - return { baseSequence: outbox.baseSequence, checkpoint, events: await events(checkpoint.sequence) }; + let checkpoint = await link.fetchCheckpoint(key); + const minimum = Math.max(outbox.baseSequence, link.localRecords(link.root, appliedSequence)); + const prefix = await events(checkpoint.sequence); + if (checkpoint.sequence < minimum) { + // An interrupted rebuild can leave durable ordered receipts but the previous sealed outbox. Never install + // an older checkpoint into that live board: first reconstruct a covering prefix in a disposable replica. + while ((prefix.at(-1)?.event_id ?? checkpoint.sequence) < minimum) { + const more = await events(prefix.at(-1)?.event_id ?? checkpoint.sequence); + if (!more.length) throw new Refused('RELAY_OUTBOX', 'the relay checkpoint history ends before this board\'s current prefix; keep the board and queued moves until the missing records or a newer checkpoint are available'); + prefix.push(...more); + } + checkpoint = await link.advanceCheckpoint(key, checkpoint, prefix, minimum); + return { baseSequence: outbox.baseSequence, checkpoint, events: [] }; + } + return { baseSequence: outbox.baseSequence, checkpoint, events: prefix }; } try { return { baseSequence: outbox.baseSequence, events: await events(outbox.baseSequence) }; } catch (error) { @@ -545,9 +556,16 @@ async function pullSinceBase(link, key, { fromCheckpoint = false } = {}) { } /** Put the board back to an image the relay ordered, keeping each seat's newer shout-read position. */ -function restoreBase(link, image, sequence) { +function restoreBase(link, image, sequence, reconstructed = false) { link.localRecords(link.root, (board) => { const cursors = board.db.prepare('SELECT agent_id, agent_last_shout_id FROM agent').all(); + if (reconstructed) { + const receipts = new Map(image.tables.board_meta.map(row => [row.meta_key, row.meta_value])); + const existing = board.db.prepare("SELECT meta_key, meta_value FROM board_meta WHERE meta_key GLOB 'relay_receipt_*' OR meta_key GLOB 'relay_refusal_*'").all(); + if (existing.some(row => receipts.get(row.meta_key) !== row.meta_value)) { + throw new Refused('RELAY_RECOVERY_MISMATCH', 'the reconstructed prefix differs from a retained native receipt; keep the local board and queue and inspect the disagreement'); + } + } restoreRelaySnapshot(board, image, sequence); // Reading shouts is this machine's own progress; the restore keeps the newer read position. keepNewerCursors(board, cursors); @@ -610,7 +628,7 @@ async function rebuild(link, key, pulled) { // Nothing new from the relay: the board already shows the base and every queued move on top. if (!pulled.checkpoint && !pulled.events.length && outbox.restored !== true) return true; // Back to the relay's order: the relay's checkpoint, an older outbox's image, or the queued moves taken back. - if (pulled.checkpoint) restoreBase(link, pulled.checkpoint.native, pulled.checkpoint.sequence); + if (pulled.checkpoint) restoreBase(link, pulled.checkpoint.native, pulled.checkpoint.sequence, pulled.checkpoint.reconstructed === true); else if (outbox.base) restoreBase(link, outbox.base, outbox.baseSequence); else if (!takeBack(link, outbox)) return 'checkpoint'; await link.applyRecords(root, key, state, pulled.events); diff --git a/src/relay.js b/src/relay.js index db4b1603f1..f47dd05a04 100644 --- a/src/relay.js +++ b/src/relay.js @@ -972,7 +972,7 @@ function reportRecoveredReply(record, io) { // Catch-up and send live in their own module, over these link and transport helpers (#1013). const ordering = relayOrdering({ request, localRecords, decoded, replayRelayRecord, reportRecoveredReply, saveLink, sealedRecord, flush: (root, file, state, io) => flushOutbox(outboxLink(root, file, state, io)) }); -const { applyRecords, fetchCheckpoint, catchUp, postPending, sendPending } = ordering; +const { applyRecords, advanceCheckpoint, fetchCheckpoint, catchUp, postPending, sendPending } = ordering; /** Set up this machine's coordinator token inside a paired join's own person sign-in (#579). */ export async function relayPersonCoordinator(root, session, io) { @@ -1017,7 +1017,8 @@ function keepMoveForLaterBaseline(file, state, error, io) { /** The relay transport the ordered outbox queues and replays through (#922). */ function outboxLink(root, file, state, io) { return { root, file, state, io, request, sealedRecord, localRecords, saveLink, safePauseCode, safePauseMessage, - applyRecords, fetchCheckpoint: (key) => fetchCheckpoint(state, io, key), postPending }; + applyRecords, advanceCheckpoint: (key, checkpoint, records, minimum) => advanceCheckpoint(key, state, checkpoint, records, minimum), + fetchCheckpoint: (key) => fetchCheckpoint(state, io, key), postPending }; } /** diff --git a/test/relay-outbox-rebuild-recovery.test.js b/test/relay-outbox-rebuild-recovery.test.js new file mode 100644 index 0000000000..5c6ee6921a --- /dev/null +++ b/test/relay-outbox-rebuild-recovery.test.js @@ -0,0 +1,126 @@ +/** Recover an interrupted local rebuild from authenticated order, never by resending its prefix [H16,H21]. */ +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import * as store from '../src/board.js'; +import { applyRelayMove, appliedSequence, checkpointSequence, engineReceipt, prepareEngineMove } from '../src/engine.js'; +import { exportBoard } from '../src/exchange.js'; +import { storeBoardKey } from '../src/relay-key.js'; +import { relayOrdering } from '../src/relay-ordering.js'; +import { flushOutbox, outboxFile, queueMove, readOutbox } from '../src/relay-outbox.js'; +import { undoQueued } from '../src/relay-outbox-undo.js'; +import { seal, unseal } from '../src/seal.js'; + +/** Real SQLite, native changesets and sealed queue; the only remote is an in-process ordered fixture. */ +async function fixture(t, { partialReapply = false } = {}) { + const directory = mkdtempSync(join(tmpdir(), 'pullboard-rebuild-recovery-')); + const names = ['PULLBOARD_HOME', 'PULLBOARD_MACHINE_HOME', 'PULLBOARD_RELAY_KEY', 'PULLBOARD_RELAY_TOKEN']; + const prior = Object.fromEntries(names.map(name => [name, process.env[name]])); + t.after(() => { for (const name of names) { if (prior[name] === undefined) delete process.env[name]; else process.env[name] = prior[name]; } }); + process.env.PULLBOARD_HOME = join(directory, 'home'); + process.env.PULLBOARD_MACHINE_HOME = join(directory, 'machine'); + delete process.env.PULLBOARD_RELAY_KEY; + delete process.env.PULLBOARD_RELAY_TOKEN; + const board = store.openBoard(':memory:', { now: () => new Date('2026-10-24T00:00:00Z') }); + t.after(() => { store.closeBoard(board); rmSync(directory, { recursive: true, force: true }); }); + store.register(board, { lane: 'coordinator', path: directory, sessionDigest: 'a'.repeat(64) }); + checkpointSequence(board, 1); + const id = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value; + const key = randomBytes(32); + storeBoardKey(id, key); + const checkpoint = { native: exportBoard(board), sequence: 1 }; + const state = { board: id, sequence: 2, mode: 'ordered', machine: 'fixture-machine', outbox: { moves: [] } }; + mkdirSync(join(directory, 'link'), { mode: 0o700 }); + const file = join(directory, 'link', 'relay.json'); + const records = [], posts = [], reads = [], errors = []; + /** Authenticate the fixture's actual sealed record and use the real deterministic board engine. */ + async function replay(board, key, state, record) { + const bytes = await unseal(key, Buffer.from(record.sealed, 'base64url'), { boardId: state.board, kind: record.kind, sequence: record.event_id }); + const move = JSON.parse(Buffer.from(bytes).toString()); + return applyRelayMove(board, move, { sequence: record.event_id, at: record.event_at, sender: record.sender, kind: record.kind }); + } + /** Preserve the exact move bytes and original sequence on the synthetic relay. */ + async function record(move, sequence) { + return { event_id: sequence, event_at: `2026-10-24T00:00:0${sequence}Z`, kind: 'move', + sender: { kind: 'agent', userId: 'fixture', agent: 'coordinator' }, + sealed: Buffer.from(await seal(key, Buffer.from(JSON.stringify(move)), { boardId: id, kind: 'move', sequence })).toString('base64url') }; + } + /** Make a normal native shout without test-only SQL mutations. */ + const move = (number) => prepareEngineMove(board, 'shout', [{ from: 'coordinator', to: 'all', text: `original-${number}`, lanes: [] }], { id: `original-${number}`, actor: 'coordinator' }); + const second = move(2); records.push(await record(second, 2)); + assert.equal((await replay(board, key, state, records[0])).error, undefined); + const ordering = relayOrdering({ replayRelayRecord: replay }); + const link = { + root: directory, file, state, io: { err: text => errors.push(text) }, + localRecords: (_root, use) => use(board), saveLink: () => {}, + request: async (_state, path) => { + const after = Number(path.split('after=')[1]); reads.push(after); + return { events: records.filter(row => row.event_id > after) }; + }, + fetchCheckpoint: async () => structuredClone(checkpoint), + advanceCheckpoint: (key, checkpoint, prefix, minimum) => ordering.advanceCheckpoint(key, state, checkpoint, prefix, minimum), + applyRecords: async (_root, key, state, prefix) => { for (const row of prefix) await replay(board, key, state, row); }, + sealedRecord: async (_key, move, _state, _kind, sequence) => (await record(move, sequence)).sealed, + postPending: async (_root, _file, _state, pending) => { posts.push(pending.move.id); records.push(await record(pending.move, pending.sequence)); }, + }; + const third = move(3), fourth = move(4); + for (const next of [third, fourth]) await queueMove(link, { operation: next.operation, args: next.args, move: next, + quiet: true, applyLocally: () => store.atomic(board, () => store.shout(board, ...next.args)) }); + const queued = await readOutbox(outboxFile(file), key, id); + assert.equal(queued.version, 3); assert.equal(queued.baseSequence, 2); + assert.equal(undoQueued(board, queued.moves), null); + records.push(await record(third, 3)); + assert.equal((await replay(board, key, state, records[1])).error, undefined); + if (partialReapply) store.atomic(board, () => store.shout(board, ...fourth.args)); + // This is the actual failure cut: ordered prefix committed, sealed queue still describes the prior local rows. + assert.equal(appliedSequence(board), 3); + const receipt = engineReceipt(board, third.id); + return { board, link, key, id, checkpoint, records, posts, reads, errors, receipt, third, fourth, ordering }; +} + +for (const mode of ['ordered-only', 'partial-reapply', 'paged']) test(`interrupted rebuild restores local pending work without resending accepted moves (${mode}) [H16,H21]`, async t => { + const f = await fixture(t, { partialReapply: mode === 'partial-reapply' }); + if (mode === 'paged') { + const request = f.link.request; + f.link.request = async (...args) => ({ events: (await request(...args)).events.slice(0, 1) }); + } + await flushOutbox(f.link); + assert.deepEqual(f.posts, ['original-4'], 'only the genuinely unperformed move is sent'); + assert.deepEqual(engineReceipt(f.board, f.third.id), f.receipt, 'the original accepted outcome is unchanged'); + assert.equal(appliedSequence(f.board), 4); + assert.equal(await readOutbox(outboxFile(f.link.file), f.key, f.id), null); + assert.deepEqual(f.board.db.prepare('SELECT shout_text FROM shout ORDER BY shout_id').all().map(row => row.shout_text), ['original-2', 'original-3', 'original-4']); +}); + +for (const kind of ['gap', 'short', 'foreign-board', 'receipt-mismatch', 'engine-failure']) test(`checkpoint bridge refuses ${kind} without changing local board or queue [H16,H21]`, async t => { + const f = await fixture(t); + const originalRequest = f.link.request; + if (kind === 'gap') f.link.request = async (state, path) => path.endsWith('after=1') ? { events: [f.records[1]] } : originalRequest(state, path); + if (kind === 'short') { + let initial = true; + f.link.request = async (_state, path) => { if (initial) { initial = false; return { events: [f.records[1]] }; } + return { events: path.endsWith('after=1') ? [f.records[0]] : [] }; }; + } + if (kind === 'foreign-board') f.link.fetchCheckpoint = async () => { + const cp = structuredClone(f.checkpoint); cp.native.tables.board_meta.find(row => row.meta_key === 'board_id').meta_value = 'b'.repeat(32); return cp; + }; + if (kind === 'receipt-mismatch') f.link.advanceCheckpoint = async (...args) => { + const cp = await f.ordering.advanceCheckpoint(args[0], f.link.state, ...args.slice(1)); + cp.native.tables.board_meta.find(row => row.meta_key.startsWith('relay_receipt_') && row.meta_value.includes('original-3')).meta_value += ' '; + return cp; + }; + if (kind === 'engine-failure') { + const row = f.records[1]; + row.sealed = Buffer.from(await seal(f.key, Buffer.from(JSON.stringify({ ...f.third, engine: 100000 })), + { boardId: f.id, kind: row.kind, sequence: row.event_id })).toString('base64url'); + } + const native = exportBoard(f.board), queued = readFileSync(outboxFile(f.link.file)); + const codes = { gap: 'RELAY_RESPONSE', short: 'RELAY_OUTBOX', 'foreign-board': 'RELAY_SNAPSHOT', 'receipt-mismatch': 'RELAY_RECOVERY_MISMATCH', 'engine-failure': 'ENGINE_VERSION' }; + await assert.rejects(flushOutbox(f.link), error => error.code === codes[kind]); + assert.deepEqual(exportBoard(f.board), native, 'failed recovery does not publish a partial replica'); + assert.deepEqual(readFileSync(outboxFile(f.link.file)), queued, 'the original sealed outbox is retained byte for byte'); + assert.deepEqual(f.posts, []); +}); From be4ed014e1b3f1d37be3f5024bbf1891ab7a7a68 Mon Sep 17 00:00:00 2001 From: McHerpes Date: Fri, 13 Nov 2026 04:16:51 +0000 Subject: [PATCH 2/7] fix(relay): retain local lease clocks during reconstruction [H21,B4,B5] --- src/relay-outbox.js | 9 +++ test/relay-outbox-rebuild-recovery.test.js | 66 +++++++++++++++++++++- 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/src/relay-outbox.js b/src/relay-outbox.js index 2ccb2b4393..b1b4d1a4cf 100644 --- a/src/relay-outbox.js +++ b/src/relay-outbox.js @@ -471,8 +471,13 @@ async function reapply(link, outbox, entry) { const { move } = resolveMove(entry, outbox, { local: true }); entry.sequences = localRecords(root, rowCounters); const applied = await captureBoardChanges(() => localRecords(root, (board) => { + // Reconstitute the local history, not a new execution now: renewing old leases here strands later claims. + // This never sets a relay receipt or changes the timestamp used by the authoritative ordered engine. + const clock = board.clock; + board.clock = { now: () => new Date(entry.queuedAt) }; try { return store.atomic(board, () => store[move.operation](board, ...executableArgs(move, board))); } catch (error) { if (!(error instanceof Refused)) throw error; return null; } + finally { board.clock = clock; } })); entry.changes = encodeChanges(applied.changes); return applied.result; @@ -627,6 +632,10 @@ async function rebuild(link, key, pulled) { if (outbox.baseSequence !== pulled.baseSequence) return true; // Nothing new from the relay: the board already shows the base and every queued move on top. if (!pulled.checkpoint && !pulled.events.length && outbox.restored !== true) return true; + // Fail before undo/restore rather than inventing a new clock for unacknowledged local history. + if (outbox.moves.some(entry => typeof entry.queuedAt !== 'string' || !Number.isFinite(Date.parse(entry.queuedAt)))) { + throw new Refused('RELAY_OUTBOX', 'a queued move has no valid original time; keep the outbox and ask for help before rebuilding this board'); + } // Back to the relay's order: the relay's checkpoint, an older outbox's image, or the queued moves taken back. if (pulled.checkpoint) restoreBase(link, pulled.checkpoint.native, pulled.checkpoint.sequence, pulled.checkpoint.reconstructed === true); else if (outbox.base) restoreBase(link, outbox.base, outbox.baseSequence); diff --git a/test/relay-outbox-rebuild-recovery.test.js b/test/relay-outbox-rebuild-recovery.test.js index 5c6ee6921a..2f1a4a533a 100644 --- a/test/relay-outbox-rebuild-recovery.test.js +++ b/test/relay-outbox-rebuild-recovery.test.js @@ -10,12 +10,12 @@ import { applyRelayMove, appliedSequence, checkpointSequence, engineReceipt, pre import { exportBoard } from '../src/exchange.js'; import { storeBoardKey } from '../src/relay-key.js'; import { relayOrdering } from '../src/relay-ordering.js'; -import { flushOutbox, outboxFile, queueMove, readOutbox } from '../src/relay-outbox.js'; +import { flushOutbox, outboxFile, queueMove, readOutbox, writeOutbox } from '../src/relay-outbox.js'; import { undoQueued } from '../src/relay-outbox-undo.js'; import { seal, unseal } from '../src/seal.js'; /** Real SQLite, native changesets and sealed queue; the only remote is an in-process ordered fixture. */ -async function fixture(t, { partialReapply = false } = {}) { +async function fixture(t, { partialReapply = false, setup, pending } = {}) { const directory = mkdtempSync(join(tmpdir(), 'pullboard-rebuild-recovery-')); const names = ['PULLBOARD_HOME', 'PULLBOARD_MACHINE_HOME', 'PULLBOARD_RELAY_KEY', 'PULLBOARD_RELAY_TOKEN']; const prior = Object.fromEntries(names.map(name => [name, process.env[name]])); @@ -27,6 +27,7 @@ async function fixture(t, { partialReapply = false } = {}) { const board = store.openBoard(':memory:', { now: () => new Date('2026-10-24T00:00:00Z') }); t.after(() => { store.closeBoard(board); rmSync(directory, { recursive: true, force: true }); }); store.register(board, { lane: 'coordinator', path: directory, sessionDigest: 'a'.repeat(64) }); + const extra = setup?.(board, directory); checkpointSequence(board, 1); const id = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value; const key = randomBytes(32); @@ -69,6 +70,7 @@ async function fixture(t, { partialReapply = false } = {}) { const third = move(3), fourth = move(4); for (const next of [third, fourth]) await queueMove(link, { operation: next.operation, args: next.args, move: next, quiet: true, applyLocally: () => store.atomic(board, () => store.shout(board, ...next.args)) }); + await pending?.({ board, link, key, id, extra }); const queued = await readOutbox(outboxFile(file), key, id); assert.equal(queued.version, 3); assert.equal(queued.baseSequence, 2); assert.equal(undoQueued(board, queued.moves), null); @@ -78,7 +80,7 @@ async function fixture(t, { partialReapply = false } = {}) { // This is the actual failure cut: ordered prefix committed, sealed queue still describes the prior local rows. assert.equal(appliedSequence(board), 3); const receipt = engineReceipt(board, third.id); - return { board, link, key, id, checkpoint, records, posts, reads, errors, receipt, third, fourth, ordering }; + return { board, link, key, id, checkpoint, records, posts, reads, errors, receipt, third, fourth, ordering, extra }; } for (const mode of ['ordered-only', 'partial-reapply', 'paged']) test(`interrupted rebuild restores local pending work without resending accepted moves (${mode}) [H16,H21]`, async t => { @@ -124,3 +126,61 @@ for (const kind of ['gap', 'short', 'foreign-board', 'receipt-mismatch', 'engine assert.deepEqual(readFileSync(outboxFile(f.link.file)), queued, 'the original sealed outbox is retained byte for byte'); assert.deepEqual(f.posts, []); }); + +/** Rebuild two genuinely queued claims made after the preceding lease expired, with no relay send. */ +async function leaseFixture(t) { + const start = Date.parse('2026-10-24T00:00:00Z'); + t.mock.timers.enable({ apis: ['Date'], now: start }); + const f = await fixture(t, { + setup(board, directory) { + const actor = store.register(board, { lane: 'core', path: join(directory, 'builder'), route: 'mid' }); + const items = [1, 2].map(n => store.addItem(board, { by: 'coordinator', lane: 'core', title: `lease-${n}`, + criterion: 'a later claim must not renew an earlier lease', check: 'true', route: 'mid', + brief: 'Files: src/relay-outbox.js\nTest: preserves historical local lease expiry' })); + return { actor, items, leases: [], moves: [] }; + }, + async pending({ board, link, extra }) { + board.clock = store.systemClock; + for (const [index, item] of extra.items.entries()) { + t.mock.timers.setTime(start + 10_000 + index * 2_000); + const args = [item, { agentId: extra.actor, lane: 'core', leaseMs: 1_000, + freeze: found => ({ text: found.item_title, digest: `digest:${found.item_title}` }) }]; + const move = prepareEngineMove(board, 'claim', args, { id: `queued-claim-${index}`, actor: extra.actor }); + const result = await queueMove(link, { operation: 'claim', args, move, quiet: true, + applyLocally: () => store.claim(board, ...args) }); + extra.leases.push(result.leaseUntil); extra.moves.push(move); + } + t.mock.timers.setTime(start + 100_000); + }, + }); + f.link.postPending = async () => { throw Object.assign(new Error('qualification stops before transport'), { code: 'NO_SEND' }); }; + return f; +} + +test('local reconstitution preserves expired claim leases without changing authoritative replay time [H21,B4,B5,H16]', async t => { + const f = await leaseFixture(t); + await assert.rejects(flushOutbox(f.link), error => error.code === 'NO_SEND'); + const rows = f.extra.items.map(id => f.board.db.prepare('SELECT item_owner,item_lease_until FROM item WHERE item_id=?').get(id)); + assert.deepEqual(rows.map(row => row.item_owner), [f.extra.actor, f.extra.actor]); + assert.deepEqual(rows.map(row => row.item_lease_until), f.extra.leases, 'reconstitution is not a new lease renewal'); + assert.equal(f.board.clock, store.systemClock, 'the caller clock is restored'); + assert.deepEqual((await readOutbox(outboxFile(f.link.file), f.key, f.id)).moves.slice(-2).map(entry => entry.move), f.extra.moves); + assert.equal(engineReceipt(f.board, f.extra.moves[0].id), null, 'local reconstitution is not an ordered receipt'); + const at = new Date().toISOString(); + assert.equal(applyRelayMove(f.board, f.extra.moves[0], { sequence: 4, at, kind: 'move', + sender: { kind: 'agent', userId: 'fixture', agent: f.extra.actor } }).error, undefined); + assert.equal(applyRelayMove(f.board, f.extra.moves[1], { sequence: 5, at, kind: 'move', + sender: { kind: 'agent', userId: 'fixture', agent: f.extra.actor } }).error.code, 'ONE_CLAIM', 'real ordering still uses the relay time and records its conflict'); +}); + +test('missing queued clock refuses before changing a board or its sealed outbox [H21,B4]', async t => { + const f = await leaseFixture(t), file = outboxFile(f.link.file); + const outbox = await readOutbox(file, f.key, f.id); + delete outbox.moves.at(-1).queuedAt; + await writeOutbox(file, f.key, f.id, outbox); + const native = exportBoard(f.board), queued = readFileSync(file); + await assert.rejects(flushOutbox(f.link), error => error.code === 'RELAY_OUTBOX'); + assert.deepEqual(exportBoard(f.board), native); + assert.deepEqual(readFileSync(file), queued); + assert.deepEqual(f.posts, []); +}); From b2212a42def8f3f3fbf674e632fa6dbcef76deba Mon Sep 17 00:00:00 2001 From: McHerpes Date: Fri, 13 Nov 2026 09:04:12 +0000 Subject: [PATCH 3/7] fix(relay): preserve captured local fact references on rebuild [H21,B29,B31,N26] --- src/relay-outbox-undo.js | 38 +++++++++++ src/relay-outbox.js | 37 ++++++++++- test/relay-outbox-rebuild-recovery.test.js | 75 ++++++++++++++++++++++ 3 files changed, 148 insertions(+), 2 deletions(-) diff --git a/src/relay-outbox-undo.js b/src/relay-outbox-undo.js index cd4cea59d2..250e88a865 100644 --- a/src/relay-outbox-undo.js +++ b/src/relay-outbox-undo.js @@ -132,6 +132,44 @@ function keyValue(encoded) { /** Quote a SQLite identifier read from the changeset or its actual table schema. */ function identifier(name) { return `"${name.replaceAll('"', '""')}"`; } +/** + * Read the original inserted rows from a queued move's own changesets without applying them. + * Local reconstruction needs the identities already returned to callers, not newly generated fact ids. + * Schema checks use the same connection as reconstruction; malformed captures fail rather than guessing. + */ +export function capturedInserts(board, changes, wanted) { + const rows = []; + for (const change of changes ?? []) { + const bytes = Buffer.from(change, 'base64'); + let columns = 0, table = null, schema = null; + for (let at = 0; at < bytes.length;) { + const marker = bytes[at]; + if (marker === 0x54) { + const count = varint(bytes, at + 1); + columns = count.value; + const end = bytes.indexOf(0, count.next + columns); + if (!Number.isSafeInteger(columns) || columns < 1 || end < 0) throw new Error('incomplete captured table'); + table = bytes.subarray(count.next + columns, end).toString('utf8'); + schema = table === wanted ? board.db.prepare(`PRAGMA table_info(${identifier(table)})`).all() : null; + if (schema && (schema.length !== columns || schema.some((column, index) => Boolean(column.pk) !== Boolean(bytes[count.next + index])))) { + throw new Error(`captured schema differs for ${table}`); + } + at = end + 1; + continue; + } + if (!table || ![INSERT, UPDATE, DELETE].includes(marker)) throw new Error('invalid captured operation'); + const before = record(bytes, at + 2, columns); + if (marker === INSERT && schema) rows.push(Object.fromEntries(schema.map((column, index) => { + const decoded = keyValue(before.values[index]); + return [column.name, typeof decoded === 'bigint' && decoded <= BigInt(Number.MAX_SAFE_INTEGER) && decoded >= BigInt(Number.MIN_SAFE_INTEGER) ? Number(decoded) : decoded]; + }))); + at = marker === UPDATE ? record(bytes, before.next, columns).next : before.next; + if (at > bytes.length) throw new Error('incomplete captured row'); + } + } + return rows; +} + /** * Numeric REPLACE also replaces a conflicting INSERT, which undo must refuse. Check row existence first, * inside the same write transaction, so only changed UPDATE/DELETE values can reach that resolution. diff --git a/src/relay-outbox.js b/src/relay-outbox.js index b1b4d1a4cf..44f3c6a982 100644 --- a/src/relay-outbox.js +++ b/src/relay-outbox.js @@ -48,7 +48,7 @@ import { unseal, } from './seal.js'; import { captureBoardChanges } from './board-capture.js'; -import { undoQueued } from './relay-outbox-undo.js'; +import { capturedInserts, undoQueued } from './relay-outbox-undo.js'; import { stampCoordinatorHolder } from './coordinator-hold.js'; import { Refused } from './refused.js'; import { @@ -465,6 +465,38 @@ function encodeChanges(changes) { return changes.map((change) => Buffer.from(change).toString('base64')); } +/** + * Keep identities already returned by a successful local operation. Ordered engine replay derives different + * identities from the move; using those for local reconstruction breaks corrections still in this outbox. + * Read only the move's own native capture, never mint an alias or change the original sealed move payload. + */ +function localExecutableArgs(board, entry, move) { + const args = executableArgs(move, board); + if (!['appendFact', 'verify', 'answerDecision'].includes(move.operation) || !entry.changes?.length) return args; + const facts = capturedInserts(board, entry.changes, 'event').filter(row => row.event_kind === 'fact') + .map(row => ({ item: row.item_id, detail: JSON.parse(row.event_detail) })); + if (move.operation === 'appendFact') { + const originals = facts.filter(row => row.item === entry.move.args[0] && !row.detail.decision); + if (originals.length !== 1 || originals[0].detail.kind !== args[1].kind || originals[0].detail.text !== args[1].text) { + throw new Refused('RELAY_OUTBOX', 'a queued fact has no unambiguous original identity in its native capture; keep the outbox for recovery'); + } + args[1].factId = originals[0].detail.id; + } else if (facts.length) { + const seeds = facts.map(({ item, detail }) => { + const suffix = `-${detail.supersededBy ? 's' : 'i'}${item}`; + if (!detail.decision || typeof detail.id !== 'string' || !detail.id.endsWith(suffix)) { + throw new Refused('RELAY_OUTBOX', 'a queued decision has an unreadable implied-fact identity; keep the outbox for recovery'); + } + return detail.id.slice(0, -suffix.length); + }); + if (new Set(seeds).size !== 1 || !/^[A-Za-z0-9_-]{1,72}$/u.test(seeds[0])) { + throw new Refused('RELAY_OUTBOX', 'a queued decision has conflicting implied-fact identities; keep the outbox for recovery'); + } + args[1].impliesId = seeds[0]; + } + return args; +} + /** Make one queued move on this board again, recording its rows; null when the board now refuses it. */ async function reapply(link, outbox, entry) { const { root, localRecords } = link; @@ -473,9 +505,10 @@ async function reapply(link, outbox, entry) { const applied = await captureBoardChanges(() => localRecords(root, (board) => { // Reconstitute the local history, not a new execution now: renewing old leases here strands later claims. // This never sets a relay receipt or changes the timestamp used by the authoritative ordered engine. + const args = localExecutableArgs(board, entry, move); const clock = board.clock; board.clock = { now: () => new Date(entry.queuedAt) }; - try { return store.atomic(board, () => store[move.operation](board, ...executableArgs(move, board))); } + try { return store.atomic(board, () => store[move.operation](board, ...args)); } catch (error) { if (!(error instanceof Refused)) throw error; return null; } finally { board.clock = clock; } })); diff --git a/test/relay-outbox-rebuild-recovery.test.js b/test/relay-outbox-rebuild-recovery.test.js index 2f1a4a533a..bb8efc0a80 100644 --- a/test/relay-outbox-rebuild-recovery.test.js +++ b/test/relay-outbox-rebuild-recovery.test.js @@ -184,3 +184,78 @@ test('missing queued clock refuses before changing a board or its sealed outbox assert.deepEqual(readFileSync(file), queued); assert.deepEqual(f.posts, []); }); + +// Retained baseline RED: the correction disappeared after its original random fact id was replaced by move.id. +test('pending fact corrections retain their genuine original identity during rebuild [H21,B29,B30,B31]', async t => { + const f = await fixture(t, { + setup(board) { return { item: store.addItem(board, { by: 'coordinator', lane: 'coordinator', title: 'fact identity', criterion: 'preserve corrections' }) }; }, + async pending({ board, link, extra }) { + for (const index of [0, 1]) { + const args = [extra.item, { agentId: 'coordinator', kind: 'note', text: index ? 'correction' : 'original', + ...(index ? { supersedes: extra.originalId } : {}) }]; + const move = prepareEngineMove(board, 'appendFact', args, { id: `fact-move-${index}`, actor: 'coordinator' }); + await queueMove(link, { operation: 'appendFact', args, move, quiet: true, applyLocally: () => store.appendFact(board, ...args) }); + if (!index) extra.originalId = JSON.parse(board.db.prepare("SELECT event_detail FROM event WHERE event_kind='fact' ORDER BY event_id DESC LIMIT 1").get().event_detail).id; + } + extra.originalFacts = board.db.prepare("SELECT event_detail FROM event WHERE event_kind='fact' ORDER BY event_id").all().map(row => JSON.parse(row.event_detail)); + assert.equal(extra.originalFacts.length, 2, 'both original operations really succeeded'); + }, + }); + f.link.postPending = async () => { throw Object.assign(new Error('stop before send'), { code: 'NO_SEND' }); }; + await assert.rejects(flushOutbox(f.link), error => error.code === 'NO_SEND'); + const facts = f.board.db.prepare("SELECT event_detail FROM event WHERE event_kind='fact' ORDER BY event_id").all().map(row => JSON.parse(row.event_detail)); + assert.deepEqual(facts.map(row => ({ id: row.id, supersedes: row.supersedes })), f.extra.originalFacts.map(row => ({ id: row.id, supersedes: row.supersedes }))); +}); + +/** The meaningful identity/reference fields, not differences in provisional versus relay timestamps. */ +function referenceProjection(board) { + return { + events: board.db.prepare('SELECT event_id,event_by,event_kind,item_id,event_detail FROM event ORDER BY event_id').all(), + shouts: board.db.prepare('SELECT shout_id,shout_from,shout_to,shout_text,shout_decision,shout_answers FROM shout ORDER BY shout_id').all(), + activity: store.activityDeliveryState(board, 'web-1'), + }; +} + +test('fact and implied-fact identities preserve later decisions, supersession and activity event references on repeated rebuild [H21,B29,B31,N26]', async t => { + const f = await fixture(t, { + setup(board, directory) { + store.register(board, { lane: 'web', path: join(directory, 'web-1') }); + return { items: [1, 2].map(n => store.addItem(board, { by: 'coordinator', lane: 'coordinator', title: `references-${n}`, criterion: 'retain exact references' })) }; + }, + async pending({ board, link, key, id, extra }) { + let serial = 0; + /** Use the normal queued local operation, including its original generated ids. */ + const queued = async (operation, args, actor = 'coordinator') => { + const move = prepareEngineMove(board, operation, args, { id: `reference-move-${++serial}`, actor }); + return queueMove(link, { operation, args, move, quiet: true, applyLocally: () => store[operation](board, ...args) }); + }; + const [one, two] = extra.items; + const fact = await queued('appendFact', [one, { agentId: 'coordinator', kind: 'note', text: 'initial evidence', implies: [two] }]); + extra.originalFactId = fact.id; + await queued('appendFact', [one, { agentId: 'coordinator', kind: 'note', text: 'corrected evidence', supersedes: fact.id, implies: [two] }]); + let answer; + for (const index of [0, 1]) { + const ask = await queued('shout', [{ from: 'web-1', to: 'coordinator', text: `choose-${index}`, decision: true, lanes: ['web'] }], 'web-1'); + answer = await queued('answerDecision', [ask, { agentId: 'coordinator', text: `answer-${index}`, lanes: ['web'], implies: [two], ...(index ? { supersedes: answer } : {}) }]); + } + const answerEvent = store.events(board).findLast(row => row.event_kind === 'answer'); + const implied = JSON.parse(board.db.prepare("SELECT event_detail FROM event WHERE event_kind='fact' AND json_extract(event_detail,'$.decision.source')='answer' ORDER BY event_id LIMIT 1").get().event_detail); + await queued('appendFact', [two, { agentId: 'coordinator', kind: 'note', text: 'qualify implication', supersedes: implied.id }]); + const through = store.events(board).at(-1).event_id; + const interrupt = { id: `event:${answerEvent.event_id}`, eventId: answerEvent.event_id, reason: 'answered' }; + await queued('recordActivityDelivery', [{ agentId: 'web-1', through, observedThrough: through, digestThrough: through, interrupts: [interrupt] }], 'web-1'); + await queued('actOnActivity', [{ agentId: 'web-1', ids: [interrupt.id] }], 'web-1'); + extra.original = referenceProjection(board); + extra.originalMoves = (await readOutbox(outboxFile(link.file), key, id)).moves.slice(2).map(entry => entry.move); + }, + }); + f.link.postPending = async () => { throw Object.assign(new Error('stop before send'), { code: 'NO_SEND' }); }; + for (const round of [1, 2]) { + await assert.rejects(flushOutbox(f.link), error => error.code === 'NO_SEND'); + assert.deepEqual(referenceProjection(f.board), f.extra.original, `all original references retain their meaning after rebuild ${round}`); + const queued = await readOutbox(outboxFile(f.link.file), f.key, f.id); + assert.deepEqual(queued.moves.slice(1).map(entry => entry.move), f.extra.originalMoves, 'no queued payload is rewritten'); + assert.deepEqual(f.posts, [], 'no real relay attempt is made by this regression'); + } + assert.throws(() => store.appendFact(f.board, f.extra.items[0], { agentId: 'web-1', kind: 'note', text: 'unauthorized correction', supersedes: f.extra.originalFactId }), error => error.code === 'FACT_JUDGEMENT'); +}); From 7014434df48bcecb160ad8c19f698eb00547f74d Mon Sep 17 00:00:00 2001 From: McHerpes Date: Fri, 13 Nov 2026 10:27:21 +0000 Subject: [PATCH 4/7] fix(relay): preflight retained recovery inputs and reference shifts [H16,H21,B4,B30,B31] --- src/relay-outbox.js | 142 ++++++++++++++++----- test/relay-outbox-rebuild-recovery.test.js | 134 ++++++++++++++++++- 2 files changed, 239 insertions(+), 37 deletions(-) diff --git a/src/relay-outbox.js b/src/relay-outbox.js index 44f3c6a982..0a5ec42f25 100644 --- a/src/relay-outbox.js +++ b/src/relay-outbox.js @@ -466,48 +466,78 @@ function encodeChanges(changes) { } /** - * Keep identities already returned by a successful local operation. Ordered engine replay derives different - * identities from the move; using those for local reconstruction breaks corrections still in this outbox. - * Read only the move's own native capture, never mint an alias or change the original sealed move payload. + * Validate retained local inputs before any undo/restore, without executing a move or requiring its item to exist. + * The captures supply original identities and exactly derivable lease clocks, never replacement queued payloads. + * Other original intra-operation timestamps are not recoverable from queuedAt and remain a separate obligation. */ -function localExecutableArgs(board, entry, move) { - const args = executableArgs(move, board); - if (!['appendFact', 'verify', 'answerDecision'].includes(move.operation) || !entry.changes?.length) return args; - const facts = capturedInserts(board, entry.changes, 'event').filter(row => row.event_kind === 'fact') - .map(row => ({ item: row.item_id, detail: JSON.parse(row.event_detail) })); - if (move.operation === 'appendFact') { - const originals = facts.filter(row => row.item === entry.move.args[0] && !row.detail.decision); - if (originals.length !== 1 || originals[0].detail.kind !== args[1].kind || originals[0].detail.text !== args[1].text) { - throw new Refused('RELAY_OUTBOX', 'a queued fact has no unambiguous original identity in its native capture; keep the outbox for recovery'); +function retainedLocalInput(board, entry) { + const { move } = entry; + const input = { at: entry.queuedAt, identities: {} }; + if (typeof input.at !== 'string' || !Number.isFinite(Date.parse(input.at))) { + throw new Refused('RELAY_OUTBOX', 'a queued move has no valid original time; keep the outbox for recovery'); + } + let events; + try { events = capturedInserts(board, entry.changes, 'event').map(row => ({ ...row, detail: JSON.parse(row.event_detail) })); } + catch { throw new Refused('RELAY_OUTBOX', 'a queued move has an unreadable native capture; keep the original board and outbox for recovery'); } + if (entry.changes?.length && ['appendFact', 'verify', 'answerDecision'].includes(move.operation)) { + const facts = events.filter(row => row.event_kind === 'fact'); + if (move.operation === 'appendFact') { + const originals = facts.filter(row => row.item_id === move.args[0] && !row.detail.decision); + if (originals.length !== 1 || originals[0].detail.kind !== move.args[1]?.kind || originals[0].detail.text !== move.args[1]?.text || + typeof originals[0].detail.id !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/u.test(originals[0].detail.id)) { + throw new Refused('RELAY_OUTBOX', 'a queued fact has no unambiguous original identity in its native capture; keep the outbox for recovery'); + } + input.identities.factId = originals[0].detail.id; + } else if (facts.length) { + const seeds = facts.map(({ item_id: item, detail }) => { + const suffix = `-${detail.supersededBy ? 's' : 'i'}${item}`; + if (!detail.decision || typeof detail.id !== 'string' || !detail.id.endsWith(suffix)) { + throw new Refused('RELAY_OUTBOX', 'a queued decision has an unreadable implied-fact identity; keep the outbox for recovery'); + } + return detail.id.slice(0, -suffix.length); + }); + if (new Set(seeds).size !== 1 || !/^[A-Za-z0-9_-]{1,72}$/u.test(seeds[0])) { + throw new Refused('RELAY_OUTBOX', 'a queued decision has conflicting implied-fact identities; keep the outbox for recovery'); + } + input.identities.impliesId = seeds[0]; } - args[1].factId = originals[0].detail.id; - } else if (facts.length) { - const seeds = facts.map(({ item, detail }) => { - const suffix = `-${detail.supersededBy ? 's' : 'i'}${item}`; - if (!detail.decision || typeof detail.id !== 'string' || !detail.id.endsWith(suffix)) { - throw new Refused('RELAY_OUTBOX', 'a queued decision has an unreadable implied-fact identity; keep the outbox for recovery'); + } + if (['claim', 'reserveReview', 'reserveNextReview'].includes(move.operation)) { + const claim = move.operation === 'claim'; + const options = move.args[move.operation === 'reserveNextReview' ? 0 : 1]; + const leases = events.filter(row => (claim ? ['claim', 'renew'].includes(row.event_kind) : row.event_kind === 'reserve') && + (move.operation === 'reserveNextReview' || row.item_id === move.args[0])); + if (leases.length) { + const deadline = leases[0].detail[claim ? 'leaseUntil' : 'until']; + const at = Date.parse(deadline) - options?.leaseMs; + if (leases.length !== 1 || typeof options?.leaseMs !== 'number' || !Number.isFinite(options.leaseMs) || + typeof deadline !== 'string' || !Number.isFinite(at) || !Number.isFinite(new Date(at).getTime())) { + throw new Refused('RELAY_OUTBOX', 'a queued lease has no unambiguous original computation time; keep the outbox for recovery'); } - return detail.id.slice(0, -suffix.length); - }); - if (new Set(seeds).size !== 1 || !/^[A-Za-z0-9_-]{1,72}$/u.test(seeds[0])) { - throw new Refused('RELAY_OUTBOX', 'a queued decision has conflicting implied-fact identities; keep the outbox for recovery'); + input.at = new Date(at).toISOString(); } - args[1].impliesId = seeds[0]; } + return input; +} + +/** Use only prevalidated original identities in local reconstruction, never in the authoritative ordered engine. */ +function localExecutableArgs(board, move, input) { + const args = executableArgs(move, board); + if (Object.keys(input.identities).length) Object.assign(args[1], input.identities); return args; } /** Make one queued move on this board again, recording its rows; null when the board now refuses it. */ -async function reapply(link, outbox, entry) { +async function reapply(link, outbox, entry, input) { const { root, localRecords } = link; const { move } = resolveMove(entry, outbox, { local: true }); entry.sequences = localRecords(root, rowCounters); const applied = await captureBoardChanges(() => localRecords(root, (board) => { // Reconstitute the local history, not a new execution now: renewing old leases here strands later claims. // This never sets a relay receipt or changes the timestamp used by the authoritative ordered engine. - const args = localExecutableArgs(board, entry, move); + const args = localExecutableArgs(board, move, input); const clock = board.clock; - board.clock = { now: () => new Date(entry.queuedAt) }; + board.clock = { now: () => new Date(input.at) }; try { return store.atomic(board, () => store[move.operation](board, ...args)); } catch (error) { if (!(error instanceof Refused)) throw error; return null; } finally { board.clock = clock; } @@ -528,6 +558,8 @@ function takeBack(link, outbox) { return false; } return localRecords(root, (board) => { + // An interrupted round already advanced the ordered prefix. Its stale captures must not undo that prefix. + if (appliedSequence(board) !== outbox.baseSequence) return false; const cursors = board.db.prepare('SELECT agent_id, agent_last_shout_id FROM agent').all(); const problem = undoQueued(board, outbox.moves); if (problem) { @@ -549,6 +581,38 @@ function keepNewerCursors(board, cursors) { for (const row of cursors) if (Number.isSafeInteger(row.agent_last_shout_id)) keep.run(row.agent_last_shout_id, row.agent_id, row.agent_last_shout_id); } +/** Numeric shout/event references that the current wire contract does not bind to their producer move. */ +function positionalTables(entries) { + const tables = new Set(); + for (const { move } of entries) { + if (['answerDecision', 'passDecision'].includes(move.operation) || + move.operation === 'shout' && move.args[0]?.answers != null) tables.add('shout'); + if (['recordActivityDelivery', 'actOnActivity'].includes(move.operation)) tables.add('event'); + } + return tables; +} + +/** + * Refuse a demonstrated positional shift before replacing any native state. Equal counters are not a proof of + * complete reference fidelity: refused producers and other dependency changes still need their owning contract. + */ +function refuseShiftedReferences(outbox, checkpoint) { + const receipts = new Set(checkpoint.native.tables.board_meta.map(row => row.meta_key)); + const waiting = outbox.moves.filter(entry => !receipts.has('relay_receipt_' + entry.move.id)); + const tables = positionalTables(waiting); + if (!tables.size) return; + const before = waiting[0]?.sequences; + const current = checkpoint.native.tables.sqlite_sequence; + if (!Array.isArray(before) || !Array.isArray(current)) { + throw new Refused('RELAY_OUTBOX_REFERENCE', 'queued numeric references have no original row-counter boundary; keep the original board and queue for supported reference recovery'); + } + for (const table of tables) { + if ((before.find(row => row.name === table)?.seq ?? 0) !== (current.find(row => row.name === table)?.seq ?? 0)) { + throw new Refused('RELAY_OUTBOX_REFERENCE', `ordered ${table} positions differ from the original queued reference boundary; keep the original board and queue until their producer identities can be reconciled`); + } + } +} + /** * Read every record the relay ordered after the outbox's base image. Network only: the board is not touched. When * the relay compacted that prefix, its checkpoint stands in for the base. @@ -582,6 +646,10 @@ async function pullSinceBase(link, key, { fromCheckpoint = false } = {}) { checkpoint = await link.advanceCheckpoint(key, checkpoint, prefix, minimum); return { baseSequence: outbox.baseSequence, checkpoint, events: [] }; } + if (prefix.length && positionalTables(outbox.moves).size) { + checkpoint = await link.advanceCheckpoint(key, checkpoint, prefix, checkpoint.sequence); + return { baseSequence: outbox.baseSequence, checkpoint, events: [] }; + } return { baseSequence: outbox.baseSequence, checkpoint, events: prefix }; } try { return { baseSequence: outbox.baseSequence, events: await events(outbox.baseSequence) }; } @@ -665,9 +733,12 @@ async function rebuild(link, key, pulled) { if (outbox.baseSequence !== pulled.baseSequence) return true; // Nothing new from the relay: the board already shows the base and every queued move on top. if (!pulled.checkpoint && !pulled.events.length && outbox.restored !== true) return true; - // Fail before undo/restore rather than inventing a new clock for unacknowledged local history. - if (outbox.moves.some(entry => typeof entry.queuedAt !== 'string' || !Number.isFinite(Date.parse(entry.queuedAt)))) { - throw new Refused('RELAY_OUTBOX', 'a queued move has no valid original time; keep the outbox and ask for help before rebuilding this board'); + // Preflight the complete retained capture before the first mutation, not halfway through local reconstruction. + const inputs = localRecords(root, board => new Map(outbox.moves.map(entry => [entry.move.id, retainedLocalInput(board, entry)]))); + if (positionalTables(outbox.moves).size) { + // Inspect a fully materialized ordered prefix before undo/restore, never after publishing shifted rows. + if (!pulled.checkpoint || pulled.events.length) return 'checkpoint'; + refuseShiftedReferences(outbox, pulled.checkpoint); } // Back to the relay's order: the relay's checkpoint, an older outbox's image, or the queued moves taken back. if (pulled.checkpoint) restoreBase(link, pulled.checkpoint.native, pulled.checkpoint.sequence, pulled.checkpoint.reconstructed === true); @@ -707,7 +778,7 @@ async function rebuild(link, key, pulled) { return false; } for (const entry of outbox.moves) { - const result = await reapply(link, outbox, entry); + const result = await reapply(link, outbox, entry, inputs.get(entry.move.id)); // A re-applied add may get another number here; later moves reach it through their bound add, not the number. const shown = entryCreatedItems(entry); rememberCreatedItems(entry, result); @@ -729,6 +800,17 @@ async function rebuild(link, key, pulled) { async function sendQueued(link, key) { const { root, file, state, io, localRecords, sealedRecord } = link; const outbox = await readOutbox(outboxFile(file), key, state.board); + // A locally returned legacy UUID absent from the sealed move cannot be reconstructed by another replica. + // Stop before even the first POST; preserve this whole ordered chain until its identity contract can express it. + localRecords(root, board => { + for (const entry of outbox?.moves ?? []) { + if (engineReceipt(board, entry.move.id)) continue; + const { identities } = retainedLocalInput(board, entry); + if (Object.values(identities).some(id => id !== entry.move.id)) { + throw new Refused('RELAY_OUTBOX_IDENTITY', 'a queued move has original fact identities missing from its sealed payload; keep the original queue and native captures for supported identity recovery before sending'); + } + } + }); let sent = 0; for (const entry of outbox?.moves ?? []) { if ((entry.refs ?? []).some((ref) => outbox.moves.some((other) => other.move.id === ref.add))) break; diff --git a/test/relay-outbox-rebuild-recovery.test.js b/test/relay-outbox-rebuild-recovery.test.js index bb8efc0a80..8e64f644ed 100644 --- a/test/relay-outbox-rebuild-recovery.test.js +++ b/test/relay-outbox-rebuild-recovery.test.js @@ -45,8 +45,8 @@ async function fixture(t, { partialReapply = false, setup, pending } = {}) { } /** Preserve the exact move bytes and original sequence on the synthetic relay. */ async function record(move, sequence) { - return { event_id: sequence, event_at: `2026-10-24T00:00:0${sequence}Z`, kind: 'move', - sender: { kind: 'agent', userId: 'fixture', agent: 'coordinator' }, + return { event_id: sequence, event_at: new Date(Date.parse('2026-10-24T00:00:00Z') + sequence * 1000).toISOString(), kind: 'move', + sender: { kind: 'agent', userId: 'fixture', agent: move.actor }, sealed: Buffer.from(await seal(key, Buffer.from(JSON.stringify(move)), { boardId: id, kind: 'move', sequence })).toString('base64url') }; } /** Make a normal native shout without test-only SQL mutations. */ @@ -80,7 +80,7 @@ async function fixture(t, { partialReapply = false, setup, pending } = {}) { // This is the actual failure cut: ordered prefix committed, sealed queue still describes the prior local rows. assert.equal(appliedSequence(board), 3); const receipt = engineReceipt(board, third.id); - return { board, link, key, id, checkpoint, records, posts, reads, errors, receipt, third, fourth, ordering, extra }; + return { board, link, key, id, checkpoint, records, posts, reads, errors, receipt, third, fourth, ordering, extra, record }; } for (const mode of ['ordered-only', 'partial-reapply', 'paged']) test(`interrupted rebuild restores local pending work without resending accepted moves (${mode}) [H16,H21]`, async t => { @@ -128,7 +128,7 @@ for (const kind of ['gap', 'short', 'foreign-board', 'receipt-mismatch', 'engine }); /** Rebuild two genuinely queued claims made after the preceding lease expired, with no relay send. */ -async function leaseFixture(t) { +async function leaseFixture(t, applicationDelay = 0) { const start = Date.parse('2026-10-24T00:00:00Z'); t.mock.timers.enable({ apis: ['Date'], now: start }); const f = await fixture(t, { @@ -147,7 +147,7 @@ async function leaseFixture(t) { freeze: found => ({ text: found.item_title, digest: `digest:${found.item_title}` }) }]; const move = prepareEngineMove(board, 'claim', args, { id: `queued-claim-${index}`, actor: extra.actor }); const result = await queueMove(link, { operation: 'claim', args, move, quiet: true, - applyLocally: () => store.claim(board, ...args) }); + applyLocally: () => { t.mock.timers.setTime(start + 10_000 + index * 2_000 + applicationDelay); return store.claim(board, ...args); } }); extra.leases.push(result.leaseUntil); extra.moves.push(move); } t.mock.timers.setTime(start + 100_000); @@ -202,7 +202,7 @@ test('pending fact corrections retain their genuine original identity during reb }, }); f.link.postPending = async () => { throw Object.assign(new Error('stop before send'), { code: 'NO_SEND' }); }; - await assert.rejects(flushOutbox(f.link), error => error.code === 'NO_SEND'); + await assert.rejects(flushOutbox(f.link), error => error.code === 'RELAY_OUTBOX_IDENTITY'); const facts = f.board.db.prepare("SELECT event_detail FROM event WHERE event_kind='fact' ORDER BY event_id").all().map(row => JSON.parse(row.event_detail)); assert.deepEqual(facts.map(row => ({ id: row.id, supersedes: row.supersedes })), f.extra.originalFacts.map(row => ({ id: row.id, supersedes: row.supersedes }))); }); @@ -251,7 +251,7 @@ test('fact and implied-fact identities preserve later decisions, supersession an }); f.link.postPending = async () => { throw Object.assign(new Error('stop before send'), { code: 'NO_SEND' }); }; for (const round of [1, 2]) { - await assert.rejects(flushOutbox(f.link), error => error.code === 'NO_SEND'); + await assert.rejects(flushOutbox(f.link), error => error.code === 'RELAY_OUTBOX_IDENTITY'); assert.deepEqual(referenceProjection(f.board), f.extra.original, `all original references retain their meaning after rebuild ${round}`); const queued = await readOutbox(outboxFile(f.link.file), f.key, f.id); assert.deepEqual(queued.moves.slice(1).map(entry => entry.move), f.extra.originalMoves, 'no queued payload is rewritten'); @@ -259,3 +259,123 @@ test('fact and implied-fact identities preserve later decisions, supersession an } assert.throws(() => store.appendFact(f.board, f.extra.items[0], { agentId: 'web-1', kind: 'note', text: 'unauthorized correction', supersedes: f.extra.originalFactId }), error => error.code === 'FACT_JUDGEMENT'); }); + +// Independent review regressions: preserve the failing baseline, not just the successful recovery cut. +test('review partial-reapply bridge failure leaves the original board and queue unchanged [H16,H21]', async t => { + const f = await fixture(t, { partialReapply: true }); + f.link.fetchCheckpoint = async () => { throw Object.assign(new Error('checkpoint unavailable'), { code: 'OFFLINE' }); }; + const native = exportBoard(f.board), queued = readFileSync(outboxFile(f.link.file)); + await assert.rejects(flushOutbox(f.link), error => error.code === 'OFFLINE'); + assert.deepEqual(exportBoard(f.board), native, 'do not undo an already-advanced prefix before failed recovery'); + assert.deepEqual(readFileSync(outboxFile(f.link.file)), queued); + assert.deepEqual(f.posts, []); +}); + +test('review delayed local application retains exact original claim deadlines [H21,B4,B5]', async t => { + const f = await leaseFixture(t, 125); + await assert.rejects(flushOutbox(f.link), error => error.code === 'NO_SEND'); + const actual = f.extra.items.map(id => f.board.db.prepare('SELECT item_lease_until FROM item WHERE item_id=?').get(id).item_lease_until); + assert.deepEqual(actual, f.extra.leases, 'queue persistence time is not the original lease-computation time'); + assert.equal(f.board.clock, store.systemClock); + assert.deepEqual(f.posts, []); +}); + +/** Two original fact captures, optionally using ids already representable by the sealed ordered moves. */ +async function deliveryFactFixture(t, compatible = false) { + return fixture(t, { + setup(board) { return { item: store.addItem(board, { by: 'coordinator', lane: 'coordinator', title: 'retained facts', criterion: 'retain exact fact identities' }) }; }, + async pending({ board, link, extra }) { + extra.moves = []; extra.ids = []; + for (const index of [0, 1]) { + const args = [extra.item, { agentId: 'coordinator', kind: 'note', text: `retained fact ${index}`, ...(index ? { supersedes: extra.ids[0] } : {}) }]; + const move = prepareEngineMove(board, 'appendFact', args, { id: `retained-fact-${index}`, actor: 'coordinator' }); + if (compatible) args[1].factId = move.id; + const fact = await queueMove(link, { operation: 'appendFact', args, move, quiet: true, applyLocally: () => store.appendFact(board, ...args) }); + extra.moves.push(move); extra.ids.push(fact.id); + } + }, + }); +} + +for (const mode of ['malformed', 'ambiguous']) test(`review ${mode} identity capture refuses before any restore or undo [H21,B30]`, async t => { + const f = await deliveryFactFixture(t), file = outboxFile(f.link.file); + const outbox = await readOutbox(file, f.key, f.id); + outbox.moves.at(-1).changes = mode === 'malformed' ? ['AA=='] : outbox.moves.at(-2).changes; + await writeOutbox(file, f.key, f.id, outbox); + const native = exportBoard(f.board), queued = readFileSync(file); + let refusal; try { await flushOutbox(f.link); } catch (error) { refusal = error; } + assert.ok(refusal, 'invalid original identity capture must refuse'); + assert.deepEqual(exportBoard(f.board), native, 'capture validation precedes every restore and local replay'); + assert.deepEqual(readFileSync(file), queued); + assert.equal(refusal.code, 'RELAY_OUTBOX'); + assert.deepEqual(f.posts, []); +}); + +test('review unrepresentable legacy fact identities stop before the first ordered send [H16,H21,B30,B31]', async t => { + const f = await deliveryFactFixture(t); + await assert.rejects(flushOutbox(f.link), error => error.code === 'RELAY_OUTBOX_IDENTITY'); + assert.deepEqual(f.posts, [], 'do not partially drain ahead of the known unrepresentable dependency'); + for (const move of f.extra.moves) assert.equal(engineReceipt(f.board, move.id), null); + const queued = await readOutbox(outboxFile(f.link.file), f.key, f.id); + assert.deepEqual(queued.moves.slice(-2).map(e => e.move), f.extra.moves, 'do not rewrite or remint the original moves'); + const facts = store.events(f.board).filter(e => e.event_kind === 'fact').map(e => JSON.parse(e.event_detail)); + assert.deepEqual(facts.map(fact => fact.id), f.extra.ids); +}); + +test('review representable original facts still deliver and retain both successful receipts [H16,H21,B30,B31]', async t => { + const f = await deliveryFactFixture(t, true); + await flushOutbox(f.link); + for (const move of f.extra.moves) { + const receipt = engineReceipt(f.board, move.id); + assert.ok(receipt); assert.equal(receipt.outcome.error, undefined); + } + assert.equal(await readOutbox(outboxFile(f.link.file), f.key, f.id), null); + const facts = store.events(f.board).filter(e => e.event_kind === 'fact').map(e => JSON.parse(e.event_detail)); + assert.deepEqual(facts.map(fact => fact.id), f.extra.ids); +}); + +/** Original numeric references, without fact IDs that would independently hold transport. */ +async function positionalFixture(t, kind) { + return fixture(t, { + setup(board, directory) { store.register(board, { lane: 'web', path: join(directory, 'web-1') }); return { moves: [] }; }, + async pending({ board, link, extra }) { + const queued = async (operation, args, actor) => { + const move = prepareEngineMove(board, operation, args, { id: `positional-${extra.moves.length}`, actor }); + extra.moves.push(move); + return queueMove(link, { operation, args, move, quiet: true, applyLocally: () => store[operation](board, ...args) }); + }; + if (kind === 'shout') { + const question = await queued('shout', [{ from: 'web-1', to: 'coordinator', text: 'original question', decision: true, lanes: ['web'] }], 'web-1'); + extra.answer = await queued('answerDecision', [question, { agentId: 'coordinator', text: 'original answer', lanes: ['web'] }], 'coordinator'); + } else { + const through = store.events(board).at(-1).event_id; + await queued('recordActivityDelivery', [{ agentId: 'web-1', through, observedThrough: through, digestThrough: through, interrupts: [] }], 'web-1'); + } + extra.original = referenceProjection(board); + }, + }); +} + +for (const kind of ['shout', 'event']) test(`review positional ${kind} shift refuses before changing the board or queue [H16,H21,B27,N26]`, async t => { + const f = await positionalFixture(t, kind); + const extra = prepareEngineMove(f.board, 'shout', [{ from: 'coordinator', to: 'all', text: 'another ordered message', lanes: [] }], { id: 'extra-ordered', actor: 'coordinator' }); + f.records.push(await f.record(extra, 4)); + const native = exportBoard(f.board), queued = readFileSync(outboxFile(f.link.file)); + let refusal; try { await flushOutbox(f.link); } catch (error) { refusal = error; } + assert.ok(refusal, 'shifted numeric references cannot silently name different records'); + assert.deepEqual(exportBoard(f.board), native, 'detect the shift before publishing any replacement state'); + assert.deepEqual(readFileSync(outboxFile(f.link.file)), queued); + assert.equal(refusal.code, 'RELAY_OUTBOX_REFERENCE'); + assert.deepEqual(f.posts, []); +}); + +for (const kind of ['shout', 'event']) test(`review unshifted positional ${kind} references retain meaning and deliver [H16,H21,B27,N26]`, async t => { + const f = await positionalFixture(t, kind); + await flushOutbox(f.link); + assert.deepEqual(referenceProjection(f.board), f.extra.original); + for (const move of f.extra.moves) { + const receipt = engineReceipt(f.board, move.id); + assert.ok(receipt); assert.equal(receipt.outcome.error, undefined); + } + assert.equal(await readOutbox(outboxFile(f.link.file), f.key, f.id), null); +}); From 01f68f779d28d37cd160d12b0777048e0ca7b8d7 Mon Sep 17 00:00:00 2001 From: McHerpes Date: Fri, 13 Nov 2026 11:17:45 +0000 Subject: [PATCH 5/7] fix(relay): retain identity veto across refused replay [H16,H21,B30,B31] --- src/relay-outbox.js | 24 ++++-- test/relay-outbox-rebuild-recovery.test.js | 97 +++++++++++++++++++++- 2 files changed, 115 insertions(+), 6 deletions(-) diff --git a/src/relay-outbox.js b/src/relay-outbox.js index 0a5ec42f25..0d4f57fc99 100644 --- a/src/relay-outbox.js +++ b/src/relay-outbox.js @@ -51,6 +51,7 @@ import { captureBoardChanges } from './board-capture.js'; import { capturedInserts, undoQueued } from './relay-outbox-undo.js'; import { stampCoordinatorHolder } from './coordinator-hold.js'; import { Refused } from './refused.js'; +import { impliesSeed } from './implies.js'; import { outboxFile, outboxSummaryFile, @@ -520,6 +521,15 @@ function retainedLocalInput(board, entry) { return input; } +/** Refuse original identities the authoritative move cannot reproduce, using its canonical implied-seed rule. */ +function refuseUnrepresentedIdentities(move, { identities }) { + if ((identities.factId !== undefined && identities.factId !== move.id) || + (identities.impliesId !== undefined && (typeof move.id !== 'string' || !/^[A-Za-z0-9_-]{1,80}$/u.test(move.id) || + identities.impliesId !== impliesSeed(move.id)))) { + throw new Refused('RELAY_OUTBOX_IDENTITY', 'a queued move has original fact identities missing from its sealed payload; keep the original queue and native captures for supported identity recovery before sending'); + } +} + /** Use only prevalidated original identities in local reconstruction, never in the authoritative ordered engine. */ function localExecutableArgs(board, move, input) { const args = executableArgs(move, board); @@ -539,7 +549,14 @@ async function reapply(link, outbox, entry, input) { const clock = board.clock; board.clock = { now: () => new Date(input.at) }; try { return store.atomic(board, () => store[move.operation](board, ...args)); } - catch (error) { if (!(error instanceof Refused)) throw error; return null; } + catch (error) { + if (!(error instanceof Refused)) throw error; + // A refused operation captures no rows. Do not erase the only retained identity evidence and then send + // the legacy chain on this or a later process's attempt. Throw before replacing/persisting any captures; + // the original sealed outbox remains the recovery input even if this rebuild advanced the local prefix. + refuseUnrepresentedIdentities(entry.move, input); + return null; + } finally { board.clock = clock; } })); entry.changes = encodeChanges(applied.changes); @@ -805,10 +822,7 @@ async function sendQueued(link, key) { localRecords(root, board => { for (const entry of outbox?.moves ?? []) { if (engineReceipt(board, entry.move.id)) continue; - const { identities } = retainedLocalInput(board, entry); - if (Object.values(identities).some(id => id !== entry.move.id)) { - throw new Refused('RELAY_OUTBOX_IDENTITY', 'a queued move has original fact identities missing from its sealed payload; keep the original queue and native captures for supported identity recovery before sending'); - } + refuseUnrepresentedIdentities(entry.move, retainedLocalInput(board, entry)); } }); let sent = 0; diff --git a/test/relay-outbox-rebuild-recovery.test.js b/test/relay-outbox-rebuild-recovery.test.js index 8e64f644ed..aba001816f 100644 --- a/test/relay-outbox-rebuild-recovery.test.js +++ b/test/relay-outbox-rebuild-recovery.test.js @@ -7,7 +7,9 @@ import { join } from 'node:path'; import test from 'node:test'; import * as store from '../src/board.js'; import { applyRelayMove, appliedSequence, checkpointSequence, engineReceipt, prepareEngineMove } from '../src/engine.js'; -import { exportBoard } from '../src/exchange.js'; +import { exportBoard, importBoard } from '../src/exchange.js'; +import { impliesSeed } from '../src/implies.js'; +import { submitFixture } from './board-submit-fixture.js'; import { storeBoardKey } from '../src/relay-key.js'; import { relayOrdering } from '../src/relay-ordering.js'; import { flushOutbox, outboxFile, queueMove, readOutbox, writeOutbox } from '../src/relay-outbox.js'; @@ -369,6 +371,99 @@ for (const kind of ['shout', 'event']) test(`review positional ${kind} shift ref assert.deepEqual(f.posts, []); }); +/** A formerly successful implied verdict is refused locally, but would succeed at the later ordered clock. */ +test('review2 refused legacy reapply retains its transport veto across persisted retries [H16,H21,B30,B31]', async t => { + const start = Date.parse('2026-10-24T00:00:00Z'); + t.mock.timers.enable({ apis: ['Date'], now: start + 5_000 }); + const f = await fixture(t, { + setup(board, directory) { + const [builder, reviewer, blocker] = [1, 2, 3].map(n => { + const seat = store.register(board, { lane: 'core', path: join(directory, `review-${n}`), route: 'mid', createdBy: 'coordinator' }); + // Synthetic prior enrollment, as in relay-client.test.js: not a live credential or approval. + board.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run(`agent_enrolled:${seat}`, 'coordinator'); + return seat; + }); + const item = store.addItem(board, { by: 'coordinator', lane: 'core', title: 'reviewed source', criterion: 'synthetic source', route: 'mid', + check: 'true', brief: 'Files: src/relay-outbox.js\nTest: retained refusal identity' }); + const target = store.addItem(board, { by: 'coordinator', lane: 'coordinator', title: 'implication', criterion: 'retain correction' }); + const text = JSON.stringify({ policy: { version: 1, commit: 'a'.repeat(40), verify: { policy: 'any', family: 'off' } } }); + store.claim(board, item, { agentId: builder, lane: 'core', leaseMs: 60_000, freeze: () => ({ text, digest: 'fixture-digest' }) }); + submitFixture(board, item, { agentId: builder, commit: 'a'.repeat(40), tree: 'b'.repeat(40) }); + return { item, target, reviewer, blocker }; + }, + async pending({ board, link, extra }) { + board.clock = store.systemClock; + const args = [extra.item, { agentId: extra.reviewer, decision: 'REJECT', reason: 'TEST_FAILURE', note: 'synthetic original verdict', + head: 'a'.repeat(40), digest: 'fixture-digest', policy: 'any', implies: [extra.target] }]; + extra.verdict = prepareEngineMove(board, 'verify', args, { id: 'legacy-verdict', actor: extra.reviewer }); + await queueMove(link, { operation: 'verify', args, move: extra.verdict, quiet: true, applyLocally: () => store.verify(board, ...args) }); + const fact = store.events(board).filter(e => e.event_kind === 'fact').at(-1); + extra.originalId = JSON.parse(fact.event_detail).id; + const correction = [extra.target, { agentId: 'coordinator', kind: 'note', text: 'original correction', supersedes: extra.originalId }]; + extra.correction = prepareEngineMove(board, 'appendFact', correction, { id: 'legacy-correction', actor: 'coordinator' }); + correction[1].factId = extra.correction.id; + await queueMove(link, { operation: 'appendFact', args: correction, move: extra.correction, quiet: true, applyLocally: () => store.appendFact(board, ...correction) }); + }, + }); + const reservation = prepareEngineMove(f.board, 'reserveReview', [f.extra.item, { agentId: f.extra.blocker, leaseMs: 2_000, policy: 'any' }], + { id: 'intervening-reservation', actor: f.extra.blocker }); + f.records.push(await f.record(reservation, 4)); + const cp = await f.ordering.advanceCheckpoint(f.key, f.link.state, f.checkpoint, f.records, 4); + for (const [elapsed, expected] of [[5_000, 'REVIEW_HELD'], [7_000, undefined]]) { + const copy = store.openBoard(':memory:'); + try { + importBoard(copy, cp.native); + const at = new Date(start + elapsed).toISOString(); + const outcome = applyRelayMove(copy, f.extra.verdict, { sequence: 5, at, kind: 'move', sender: { kind: 'agent', userId: 'fixture', agent: f.extra.reviewer } }); + assert.equal(outcome.error?.code, expected, 'the authentic reservation distinguishes local refusal from later ordered success'); + if (!expected) { + const correction = applyRelayMove(copy, f.extra.correction, { sequence: 6, at, kind: 'move', sender: { kind: 'agent', userId: 'fixture', agent: 'coordinator' } }); + assert.equal(correction.error?.code, 'NO_FACT', 'sending would lose the original correction'); + } + } finally { store.closeBoard(copy); } + } + const original = readFileSync(outboxFile(f.link.file)); + const queued = await readOutbox(outboxFile(f.link.file), f.key, f.id); + for (const attempt of [1, 2]) { + // A fresh link/state still reads the sealed original; no process-local veto may be required. + const link = { ...f.link, state: structuredClone(f.link.state) }; + let refusal; try { await flushOutbox(link); } catch (error) { refusal = error; } + assert.deepEqual(f.posts, [], `attempt ${attempt} must not send even the earlier unrelated queued move`); + assert.equal(refusal?.code, 'RELAY_OUTBOX_IDENTITY'); + assert.deepEqual(readFileSync(outboxFile(f.link.file)), original, 'the refused replay must not replace its only identity evidence with empty captures'); + assert.deepEqual((await readOutbox(outboxFile(f.link.file), f.key, f.id)).moves, queued.moves); + assert.equal(engineReceipt(f.board, f.extra.verdict.id), null); + t.mock.timers.setTime(start + 20_000); + } +}); + +for (const length of [73, 80]) test(`review2 canonical ${length}-character implied move seed remains deliverable [H16,H21,B31]`, async t => { + const f = await fixture(t, { + setup(board, directory) { + store.register(board, { lane: 'web', path: join(directory, 'web-1') }); + const target = store.addItem(board, { by: 'coordinator', lane: 'coordinator', title: 'long implied identity', criterion: 'canonical seed' }); + const question = store.shout(board, { from: 'web-1', to: 'coordinator', text: 'original stable question', decision: true, lanes: ['web'] }); + return { target, question }; + }, + async pending({ board, link, extra }) { + const id = 'v'.repeat(length); + const args = [extra.question, { agentId: 'coordinator', text: 'canonical long answer', lanes: ['web'], implies: [extra.target] }]; + extra.move = prepareEngineMove(board, 'answerDecision', args, { id, actor: 'coordinator' }); + args[1].impliesId = id; + await queueMove(link, { operation: 'answerDecision', args, move: extra.move, quiet: true, applyLocally: () => store.answerDecision(board, ...args) }); + extra.originalId = JSON.parse(store.events(board).filter(e => e.event_kind === 'fact').at(-1).event_detail).id; + assert.equal(extra.originalId, `${impliesSeed(id)}-i${extra.target}`); + }, + }); + await flushOutbox(f.link); + assert.deepEqual(f.posts, [f.fourth.id, f.extra.move.id]); + assert.equal(engineReceipt(f.board, f.extra.move.id)?.outcome.error, undefined); + assert.ok(engineReceipt(f.board, f.extra.move.id), 'the canonical implied answer really reached ordered application'); + const facts = store.events(f.board).filter(e => e.event_kind === 'fact').map(e => JSON.parse(e.event_detail)); + assert.deepEqual(facts.map(fact => fact.id), [f.extra.originalId]); + assert.equal(await readOutbox(outboxFile(f.link.file), f.key, f.id), null); +}); + for (const kind of ['shout', 'event']) test(`review unshifted positional ${kind} references retain meaning and deliver [H16,H21,B27,N26]`, async t => { const f = await positionalFixture(t, kind); await flushOutbox(f.link); From dcc92fa28142ed3a2907a700e3216d3077d2d9b7 Mon Sep 17 00:00:00 2001 From: McHerpes Date: Fri, 13 Nov 2026 21:02:01 +0000 Subject: [PATCH 6/7] feat(relay): recover an explicitly abandoned unpublished queue [H16,H21] --- src/relay-local-recovery.js | 132 +++++++++++++++++++++ src/relay.js | 16 +++ test/relay-outbox-rebuild-recovery.test.js | 95 ++++++++++++++- 3 files changed, 241 insertions(+), 2 deletions(-) create mode 100644 src/relay-local-recovery.js diff --git a/src/relay-local-recovery.js b/src/relay-local-recovery.js new file mode 100644 index 0000000000..494d3bf33e --- /dev/null +++ b/src/relay-local-recovery.js @@ -0,0 +1,132 @@ +/** Explicit operator-selected loss of unpublished local moves, not fabricated relay refusals [H16,H21]. */ +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { appliedSequence } from './engine.js'; +import { exportBoard, restoreRelaySnapshot, semanticBoardDigest } from './exchange.js'; +import { outboxFile, readOutbox } from './relay-outbox.js'; +import { withOutboxGuard } from './relay-outbox-guard.js'; +import { readBoardKey } from './relay-key.js'; +import { Refused } from './refused.js'; + +const digest = bytes => createHash('sha256').update(bytes).digest('hex'); +const refusal = text => new Refused('RELAY_LOCAL_RECOVERY', text); +const nativeDigest = board => semanticBoardDigest(exportBoard(board)); + +/** Preserve every existing ordered outcome exactly; loss permission applies only to local unpublished work. */ +function preservesReceipts(before, after) { + const meta = new Map(after.tables.board_meta.map(row => [row.meta_key, row.meta_value])); + if (before.tables.board_meta.some(row => /^relay_(receipt|refusal)_/u.test(row.meta_key) && meta.get(row.meta_key) !== row.meta_value)) { + throw refusal('the authenticated prefix disagrees with an existing receipt; no local recovery was applied'); + } +} + +/** + * Caller holds the ordinary relay lock and has quiesced native writers, checkpoint publishers and old callers. + * The exact queue digest is the loss selection, not an authentication credential. Only the existing machine's + * authenticated relay prefix is adopted. No POST/PUT, queued operation, person event or invented refusal is made. + * A durable existing recovery hold fences ordinary traffic across each local crash cut; retry the same selection. + * io.recoveryCut is an injectable fixture cut, never an alternate persistence or authority path. + */ +export async function discardUnpublished(link, { queueSha256, decision }) { + const { root, file, state, io, localRecords, saveLink, loadLink } = link; + if (!/^[0-9a-f]{64}$/u.test(queueSha256 ?? '') || typeof decision !== 'string' || !decision.trim() || decision.length > 2000) { + throw refusal('supply the exact inspected queue SHA-256 and attributable loss decision'); + } + if (state.mode !== 'ordered' || state.unlinking || state.environment || state.baselineAccepted === false) { + throw refusal('recover only an existing accepted machine-owned ordered board'); + } + const directory = join(dirname(file), 'local-recovery', queueSha256); + const queueFile = outboxFile(file), archive = join(directory, 'outbox.sealed'); + const planFile = join(directory, 'plan.json'); + const key = readBoardKey(state.board); + if (!state.recovery && state.localRecovery?.kind === 'discard-unpublished' && state.localRecovery.queueSha256 === queueSha256 && state.localRecovery.decision === decision) { + if (!existsSync(archive) || digest(readFileSync(archive)) !== queueSha256 || digest(readFileSync(planFile)) !== state.localRecovery.planSha256) { + throw refusal('the completed recovery custody changed; do not repeat the reset'); + } + return { board: state.board, sequence: state.localRecovery.sequence, queueSha256, alreadyCompleted: true, archive, plan: planFile, + disposition: 'read back the original recovery completion; later native work was not reset' }; + } + let marker = state.recovery; + if (marker && (marker.kind !== 'discard-unpublished' || marker.queueSha256 !== queueSha256 || marker.decision !== decision)) { + throw refusal('another recovery selection is pending; preserve it and finish that exact selection'); + } + if (!marker) { + if (!existsSync(queueFile) || digest(readFileSync(queueFile)) !== queueSha256) throw refusal('the local queue changed or is absent; no recovery applied'); + const original = localRecords(root, exportBoard); + const sourceDigest = semanticBoardDigest(original); + const initialLink = digest(readFileSync(file)); + const queue = await readOutbox(queueFile, key, state.board); + if (!queue?.moves?.length) throw refusal('this selection has no queued moves'); + let checkpoint = await link.fetchCheckpoint(key); + const records = []; + let after = checkpoint.sequence; + for (;;) { + const page = await link.request(state, '/api/v1/boards/' + state.board + '/events?after=' + after, { method: 'GET' }, io); + if (!Array.isArray(page.events) || page.events.some((record, i) => record?.event_id !== after + i + 1 || !['move', 'request'].includes(record.kind) || typeof record.sealed !== 'string')) { + throw refusal('the relay did not supply a contiguous authenticated-prefix candidate'); + } + if (!page.events.length) break; + records.push(...page.events); after = records.at(-1).event_id; + } + const minimum = Math.max(queue.baseSequence, localRecords(root, appliedSequence), checkpoint.sequence); + checkpoint = await link.advanceCheckpoint(key, checkpoint, records, minimum); + preservesReceipts(original, checkpoint.native); + const targetDigest = semanticBoardDigest(checkpoint.native); + const receipts = new Map(checkpoint.native.tables.board_meta.map(row => [row.meta_key, row.meta_value])); + // The individual identities remain in encrypted custody; the report never calls abandonment absence or success. + const plan = { version: 1, board: state.board, queueSha256, decision, sourceDigest, targetDigest, + sequence: checkpoint.sequence, queued: queue.moves.length, native: checkpoint.native, + previousLinkState: { pending: state.pending ?? null, recovered: state.recovered ?? null, + snapshot: state.snapshot ?? null, checkpoint: state.checkpoint ?? null }, + originalReceiptCount: [...receipts.keys()].filter(key => key.startsWith('relay_receipt_')).length }; + await withOutboxGuard(file, () => { + if (digest(readFileSync(file)) !== initialLink || digest(readFileSync(queueFile)) !== queueSha256 || localRecords(root, nativeDigest) !== sourceDigest) { + throw refusal('local state changed during preparation; no recovery applied'); + } + // Reusing an uncommitted staged plan is not a state effect. It is safe to replace only under unchanged inputs. + mkdirSync(directory, { recursive: true, mode: 0o700 }); + const bytes = JSON.stringify(plan); + const temporary = planFile + '.tmp'; + writeFileSync(temporary, bytes, { mode: 0o600 }); renameSync(temporary, planFile); + marker = { kind: 'discard-unpublished', queueSha256, decision, planSha256: digest(bytes), sourceDigest, targetDigest, sequence: checkpoint.sequence }; + state.recovery = marker; saveLink(file, state); + }); + await io.recoveryCut?.('held'); + } + return withOutboxGuard(file, async () => { + const current = loadLink(file); + if (JSON.stringify(current.recovery) !== JSON.stringify(marker)) throw refusal('the selected recovery hold changed'); + const bytes = readFileSync(planFile); + if (digest(bytes) !== marker.planSha256) throw refusal('the retained recovery plan changed; keep its hold'); + const plan = JSON.parse(bytes); + if (plan.board !== state.board || plan.queueSha256 !== queueSha256 || plan.decision !== decision || plan.sourceDigest !== marker.sourceDigest || plan.targetDigest !== marker.targetDigest || plan.sequence !== marker.sequence || semanticBoardDigest(plan.native) !== marker.targetDigest) { + throw refusal('the retained plan does not match this board and recovery selection'); + } + let actual = localRecords(root, nativeDigest); + if (![marker.sourceDigest, marker.targetDigest].includes(actual)) throw refusal('native state changed after the recovery hold; keep it and reconcile that writer'); + if (existsSync(queueFile)) { + if (digest(readFileSync(queueFile)) !== queueSha256 || existsSync(archive)) throw refusal('the active or archived queue changed; no replacement is allowed'); + renameSync(queueFile, archive); + } + if (!existsSync(archive) || digest(readFileSync(archive)) !== queueSha256) throw refusal('original encrypted queue custody is missing; keep the recovery hold'); + await io.recoveryCut?.('archived'); + if (actual !== marker.targetDigest) { + localRecords(root, board => restoreRelaySnapshot(board, plan.native, plan.sequence, marker.sourceDigest)); + actual = localRecords(root, nativeDigest); + if (actual !== marker.targetDigest) throw refusal('native recovery readback differs; keep the recovery hold'); + } + await io.recoveryCut?.('restored'); + rmSync(join(dirname(file), 'relay-outbox.summary.json'), { force: true }); + for (const name of ['pending', 'recovered', 'snapshot', 'checkpoint', 'outbox', 'recovery']) delete current[name]; + current.sequence = plan.sequence; + // Mirror cursor names native event IDs, not relay positions; retain that distinction after a lossy rebase. + current.cursor = localRecords(root, board => board.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id); + current.localRecovery = { kind: 'discard-unpublished', queueSha256, decision, sequence: plan.sequence, planSha256: marker.planSha256 }; + saveLink(file, current); + Object.keys(state).forEach(key => delete state[key]); Object.assign(state, current); + return { board: state.board, sequence: plan.sequence, queueSha256, retiredQueuedEntries: plan.queued, + archive, plan: planFile, originalReceiptCount: plan.originalReceiptCount, + disposition: 'authenticated ordered baseline restored; unpublished local messages abandoned, not declared absent or successful' }; + }); +} diff --git a/src/relay.js b/src/relay.js index f47dd05a04..80deb4449b 100644 --- a/src/relay.js +++ b/src/relay.js @@ -124,6 +124,7 @@ import { environmentLink } from './relay-environment.js'; import { locked } from './relay-lock.js'; import { withOutboxGuard } from './relay-outbox-guard.js'; import { relayOrdering } from './relay-ordering.js'; +import { discardUnpublished } from './relay-local-recovery.js'; import { nudgeRelaySender } from './relay-local-first.js'; import { checkpointPublisher } from './relay-checkpoint-publish.js'; import { @@ -1054,6 +1055,7 @@ async function queueLocally(root, file, operation, args, io, command, applyLocal const result = await withOutboxGuard(file, () => { // A revoke can finish while this move waits: admission uses the cache protected by this guard, never its earlier snapshot. const current = loadLink(file); + if (current?.recovery) throw new Refused('RELAY_RECOVERY_PENDING', 'finish the exact selected recovery before queuing another move'); return !current ? guarded.apply() : queueMove(outboxLink(root, file, current, io), { operation, args, command, applyLocally: guarded.apply, quiet: true }); }); @@ -1382,6 +1384,20 @@ export function relayRecovered(root, { includePending = false } = {}) { return state ? state.recovered?.move ?? (includePending ? state.pending?.move : null) ?? null : deletedRecovery(root)?.move ?? null; } +/** + * Operator recovery API: explicitly abandon a selected unpublished local queue, keeping authenticated order. + * The runtime owner must quiesce old writers/publishers and supply the real principal loss decision; this API + * neither impersonates a person nor changes relay credentials, identity, remote state or source files. + */ +export async function relayDiscardUnpublished(root, queueSha256, decision, io) { + const file = linkFile(root); + return locked(file, async () => { + const state = loadLink(file); + if (!state) throw new Refused('RELAY_NOT_LINKED', 'this board has no retained relay link'); + return discardUnpublished({ ...outboxLink(root, file, state, io), loadLink }, { queueSha256, decision }); + }, io); +} + /** Explicitly refuse one blocked position, replay its valid tail on a private copy, then publish it. */ export async function relayRecover(root, skip, io) { const file = linkFile(root); diff --git a/test/relay-outbox-rebuild-recovery.test.js b/test/relay-outbox-rebuild-recovery.test.js index aba001816f..90dce119b8 100644 --- a/test/relay-outbox-rebuild-recovery.test.js +++ b/test/relay-outbox-rebuild-recovery.test.js @@ -1,7 +1,8 @@ /** Recover an interrupted local rebuild from authenticated order, never by resending its prefix [H16,H21]. */ import assert from 'node:assert/strict'; -import { randomBytes } from 'node:crypto'; -import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { createHash, randomBytes } from 'node:crypto'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { discardUnpublished } from '../src/relay-local-recovery.js'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import test from 'node:test'; @@ -474,3 +475,93 @@ for (const kind of ['shout', 'event']) test(`review unshifted positional ${kind} } assert.equal(await readOutbox(outboxFile(f.link.file), f.key, f.id), null); }); + +/** Explicit service-first selection uses real durable queue/link files and native SQLite, no live relay. */ +async function lossFixture(t) { + const f = await fixture(t, { partialReapply: true, + setup(board, directory) { + const actor = store.register(board, { lane: 'core', path: join(directory, 'builder'), route: 'mid' }); + return { actor }; + } }); + f.link.state.token = 'synthetic-machine-credential'; + f.link.state.pending = { move: { id: 'uncertain-original' }, sequence: 4, sealed: 'synthetic-retained-ciphertext' }; + f.link.loadLink = () => JSON.parse(readFileSync(f.link.file)); + f.link.saveLink = (file, state) => writeFileSync(file, JSON.stringify(state), { mode: 0o600 }); + f.link.saveLink(f.link.file, f.link.state); + const queue = readFileSync(outboxFile(f.link.file)); + const choice = { queueSha256: createHash('sha256').update(queue).digest('hex'), decision: 'fixture principal accepts unpublished message loss' }; + return { ...f, queue, choice }; +} + +for (const cut of ['none', 'held', 'archived', 'restored']) test(`service-first recovery survives ${cut} cut without replay and resumes useful native work [H16,H21]`, async t => { + const f = await lossFixture(t); + const before = JSON.stringify(f.link.state); + if (cut !== 'none') { + f.link.io.recoveryCut = name => { if (name === cut) throw new Error('fixture interruption'); }; + await assert.rejects(discardUnpublished(f.link, f.choice), /fixture interruption/u); + assert.equal(f.link.loadLink().recovery.kind, 'discard-unpublished'); + // Reopen the persisted link, rather than relying on the interrupted call's in-memory state. + f.link.state = f.link.loadLink(); delete f.link.io.recoveryCut; + } + const result = await discardUnpublished(f.link, f.choice); + assert.equal(result.sequence, 3); + assert.deepEqual(f.posts, [], 'neither settled nor uncertain nor abandoned old moves were posted'); + assert.deepEqual(engineReceipt(f.board, f.third.id), f.receipt); + assert.equal(engineReceipt(f.board, f.fourth.id), null, 'abandonment did not invent a refusal/receipt'); + assert.equal(engineReceipt(f.board, 'uncertain-original'), null); + assert.deepEqual(readFileSync(result.archive), f.queue); + assert.equal(existsSync(outboxFile(f.link.file)), false); + assert.equal(f.link.loadLink().token, JSON.parse(before).token); + assert.equal(f.link.loadLink().board, f.id); + assert.equal(f.link.loadLink().pending, undefined); + assert.equal(JSON.parse(readFileSync(result.plan)).previousLinkState.pending.move.id, 'uncertain-original'); + assert.equal(f.link.loadLink().recovery, undefined); + assert.equal(f.link.loadLink().cursor, f.board.db.prepare('SELECT max(event_id) AS id FROM event').get().id); + const item = store.addItem(f.board, { by: 'coordinator', lane: 'core', title: 'new useful source work', criterion: 'claim exact source', route: 'mid', + check: 'node --test test/relay-outbox-rebuild-recovery.test.js', brief: 'Files: src/relay-local-recovery.js\nTest: new native work can be claimed after explicit recovery' }); + const claimed = store.claim(f.board, item, { agentId: f.extra.actor, lane: 'core', leaseMs: 60000, + freeze: () => ({ text: 'new source obligation', digest: 'fixture-source-digest' }) }); + assert.ok(claimed); + const after = exportBoard(f.board); + const again = await discardUnpublished(f.link, f.choice); + assert.equal(again.alreadyCompleted, true); + assert.deepEqual(exportBoard(f.board), after, 'response recovery never overwrites later native work'); +}); + +for (const failure of ['wrong-digest', 'changed-during-fetch', 'foreign-checkpoint', 'short-prefix', 'receipt-mismatch']) test(`service-first preflight refuses ${failure} before losing local work [H16,H21]`, async t => { + const f = await lossFixture(t); + const native = exportBoard(f.board), link = readFileSync(f.link.file); + if (failure === 'wrong-digest') f.choice.queueSha256 = 'f'.repeat(64); + if (failure === 'changed-during-fetch') { + const fetch = f.link.fetchCheckpoint; + f.link.fetchCheckpoint = async key => { const cp = await fetch(key); f.link.state.testConcurrent = true; f.link.saveLink(f.link.file, f.link.state); return cp; }; + } + if (failure === 'foreign-checkpoint') { + const fetch = f.link.fetchCheckpoint; + f.link.fetchCheckpoint = async key => { const cp = await fetch(key); cp.native.tables.board_meta.find(r => r.meta_key === 'board_id').meta_value = 'f'.repeat(32); return cp; }; + } + if (failure === 'short-prefix') f.link.request = async () => ({ events: [] }); + if (failure === 'receipt-mismatch') { + const advance = f.link.advanceCheckpoint; + f.link.advanceCheckpoint = async (...args) => { const cp = await advance(...args); cp.native.tables.board_meta.find(r => r.meta_key === 'relay_receipt_' + f.third.id).meta_value += ' '; return cp; }; + } + await assert.rejects(discardUnpublished(f.link, f.choice)); + assert.deepEqual(exportBoard(f.board), native); + assert.deepEqual(readFileSync(outboxFile(f.link.file)), f.queue); + if (failure !== 'changed-during-fetch') assert.deepEqual(readFileSync(f.link.file), link); + assert.deepEqual(f.posts, []); +}); + +for (const failure of ['changed-plan', 'changed-queue', 'changed-board']) test(`service-first persisted ${failure} keeps its recovery hold and refuses replacement [H16,H21]`, async t => { + const f = await lossFixture(t); + f.link.io.recoveryCut = name => { if (name === 'held') throw new Error('fixture interruption'); }; + await assert.rejects(discardUnpublished(f.link, f.choice), /fixture interruption/u); + delete f.link.io.recoveryCut; f.link.state = f.link.loadLink(); + if (failure === 'changed-plan') writeFileSync(join(f.link.root, 'link', 'local-recovery', f.choice.queueSha256, 'plan.json'), '{}'); + if (failure === 'changed-queue') writeFileSync(outboxFile(f.link.file), 'changed queue'); + if (failure === 'changed-board') store.shout(f.board, { from: 'coordinator', to: 'all', text: 'new writer must not be lost', lanes: [] }); + const after = exportBoard(f.board), queue = readFileSync(outboxFile(f.link.file)); + await assert.rejects(discardUnpublished(f.link, f.choice)); + assert.deepEqual(exportBoard(f.board), after); assert.deepEqual(readFileSync(outboxFile(f.link.file)), queue); + assert.equal(f.link.loadLink().recovery.kind, 'discard-unpublished'); assert.deepEqual(f.posts, []); +}); From 3595c018f3b3e34c559971a600779f505d533839 Mon Sep 17 00:00:00 2001 From: McHerpes Date: Fri, 13 Nov 2026 22:23:55 +0000 Subject: [PATCH 7/7] Bind local recovery to continuous locks and retained inputs --- src/relay-local-recovery.js | 15 ++++++-- src/relay-recovery-boundary.js | 8 ++++ src/relay.js | 11 ++++-- test/relay-local-recovery-api.test.js | 43 ++++++++++++++++++++++ test/relay-outbox-rebuild-recovery.test.js | 22 +++++++---- 5 files changed, 85 insertions(+), 14 deletions(-) create mode 100644 src/relay-recovery-boundary.js create mode 100644 test/relay-local-recovery-api.test.js diff --git a/src/relay-local-recovery.js b/src/relay-local-recovery.js index 494d3bf33e..31f075adda 100644 --- a/src/relay-local-recovery.js +++ b/src/relay-local-recovery.js @@ -13,6 +13,12 @@ const digest = bytes => createHash('sha256').update(bytes).digest('hex'); const refusal = text => new Refused('RELAY_LOCAL_RECOVERY', text); const nativeDigest = board => semanticBoardDigest(exportBoard(board)); +/** Bind all retained link inputs across a held retry, not only its recovery marker. */ +function linkInputs(state) { + const { recovery, ...inputs } = state; + return digest(JSON.stringify(inputs)); +} + /** Preserve every existing ordered outcome exactly; loss permission applies only to local unpublished work. */ function preservesReceipts(before, after) { const meta = new Map(after.tables.board_meta.map(row => [row.meta_key, row.meta_value])); @@ -44,7 +50,7 @@ export async function discardUnpublished(link, { queueSha256, decision }) { if (!existsSync(archive) || digest(readFileSync(archive)) !== queueSha256 || digest(readFileSync(planFile)) !== state.localRecovery.planSha256) { throw refusal('the completed recovery custody changed; do not repeat the reset'); } - return { board: state.board, sequence: state.localRecovery.sequence, queueSha256, alreadyCompleted: true, archive, plan: planFile, + return { board: state.board, sequence: state.localRecovery.sequence, nativeEventCursor: state.localRecovery.nativeEventCursor, targetDigest: state.localRecovery.targetDigest, queueSha256, alreadyCompleted: true, archive, plan: planFile, disposition: 'read back the original recovery completion; later native work was not reset' }; } let marker = state.recovery; @@ -89,7 +95,7 @@ export async function discardUnpublished(link, { queueSha256, decision }) { const bytes = JSON.stringify(plan); const temporary = planFile + '.tmp'; writeFileSync(temporary, bytes, { mode: 0o600 }); renameSync(temporary, planFile); - marker = { kind: 'discard-unpublished', queueSha256, decision, planSha256: digest(bytes), sourceDigest, targetDigest, sequence: checkpoint.sequence }; + marker = { kind: 'discard-unpublished', queueSha256, decision, planSha256: digest(bytes), sourceDigest, targetDigest, sequence: checkpoint.sequence, linkInputsSha256: linkInputs(state) }; state.recovery = marker; saveLink(file, state); }); await io.recoveryCut?.('held'); @@ -97,6 +103,7 @@ export async function discardUnpublished(link, { queueSha256, decision }) { return withOutboxGuard(file, async () => { const current = loadLink(file); if (JSON.stringify(current.recovery) !== JSON.stringify(marker)) throw refusal('the selected recovery hold changed'); + if (linkInputs(current) !== marker.linkInputsSha256) throw refusal('retained link inputs changed after the recovery hold; reconcile that writer before resuming'); const bytes = readFileSync(planFile); if (digest(bytes) !== marker.planSha256) throw refusal('the retained recovery plan changed; keep its hold'); const plan = JSON.parse(bytes); @@ -122,10 +129,10 @@ export async function discardUnpublished(link, { queueSha256, decision }) { current.sequence = plan.sequence; // Mirror cursor names native event IDs, not relay positions; retain that distinction after a lossy rebase. current.cursor = localRecords(root, board => board.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id); - current.localRecovery = { kind: 'discard-unpublished', queueSha256, decision, sequence: plan.sequence, planSha256: marker.planSha256 }; + current.localRecovery = { kind: 'discard-unpublished', queueSha256, decision, sequence: plan.sequence, nativeEventCursor: current.cursor, targetDigest: plan.targetDigest, planSha256: marker.planSha256 }; saveLink(file, current); Object.keys(state).forEach(key => delete state[key]); Object.assign(state, current); - return { board: state.board, sequence: plan.sequence, queueSha256, retiredQueuedEntries: plan.queued, + return { board: state.board, sequence: plan.sequence, nativeEventCursor: current.cursor, targetDigest: plan.targetDigest, queueSha256, retiredQueuedEntries: plan.queued, archive, plan: planFile, originalReceiptCount: plan.originalReceiptCount, disposition: 'authenticated ordered baseline restored; unpublished local messages abandoned, not declared absent or successful' }; }); diff --git a/src/relay-recovery-boundary.js b/src/relay-recovery-boundary.js new file mode 100644 index 0000000000..b12f95d1dc --- /dev/null +++ b/src/relay-recovery-boundary.js @@ -0,0 +1,8 @@ +/** Keep actual native relay and reentrant outbox exclusion through the entire operator recovery [H16,H21]. */ +import { locked } from './relay-lock.js'; +import { withOutboxGuard } from './relay-outbox-guard.js'; + +/** Nested helper guard entries share this module's real owner; no recursive relay lock or inode replacement. */ +export function withLocalRecoveryBoundary(file, work, io) { + return locked(file, () => withOutboxGuard(file, work), io); +} diff --git a/src/relay.js b/src/relay.js index 80deb4449b..46cff23a36 100644 --- a/src/relay.js +++ b/src/relay.js @@ -125,6 +125,7 @@ import { locked } from './relay-lock.js'; import { withOutboxGuard } from './relay-outbox-guard.js'; import { relayOrdering } from './relay-ordering.js'; import { discardUnpublished } from './relay-local-recovery.js'; +import { withLocalRecoveryBoundary } from './relay-recovery-boundary.js'; import { nudgeRelaySender } from './relay-local-first.js'; import { checkpointPublisher } from './relay-checkpoint-publish.js'; import { @@ -1080,7 +1081,9 @@ export async function relayOperation(root, operation, args, io, command, applyLo const applyPausedMoveLocally = guarded.apply; if (!state && deletedRecovery(root)) return deletedMoveResult(root, operation, args, command, io, applyPausedMoveLocally); if (!state || state.unlinking) throw new Refused('RELAY_UNLINK_PENDING', 'finish unlinking this device with pullboard relay off before sending a move'); - if (state.recovery) throw new Refused('RELAY_RECOVERY_PENDING', `finish the saved recovery for sequence ${state.recovery.skip} before sending a linked move`); + if (state.recovery) throw new Refused('RELAY_RECOVERY_PENDING', state.recovery.kind === 'discard-unpublished' + ? 'finish the exact operator-selected local recovery before sending a linked move; relay recover --skip is not this operation' + : `finish the saved recovery for sequence ${state.recovery.skip} before sending a linked move`); if (credentialActor({ operation, args, personRequest: io?.personRequest }) === 'person') { throw new Refused('HUMAN_REQUIRED', 'send this person action from the paired phone'); } @@ -1221,7 +1224,9 @@ export async function syncRelay(root, io) { if (!state) return null; if (state.unlinking) { io.err('pullboard: [RELAY_UNLINK_PENDING] the remote board is deleted; run pullboard relay off to finish forgetting this device key'); return summary(root, state); } try { - if (state.recovery) throw new Refused('RELAY_RECOVERY_PENDING', `a relay recovery for sequence ${state.recovery.skip} is pending; retry pullboard relay recover --skip ${state.recovery.skip} before syncing`); + if (state.recovery) throw new Refused('RELAY_RECOVERY_PENDING', state.recovery.kind === 'discard-unpublished' + ? 'finish the exact operator-selected local recovery before syncing; relay recover --skip is not this operation' + : `a relay recovery for sequence ${state.recovery.skip} is pending; retry pullboard relay recover --skip ${state.recovery.skip} before syncing`); if (!await ensureOrdered(root, file, state, io)) return summary(root, state); await flushOutbox(outboxLink(root, file, state, io)); await catchUp(root, file, state, io); @@ -1391,7 +1396,7 @@ export function relayRecovered(root, { includePending = false } = {}) { */ export async function relayDiscardUnpublished(root, queueSha256, decision, io) { const file = linkFile(root); - return locked(file, async () => { + return withLocalRecoveryBoundary(file, async () => { const state = loadLink(file); if (!state) throw new Refused('RELAY_NOT_LINKED', 'this board has no retained relay link'); return discardUnpublished({ ...outboxLink(root, file, state, io), loadLink }, { queueSha256, decision }); diff --git a/test/relay-local-recovery-api.test.js b/test/relay-local-recovery-api.test.js new file mode 100644 index 0000000000..6cb57b19d6 --- /dev/null +++ b/test/relay-local-recovery-api.test.js @@ -0,0 +1,43 @@ +/** Exercise the public recovery entrance with real private link persistence and native SQLite [H16,H21]. */ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { existsSync, readFileSync } from 'node:fs'; +import { lossFixture } from './relay-outbox-rebuild-recovery.test.js'; +import { relayDiscardUnpublished, saveLink } from '../src/relay.js'; +import { seal } from '../src/seal.js'; +import { engineReceipt } from '../src/engine.js'; +import { outboxFile } from '../src/relay-outbox.js'; +import { exportBoard } from '../src/exchange.js'; + +for (const cut of ['none', 'held', 'archived']) test(`installed API recovery ${cut}: actual binding, locks and persisted link [H16,H21]`, async t => { + const f = await lossFixture(t, { fileBacked: true }); + Object.assign(f.link.state, { version: 1, url: 'https://relay.example.invalid', cursor: 0, token: 'pm_' + 'a'.repeat(43) }); + saveLink(f.link.file, f.link.state); + const snapshot = { sequence: f.checkpoint.sequence, sender: { kind: 'machine', userId: 'fixture', machine: 'fixture-machine' }, + sealed: Buffer.from(await seal(f.key, Buffer.from(JSON.stringify(f.checkpoint.native)), { boardId: f.id, kind: 'snapshot', sequence: f.checkpoint.sequence })).toString('base64url') }; + const calls = [], previous = globalThis.fetch; + t.after(() => { globalThis.fetch = previous; }); + globalThis.fetch = async (url, options) => { + const u = new URL(url); calls.push({ method: options.method, path: u.pathname + u.search }); + assert.equal(u.origin, 'https://relay.example.invalid'); assert.equal(options.method, 'GET'); + assert.equal(options.headers.authorization, 'Bearer ' + f.link.state.token); + if (u.pathname.endsWith('/state')) return Response.json({ version: 1, state: snapshot }); + assert.equal(u.pathname, '/api/v1/boards/' + f.id + '/events'); + const after = Number(u.searchParams.get('after')); + return Response.json({ version: 1, events: f.records.filter(row => row.event_id > after) }); + }; + const io = { err() {}, out() {}, ignoreRelayEnvironmentToken: true }; + if (cut !== 'none') { + io.recoveryCut = name => { if (name === cut) throw new Error('fixture API interruption'); }; + await assert.rejects(relayDiscardUnpublished(f.link.root, f.choice.queueSha256, f.choice.decision, io), /fixture API interruption/); + delete io.recoveryCut; + } + const result = await relayDiscardUnpublished(f.link.root, f.choice.queueSha256, f.choice.decision, io); + assert.equal(result.sequence, 3); assert.equal(result.nativeEventCursor, f.board.db.prepare('SELECT max(event_id) AS id FROM event').get().id); + assert.deepEqual(engineReceipt(f.board, f.third.id), f.receipt); + assert.equal(engineReceipt(f.board, f.fourth.id), null); + assert.deepEqual(readFileSync(result.archive), f.queue); assert.equal(existsSync(outboxFile(f.link.file)), false); + const before = exportBoard(f.board), count = calls.length; + assert.equal((await relayDiscardUnpublished(f.link.root, f.choice.queueSha256, f.choice.decision, io)).alreadyCompleted, true); + assert.equal(calls.length, count); assert.deepEqual(exportBoard(f.board), before); +}); diff --git a/test/relay-outbox-rebuild-recovery.test.js b/test/relay-outbox-rebuild-recovery.test.js index 90dce119b8..95edf9c857 100644 --- a/test/relay-outbox-rebuild-recovery.test.js +++ b/test/relay-outbox-rebuild-recovery.test.js @@ -6,6 +6,7 @@ import { discardUnpublished } from '../src/relay-local-recovery.js'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import test from 'node:test'; +import { spawnSync } from 'node:child_process'; import * as store from '../src/board.js'; import { applyRelayMove, appliedSequence, checkpointSequence, engineReceipt, prepareEngineMove } from '../src/engine.js'; import { exportBoard, importBoard } from '../src/exchange.js'; @@ -18,7 +19,7 @@ import { undoQueued } from '../src/relay-outbox-undo.js'; import { seal, unseal } from '../src/seal.js'; /** Real SQLite, native changesets and sealed queue; the only remote is an in-process ordered fixture. */ -async function fixture(t, { partialReapply = false, setup, pending } = {}) { +async function fixture(t, { partialReapply = false, setup, pending, fileBacked = false } = {}) { const directory = mkdtempSync(join(tmpdir(), 'pullboard-rebuild-recovery-')); const names = ['PULLBOARD_HOME', 'PULLBOARD_MACHINE_HOME', 'PULLBOARD_RELAY_KEY', 'PULLBOARD_RELAY_TOKEN']; const prior = Object.fromEntries(names.map(name => [name, process.env[name]])); @@ -27,7 +28,11 @@ async function fixture(t, { partialReapply = false, setup, pending } = {}) { process.env.PULLBOARD_MACHINE_HOME = join(directory, 'machine'); delete process.env.PULLBOARD_RELAY_KEY; delete process.env.PULLBOARD_RELAY_TOKEN; - const board = store.openBoard(':memory:', { now: () => new Date('2026-10-24T00:00:00Z') }); + if (fileBacked) { + assert.equal(spawnSync('git', ['-c', 'init.defaultBranch=main', 'init', '-q', directory]).status, 0); + mkdirSync(join(directory, '.git', 'pullboard'), { mode: 0o700 }); + } + const board = store.openBoard(fileBacked ? join(directory, '.git', 'pullboard', 'board.sqlite') : ':memory:', { now: () => new Date('2026-10-24T00:00:00Z') }); t.after(() => { store.closeBoard(board); rmSync(directory, { recursive: true, force: true }); }); store.register(board, { lane: 'coordinator', path: directory, sessionDigest: 'a'.repeat(64) }); const extra = setup?.(board, directory); @@ -37,8 +42,8 @@ async function fixture(t, { partialReapply = false, setup, pending } = {}) { storeBoardKey(id, key); const checkpoint = { native: exportBoard(board), sequence: 1 }; const state = { board: id, sequence: 2, mode: 'ordered', machine: 'fixture-machine', outbox: { moves: [] } }; - mkdirSync(join(directory, 'link'), { mode: 0o700 }); - const file = join(directory, 'link', 'relay.json'); + if (!fileBacked) mkdirSync(join(directory, 'link'), { mode: 0o700 }); + const file = fileBacked ? join(directory, '.git', 'pullboard', 'relay.json') : join(directory, 'link', 'relay.json'); const records = [], posts = [], reads = [], errors = []; /** Authenticate the fixture's actual sealed record and use the real deterministic board engine. */ async function replay(board, key, state, record) { @@ -477,8 +482,8 @@ for (const kind of ['shout', 'event']) test(`review unshifted positional ${kind} }); /** Explicit service-first selection uses real durable queue/link files and native SQLite, no live relay. */ -async function lossFixture(t) { - const f = await fixture(t, { partialReapply: true, +export async function lossFixture(t, options = {}) { + const f = await fixture(t, { partialReapply: true, ...options, setup(board, directory) { const actor = store.register(board, { lane: 'core', path: join(directory, 'builder'), route: 'mid' }); return { actor }; @@ -505,6 +510,8 @@ for (const cut of ['none', 'held', 'archived', 'restored']) test(`service-first } const result = await discardUnpublished(f.link, f.choice); assert.equal(result.sequence, 3); + assert.equal(result.nativeEventCursor, f.board.db.prepare('SELECT max(event_id) AS id FROM event').get().id); + assert.match(result.targetDigest, /^[0-9a-f]{64}$/u); assert.deepEqual(f.posts, [], 'neither settled nor uncertain nor abandoned old moves were posted'); assert.deepEqual(engineReceipt(f.board, f.third.id), f.receipt); assert.equal(engineReceipt(f.board, f.fourth.id), null, 'abandonment did not invent a refusal/receipt'); @@ -552,7 +559,7 @@ for (const failure of ['wrong-digest', 'changed-during-fetch', 'foreign-checkpoi assert.deepEqual(f.posts, []); }); -for (const failure of ['changed-plan', 'changed-queue', 'changed-board']) test(`service-first persisted ${failure} keeps its recovery hold and refuses replacement [H16,H21]`, async t => { +for (const failure of ['changed-plan', 'changed-queue', 'changed-board', 'changed-link']) test(`service-first persisted ${failure} keeps its recovery hold and refuses replacement [H16,H21]`, async t => { const f = await lossFixture(t); f.link.io.recoveryCut = name => { if (name === 'held') throw new Error('fixture interruption'); }; await assert.rejects(discardUnpublished(f.link, f.choice), /fixture interruption/u); @@ -560,6 +567,7 @@ for (const failure of ['changed-plan', 'changed-queue', 'changed-board']) test(` if (failure === 'changed-plan') writeFileSync(join(f.link.root, 'link', 'local-recovery', f.choice.queueSha256, 'plan.json'), '{}'); if (failure === 'changed-queue') writeFileSync(outboxFile(f.link.file), 'changed queue'); if (failure === 'changed-board') store.shout(f.board, { from: 'coordinator', to: 'all', text: 'new writer must not be lost', lanes: [] }); + if (failure === 'changed-link') { const state = f.link.loadLink(); state.pending = { move: { id: 'new-uncertain-writer' } }; f.link.saveLink(f.link.file, state); } const after = exportBoard(f.board), queue = readFileSync(outboxFile(f.link.file)); await assert.rejects(discardUnpublished(f.link, f.choice)); assert.deepEqual(exportBoard(f.board), after); assert.deepEqual(readFileSync(outboxFile(f.link.file)), queue);