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): a local-first move queues at once for the sender [H21,H16]
Corey Olson6fde298b832b
diff --git a/bin/run-tests.js b/bin/run-tests.jsindex 1da7b1f0..49d9bc93 100644--- a/bin/run-tests.js+++ b/bin/run-tests.js@@ -243,6 +243,8 @@ function testEnvironment(sandbox, gateMarkers = {}) {env.PULLBOARD_VIEW_BACKGROUND = '0';// Likewise the relay checkpoint publishes inside the command; a test of the background publisher opts in (#1014).env.PULLBOARD_RELAY_CHECKPOINT_BACKGROUND = '0';+ // And a local-first board's relay sender runs inside each command; a test of the machine's sender opts in (#1013).+ env.PULLBOARD_RELAY_SENDER_BACKGROUND = '0';env.TMPDIR = sandbox;env.TMP = sandbox;env.TEMP = sandbox;diff --git a/relay/auth.js b/relay/auth.jsindex 0e6b7e70..e574bbf0 100644--- a/relay/auth.js+++ b/relay/auth.js@@ -241,14 +241,19 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =return { ...linked, permission: permission.role, public: permission.public };}- /** Require current repository roles; cache visibility for ten minutes but never authorize a write from cache. */+ /**+ * Require current repository roles, asking GitHub once per sign-in and board in each ten-minute window (#1013).+ * Why: a write that asked GitHub every time made every move wait on GitHub; a cached grant still ends at ten+ * minutes, and any denial GitHub returns meanwhile replaces it at once, so lost access takes effect within the+ * window for reads and writes alike.+ */async function access(row, board, write) {const linked = db.prepare('SELECT * FROM relay_boards WHERE id=?').get(board);if (!linked) throw new Refused('BOARD_NOT_LINKED', 'link this board to a readable GitHub repository before using it');const key = row.user_id + ':' + board;const prior = permissions.get(key);const started = now();- if (!write && prior && started >= prior.checked && started - prior.checked < ACCESS_WINDOW_MS) return authorize(prior, linked, false);+ if (prior && started >= prior.checked && started - prior.checked < ACCESS_WINDOW_MS && (!write || prior.allowed)) return authorize(prior, linked, write);let repo;try {repo = await github.access({ id: row.user_id, login: row.login }, linked.repository);@@ -490,7 +495,7 @@ export function createRelayAuth({ database, github, now = Date.now, sessionTTL =}return { confirmed: true, board: flow.intent.board };},- /** Authenticate a human or a scoped agent; every board write asks GitHub again. */+ /** Authenticate a human or a scoped agent; GitHub is asked once per sign-in and board in each access window. */async authenticate(token, { board, write = false } = {}) {const row = credential(token);if (row.kind === 'board' && board !== row.board) throw new Refused('TOKEN_BOARD', 'use this token only on its named board; obtain another token for another board');diff --git a/src/cli-sync.js b/src/cli-sync.jsindex 99cd702e..8a055dbd 100644--- a/src/cli-sync.js+++ b/src/cli-sync.js@@ -10,7 +10,17 @@ import { Refused } from './refused.js';import { syncRelay } from './relay.js';import { executePersonRequests } from './relay-request-execution.js';import { autoLinkProject } from './relay-setup.js';-import { gitSyncLinked } from './local-state.js';+import {+ gitSyncLinked,+ relayLinkFile,+} from './local-state.js';+import { repoInfo } from './git.js';+import { takeConflictNotices } from './relay-conflicts.js';+import {+ localFirstBoard,+ nudgeRelaySender,+ senderInBackground,+} from './relay-local-first.js';import {context,withBoard,@@ -29,8 +39,34 @@ async function reportQuietly(io, error) {}}+/**+ * The relay link of a local-first board at this checkout, or null (#1013): its commands neither sync nor wait, and+ * the machine's background sender does the relay's work. With the sender off (the test runner), commands sync+ * themselves as before.+ */+function localFirstLink(io) {+ try {+ const info = repoInfo(io.cwd);+ const file = relayLinkFile(info.commonDir);+ return localFirstBoard(file, () => relayOutboxSetting(info.root)) ? { root: info.root, file } : null;+ } catch { return null; }+}++/** Say once, loudly, each queued move of this checkout's agent that lost to another machine's move (#1013). */+function tellConflicts(io, link) {+ if (!link) return;+ for (const line of takeConflictNotices(link.file, link.root)) io.err(`pullboard: ${line}`);+}+/** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */export async function retrySync(io) {+ const local = senderInBackground() ? localFirstLink(io) : null;+ if (local) {+ // No sync and no lock: hand the relay's work to the machine's sender, and deliver finished baselines here.+ nudgeRelaySender(local.root, local.file);+ try { await retryCheckBaselines(io.cwd, io); } catch (error) { await reportQuietly(io, error); }+ return;+ }try {if (io.relayCommand?.cliOperation !== 'sync' && gitSyncLinked(io.cwd)) {const ctx = context(io);@@ -46,7 +82,15 @@ export async function retrySync(io) {/** Before a command: link this project when the machine links new ones, sync, then run the person's waiting requests. */export async function syncBefore(io, main) {try { if (io.relayCommand?.cliOperation !== 'sync' && !gitSyncLinked(io.cwd)) await autoLinkProject(io.cwd, io); } catch (error) { if (!(error instanceof Refused)) throw error; }+ const local = localFirstLink(io);+ if (local && senderInBackground()) {+ // The sender runs the person's waiting requests too, so a read never waits on them.+ await retrySync(io);+ tellConflicts(io, local);+ return;+ }await retrySync(io);try { await executePersonRequests(io.cwd, io, main); }catch (error) { await reportQuietly(io, error); }+ tellConflicts(io, local);}diff --git a/src/relay-checkpoint-publish.js b/src/relay-checkpoint-publish.jsindex e82ab94c..9624da0f 100644--- a/src/relay-checkpoint-publish.js+++ b/src/relay-checkpoint-publish.js@@ -14,6 +14,11 @@ import {relaySnapshot,} from './relay-presentation.js';import { locked } from './relay-lock.js';+import {+ outboxGeneration,+ outboxWaiting,+} from './relay-outbox.js';+import { withOutboxGuard } from './relay-outbox-guard.js';import { Refused } from './refused.js';/**@@ -69,7 +74,10 @@ export function checkpointPublisher({ request, saveLink, loadLink, linkFile, readelete state.checkpointRefusal;saveLink(file, state);} else {- const fresh = prepared && !(state.checkpoint?.sequence > prepared.sequence) ? prepared : await prepareCheckpoint(root, state);+ // A queued move shows on the board before the relay orders it, so a board with one is never published (#1013).+ const fresh = prepared && !(state.checkpoint?.sequence > prepared.sequence) ? prepared+ : await withOutboxGuard(file, () => outboxWaiting(file) ? null : prepareCheckpoint(root, state));+ if (!fresh) return null;if (!state.checkpoint || state.checkpoint.sequence !== fresh.sequence || state.checkpointPresentationDigest !== fresh.digest) {delete state.checkpointRefusal;state.checkpointPresentationDigest = fresh.digest;@@ -130,10 +138,14 @@ export function checkpointPublisher({ request, saveLink, loadLink, linkFile, reaconst paused = Boolean(linked.checkpointRefusal && uploadPauseType(linked.checkpointRefusal));if (!await probeUploadPause(file, linked, io)) return false;// Reading and sealing a large board takes about a second; it happens before the lock, so moves never wait on it.+ // A move queued before or while it is read shows on the board unordered, so that read is not published (#1013).+ const generation = outboxGeneration(file);+ if (outboxWaiting(file)) return false;const prepared = await prepareCheckpoint(root, linked);const staged = await locked(file, async () => {const state = loadLink(file);if (!state || state.unlinking || state.recovery || state.pending || state.board !== linked.board) return null;+ if (outboxWaiting(file) || outboxGeneration(file) !== generation) return null;if (ifChanged && !state.checkpoint && !state.checkpointRefusal && state.presentationDigest === prepared.digest) return { current: true };const result = await stageCheckpoint(root, file, state, io, prepared, { probe: false });// A pause the probe ended counts as resumed, so its notices clear once this upload is acknowledged.diff --git a/src/relay-conflicts.js b/src/relay-conflicts.jsnew file mode 100644index 00000000..2513f359--- /dev/null+++ b/src/relay-conflicts.js@@ -0,0 +1,58 @@+/**+ * Conflict notices (#1013): a queued move another machine beat is refused when the relay's order replays, in the+ * background sender, which has no terminal. The refusal is left beside the link for the worktree whose agent made+ * the move, and that worktree's next command says it, loudly, once.+ */+import { createHash } from 'node:crypto';+import {+ appendFileSync,+ mkdirSync,+ readFileSync,+ renameSync,+ rmSync,+} from 'node:fs';+import {+ dirname,+ join,+} from 'node:path';++/** The folder of notices beside a link file. */+function noticeDirectory(linkFile) {+ return join(dirname(linkFile), 'relay-conflicts');+}++/** The notice file for one worktree, named by a digest of its path so no path text lands in a file name. */+function noticeFile(linkFile, worktree) {+ return join(noticeDirectory(linkFile), createHash('sha256').update(worktree).digest('hex').slice(0, 32) + '.txt');+}++/**+ * Leave a refusal line for the agent working in `worktree`.+ *+ * @param {string} linkFile - The board's relay link file.+ * @param {string} worktree - The agent's worktree path, as the board registers it.+ * @param {string} line - The refusal, naming the move that won.+ */+export function leaveConflictNotice(linkFile, worktree, line) {+ mkdirSync(noticeDirectory(linkFile), { recursive: true, mode: 0o700 });+ appendFileSync(noticeFile(linkFile, worktree), JSON.stringify(line) + '\n', { mode: 0o600 });+}++/**+ * Take the refusals left for `worktree`, oldest first, removing them so each is said once. A notice is moved aside+ * before it is read, so a sender adding one meanwhile starts a fresh file instead of losing its line.+ *+ * @param {string} linkFile+ * @param {string} worktree+ * @returns {string[]}+ */+export function takeConflictNotices(linkFile, worktree) {+ const file = noticeFile(linkFile, worktree);+ const taken = `${file}.${process.pid}.taken`;+ try { renameSync(file, taken); } catch { return []; }+ try {+ return readFileSync(taken, 'utf8').split('\n').filter(Boolean).flatMap((row) => {+ try { return [String(JSON.parse(row))]; } catch { return []; }+ });+ } finally { rmSync(taken, { force: true }); }+}diff --git a/src/relay-local-first.js b/src/relay-local-first.jsnew file mode 100644index 00000000..60e6ca60--- /dev/null+++ b/src/relay-local-first.js@@ -0,0 +1,115 @@+/**+ * Local first (#1013, H21): on a linked board whose relay.outbox is on, the local board is the source of truth and+ * the relay is a mailbox. A move applies here and returns at once; a read never syncs or takes a lock. One+ * background sender per machine pushes the queued moves and pulls other machines' moves, for every board on it.+ */+import { spawn } from 'node:child_process';+import { createHash, randomUUID } from 'node:crypto';+import {+ existsSync,+ mkdirSync,+ readFileSync,+ renameSync,+ rmSync,+ statSync,+ writeFileSync,+} from 'node:fs';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { pullboardHome } from './local-state.js';++/** Set to 0 to send inside each command instead, as before #1013; the test runner sets it, like the view. */+export const SENDER_BACKGROUND_ENV = 'PULLBOARD_RELAY_SENDER_BACKGROUND';+const WORKER = fileURLToPath(new URL('./relay-sender-worker.js', import.meta.url));++/**+ * Whether this process leaves sending to the machine's background sender.+ *+ * @param {NodeJS.ProcessEnv} env+ * @returns {boolean}+ */+export function senderInBackground(env = process.env) {+ return env[SENDER_BACKGROUND_ENV] !== '0';+}++/**+ * The machine sender's files: its claim, its short log, and one note per board it serves.+ *+ * @returns {{ directory: string, pid: string, log: string, boards: string }}+ */+export function senderFiles() {+ const directory = join(pullboardHome(), 'relay-sender');+ return { directory, pid: join(directory, 'sender.pid'), log: join(directory, 'sender.log'), boards: join(directory, 'boards') };+}++// Budget: a sender refreshes its claim every few seconds while it runs; a claim this old belongs to a process that+// died, whose number may since have been reused.+const CLAIM_STALE_MS = 120_000;++/** Whether a process is alive; one another user owns still is. */+export function alive(pid) {+ if (!Number.isSafeInteger(pid) || pid < 1) return false;+ try { process.kill(pid, 0); return true; }+ catch (error) { return error.code === 'EPERM'; }+}++/**+ * The live sender holding this machine's claim, or 0.+ *+ * @returns {number}+ */+export function senderHolding() {+ const { pid } = senderFiles();+ try {+ if (Date.now() - statSync(pid).mtimeMs > CLAIM_STALE_MS) return 0;+ const holder = Number(readFileSync(pid, 'utf8'));+ return alive(holder) ? holder : 0;+ } catch { return 0; }+}++/** The note a board keeps in the sender's folder, named by its link file. */+export function boardNote(file) {+ return join(senderFiles().boards, createHash('sha256').update(file).digest('hex').slice(0, 32) + '.json');+}++/**+ * Tell the machine's sender that a board has work, and start the sender unless a live one runs. Never waits and+ * never touches the network: the command that calls it returns at once.+ *+ * @param {string} root - The board's checkout.+ * @param {string} file - The board's relay link file.+ */+export function nudgeRelaySender(root, file) {+ if (!senderInBackground()) return;+ try {+ const note = boardNote(file);+ mkdirSync(senderFiles().boards, { recursive: true, mode: 0o700 });+ const temporary = `${note}.${randomUUID()}.tmp`;+ try {+ writeFileSync(temporary, JSON.stringify({ root, file, due: Date.now() }) + '\n', { flag: 'wx', mode: 0o600 });+ renameSync(temporary, note);+ } finally { rmSync(temporary, { force: true }); }+ if (senderHolding()) return;+ const env = { ...process.env };+ delete env.PULLBOARD_RELAY_TOKEN; // The sender works only with this machine's own saved credentials.+ const child = spawn(process.execPath, [WORKER], { cwd: root, detached: true, stdio: 'ignore', env });+ child.unref();+ } catch { /* A board the sender misses now is served by the next command's nudge; the move is already saved. */ }+}++/**+ * Whether the board at this checkout is local first: linked in order, its baseline accepted, its relay.outbox on,+ * and no environment token in this shell. Reads two small local files and the committed setting, nothing more.+ *+ * @param {string} file - The board's relay link file.+ * @param {() => boolean} outboxSetting - Reads the board's committed relay.outbox setting.+ * @returns {boolean}+ */+export function localFirstBoard(file, outboxSetting) {+ if (process.env.PULLBOARD_RELAY_TOKEN !== undefined || !existsSync(file)) return false;+ let state;+ try { state = JSON.parse(readFileSync(file, 'utf8')); } catch { return false; }+ if (!state || state.unlinking || state.recovery || state.mode !== 'ordered' || state.baselineAccepted !== true+ || state.baselineConflict || state.environment) return false;+ try { return outboxSetting() === true; } catch { return false; }+}diff --git a/src/relay-outbox-guard.js b/src/relay-outbox-guard.jsnew file mode 100644index 00000000..4fc3ecda--- /dev/null+++ b/src/relay-outbox-guard.js@@ -0,0 +1,66 @@+/**+ * The outbox guard (#1013): a short local lock around the relay outbox and the board changes it stands for. A move+ * holds it while it queues and applies itself; the background sender holds it only while it rebuilds the board from+ * what the relay ordered. Neither holds it across a network call, so a move never waits on the relay.+ */+import {+ mkdirSync,+} from 'node:fs';+import { DatabaseSync } from 'node:sqlite';+import {+ dirname,+ join,+} from 'node:path';++// Budget: the guard is held only for local SQLite work (queue one move, or rebuild a board); a minute covers the+// largest board's rebuild with room, and a holder that died releases its lock with its process.+const GUARD_WAIT_MS = 60_000;++/** Guards this process holds now, by file, so a nested section inside one holder does not wait on itself. */+const HELD = new Map();++/** The guard file beside a relay link file. */+export function outboxGuardFile(linkFile) {+ return join(dirname(linkFile), 'relay-outbox.guard.sqlite');+}++/**+ * Run `work` holding the board's outbox guard, waiting while another process holds it.+ *+ * @template T+ * @param {string} linkFile - The board's relay link file.+ * @param {() => Promise<T> | T} work+ * @returns {Promise<T>}+ */+export function withOutboxGuard(linkFile, work) {+ return withFileLock(outboxGuardFile(linkFile), work);+}++/**+ * Run `work` holding an exclusive SQLite lock on `file`, waiting while another process holds it.+ * Why: SQLite's exclusive lock is released by the operating system when its holder dies, so a crashed command or+ * sender never leaves a board stuck; and it needs no polling, so a waiter starts the moment the holder finishes.+ *+ * @template T+ * @param {string} file+ * @param {() => Promise<T> | T} work+ * @returns {Promise<T>}+ */+export async function withFileLock(file, work) {+ if (HELD.get(file)) {+ HELD.set(file, HELD.get(file) + 1);+ try { return await work(); } finally { HELD.set(file, HELD.get(file) - 1); }+ }+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });+ const db = new DatabaseSync(file);+ try {+ db.exec(`PRAGMA busy_timeout = ${GUARD_WAIT_MS}`);+ db.exec('BEGIN EXCLUSIVE');+ HELD.set(file, 1);+ try { return await work(); }+ finally {+ HELD.delete(file);+ try { db.exec('COMMIT'); } catch { /* Nothing was written; closing releases the lock either way. */ }+ }+ } finally { db.close(); }+}diff --git a/src/relay-outbox.js b/src/relay-outbox.jsindex c1c65150..0e33fa80 100644--- a/src/relay-outbox.js+++ b/src/relay-outbox.js@@ -30,9 +30,10 @@ import {restoreRelaySnapshot,} from './exchange.js';import { readBoardKey } from './relay-key.js';+import { leaveConflictNotice } from './relay-conflicts.js';+import { withOutboxGuard } from './relay-outbox-guard.js';import { transientRelayFailure } from './relay-move-fallback.js';import {- actorTransport,seatReceipt,withSeatName,} from './relay-seats.js';@@ -150,10 +151,11 @@ export function keepRefusal(state, entry, refusal, earlier) {return refusalLine(kept);}-/** Say what a refused replay was and which ordered moves came first. */+/** Say what a refused replay was, which move won, and which ordered moves came first. */export function refusalLine(kept) {+ const winner = kept.earlier.at(-1);const first = kept.earlier.length- ? `; moves the relay ordered first: ${kept.earlier.map(({ sequence, move }) => `sequence ${sequence} ${move}`).join(', ')}`+ ? `; won by sequence ${winner.sequence} ${winner.move}; moves the relay ordered first: ${kept.earlier.map(({ sequence, move }) => `sequence ${sequence} ${move}`).join(', ')}`: '; no other move reached the relay first';return `[RELAY_OUTBOX_REFUSED] the queued move ${kept.move} (made ${kept.queuedAt}) was refused when it replayed: [${kept.code}] ${kept.message}${first}`;}@@ -317,20 +319,71 @@ function exportedSequence(native) {return Number(native.tables.board_meta.find((row) => row.meta_key === 'relay_applied_sequence')?.meta_value ?? 0);}-/** Keep the key-free outbox summary on the link, or drop it once the outbox is empty. */-function saveOutboxSummary({ file, state, saveLink }, outbox) {- if (outbox?.moves.length) state.outbox = { restored: outbox.restored, moves: outbox.moves.map(outboxEntrySummary) };- else delete state.outbox;- saveLink(file, state);+/** 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');+}++/**+ * Read the key-free outbox summary, or null when no move waits.+ * Why: a move queues itself without the relay lock, so it never writes relay.json, which the sender owns; the+ * summary lives in its own file, and the link reads it from there (#1013).+ */+export function readOutboxSummary(linkFile) {+ try {+ const summary = JSON.parse(readFileSync(outboxSummaryFile(linkFile), 'utf8'));+ return Array.isArray(summary?.moves) && summary.moves.length ? summary : null;+ } catch { return null; }+}++/** Keep the key-free outbox summary beside the link, or drop it once the outbox is empty. */+function saveOutboxSummary({ file, state }, outbox) {+ const where = outboxSummaryFile(file);+ if (outbox?.moves.length) {+ state.outbox = { restored: outbox.restored, moves: outbox.moves.map(outboxEntrySummary) };+ mkdirSync(dirname(where), { recursive: true, mode: 0o700 });+ const temporary = where + '.' + randomUUID() + '.tmp';+ try {+ writeFileSync(temporary, JSON.stringify(state.outbox) + '\n', { flag: 'wx', mode: 0o600 });+ renameSync(temporary, where);+ } finally { rmSync(temporary, { force: true }); }+ } else {+ delete state.outbox;+ rmSync(where, { force: true });+ }+}++/** Whether a move waits in the outbox now, read from disk rather than from a link loaded earlier. */+export function outboxWaiting(linkFile) {+ return existsSync(outboxFile(linkFile));+}++/** The file counting moves ever queued on this board, beside its link. */+function generationFile(linkFile) {+ return join(dirname(linkFile), 'relay-outbox.generation');+}++/**+ * How many moves this machine has queued on the board, as a number that only grows.+ * Why: a checkpoint read without the outbox guard is safe to publish only if no move was queued while it was read,+ * since a queued move shows on the board before the relay orders it (#1013).+ */+export function outboxGeneration(linkFile) {+ try { return Number(readFileSync(generationFile(linkFile), 'utf8')) || 0; } catch { return 0; }+}++/** Count one more queued move. */+function bumpGeneration(linkFile) {+ writeFileSync(generationFile(linkFile), `${outboxGeneration(linkFile) + 1}\n`, { mode: 0o600 });}/**- * Queue a move the relay could not take on an accepted link, then make it on this machine (#922).- * The first queued move seals the board as the relay last ordered it; the move is written before it is applied,- * so a crash between the two leaves it queued and the replay starts from that image anyway. A move this board- * refuses is refused now and never queued.+ * Queue a move on an accepted link, then make it on this machine (#922, #1013). The caller holds the outbox guard.+ * The first queued move seals the board as the relay last ordered it; the move is written before it is applied, so+ * a crash between the two leaves it queued and the next rebuild starts from that image anyway. A move this board+ * refuses is refused now and never queued. `quiet` is a local-first move, which says nothing: queuing is normal.*/-export async function queueMove(link, { operation, args, command, move, error, applyLocally }) {+export async function queueMove(link, { operation, args, command, move, error, applyLocally, quiet = false }) {const { root, file, state, io, localRecords, safePauseCode, safePauseMessage } = link;const key = readBoardKey(state.board);const where = outboxFile(file);@@ -340,7 +393,7 @@ export async function queueMove(link, { operation, args, command, move, error, a})();if (!move) {const sent = withSeatName(root, operation, args);- move = stampCoordinatorHolder(localRecords(root, (board) => prepareEngineMove(board, operation, sent)), state.machine);+ move = stampCoordinatorHolder(localRecords(root, (board) => prepareEngineMove(board, operation, sent)), state.machine, state.computerName);move.actor = relayMoveActor(move) ?? credentialActor(move);}const stray = strayItemRefs(outbox, move);@@ -348,11 +401,16 @@ export async function queueMove(link, { operation, args, command, move, error, athrow new Refused('RELAY_OUTBOX_UNBOUND', `this move names #${stray[0]}, which this machine added while the relay was down, in a field the outbox cannot follow if the relay renumbers it; run it again once the relay answers`);}// `after` is the relay sequence this machine had seen: a refusal at replay names the moves ordered since.- const entry = { move, refs: bindRefs(outbox, move), intent: operationIntent(operation, args), queuedAt: new Date().toISOString(), after: state.sequence,+ const 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) } : {}) };outbox.moves.push(entry);+ bumpGeneration(file);await writeOutbox(where, key, state.board, outbox);- if (state.pending?.move?.id === move.id) delete state.pending;+ if (state.pending?.move?.id === move.id) {+ delete state.pending;+ link.saveLink(file, state);+ }saveOutboxSummary(link, outbox);let result;try { result = await applyLocally(); }@@ -367,28 +425,141 @@ export async function queueMove(link, { operation, args, command, move, error, arememberCreatedItems(entry, result);await writeOutbox(where, key, state.board, outbox);}- if (!OUTBOX_NOTICES.has(io)) {+ 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`);}return result;}+/** Most send-and-rebuild rounds one flush takes before it leaves the rest to the next. */+const FLUSH_ROUNDS = 100;++/**+ * 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) {+ const { file, state, io, request } = link;+ const outbox = await readOutbox(outboxFile(file), key, state.board);+ if (!outbox?.moves.length) return null;+ const events = async (after) => {+ const remote = await request(state, '/api/v1/boards/' + state.board + '/events?after=' + after, {}, io);+ if ([remote.warning, ...(remote.warnings ?? [])].some((warning) => warning?.code === 'KEY_REQUESTS')) io.keyRequestsWaiting = true;+ if (!Array.isArray(remote.events) || remote.events.some((record, index) => !record || record.event_id !== after + index + 1 || !['move', 'request'].includes(record.kind) || typeof record.sealed !== 'string')) {+ throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid ordered prefix; fetch a consistent relay snapshot');+ }+ return remote.events;+ };+ try { return { baseSequence: outbox.baseSequence, events: await events(outbox.baseSequence) }; }+ catch (error) {+ if (error.code !== 'SNAPSHOT_REQUIRED') throw error;+ const checkpoint = await link.fetchCheckpoint(key);+ if (checkpoint.sequence <= outbox.baseSequence) throw new Refused('RELAY_RESPONSE', 'the relay checkpoint did not advance the missing prefix; fetch a consistent newer snapshot');+ return { baseSequence: outbox.baseSequence, checkpoint, events: await events(checkpoint.sequence) };+ }+}++/** Put the board back to an image the relay ordered, keeping each seat's newer shout-read position. */+function restoreBase(link, image, sequence) {+ link.localRecords(link.root, (board) => {+ 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);+ });+}++/** Settle one queued move the relay ordered: report a refusal with the move that won, and note a renumbered item. */+function settle(link, outbox, entry, receipt) {+ const { root, state, io, localRecords } = link;+ if (receipt.outcome.error) {+ const earlier = localRecords(root, (board) => earlierMoves(board, { ...entry, move: resolveMove(entry, outbox).move }, receipt.sequence));+ const line = keepRefusal(state, entry, receipt.outcome.error, earlier);+ io.err(`pullboard: ${line}`);+ tellAgent(link, entry.move.actor, line);+ }+ if (!createsItems(entry.move.operation)) return;+ outbox.results[entry.move.id] = receipt.outcome.error ? null : receipt.outcome.result;+ for (const { item: was, resultPath } of entryCreatedItems(entry)) {+ const is = createdItemAt(receipt.outcome.result, resultPath);+ if (!receipt.outcome.error && Number.isSafeInteger(is) && is !== was) {+ state.outboxRenumbered = [...(state.outboxRenumbered ?? []), { was, is }].slice(-KEPT_REFUSALS);+ io.err(`pullboard: the item this machine showed as #${was} while the relay was down is #${is} on the board; its queued moves follow it`);+ }+ }+}++/**+ * Leave a refusal found at replay for the agent whose move it was, so its next command says it (#1013).+ * Why: the background sender has no terminal; the agent that made the move is the one that must hear it lost.+ */+function tellAgent(link, actor, line) {+ if (typeof actor !== 'string') return;+ try {+ const path = link.localRecords(link.root, (board) => board.db.prepare('SELECT agent_path FROM agent WHERE agent_id = ?').get(actor)?.agent_path);+ if (path) leaveConflictNotice(link.file, path, line);+ } catch { /* The refusal stays in pullboard status even when no notice can be left. */ }+}+/**- * Put the queued moves back on top of the board after a replay stopped part way (#922): seal the board as the relay- * has now ordered it, then apply each remaining move here again, so this machine keeps showing them.+ * Rebuild the board from what the relay ordered (#1013); the caller holds the outbox guard. The board goes back to+ * the outbox's base image (or the relay's checkpoint), every ordered record replays through the engine, each queued+ * move the relay now holds is settled by its receipt, and the moves still queued are made again on top, so this+ * machine keeps showing them. Returns whether moves still wait.*/-async function rebaseOutbox(link, outbox, key) {- const { root, file, state, localRecords } = link;+async function rebuild(link, key, pulled) {+ const { root, file, state, localRecords, saveLink } = link;+ const where = outboxFile(file);+ // Read again under the guard: a move may have queued itself while the relay was being read.+ const outbox = await readOutbox(where, key, state.board);+ if (!outbox?.moves.length) {+ removeOutbox(where);+ saveOutboxSummary(link, null);+ return false;+ }+ 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;+ if (pulled.checkpoint) restoreBase(link, pulled.checkpoint.native, pulled.checkpoint.sequence);+ else restoreBase(link, outbox.base, outbox.baseSequence);+ 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));+ outbox.results ??= {};+ const waiting = [];+ for (const entry of outbox.moves) {+ const receipt = localRecords(root, (board) => engineReceipt(board, entry.move.id));+ if (!receipt) { waiting.push(entry); continue; }+ if (state.pending?.move?.id === entry.move.id) delete state.pending;+ if (state.recovered?.move?.id === entry.move.id) delete state.recovered;+ settle(link, outbox, entry, receipt);+ }+ outbox.moves = [];+ for (const entry of waiting) {+ const { lost } = resolveMove(entry, { ...outbox, moves: waiting });+ // A move on an item whose add was refused is refused itself; sent, it would act on another item.+ if (lost.length && (entry.refs ?? []).every((ref) => !waiting.some((other) => other.move.id === ref.add))) {+ const line = keepRefusal(state, entry, { code: 'RELAY_OUTBOX_DEPENDS', message: `it acts on #${lost[0]}, which this machine added while the relay was down, and that add was refused` }, []);+ link.io.err(`pullboard: ${line}`);+ tellAgent(link, entry.move.actor, line);+ continue;+ }+ outbox.moves.push(entry);+ }outbox.base = localRecords(root, (board) => exportBoard(board));outbox.baseSequence = exportedSequence(outbox.base);outbox.restored = false;- await writeOutbox(outboxFile(file), key, state.board, outbox);- saveOutboxSummary(link, outbox);+ if (!outbox.moves.length) {+ removeOutbox(where);+ saveOutboxSummary(link, null);+ saveLink(file, state);+ return false;+ }for (const entry of outbox.moves) {- const { move, lost } = resolveMove(entry, outbox, { local: true });- // A move on an item whose add was refused stays queued for its own refusal; here it would hit another item.- if (lost.length) continue;+ 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; }@@ -396,98 +567,67 @@ async function rebaseOutbox(link, outbox, key) {// A re-applied add may get another number here; later moves reach it through their bound add, not the number.rememberCreatedItems(entry, result);}- await writeOutbox(outboxFile(file), key, state.board, outbox);+ await writeOutbox(where, key, state.board, outbox);+ saveOutboxSummary(link, outbox);+ saveLink(file, state);+ return true;+}++/**+ * Send the queued moves the relay does not hold yet, in order, each at the next sequence (#1013). Network only: the+ * board is not touched; the next rebuild applies what the relay took. Stops at a move that names an item whose add+ * the relay has not numbered yet, and at another machine's move in the way. Returns how many went up.+ */+async function sendQueued(link, key) {+ const { root, file, state, io, localRecords, sealedRecord } = link;+ const outbox = await readOutbox(outboxFile(file), key, state.board);+ let sent = 0;+ for (const entry of outbox?.moves ?? []) {+ if ((entry.refs ?? []).some((ref) => outbox.moves.some((other) => other.move.id === ref.add))) break;+ const { move, lost } = resolveMove(entry, outbox);+ if (lost.length) break;+ if (localRecords(root, (board) => engineReceipt(board, move.id))) continue;+ const sequence = outbox.baseSequence + sent + 1;+ const sealed = await sealedRecord(key, move, state, 'move', sequence);+ const registration = seatReceipt(move, sequence, sealed);+ const pending = { move, intent: entry.intent, ...(entry.command ? { command: entry.command, commandIntent: entry.commandIntent } : {}),+ sequence, sealed, ...(registration ? { registration } : {}) };+ try { await link.postPending(root, file, state, pending, io); }+ catch (error) {+ // Another machine's move took this place: the next pull orders it first and this move goes after it.+ if (['SEQUENCE_REPEAT', 'SEQUENCE_GAP'].includes(error.code)) break;+ // A lost reply may have been taken; the next pull says, by the move's receipt, without sending it twice.+ if (sent && transientRelayFailure(error)) break;+ throw error;+ }+ sent += 1;+ }+ return sent;}/**- * Replay the ordered outbox before this machine applies or sends anything else (#922). The board goes back to the- * image the relay last ordered, catches up with every other machine's moves, then sends each queued move in order:- * a move the relay already holds from a lost reply is not sent twice, and a move refused at replay is reported with- * the moves ordered before it. A relay that fails again part way puts the rest back on top and throws its failure.+ * Send the outbox and bring this machine up to the relay's order (#922, #1013). Each round reads what the relay+ * ordered since the base image, rebuilds the board under the outbox guard, then sends what still waits. Only the+ * rebuild holds the guard, so moves keep queuing while the relay is read or written, and the board never shows a+ * half-replayed state between rounds. A relay failure leaves every move queued and the board as its person last saw+ * it, and is thrown for the caller to report.*/export async function flushOutbox(link) {- const { root, file, state, io, request, catchUp, sendPending, sealedRecord, localRecords, saveLink } = link;+ const { file, state } = link;const where = outboxFile(file);if (!state.outbox && !existsSync(where)) return;const key = readBoardKey(state.board);- const outbox = await readOutbox(where, key, state.board);- if (!outbox?.moves.length) {- removeOutbox(where);- saveOutboxSummary(link, null);- return;- }- try {- if (!outbox.restored) {- // Probe first: a relay that is still down leaves this machine's board exactly as its person last saw it.- try { await request(state, '/api/v1/boards/' + state.board + '/events?after=' + outbox.baseSequence, {}, io); }- catch (error) { if (error.code !== 'SNAPSHOT_REQUIRED') throw error; }- localRecords(root, (board) => {- const cursors = board.db.prepare('SELECT agent_id, agent_last_shout_id FROM agent').all();- restoreRelaySnapshot(board, outbox.base, outbox.baseSequence);- // 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);+ for (let round = 0; round < FLUSH_ROUNDS; round += 1) {+ const pulled = await pullSinceBase(link, key);+ const waiting = pulled ? await withOutboxGuard(file, () => rebuild(link, key, pulled))+ : await withOutboxGuard(file, async () => {+ if (await readOutbox(where, key, state.board)) return true;+ saveOutboxSummary(link, null);+ return false;});- state.sequence = outbox.baseSequence;- outbox.restored = true;- await writeOutbox(where, key, state.board, outbox);- saveOutboxSummary(link, outbox);- }- await catchUp(root, file, state, io);- outbox.results ??= {};- while (outbox.moves.length) {- const entry = outbox.moves[0];- const receiptOf = () => localRecords(root, (board) => engineReceipt(board, entry.move.id));- let receipt = receiptOf();- let sequence = receipt?.sequence;- if (!receipt) {- const { move, lost } = resolveMove(entry, outbox);- if (lost.length) {- io.err(`pullboard: ${keepRefusal(state, entry, { code: 'RELAY_OUTBOX_DEPENDS', message: `it acts on #${lost[0]}, which this machine added while the relay was down, and that add was refused` }, [])}`);- await finishEntry(link, outbox, where, key);- continue;- }- // The queued move keeps its bindings; the resolved copy is what goes up, under the same move id.- await actorTransport(root, file, state, credentialActor(move), io);- sequence = state.sequence + 1;- const sealed = await sealedRecord(key, move, state, 'move', sequence);- const registration = seatReceipt(move, sequence, sealed);- state.pending = { move, intent: entry.intent, ...(entry.command ? { command: entry.command, commandIntent: entry.commandIntent } : {}),- sequence, sealed, ...(registration ? { registration } : {}) };- saveLink(file, state);- let failure;- try { await sendPending(root, file, state, io); } catch (error) { failure = error; }- if (failure && !receiptOf()) {- if (!['RELAY_UNAVAILABLE', 'RELAY_RESPONSE'].includes(failure.code)) throw failure;- try { await catchUp(root, file, state, io); } catch { throw failure; }- }- receipt = receiptOf();- if (!receipt) throw failure ?? new Refused('RELAY_RESPONSE', 'the relay acknowledged a queued move without its replay receipt; run pullboard status to retry the outbox');- sequence = receipt.sequence;- }- if (state.pending?.move?.id === entry.move.id) delete state.pending;- if (state.recovered?.move?.id === entry.move.id) delete state.recovered;- if (receipt.outcome.error) {- const earlier = localRecords(root, (board) => earlierMoves(board, { ...entry, move: resolveMove(entry, outbox).move }, sequence));- io.err(`pullboard: ${keepRefusal(state, entry, receipt.outcome.error, earlier)}`);- }- if (createsItems(entry.move.operation)) {- outbox.results[entry.move.id] = receipt.outcome.error ? null : receipt.outcome.result;- for (const { item: was, resultPath } of entryCreatedItems(entry)) {- const is = createdItemAt(receipt.outcome.result, resultPath);- if (!receipt.outcome.error && Number.isSafeInteger(is) && is !== was) {- state.outboxRenumbered = [...(state.outboxRenumbered ?? []), { was, is }].slice(-KEPT_REFUSALS);- io.err(`pullboard: the item this machine showed as #${was} while the relay was down is #${is} on the board; its queued moves follow it`);- }- }- }- await finishEntry(link, outbox, where, key);- }- } catch (error) {- if (outbox.restored && outbox.moves.length) {- if (state.pending && outbox.moves.some((entry) => entry.move.id === state.pending.move?.id)) delete state.pending;- await rebaseOutbox(link, outbox, key);- }- throw error;+ if (!waiting) return;+ if (!pulled) 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-sender-worker.js b/src/relay-sender-worker.jsnew file mode 100644index 00000000..8384c3ec--- /dev/null+++ b/src/relay-sender-worker.js@@ -0,0 +1,137 @@+/**+ * The machine's background relay sender (#1013): one per machine, serving every local-first board on it. For each+ * board a command nudged, and every few seconds while it runs, it sends the queued moves and pulls other machines'+ * moves under that board's relay lock, then runs the person's waiting requests. Commands never wait on it. It exits+ * once no board has been nudged for a while and no move waits; a failure backs off and is kept in its short log.+ *+ * Usage (spawned by nudgeRelaySender): node relay-sender-worker.js+ */+import {+ appendFileSync,+ existsSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ rmSync,+ utimesSync,+ writeFileSync,+} from 'node:fs';+import { join } from 'node:path';+import { withFileLock } from './relay-outbox-guard.js';+import { outboxWaiting } from './relay-outbox.js';+import {+ senderFiles,+ senderHolding,+} from './relay-local-first.js';++const files = senderFiles();+// Budget: a board is pulled this often while the sender runs, so another machine's move shows here within seconds.+const PULL_MS = Number(process.env.PULLBOARD_RELAY_SENDER_PULL_MS) || 3_000;+// Budget: the sender stays this long after the last nudge, so a working session keeps one warm sender.+const IDLE_MS = Number(process.env.PULLBOARD_RELAY_SENDER_IDLE_MS) || 60_000;+// Budget: a failing board is retried no more often than this at worst, and once a second at best.+const BACKOFF_MAX_MS = 30_000;+const TICK_MS = 100;++/** Keep a short record of each pass beside the claim; status and a person debugging read it. */+const io = {+ say(line) { io.err(line); },+ err(line) {+ try { appendFileSync(files.log, `${new Date().toISOString()} ${String(line).trim()}\n`, { mode: 0o600 }); } catch { /* No log is no worse than none. */ }+ },+};++/** Read every board note: the board's checkout, its link file, and when a command last nudged it. */+function notes() {+ let names = [];+ try { names = readdirSync(files.boards).filter((name) => name.endsWith('.json')); } catch { return []; }+ return names.flatMap((name) => {+ try {+ const note = JSON.parse(readFileSync(join(files.boards, name), 'utf8'));+ return typeof note.root === 'string' && typeof note.file === 'string' && Number.isFinite(note.due) ? [{ ...note, path: join(files.boards, name) }] : [];+ } catch { return []; }+ });+}++/**+ * Claim the machine's sender place. The decision is made under a lock, so two senders started together cannot+ * both take it: the second sees the first's live claim and exits.+ */+async function claim() {+ mkdirSync(files.directory, { recursive: true, mode: 0o700 });+ return withFileLock(join(files.directory, 'claim.sqlite'), () => {+ const holder = senderHolding();+ if (holder && holder !== process.pid) return false;+ writeFileSync(files.pid, `${process.pid}\n`, { mode: 0o600 });+ writeFileSync(files.log, '', { mode: 0o600 }); // Each sender keeps only its own short story.+ io.say(`claimed by ${process.pid}`);+ return true;+ });+}++/** Give up the claim, only while it is still this process's own. */+async function release() {+ await withFileLock(join(files.directory, 'claim.sqlite'), () => {+ try { if (Number(readFileSync(files.pid, 'utf8')) === process.pid) rmSync(files.pid, { force: true }); } catch { /* Already gone. */ }+ });+}++/** Send and pull one board under its relay lock, then run the person's waiting requests. True when nothing waits. */+async function serve(root, file) {+ const { syncRelay } = await import('./relay.js');+ const { relayOutboxSetting } = await import('./cli.js');+ const boardIo = { ...io, relayOutbox: () => relayOutboxSetting(root) };+ await syncRelay(root, boardIo);+ try {+ const { executePersonRequests } = await import('./relay-request-execution.js');+ const { main } = await import('./cli-main.js');+ await executePersonRequests(root, boardIo, main);+ } catch (error) { io.err(`person requests not run: ${error.message}`); }+ return !outboxWaiting(file);+}++/** Per board: when it was last served, and when a failing board may be tried again. */+const boards = new Map();++/**+ * Serve boards until none has been nudged for the idle period and no move waits; returns the newest nudge seen.+ * A board is served when a command nudged it since its last pass, or once the pull period has passed.+ */+async function serveUntilIdle() {+ let newest = 0;+ for (;;) {+ try { utimesSync(files.pid, new Date(), new Date()); } catch { /* A removed claim is re-made by the next sender. */ }+ const now = Date.now();+ const seen = notes();+ let waiting = false;+ for (const note of seen) {+ newest = Math.max(newest, note.due);+ if (!existsSync(note.file)) { rmSync(note.path, { force: true }); continue; }+ const board = boards.get(note.file) ?? { served: 0, failures: 0, retryAt: 0 };+ boards.set(note.file, board);+ const nudged = note.due > board.served;+ if (now < board.retryAt || !(nudged || now - board.served >= PULL_MS)) { waiting ||= outboxWaiting(note.file); continue; }+ board.served = Date.now();+ let settled = false;+ try { settled = await serve(note.root, note.file); }+ catch (error) { io.err(`${note.root}: ${error.message}`); }+ if (settled) { board.failures = 0; board.retryAt = 0; }+ else {+ board.failures += 1;+ board.retryAt = Date.now() + Math.min(BACKOFF_MAX_MS, 1000 * 2 ** Math.min(board.failures - 1, 5));+ waiting = true;+ }+ }+ if (!waiting && Date.now() - newest >= IDLE_MS) return newest;+ await new Promise((next) => setTimeout(next, TICK_MS));+ }+}++// A nudge after the last look, but before the claim was released, saw a live sender and started none: look once+// more after releasing, and go again if a newer one came.+for (let newest = -1; await claim();) {+ try { newest = await serveUntilIdle(); }+ catch (error) { io.err(`sender stopped: ${error.message}`); newest = Infinity; }+ finally { await release(); }+ if (!notes().some((note) => note.due > newest)) break;+}diff --git a/src/relay.js b/src/relay.jsindex 08b30e8c..4667147b 100644--- a/src/relay.js+++ b/src/relay.js@@ -111,6 +111,8 @@ import {import { terminalQr } from './qr.js';import { environmentLink } from './relay-environment.js';import { locked } from './relay-lock.js';+import { withOutboxGuard } from './relay-outbox-guard.js';+import { nudgeRelaySender } from './relay-local-first.js';import { checkpointPublisher } from './relay-checkpoint-publish.js';import {checkpointInBackground,@@ -131,7 +133,10 @@ import {flushOutbox,outboxAhead,outboxFields,+ outboxFile,outboxQueueable,+ outboxWaiting,+ readOutboxSummary,queueMove,} from './relay-outbox.js';import { stampCoordinatorHolder } from './coordinator-hold.js';@@ -327,6 +332,10 @@ function loadLink(file) {saveLink(file, state);}STATE_FILES.set(state, file);+ // A move queues itself without the relay lock, so the outbox summary lives in its own file (#1013).+ const waiting = readOutboxSummary(file);+ if (waiting) state.outbox = waiting;+ else if (!existsSync(outboxFile(file))) delete state.outbox;return state;}@@ -336,7 +345,8 @@ export function saveLink(file, state) {mkdirSync(dirname(file), { recursive: true, mode: 0o700 });const temporary = file + '.' + randomUUID() + '.tmp';try {- writeFileSync(temporary, JSON.stringify(state) + '\n', { flag: 'wx', mode: 0o600 });+ // The outbox summary is the outbox's own file; a link saved by the sender never overwrites a move's (#1013).+ writeFileSync(temporary, JSON.stringify({ ...state, outbox: undefined }) + '\n', { flag: 'wx', mode: 0o600 });renameSync(temporary, file);} finally { rmSync(temporary, { force: true }); }}@@ -961,29 +971,63 @@ function reportRecoveredReply(record, io) {delete record.lostReply;}+/** Apply authenticated relay records in order, each in its own board transaction with a durable receipt. */+async function applyRecords(root, key, state, records) {+ const outcomes = [];+ for (const record of records) {+ const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });+ try { outcomes.push(await replayRelayRecord(board, key, state, record)); } finally { store.closeBoard(board); }+ }+ return outcomes;+}++/** 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);+ const snapshot = document.state;+ if (!snapshot || !Number.isSafeInteger(snapshot.sequence) || snapshot.sequence < 0) throw new Refused('RELAY_RESPONSE', 'the relay snapshot has no valid coverage sequence; fetch it again');+ const senderProblem = relaySenderProblem(null, snapshot.sender, 'snapshot');+ if (senderProblem) throw senderProblem;+ return { native: await decoded(key, snapshot, state, 'snapshot', snapshot.sequence), sequence: snapshot.sequence };+}++/** Most catch-up passes one command makes when moves keep queuing on this machine meanwhile. */+const CATCH_UP_PASSES = 10;+/** Apply a validated relay prefix with durable, transaction-bound receipts on this replica. */-async function catchUp(root, file, state, io) {- // Queued moves sit on top of this board until the outbox replays; another machine's moves must not land under them.- if (outboxAhead(state)) throw new Refused('RELAY_OUTBOX_PENDING', 'this machine holds moves the relay has not ordered yet; run pullboard status to send them first');+async function catchUp(root, file, state, io, pass = 0) {+ if (pass >= CATCH_UP_PASSES) throw new Refused('RELAY_BUSY', 'moves kept queuing on this machine while it caught up; they stay queued for the next send');+ // Queued moves sit on top of this board: the outbox rebuilds it from the relay's order with them on top (#1013).+ if (outboxAhead(state) || outboxWaiting(file)) await flushOutbox(outboxLink(root, file, state, io));const key = readBoardKey(state.board);const after = localRecords(root, appliedSequence);let remote;try { remote = await request(state, '/api/v1/boards/' + state.board + '/events?after=' + after, {}, io); }catch (error) {if (error.code !== 'SNAPSHOT_REQUIRED') throw error;- await restoreCheckpoint(root, state, io, key);+ const checkpoint = await fetchCheckpoint(state, io, key);+ const restored = await withOutboxGuard(file, () => {+ if (outboxWaiting(file)) return false;+ localRecords(root, (board) => restoreRelaySnapshot(board, checkpoint.native, checkpoint.sequence));+ return true;+ });+ if (!restored) return catchUp(root, file, state, io, pass + 1);if (localRecords(root, appliedSequence) <= after) throw new Refused('RELAY_RESPONSE', 'the relay checkpoint did not advance the missing prefix; fetch a consistent newer snapshot');- return catchUp(root, file, state, io);+ return catchUp(root, file, state, io, pass);}if ([remote.warning, ...(remote.warnings ?? [])].some((warning) => warning?.code === 'KEY_REQUESTS')) io.keyRequestsWaiting = true;if (!Array.isArray(remote.events) || remote.events.some((record, index) => !record || record.event_id !== after + index + 1 || !['move', 'request'].includes(record.kind) || typeof record.sealed !== 'string')) {throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid ordered prefix; fetch a consistent relay snapshot');}+ // Another machine's moves land only on a board with nothing queued on top; a move may have queued meanwhile.+ const outcomes = await withOutboxGuard(file, async () => {+ if (outboxWaiting(file) || localRecords(root, appliedSequence) !== after) return null;+ return applyRecords(root, key, state, remote.events);+ });+ if (!outcomes) return catchUp(root, file, state, io, pass + 1);let pendingRefusal;- for (const record of remote.events) {- const board = store.openBoard(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });- let outcome;- try { outcome = await replayRelayRecord(board, key, state, record); } finally { store.closeBoard(board); }+ remote.events.forEach((record, index) => {+ const outcome = outcomes[index];// Exact ciphertext identifies an interrupted send even when its document was refused before replay.if (record.kind === 'move' && state.pending?.move && record.event_id === state.pending.sequence&& record.sealed === state.pending.sealed && outcome?.error@@ -993,7 +1037,7 @@ async function catchUp(root, file, state, io) {delete state.pending;delete state.recovered;}- }+ });state.sequence = localRecords(root, appliedSequence);if (state.pending?.move && localRecords(root, (board) => engineReceipt(board, state.pending.move.id))) {reportRecoveredReply(state.pending, io);@@ -1004,11 +1048,14 @@ async function catchUp(root, file, state, io) {if (pendingRefusal) throw refusalFromReceipt(pendingRefusal);}-/** Finish a durable executable send; a collision reseals its unchanged id after applying the winner. */-async function sendPending(root, file, state, io) {+/**+ * Post one sealed move to the relay as its actor, renewing an expired seat token once and taking the next free seat+ * name for a registration the relay already gave out. Network only: it applies nothing, so the outbox can send a+ * move while this machine's board still shows its queued moves on top (#1013).+ */+async function postPending(root, file, state, pending, io) {let renewedAgentToken = false;- for (let tries = 0; state.pending && tries < 100; tries += 1) {- const pending = state.pending;+ for (let tries = 0; tries < 100; tries += 1) {const actor = credentialActor(pending.move);try {const transport = await actorTransport(root, file, state, actor, io);@@ -1023,6 +1070,7 @@ async function sendPending(root, file, state, io) {// A retried registration returns the same issuance without a token; its creator reissues it on first use.if (enrollment.token !== undefined) cacheSeatToken(file, state, pending.registration.target, enrollment);}+ return;} catch (error) {if (error.code === 'AUTH_REQUIRED' && !renewedAgentToken && actor !== 'machine' && actor !== 'person'&& process.env.PULLBOARD_RELAY_TOKEN === undefined && state.agentTokens?.[actor]?.token) {@@ -1045,6 +1093,17 @@ async function sendPending(root, file, state, io) {saveLink(file, state);continue;}+ throw error;+ }+ }+ throw new Refused('RELAY_BUSY', 'the relay kept refusing this seat name; retry this command after other clients finish');+}++/** Finish a durable executable send; a collision reseals its unchanged id after applying the winner. */+async function sendPending(root, file, state, io) {+ for (let tries = 0; state.pending && tries < 100; tries += 1) {+ try { await postPending(root, file, state, state.pending, io); }+ catch (error) {if (!['SEQUENCE_REPEAT', 'SEQUENCE_GAP'].includes(error.code)) throw error;await catchUp(root, file, state, io);if (state.pending) {@@ -1103,12 +1162,48 @@ 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, catchUp, sendPending, sealedRecord, localRecords, saveLink, safePauseCode, safePauseMessage };+ return { root, file, state, io, request, sealedRecord, localRecords, saveLink, safePauseCode, safePauseMessage,+ applyRecords, fetchCheckpoint: (key) => fetchCheckpoint(state, io, key), postPending };+}++/**+ * The link a move may queue on and return at once (#1013), or null when it must reach the relay first: the board's+ * relay.outbox is on and the relay accepted its baseline, and the move needs no relay answer to exist (a+ * registration mints its token there, a person's request is the phone's, and landing authority needs real order).+ */+function localFirstLink(file, operation, args, io) {+ let state;+ try { state = loadLink(file); } catch { return null; }+ if (!state || state.unlinking || state.recovery || state.mode !== 'ordered' || state.baselineAccepted !== true+ || state.baselineConflict || state.baselinePause || state.baselineStale || state.environment) return null;+ if (process.env.PULLBOARD_RELAY_TOKEN !== undefined || io?.personRequest || io?.personRequestMoveId) return null;+ if (['register', 'ensureCoordinator', 'landingLeaseMove'].includes(operation) || args?.[0]?.landingFence !== undefined) return null;+ if (credentialActor({ operation, args }) === 'person') return null;+ try { if (io?.relayOutbox?.() !== true) return null; } catch { return null; }+ return state;+}++/**+ * Make a move on this machine at once and queue it for the relay (#1013): no network call and no relay lock, only+ * the short outbox guard. The background sender sends it and rebuilds the board once the relay has ordered it.+ */+async function queueLocally(root, file, state, operation, args, io, command, applyLocally, onRecorded) {+ const guarded = landingRelayCallbacks(operation, args, {+ apply: () => 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),+ { operation, args, command, applyLocally: guarded.apply, quiet: true }));+ onRecorded?.();+ nudgeRelaySender(root, file);+ return result;}/** Send one board operation before executing it locally, and report its canonical engine result. */export async function relayOperation(root, operation, args, io, command, applyLocally, onRecorded) {const file = linkFile(root);+ const local = localFirstLink(file, operation, args, io);+ if (local) return queueLocally(root, file, local, operation, args, io, command, applyLocally, onRecorded);return locked(file, async () => {const state = loadLink(file);const guarded = landingRelayCallbacks(operation, args, {