Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(core): queued moves are taken back by their own rows [H21,H16]
Corey Olsond6147d853b65
diff --git a/src/board-capture.js b/src/board-capture.jsnew file mode 100644index 00000000..51222917--- /dev/null+++ b/src/board-capture.js@@ -0,0 +1,42 @@+/**+ * Change capture (#1013): while `captureBoardChanges` runs, every outermost board transaction records the exact+ * rows it changed as a SQLite changeset, so a local-first move made ahead of the relay's order can later be taken+ * back row for row instead of restoring the whole board.+ */++/** The capture lists of the calls running now, innermost last. */+const CAPTURES = [];++/**+ * Run `work`, collecting the changeset of every board transaction it commits, in order.+ *+ * @template T+ * @param {() => Promise<T> | T} work+ * @returns {Promise<{ result: T, changes: Uint8Array[] }>}+ */+export async function captureBoardChanges(work) {+ const changes = [];+ CAPTURES.push(changes);+ try { return { result: await work(), changes }; }+ finally { CAPTURES.splice(CAPTURES.lastIndexOf(changes), 1); }+}++/**+ * Start recording one outermost board transaction when a capture is running; returns how to finish it.+ * Why: a session sees only the rows its own connection changes, so each transaction opens its own on its board.+ *+ * @param {import('node:sqlite').DatabaseSync} db+ * @returns {{ commit: () => void, close: () => void } | null}+ */+export function beginCapture(db) {+ const into = CAPTURES.at(-1);+ if (!into) return null;+ const session = db.createSession();+ return {+ commit() {+ const changeset = session.changeset();+ if (changeset.length) into.push(changeset);+ },+ close() { session.close(); },+ };+}diff --git a/src/board-event-log.js b/src/board-event-log.jsindex b889e71b..edf42c1f 100644--- a/src/board-event-log.js+++ b/src/board-event-log.js@@ -6,6 +6,7 @@ import { appendProofCounter } from './proof-counters.js';import { ensureProofCounters } from './proof-counters.js';import { boardWriteBusyError } from './board-busy.js';+import { beginCapture } from './board-capture.js';import {beginBoardWrite,finishBoardWrite,@@ -33,6 +34,8 @@ export function atomic(board, work) {catch (error) { throw boardWriteBusyError(board.db, startedAt, error); }TRANSACTION_DEPTH.set(board, depth + 1);const writeRecord = depth ? null : beginBoardWrite(board.db, board.writeContext);+ // A local-first move records the rows it changed, so the relay's order can take it back later (#1013).+ const capture = depth ? null : beginCapture(board.db);let released = false;let outcome = 'release-failed';const lastEvent = board.lastEvent;@@ -42,6 +45,7 @@ export function atomic(board, work) {board.db.exec(depth ? `RELEASE ${savepoint}` : 'COMMIT');released = true;outcome = 'committed';+ capture?.commit();return result;} catch (error) {board.db.exec(depth ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : 'ROLLBACK');@@ -51,6 +55,7 @@ export function atomic(board, work) {board.emittedEvents?.splice(emitted);throw error;} finally {+ capture?.close();TRANSACTION_DEPTH.set(board, depth);finishBoardWrite(writeRecord, released, outcome);}diff --git a/src/relay-outbox-undo.js b/src/relay-outbox-undo.jsnew file mode 100644index 00000000..541b5963--- /dev/null+++ b/src/relay-outbox-undo.js@@ -0,0 +1,138 @@+/**+ * Taking queued moves back (#1013): a local-first move is made on this machine before the relay orders it, and its+ * rows are captured as a SQLite changeset. When the relay's order arrives, the queued moves are taken back by their+ * inverted changesets, newest first, so the board is exactly as the relay last ordered it; replaying the relay's+ * records and making the queued moves again on top costs only the rows they touch, never a whole-board restore.+ */+import { storeTriggers } from './machine.js';+import { atomic } from './board-event-log.js';++/** SQLite's changeset conflict type for a row whose values changed, and the answers to a conflict. */+const CHANGED = 1;+const REPLACE = 1;+const ABORT = 2;++/** SQLite's changeset operation codes. */+const INSERT = 18;+const UPDATE = 23;+const DELETE = 9;++/** Read one SQLite varint at `at`; returns its value and the next offset. */+function varint(bytes, at) {+ let value = 0;+ for (let index = 0; index < 8; index += 1) {+ const byte = bytes[at + index];+ value = value * 128 + (byte & 0x7f);+ if (!(byte & 0x80)) return { value, next: at + index + 1 };+ }+ return { value: value * 256 + bytes[at + 8], next: at + 9 };+}++/** Read one changeset value; returns its encoded bytes, whether it is defined, and the next offset. */+function value(bytes, at) {+ const type = bytes[at];+ if (type === 0 || type === 5) return { bytes: bytes.subarray(at, at + 1), defined: type !== 0, next: at + 1 };+ if (type === 1 || type === 2) return { bytes: bytes.subarray(at, at + 9), defined: true, next: at + 9 };+ if (type === 3 || type === 4) {+ const length = varint(bytes, at + 1);+ return { bytes: bytes.subarray(at, length.next + length.value), defined: true, next: length.next + length.value };+ }+ throw new Error(`changeset value type ${type} is not one SQLite writes`);+}++/** Read a record of `columns` values. */+function record(bytes, at, columns) {+ const values = [];+ let next = at;+ for (let column = 0; column < columns; column += 1) {+ const read = value(bytes, next);+ values.push(read);+ next = read.next;+ }+ return { values, next };+}++/** The encoded bytes of an undefined value. */+const UNDEFINED = Uint8Array.of(0);++/**+ * Invert a SQLite changeset, as sqlite3changeset_invert does: an insert becomes a delete of the same row, a delete an+ * insert, and an update swaps its changed values, so applying the result takes the original change back.+ *+ * @param {Uint8Array} changeset+ * @returns {Uint8Array}+ */+export function invertChangeset(changeset) {+ const bytes = Buffer.from(changeset);+ const out = [];+ let columns = 0;+ for (let at = 0; at < bytes.length;) {+ const marker = bytes[at];+ if (marker === 0x54) { // 'T': a table header, copied as it is.+ const count = varint(bytes, at + 1);+ columns = count.value;+ const end = bytes.indexOf(0, count.next + columns);+ out.push(bytes.subarray(at, end + 1));+ at = end + 1;+ continue;+ }+ const indirect = bytes[at + 1];+ if (marker === INSERT || marker === DELETE) {+ const row = record(bytes, at + 2, columns);+ out.push(Uint8Array.of(marker === INSERT ? DELETE : INSERT, indirect), bytes.subarray(at + 2, row.next));+ at = row.next;+ } else if (marker === UPDATE) {+ const before = record(bytes, at + 2, columns);+ const after = record(bytes, before.next, columns);+ out.push(Uint8Array.of(UPDATE, indirect));+ // The inverted update expects each changed column at its new value and keys the row as before.+ for (let column = 0; column < columns; column += 1) out.push(after.values[column].defined ? after.values[column].bytes : before.values[column].bytes);+ for (let column = 0; column < columns; column += 1) out.push(after.values[column].defined ? before.values[column].bytes : UNDEFINED);+ at = after.next;+ } else throw new Error(`changeset operation ${marker} is not one SQLite writes`);+ }+ return Buffer.concat(out);+}++/**+ * Take queued moves back on `board`, newest first, in one transaction, and put the row counters back as they were+ * before the oldest. Returns false, changing nothing, when a row they made is gone or a row they removed is back, so+ * the caller rebuilds from a whole image instead.+ * Why: the board's lifecycle triggers refuse removing events or moving an item backwards, as any command should;+ * taking back an unordered move is the one exception, so they are lifted inside this transaction only, as a+ * snapshot restore lifts them.+ *+ * @param {any} board+ * @param {{ changes?: string[], sequences?: { name: string, seq: number }[] }[]} entries - Oldest first.+ * @returns {boolean}+ */+export function undoQueued(board, entries) {+ const db = board.db;+ let conflict = false;+ try {+ atomic(board, () => {+ const triggers = db.prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'machine_%'").all();+ for (const { name } of triggers) db.exec(`DROP TRIGGER "${name.replaceAll('"', '""')}"`);+ for (const entry of [...entries].reverse()) {+ for (const change of [...(entry.changes ?? [])].reverse()) {+ // A row changed again since, as a seat's read position is, is put back all the same (its newer read+ // position is kept by the caller); a row gone or taken is not this undo's to guess at.+ const applied = db.applyChangeset(invertChangeset(Buffer.from(change, 'base64')), {+ onConflict: (type) => { if (type === CHANGED) return REPLACE; conflict = true; return ABORT; } });+ if (conflict || applied === false) throw new Error('a queued move\'s rows changed since it was made');+ }+ }+ const counters = entries.find((entry) => Array.isArray(entry.sequences))?.sequences;+ if (counters) {+ db.exec('DELETE FROM sqlite_sequence');+ const insert = db.prepare('INSERT INTO sqlite_sequence (name, seq) VALUES (?, ?)');+ for (const row of counters) insert.run(row.name, row.seq);+ }+ for (const { sql } of storeTriggers()) db.exec(sql);+ });+ } catch (error) {+ if (conflict) return false;+ throw error;+ }+ return true;+}diff --git a/src/relay-outbox.js b/src/relay-outbox.jsindex b8f80bc7..67946ed5 100644--- a/src/relay-outbox.js+++ b/src/relay-outbox.js@@ -46,6 +46,8 @@ import {seal,unseal,} from './seal.js';+import { captureBoardChanges } from './board-capture.js';+import { undoQueued } from './relay-outbox-undo.js';import { stampCoordinatorHolder } from './coordinator-hold.js';import { Refused } from './refused.js';import {@@ -79,7 +81,8 @@ export async function readOutbox(file, key, boardId) {if (!existsSync(file)) return null;const plain = await unseal(key, readFileSync(file), { boardId, kind: 'outbox', sequence: 0 });const document = JSON.parse(gunzipSync(plain).toString('utf8'));- if (![1, 2].includes(document?.version) || !Array.isArray(document.moves) || !document.base || !Number.isSafeInteger(document.baseSequence)) {+ // Version 3 (#1013) keeps no board image: each move carries the rows it changed, to be taken back by them.+ if (![1, 2, 3].includes(document?.version) || !Array.isArray(document.moves) || !(document.base || document.version === 3) || !Number.isSafeInteger(document.baseSequence)) {throw new Refused('RELAY_OUTBOX', 'the relay outbox on this machine is unreadable; keep it, and ask for help before relinking this board');}return document;@@ -88,7 +91,8 @@ export async function readOutbox(file, key, boardId) {/** Seal and atomically replace the outbox, readable only by this user. */export async function writeOutbox(file, key, boardId, document) {// Old clients must refuse richer result bindings rather than treating temporary item numbers as final.- if (document.moves.some(entry => (entry.move.operation !== 'addItem' && createsItems(entry.move.operation))+ if (!document.base) document.version = 3;+ else if (document.moves.some(entry => (entry.move.operation !== 'addItem' && createsItems(entry.move.operation))|| entry.created?.some(row => row.resultPath.length)|| entry.refs?.some(ref => ref.resultPath?.length))) document.version = 2;const sealed = await seal(key, gzipSync(Buffer.from(JSON.stringify(document))), { boardId, kind: 'outbox', sequence: 0 });@@ -315,11 +319,6 @@ export function outboxQueueable(state, error, operation, io) {&& !['register', 'ensureCoordinator'].includes(operation) && transientRelayFailure(error) && outboxEnabled(io);}-/** The board's relay-applied sequence, read from an exported image. */-function exportedSequence(native) {- return Number(native.tables.board_meta.find((row) => row.meta_key === 'relay_applied_sequence')?.meta_value ?? 0);-}-/** The key-free summary of the outbox beside a link file, which pullboard status reads (#1013). */export function outboxSummaryFile(linkFile) {return join(dirname(linkFile), 'relay-outbox.summary.json');@@ -388,10 +387,9 @@ export async function queueMove(link, { operation, args, command, move, error, aconst { root, file, state, io, localRecords, safePauseCode, safePauseMessage } = link;const key = readBoardKey(state.board);const where = outboxFile(file);- const outbox = await readOutbox(where, key, state.board) ?? (() => {- const base = localRecords(root, (board) => exportBoard(board));- return { version: 1, base, baseSequence: exportedSequence(base), restored: false, moves: [] };- })();+ // A new outbox holds no board image: the moves are taken back by their own rows, so queuing costs no export.+ const outbox = await readOutbox(where, key, state.board)+ ?? { version: 3, baseSequence: localRecords(root, appliedSequence), restored: false, moves: [] };if (!move) {const sent = withSeatName(root, operation, args);move = stampCoordinatorHolder(localRecords(root, (board) => prepareEngineMove(board, operation, sent)), state.machine, state.computerName);@@ -405,8 +403,12 @@ export async function queueMove(link, { operation, args, command, move, error, aconst entry = { move, refs: bindRefs(outbox, move), intent: operationIntent(operation, args), queuedAt: new Date().toISOString(),after: Math.max(state.sequence, outbox.baseSequence),...(command ? { command, commandIntent: operationIntent('cli:' + command.cliOperation, command) } : {}) };+ // The row counters as they were before this move, so taking it back puts the next numbers back too.+ entry.sequences = localRecords(root, rowCounters);outbox.moves.push(entry);bumpGeneration(file);+ // Written before it is applied: a crash between leaves a move with no captured rows, which a rebuild from the+ // relay's checkpoint takes care of.await writeOutbox(where, key, state.board, outbox);if (state.pending?.move?.id === move.id) {delete state.pending;@@ -414,18 +416,19 @@ export async function queueMove(link, { operation, args, command, move, error, a}saveOutboxSummary(link, outbox);let result;- try { result = await applyLocally(); }- catch (refusal) {+ try {+ const applied = await captureBoardChanges(() => applyLocally());+ result = applied.result;+ entry.changes = encodeChanges(applied.changes);+ } catch (refusal) {outbox.moves.pop();if (outbox.moves.length) await writeOutbox(where, key, state.board, outbox);else removeOutbox(where);saveOutboxSummary(link, outbox);throw refusal;}- if (createsItems(move.operation)) {- rememberCreatedItems(entry, result);- await writeOutbox(where, key, state.board, outbox);- }+ rememberCreatedItems(entry, result);+ await writeOutbox(where, key, state.board, outbox);if (!quiet && !OUTBOX_NOTICES.has(io)) {OUTBOX_NOTICES.add(io);io.err(`pullboard: [${safePauseCode(error)}] ${error.transportFailure ? `the relay did not answer (${error.transportFailure})` : safePauseMessage(error)}; the move is saved on this machine and waits in the relay outbox (${outbox.moves.length} pending); it goes up in order when the relay answers, and pullboard status lists it`);@@ -436,13 +439,64 @@ export async function queueMove(link, { operation, args, command, move, error, a/** Most send-and-rebuild rounds one flush takes before it leaves the rest to the next. */const FLUSH_ROUNDS = 100;+/** The board's relay-applied sequence. */+function appliedSequence(board) {+ return Number(board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key = 'relay_applied_sequence'").get()?.meta_value ?? 0);+}++/** The board's row counters, which SQLite keeps outside any row a changeset records. */+function rowCounters(board) {+ return board.db.prepare('SELECT name, seq FROM sqlite_sequence ORDER BY name').all().map((row) => ({ name: row.name, seq: row.seq }));+}++/** Changesets as the outbox keeps them. */+function encodeChanges(changes) {+ return changes.map((change) => Buffer.from(change).toString('base64'));+}++/** 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;+ const { move } = resolveMove(entry, outbox, { local: true });+ entry.sequences = localRecords(root, rowCounters);+ const applied = await captureBoardChanges(() => localRecords(root, (board) => {+ try { return store.atomic(board, () => store[move.operation](board, ...executableArgs(move, board))); }+ catch (error) { if (!(error instanceof Refused)) throw error; return null; }+ }));+ entry.changes = encodeChanges(applied.changes);+ return applied.result;+}++/**+ * Take every queued move back so the board is exactly as the relay last ordered it; false when that cannot be done+ * row for row (a move with no captured rows, or a row changed in a way the undo cannot follow), and the caller+ * restores the relay's checkpoint instead. Each seat's newer shout-read position is kept, as a restore keeps it.+ */+function takeBack(link, outbox) {+ const { root, localRecords } = link;+ if (!outbox.moves.every((entry) => Array.isArray(entry.changes) && Array.isArray(entry.sequences))) return false;+ return localRecords(root, (board) => {+ const cursors = board.db.prepare('SELECT agent_id, agent_last_shout_id FROM agent').all();+ if (!undoQueued(board, outbox.moves)) return false;+ if (appliedSequence(board) !== outbox.baseSequence) return false;+ keepNewerCursors(board, cursors);+ return true;+ });+}++/** Keep each seat's newer shout-read position over the one an undo or restore put back. */+function keepNewerCursors(board, cursors) {+ const keep = board.db.prepare('UPDATE agent SET agent_last_shout_id = ? WHERE agent_id = ? AND (agent_last_shout_id IS NULL OR agent_last_shout_id < ?)');+ 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);+}+/*** 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.** @returns {Promise<{ baseSequence: number, checkpoint?: { native: any, sequence: number }, events: any[] } | null>}*/-async function pullSinceBase(link, key) {+async function pullSinceBase(link, key, { fromCheckpoint = false } = {}) {const { file, state, io, request } = link;const outbox = await readOutbox(outboxFile(file), key, state.board);if (!outbox?.moves.length) return null;@@ -454,6 +508,12 @@ async function pullSinceBase(link, key) {}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) };+ }try { return { baseSequence: outbox.baseSequence, events: await events(outbox.baseSequence) }; }catch (error) {if (error.code !== 'SNAPSHOT_REQUIRED') throw error;@@ -469,8 +529,7 @@ function restoreBase(link, image, sequence) {const cursors = board.db.prepare('SELECT agent_id, agent_last_shout_id FROM agent').all();restoreRelaySnapshot(board, image, sequence);// Reading shouts is this machine's own progress; the restore keeps the newer read position.- const keep = board.db.prepare('UPDATE agent SET agent_last_shout_id = ? WHERE agent_id = ? AND (agent_last_shout_id IS NULL OR agent_last_shout_id < ?)');- 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);+ keepNewerCursors(board, cursors);});}@@ -529,10 +588,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;+ // 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);- else restoreBase(link, outbox.base, outbox.baseSequence);+ 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);- state.sequence = localRecords(root, (board) => Number(board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key = 'relay_applied_sequence'").get()?.meta_value ?? 0));+ state.sequence = localRecords(root, appliedSequence);outbox.results ??= {};const waiting = [];for (const entry of outbox.moves) {@@ -554,8 +615,9 @@ async function rebuild(link, key, pulled) {}outbox.moves.push(entry);}- outbox.base = localRecords(root, (board) => exportBoard(board));- outbox.baseSequence = exportedSequence(outbox.base);+ // An older outbox keeps its image until it empties; a new one keeps only the sequence its moves sit on.+ if (outbox.base) outbox.base = localRecords(root, (board) => exportBoard(board));+ outbox.baseSequence = state.sequence;outbox.restored = false;if (!outbox.moves.length) {removeOutbox(where);@@ -564,11 +626,7 @@ async function rebuild(link, key, pulled) {return false;}for (const entry of outbox.moves) {- const { move } = resolveMove(entry, outbox, { local: true });- const result = localRecords(root, (board) => {- try { return store.atomic(board, () => store[move.operation](board, ...executableArgs(move, board))); }- catch (error) { if (!(error instanceof Refused)) throw error; return null; }- });+ const result = await reapply(link, outbox, entry);// 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);@@ -626,8 +684,9 @@ export async function flushOutbox(link) {const where = outboxFile(file);if (!state.outbox && !existsSync(where)) return;const key = readBoardKey(state.board);+ let fromCheckpoint = false;for (let round = 0; round < FLUSH_ROUNDS; round += 1) {- const pulled = await pullSinceBase(link, key);+ const pulled = await pullSinceBase(link, key, { fromCheckpoint });const waiting = pulled ? await withOutboxGuard(file, () => rebuild(link, key, pulled)): await withOutboxGuard(file, async () => {if (await readOutbox(where, key, state.board)) return true;@@ -635,7 +694,9 @@ export async function flushOutbox(link) {return false;});if (!waiting) return;- if (!pulled) continue;+ // The queued moves could not be taken back row for row: the next round restores the relay's checkpoint.+ fromCheckpoint = waiting === 'checkpoint';+ if (!pulled || fromCheckpoint) continue;await sendQueued(link, key);}throw new Refused('RELAY_BUSY', 'the relay order stayed busy while this machine sent its queued moves; they stay queued for the next send');diff --git a/src/relay-relink.js b/src/relay-relink.jsindex 70970891..c5eb1b63 100644--- a/src/relay-relink.js+++ b/src/relay-relink.js@@ -75,6 +75,8 @@ export function archiveRelinkOutbox(root, state) {url: state.url, sequence: state.sequence, machine: state.machine, records,...(queued ? { encryptedFile: name + '.sealed' } : {}) }) + '\n', { flag: 'wx', mode: 0o600 });if (queued) renameSync(file, join(directory, name + '.sealed'));+ // The key-free summary went with the outbox it described (#1013).+ rmSync(join(directory, 'relay-outbox.summary.json'), { force: true });}/** Consume the intent only after the new link and its exact sealed baseline are durable. */diff --git a/src/relay.js b/src/relay.jsindex 3b83cec6..929456b9 100644--- a/src/relay.js+++ b/src/relay.js@@ -1194,7 +1194,8 @@ async function queueLocally(root, file, state, operation, args, io, command, appapply: () => typeof applyLocally === 'function' ? applyLocally() : localRecords(root, (board) => store[operation](board, ...args)),queue: () => { throw new Refused('RELAY_OUTBOX', 'a local-first move queues itself; it is never queued twice'); },});- const result = await withOutboxGuard(file, () => queueMove(outboxLink(root, file, state, io),+ // An unlink that finished while this move waited for the guard leaves an ordinary local board.+ const result = await withOutboxGuard(file, () => !existsSync(file) ? guarded.apply() : queueMove(outboxLink(root, file, state, io),{ operation, args, command, applyLocally: guarded.apply, quiet: true }));onRecorded?.();nudgeRelaySender(root, file);@@ -1787,7 +1788,8 @@ export async function relayOff(root, io) {try { proposal = await phoneProposal(state, 'delete-board', state.board, { root }); }catch { /* Missing key or pairing cannot stop local unlinking. */ }rememberRelink(root, state.board);- archiveRelinkOutbox(root, state);+ // A local-first move queues under the outbox guard, so the outbox is set aside under it too (#1013).+ await withOutboxGuard(file, () => archiveRelinkOutbox(root, state));rmSync(file, { force: true });try { forgetBoardKey(state.board, state.keyStorage); }catch { /* The local opt-out is complete even when secure key storage is temporarily locked. */ }