Skip to content

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

fix(relay): pause refused baselines without blocking work [H16,B26]

Corey Olson96e557beba17
diff --git a/relay/journal.js b/relay/journal.js
index e66b6771..f3f0065c 100644
--- a/relay/journal.js
+++ b/relay/journal.js
@@ -143,7 +143,7 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
}
/** Replace a covered snapshot and compact only its acknowledged prefix, keeping the head. */
- function saveSnapshot(sequence, bytes, principal) {
+ function saveSnapshot(sequence, bytes, principal, { initialOnly = false } = {}) {
open();
if (!Number.isSafeInteger(sequence) || sequence < 0) throw new Refused('BAD_SEQUENCE', 'name the nonnegative sequence this snapshot covers');
const sealed = payload(bytes);
@@ -152,6 +152,7 @@ export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTE
try {
if (sequence > latest()) throw new Refused('SEQUENCE_GAP', 'upload the missing moves before a snapshot that covers them');
const previous = snapshot();
+ if (initialOnly && previous) throw new Refused('BASELINE_EXISTS', 'this board already has a baseline; preserve the local board before choosing which history to keep');
if (previous && sequence < previous.sequence) throw new Refused('SNAPSHOT_STALE', 'use the latest stored snapshot and seal a snapshot that covers at least its sequence');
const at = now();
if (!(at instanceof Date) || !Number.isFinite(at.getTime())) throw new Refused('RELAY_CONFIG', 'the journal clock must return a valid Date');
diff --git a/relay/service.js b/relay/service.js
index 0d5510fe..18691b17 100644
--- a/relay/service.js
+++ b/relay/service.js
@@ -232,7 +232,7 @@ export function createRelayHandler({ directory, auth, pollMs = 200, publicOrigin
if (!Number.isSafeInteger(body.sequence) || body.sequence < 0) throw new Refused('BAD_SEQUENCE', 'name the nonnegative sequence covered by the sealed snapshot');
const who = await authorizedRequest(req, id, true);
const principal = sender(who, true);
- const saved = withJournal(id, (journal) => journal.saveSnapshot(body.sequence, bytes, principal), true, who.engineVersion);
+ const saved = withJournal(id, (journal) => journal.saveSnapshot(body.sequence, bytes, principal, { initialOnly: req.headers['if-none-match'] === '*' }), true, who.engineVersion);
return apiJson(res, 200, { state: annotated(saved, id) });
}
if (req.method === 'DELETE' && deletion) {
diff --git a/src/api-http.js b/src/api-http.js
index 7062bb0b..fc6cb3ff 100644
--- a/src/api-http.js
+++ b/src/api-http.js
@@ -183,7 +183,7 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
/** Choose the same HTTP refusal class for local and sealed relay adapters. */
export function apiStatus(error) {
- return { AUTH_REQUIRED: 401, TOKEN_BOARD: 403, API_ORIGIN: 403, BAD_ORIGIN: 403, WRITE_REQUIRED: 403, HUMAN_REQUIRED: 403, NO_REPO_ACCESS: 403, NO_BOARD: 404, NO_SHOUT: 404, BOARD_NOT_LINKED: 404, NO_SNAPSHOT: 404, SNAPSHOT_REQUIRED: 409, SEQUENCE_REPEAT: 409, SEQUENCE_GAP: 409 }[error.code] ?? (error instanceof Refused ? 400 : 500);
+ return { AUTH_REQUIRED: 401, TOKEN_BOARD: 403, API_ORIGIN: 403, BAD_ORIGIN: 403, WRITE_REQUIRED: 403, HUMAN_REQUIRED: 403, NO_REPO_ACCESS: 403, NO_BOARD: 404, NO_SHOUT: 404, BOARD_NOT_LINKED: 404, NO_SNAPSHOT: 404, BASELINE_EXISTS: 412, SNAPSHOT_REQUIRED: 409, SEQUENCE_REPEAT: 409, SEQUENCE_GAP: 409 }[error.code] ?? (error instanceof Refused ? 400 : 500);
}
// Relay-only snapshot/delete routes reuse the exact shared bounded-body and refusal boundary.
diff --git a/src/cli.js b/src/cli.js
index 60b89164..c1f4d6ee 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -730,7 +730,7 @@ async function ordered(ctx, board, operation, args) {
const command = ['add', 'edit', 'merged'].includes(ctx.io.relayCommand?.cliOperation) ? ctx.io.relayCommand : undefined;
/** Dispatch while this session holds the checkout, including long-running next/run loops. */
const execute = () => relayLinked(ctx.info.root)
- ? relayOperation(ctx.info.root, operation, args, ctx.io, command) : store[operation](board, ...args);
+ ? relayOperation(ctx.info.root, operation, args, ctx.io, command, () => store[operation](board, ...args)) : store[operation](board, ...args);
const digest = agentSessionDigest();
if (CHECKOUT_LEASES.has(ctx.io) || !digest || ctx.io.personChannel === 'view' || ctx.io.personRequest) return execute();
const agent = ctx.info.isMain ? COORDINATOR : store.agentAt(board, ctx.info.root)?.agent_id ?? 'unjoined agent';
@@ -770,7 +770,7 @@ async function bindCheckoutSession(io, positionals, values) {
const me = whoAmI(ctx, board);
const message = { from: me.id, to: info.isMain ? 'person' : COORDINATOR,
text: `${me.id} took over this checkout in a new agent session.`, lanes: laneNames(ctx.config) };
- if (relayLinked(info.root)) await relayOperation(info.root, 'shout', [message], io);
+ if (relayLinked(info.root)) await relayOperation(info.root, 'shout', [message], io, undefined, () => store.shout(board, message));
else store.shout(board, message);
});
},
diff --git a/src/relay.js b/src/relay.js
index 47e08645..e5b78dbc 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -23,6 +23,10 @@ const SEALED_SNAPSHOT_LIMIT = 10_000_000;
const LINK_FILES = new WeakMap();
const WARNED_COMMANDS = new WeakSet();
const KEY_WARNED_COMMANDS = new WeakSet();
+const BASELINE_ATTEMPTS = new WeakMap();
+const BASELINE_NOTICES = new WeakSet();
+const BASELINE_LOCAL_MOVES = new WeakSet();
+const BASELINE_FAILURES = new WeakMap();
/** Require a trusted origin; HTTP exists only for loopback development and test relays. */
export function relayOrigin(address) {
@@ -119,7 +123,7 @@ function notices(document, io) {
}
/** The sole outbound transport in the CLI: explicit sign-in or a saved, opted-in board link. */
-async function request(state, path, { method = 'GET', body, allowMissing = false } = {}, io) {
+async function request(state, path, { method = 'GET', body, allowMissing = false, initialBaseline = false } = {}, io) {
const supplied = process.env.PULLBOARD_RELAY_TOKEN;
const readToken = method === 'GET' && path.startsWith('/api/v1/boards/') ? supplied : undefined;
if (readToken !== undefined && !/^pa_[A-Za-z0-9_-]{43}$/.test(readToken)) throw new Refused('AUTH_REQUIRED', 'supply a current scoped board token without including it in command arguments');
@@ -128,16 +132,28 @@ async function request(state, path, { method = 'GET', body, allowMissing = false
try {
response = await fetch(relayOrigin(state.url) + path, {
method, redirect: 'error', signal: AbortSignal.timeout(10000),
- headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(token ? { authorization: 'Bearer ' + token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
+ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(token ? { authorization: 'Bearer ' + token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...(initialBaseline ? { 'if-none-match': '*' } : {}) },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
} catch { throw new Refused('RELAY_UNAVAILABLE', `the relay ${state.url} did not answer; read the local board offline, then retry this move when the relay is reachable`); }
let document;
- try { document = await response.json(); } catch { throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid response; retry with the configured relay address'); }
+ try { document = await response.json(); }
+ catch {
+ const error = new Refused('RELAY_RESPONSE', 'the relay returned an invalid response; retry with the configured relay address');
+ error.httpStatus = response.status;
+ throw error;
+ }
notices(document, io);
// Only off can forget a link after a supported API reports that the board is gone.
if (allowMissing && method === 'DELETE' && response.status === 404 && document.version === 1) return { alreadyDeleted: true };
- if (!response.ok) throw new Refused(document.error?.code || 'RELAY_UNAVAILABLE', (document.error?.code === 'AUTH_REQUIRED' ? ((state.agent || token?.startsWith('pa_')) ? 'this agent token is expired or revoked; use a new token issued by the person for this agent, then retry with PULLBOARD_RELAY_TOKEN' : 'the relay sign-in expired or was revoked; run pullboard relay on to sign in again without changing the board key') : (document.error?.message ? `the relay ${state.url}: ${document.error.message}` : null)) || 'the relay refused this send; retry this command explicitly when reachable');
+ if (!response.ok) {
+ const error = new Refused(document.error?.code || 'RELAY_UNAVAILABLE', (document.error?.code === 'AUTH_REQUIRED' ? ((state.agent || token?.startsWith('pa_')) ? 'this agent token is expired or revoked; use a new token issued by the person for this agent, then retry with PULLBOARD_RELAY_TOKEN' : 'the relay sign-in expired or was revoked; run pullboard relay on to sign in again without changing the board key') : (document.error?.message ? `the relay ${state.url}: ${document.error.message}` : null)) || 'the relay refused this send; retry this command explicitly when reachable');
+ error.httpStatus = response.status;
+ error.relayVersion = document.version;
+ error.relayCode = document.error?.code;
+ error.relayMessage = document.error?.message;
+ throw error;
+ }
if (document.version !== 1) throw new Refused('RELAY_VERSION', 'the relay API version is unsupported; upgrade Pullboard before syncing');
return document;
}
@@ -162,8 +178,9 @@ function summary(root, state, { pairing = false } = {}) {
const oversizedSnapshot = snapshotSize(state);
return { linked: true, board: state.board, url: state.url,
link: 'https://app.pullboard.dev/#board=' + state.board + fragment,
- sequence: state.sequence, behind: (state.mode === 'ordered' ? Number(Boolean(state.pending)) : behind(root, state)) + Number(Boolean(state.snapshot || state.checkpoint)),
- ...(oversizedSnapshot ? { oversizedSnapshot } : {}) };
+ sequence: state.sequence, behind: (state.baselinePause ? behind(root, state) : state.mode === 'ordered' ? Number(Boolean(state.pending)) : behind(root, state)) + Number(Boolean(state.snapshot || state.checkpoint)),
+ ...(oversizedSnapshot ? { oversizedSnapshot } : {}),
+ ...(state.baselinePause ? { pausedUpload: structuredClone(state.baselinePause) } : {}) };
}
/** Measure a pending sealed snapshot against the relay's decoded journal limit. */
@@ -188,6 +205,166 @@ export function formatSnapshotLimit(problem, { paused = false } = {}) {
return `relay snapshot for ${problem.board}: sealed snapshot ${size} over the relay limit ${limit}`;
}
+/** Keep a permanent refusal only as a bounded, credential-free diagnostic. */
+function safePauseMessage(error) {
+ const message = String(error.relayMessage ?? error.message ?? 'the relay refused the baseline upload')
+ .replace(/https?:\/\/[^\s]+/gu, '[relay]')
+ .replace(/\b(?:Bearer\s+)?(?:ps|pa)_[A-Za-z0-9_-]{20,}\b/gu, '[credential]')
+ .replace(/[\r\n\t\x00-\x1f\x7f]+/gu, ' ')
+ .replace(/\s+/gu, ' ').trim();
+ return message.slice(0, 240) || 'the relay refused the baseline upload';
+}
+
+/** Pause only definitive baseline 4xx refusals; throttling and transient errors retain retries. */
+function permanentBaselineRefusal(error) {
+ return Number.isInteger(error?.httpStatus) && error.httpStatus >= 400 && error.httpStatus < 500 &&
+ ![408, 425, 429].includes(error.httpStatus);
+}
+
+/** Name the safe next step for the saved permanent refusal. */
+function pauseFix(state) {
+ const pause = state.baselinePause;
+ if (pause.size || /(?:exceeds?|over|larger than|too large).{0,40}(?:bytes|snapshot|limit)|(?:snapshot|limit).{0,40}(?:exceeds?|over|too large)/iu.test(pause.message)) {
+ return 'it resumes automatically once a snapshot fits';
+ }
+ if ([401, 403].includes(pause.status) || pause.code === 'AUTH_REQUIRED') return 'run pullboard relay on to sign in again';
+ return 'upgrade Pullboard or run pullboard relay on again, then report the refusal if it persists';
+}
+
+/** Render one bounded line with board, safe refusal reason and recovery step. */
+function baselinePauseLine(state) {
+ const pause = state.baselinePause;
+ const code = /^[A-Z][A-Z0-9_]{0,63}$/.test(pause.code) ? pause.code : 'RELAY_REFUSED';
+ const size = pause.size && Number.isSafeInteger(pause.size.sealedBytes) && Number.isSafeInteger(pause.size.limit)
+ ? formatSnapshotLimit({ board: state.board, ...pause.size }, { paused: true }) : `relay paused for ${state.board} before its baseline upload`;
+ return `pullboard: [${code}] ${size}: ${pause.message}; ${pauseFix(state)}`;
+}
+
+/** Report the durable pause once across preflight, move and postflight in one command. */
+function reportBaselinePause(state, io) {
+ if (!BASELINE_NOTICES.has(io)) {
+ BASELINE_NOTICES.add(io);
+ io.err(baselinePauseLine(state));
+ }
+}
+
+/** Limit a paused board to one fresh baseline attempt within this command. */
+function attemptedBaselineThisCommand(io, file) {
+ let attempts = BASELINE_ATTEMPTS.get(io);
+ if (!attempts) { attempts = new Set(); BASELINE_ATTEMPTS.set(io, attempts); }
+ if (attempts.has(file)) return true;
+ attempts.add(file);
+ return false;
+}
+
+/** Retain an uncertain attempt in RAM so preflight failure cannot permit local fallback in this command. */
+function rememberBaselineFailure(io, file, error) {
+ let failures = BASELINE_FAILURES.get(io);
+ if (!failures) { failures = new Map(); BASELINE_FAILURES.set(io, failures); }
+ failures.set(file, error);
+}
+
+/** Confirm absence through authenticated API v1; a lost ACK or another live device must stay ordered. */
+async function remoteBaselineAbsent(state, io) {
+ try { await request(state, '/api/v1/boards/' + state.board + '/state', {}, io); }
+ catch (error) {
+ if (error.httpStatus === 404 && error.relayVersion === 1 && ['NO_BOARD', 'NO_SNAPSHOT'].includes(error.code)) return true;
+ throw error;
+ }
+ return false;
+}
+
+/** Persist only a stable refusal code, never arbitrary relay text masquerading as a code. */
+function safePauseCode(error) {
+ const code = error.relayCode ?? error.code;
+ return typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : 'RELAY_REFUSED';
+}
+
+/** Keep a conflicting remote baseline fenced across process restarts without discarding local work. */
+function requireUnconflictedBaseline(state) {
+ if (state.baselineConflict) throw new Refused('RELAY_BASELINE_EXISTS', 'the relay already holds this board; save the local board with pullboard export, then run pullboard relay off to keep working locally; local moves stay off to protect its ordered history');
+}
+
+/** Preserve the unaccepted local candidate and persist a refusal across process restarts. */
+function fenceBaseline(file, state) {
+ state.baselineAccepted = true;
+ state.baselineConflict = true;
+ delete state.baselinePause;
+ saveLink(file, state);
+ requireUnconflictedBaseline(state);
+}
+
+/** Fence another device's baseline before a retry can replace its sequence-zero snapshot. */
+async function requireAbsentBaseline(file, state, io) {
+ if (!await remoteBaselineAbsent(state, io)) {
+ fenceBaseline(file, state);
+ }
+}
+
+/** Send the sequence-zero board image; only its first permanent HTTP refusal pauses relay sends. */
+async function uploadInitialBaseline(root, file, state, io) {
+ attemptedBaselineThisCommand(io, file);
+ try {
+ await requireAbsentBaseline(file, state, io);
+ const pending = state.snapshot;
+ const reply = await request(state, '/api/v1/boards/' + state.board + '/state', { method: 'PUT', body: pending, initialBaseline: true }, io);
+ if (reply.state?.sequence !== pending.sequence || reply.state.sealed !== pending.sealed) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge the initial snapshot; retry the configured relay');
+ state.baselineAccepted = true;
+ state.cursor = Number.isSafeInteger(state.baselineCursor) ? state.baselineCursor : localRecords(root, (board) => board.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id);
+ delete state.baselineCursor;
+ delete state.baselinePause;
+ delete state.snapshot;
+ state.presentationDigest = state.snapshotPresentationDigest ?? state.presentationDigest;
+ delete state.snapshotPresentationDigest;
+ state.needsPresentation = false;
+ saveLink(file, state);
+ return true;
+ } catch (error) {
+ if (error.relayVersion === 1 && error.code === 'BASELINE_EXISTS') fenceBaseline(file, state);
+ if (!permanentBaselineRefusal(error) || state.baselineAccepted) {
+ rememberBaselineFailure(io, file, error);
+ throw error;
+ }
+ try {
+ await requireAbsentBaseline(file, state, io);
+ } catch (uncertain) {
+ rememberBaselineFailure(io, file, uncertain);
+ throw uncertain;
+ }
+ const size = pendingSnapshotSize(root);
+ state.baselinePause = {
+ status: error.httpStatus,
+ code: safePauseCode(error),
+ message: safePauseMessage(error),
+ ...(size ? { size: { sealedBytes: size.sealedBytes, limit: size.limit } } : {}),
+ };
+ delete state.snapshot;
+ delete state.snapshotPresentationDigest;
+ delete state.baselineCursor;
+ saveLink(file, state);
+ reportBaselinePause(state, io);
+ return false;
+ }
+}
+
+/** Rebuild from current local state once per command, so paused moves become the accepted baseline. */
+async function retryPausedBaseline(root, file, state, io) {
+ if (!state.baselinePause || attemptedBaselineThisCommand(io, file)) return !state.baselinePause;
+ try {
+ const document = relaySnapshot(root);
+ state.snapshot = { sequence: 0, sealed: await sealedRecord(readBoardKey(state.board), document, state, 'snapshot', 0) };
+ state.snapshotPresentationDigest = presentationDigest(document.presentation);
+ state.baselineCursor = document.tables.event.at(-1)?.event_id ?? 0;
+ saveLink(file, state);
+ const accepted = await uploadInitialBaseline(root, file, state, io);
+ if (!accepted) reportBaselinePause(state, io);
+ return accepted;
+ } catch (error) {
+ rememberBaselineFailure(io, file, error);
+ throw error;
+ }
+}
+
/** Seal a client record at its proposed public sequence, with no board key in its envelope. */
async function sealedRecord(key, value, state, kind, sequence) {
const plain = Buffer.from(JSON.stringify(value));
@@ -322,19 +499,34 @@ async function publishCheckpoint(root, file, state, io) {
/** Drain a legacy source once, refusing foreign history before it can be silently checkpointed. */
async function ensureOrdered(root, file, state, io) {
+ requireUnconflictedBaseline(state);
+ const previousFailure = BASELINE_FAILURES.get(io)?.get(file);
+ if (previousFailure) throw previousFailure;
if (state.mode === 'ordered') {
+ // Older links with no pending sequence-zero snapshot necessarily accepted their baseline.
+ if (state.baselineAccepted === undefined) {
+ state.baselineAccepted = !(state.snapshot?.sequence === 0);
+ saveLink(file, state);
+ }
+ if (state.baselinePause) {
+ if (!await retryPausedBaseline(root, file, state, io)) return false;
+ }
if (state.linkPending) {
await request(state, '/auth/boards/link', { method: 'POST', body: { board: state.board, repository: state.repository } }, io);
delete state.linkPending;
saveLink(file, state);
}
if (state.snapshot) {
- const reply = await request(state, '/api/v1/boards/' + state.board + '/state', { method: 'PUT', body: state.snapshot }, io);
- if (reply.state?.sequence !== state.snapshot.sequence || reply.state.sealed !== state.snapshot.sealed) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge the initial snapshot; retry the configured relay');
- delete state.snapshot;
- saveLink(file, state);
+ if (!state.baselineAccepted && state.snapshot.sequence === 0) {
+ if (!await uploadInitialBaseline(root, file, state, io)) return false;
+ } else {
+ const reply = await request(state, '/api/v1/boards/' + state.board + '/state', { method: 'PUT', body: state.snapshot }, io);
+ if (reply.state?.sequence !== state.snapshot.sequence || reply.state.sealed !== state.snapshot.sealed) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge the initial snapshot; retry the configured relay');
+ delete state.snapshot;
+ saveLink(file, state);
+ }
}
- return;
+ return true;
}
if (!state.checkpoint) {
const path = '/api/v1/boards/' + state.board;
@@ -357,7 +549,9 @@ async function ensureOrdered(root, file, state, io) {
}
await publishCheckpoint(root, file, state, io);
state.mode = 'ordered';
+ state.baselineAccepted = true;
saveLink(file, state);
+ return true;
}
/** Restore a compacted, authenticated native prefix before receiving any following operations. */
@@ -506,12 +700,22 @@ function recoveredMove(root, state, operation, args, command) {
}
/** Send one board operation before executing it locally, and report its canonical engine result. */
-export async function relayOperation(root, operation, args, io, command) {
+export async function relayOperation(root, operation, args, io, command, applyLocally) {
const file = linkFile(root);
return locked(file, async () => {
const state = loadLink(file);
if (!state || state.unlinking) throw new Refused('RELAY_UNLINK_PENDING', 'finish unlinking this device with pullboard relay off before sending a move');
- await ensureOrdered(root, file, state, io);
+ /** Apply through the CLI's existing board handle so local events and guards remain unchanged. */
+ const applyPausedMoveLocally = () => typeof applyLocally === 'function'
+ ? applyLocally()
+ : localRecords(root, (board) => store[operation](board, ...args));
+ if (!await ensureOrdered(root, file, state, io)) {
+ // Preflight's notice covers the first move; long-running commands still name every later move.
+ if (BASELINE_LOCAL_MOVES.has(io)) BASELINE_NOTICES.delete(io);
+ reportBaselinePause(state, io);
+ BASELINE_LOCAL_MOVES.add(io);
+ return applyPausedMoveLocally();
+ }
await catchUp(root, file, state, io);
if (state.pending) {
delete state.pending;
@@ -573,7 +777,7 @@ 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 {
- await ensureOrdered(root, file, state, io);
+ if (!await ensureOrdered(root, file, state, io)) return summary(root, state);
await catchUp(root, file, state, io);
if (state.pending) {
// The complete prefix did not acknowledge this interrupted send. It must not run later.
@@ -716,6 +920,7 @@ export async function relayOn(root, address, io, { session, quiet = false, stric
const file = linkFile(root);
return locked(file, async () => {
let state = loadLink(file);
+ if (state) requireUnconflictedBaseline(state);
if (state?.unlinking) throw new Refused('RELAY_UNLINK_PENDING', 'finish this device key cleanup with pullboard relay off before linking again');
const url = relayOrigin(address || state?.url || DEFAULT_RELAY);
if (state && (state.url !== url || state.repository !== repository)) throw new Refused('RELAY_LINKED', 'this board is linked to another relay or repository; run relay off before changing its link');
@@ -731,7 +936,9 @@ export async function relayOn(root, address, io, { session, quiet = false, stric
// Save the device key before creating any remote link; a locked keychain cannot strand it.
const keyStorage = storeBoardKey(snapshot.board, key);
state = { version: 1, mode: 'ordered', board: snapshot.board, url, repository, token: signed.token,
- tokenId: signed.id, keyStorage, presentationDigest: presentationDigest(snapshot.document.presentation), sequence: 0, cursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0, linkPending: true };
+ tokenId: signed.id, keyStorage, presentationDigest: presentationDigest(snapshot.document.presentation), sequence: 0,
+ cursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0, baselineCursor: snapshot.document.tables.event.at(-1)?.event_id ?? 0,
+ baselineAccepted: false, linkPending: true };
state.snapshot = { sequence: 0, sealed: await sealedRecord(key, snapshot.document, state, 'snapshot', 0) };
} else { state.token = signed.token; state.tokenId = signed.id; }
state.account = signed.account ?? signed.user?.id;
@@ -744,16 +951,22 @@ export async function relayOn(root, address, io, { session, quiet = false, stric
}
let result;
try {
+ let ready = true;
if (state.mode === 'ordered' && state.snapshot) {
- const reply = await request(state, '/api/v1/boards/' + state.board + '/state', { method: 'PUT', body: state.snapshot }, io);
- if (reply.state?.sequence !== state.snapshot.sequence || reply.state.sealed !== state.snapshot.sealed) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge the initial snapshot; retry the configured relay');
- delete state.snapshot;
- saveLink(file, state);
+ if (!state.baselineAccepted && state.snapshot.sequence === 0) ready = await uploadInitialBaseline(root, file, state, io);
+ else {
+ const reply = await request(state, '/api/v1/boards/' + state.board + '/state', { method: 'PUT', body: state.snapshot }, io);
+ if (reply.state?.sequence !== state.snapshot.sequence || reply.state.sealed !== state.snapshot.sealed) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge the initial snapshot; retry the configured relay');
+ delete state.snapshot;
+ saveLink(file, state);
+ }
+ }
+ if (ready) ready = await ensureOrdered(root, file, state, io);
+ if (ready) {
+ await catchUp(root, file, state, io);
+ await deliverDeviceWraps(root, io);
+ updateRelayMachine(machine => { machine.excluded = machine.excluded.filter(entry => entry !== repoInfo(root).root); });
}
- await ensureOrdered(root, file, state, io);
- await catchUp(root, file, state, io);
- await deliverDeviceWraps(root, io);
- updateRelayMachine(machine => { machine.excluded = machine.excluded.filter(entry => entry !== repoInfo(root).root); });
result = summary(root, state, { pairing: !quiet });
}
catch (error) { if (strict || !(error instanceof Refused)) throw error; io.err(`pullboard: ${error.message}; pending records are queued for the next command`); result = summary(root, state, { pairing: !quiet }); }
diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.js
index 25b423da..28847ac2 100644
--- a/test/relay-client-fixture.js
+++ b/test/relay-client-fixture.js
@@ -91,6 +91,9 @@ export async function relayClientFixture(t, { cliChildren } = {}) {
let stateReadDelayMs = 0;
let stateReadStarted = 0;
let refuseSnapshotWrites = false;
+ let rejectSnapshotWrites = null;
+ let rejectedStateReads = null;
+ let beforeSnapshotWrite = null;
let refuseRequestWrites = false;
let signIn;
let api;
@@ -143,6 +146,12 @@ export async function relayClientFixture(t, { cliChildren } = {}) {
res.end(JSON.stringify({ version: 1, error: { code: 'NO_BOARD', message: 'upload the sealed snapshot for this linked board first' } }));
return;
}
+ if (rejectedStateReads && req.method === 'GET' && missingSnapshot?.[2] === 'state') {
+ res.writeHead(rejectedStateReads.status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ version: rejectedStateReads.version ?? 1,
+ error: { code: rejectedStateReads.code, message: 'fixture uncertain remote state' } }));
+ return;
+ }
if (mintFailures > 0 && req.method === 'POST' && req.url === '/auth/tokens') {
mintFailures -= 1;
req.resume();
@@ -170,6 +179,17 @@ export async function relayClientFixture(t, { cliChildren } = {}) {
res.end(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture snapshot outage' } }));
return;
}
+ if (rejectSnapshotWrites && req.method === 'PUT' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) {
+ req.resume();
+ res.writeHead(rejectSnapshotWrites.status, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ version: 1, error: { code: rejectSnapshotWrites.code, message: rejectSnapshotWrites.message } }));
+ return;
+ }
+ if (beforeSnapshotWrite && req.method === 'PUT' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) {
+ const before = beforeSnapshotWrite;
+ beforeSnapshotWrite = null;
+ await before(req.headers);
+ }
const stateSnapshotDelayMs = Math.max(snapshotWriteDelayMs, injectedSnapshotWriteDelayMs);
if (stateSnapshotDelayMs && req.method === 'PUT' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) {
const delay = stateSnapshotDelayMs;
@@ -244,6 +264,10 @@ export async function relayClientFixture(t, { cliChildren } = {}) {
async function cli(...args) {
return runCliChild(args);
}
+ /** Invoke the production CLI from another worktree sharing this fixture's repository and home. */
+ async function cliAt(cwd, ...args) {
+ return childResult(cwd, env, [CLI, ...args, '--json']);
+ }
/** Bound a CLI child using the exact snapshot count asserted by its fixture flow. */
async function cliWithSnapshotUploads(snapshotUploads, ...args) {
cliChildDeadlineMs(snapshotUploads);
@@ -345,7 +369,7 @@ export async function relayClientFixture(t, { cliChildren } = {}) {
}
return {
transit, relayDirectory: join(scratch, 'relay'), authDatabase, otherDeviceJoin,
- root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliWithSnapshotUploads, link, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,
+ root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliAt, cliWithSnapshotUploads, link, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,
/** Assert the test consumed every declared child budget, with no hidden CLI calls. */
assertCliChildrenComplete() {
if (cliChildren) assert.equal(cliChildIndex, cliChildren.length, 'every planned private CLI child ran exactly once');
@@ -354,6 +378,12 @@ export async function relayClientFixture(t, { cliChildren } = {}) {
overrideDelete(value) { override = value; },
failTokenMints(count) { mintFailures = count; },
refuseSnapshotWrites(value) { refuseSnapshotWrites = value; },
+ /** Return a chosen HTTP refusal for snapshot writes, without inspecting the sealed body. */
+ rejectSnapshots(value) { rejectSnapshotWrites = value ? { ...value } : null; },
+ /** Order a competing real HTTP upload before the next native snapshot reaches the journal. */
+ beforeNextSnapshot(value) { beforeSnapshotWrite = value; },
+ /** Return a chosen real HTTP state refusal to exercise uncertain-baseline safety. */
+ rejectStateReads(value) { rejectedStateReads = value ? { ...value } : null; },
/** Delay each real relay snapshot upload until disabled to model late native checkpoints. */
delaySnapshotWrites(ms) {
assert.ok(Number.isSafeInteger(ms) && ms >= 0 && ms <= 15000, 'snapshot delay is within the product wait bound');
diff --git a/test/relay-stuck-upload.test.js b/test/relay-stuck-upload.test.js
new file mode 100644
index 00000000..a05bb32b
--- /dev/null
+++ b/test/relay-stuck-upload.test.js
@@ -0,0 +1,412 @@
+/** A refused baseline pauses safely and recovers without blocking ordered moves [H16,B26]. */
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { mkdirSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { test } from 'node:test';
+import { gunzipSync } from 'node:zlib';
+import { decodeBoardKey, unseal } from '../src/seal.js';
+import { ENGINE_VERSION } from '../src/machine.js';
+import { relayClientFixture } from './relay-client-fixture.js';
+
+test('a refused upload never blocks board moves [H16,B26]', async (t) => {
+ const box = await relayClientFixture(t);
+ const buildLane = 'fixture-build';
+ const gate = 'node --check src/relay-pause-fixture.js';
+ const configPath = join(box.root, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
+ config.gate = gate;
+ config.lanes[buildLane] = { owns: ['src/'], specs: ['G'], starts: 'now' };
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
+ const specPath = join(box.root, 'SPEC.md');
+ const spec = readFileSync(specPath, 'utf8').replace('\n## K · Constraints',
+ `\n- G1 [approved, must] The fixture builder's file parses. | gate: ${gate}\n\n## K · Constraints`);
+ writeFileSync(specPath, spec);
+ const added = await box.cli('add', buildLane, 'paused relay fixture task', '--specs', 'G1', '--criterion', 'the fixture agent completes this task',
+ '--check', gate);
+ assert.equal(added.code, 0, `the fixture creates its task; result=${JSON.stringify(added.document)}`);
+ const item = added.document.item.item_id;
+ box.rejectSnapshots({ status: 400, code: 'BAD_REQUEST', message: 'the body exceeds 14000000 bytes; send a smaller snapshot' });
+ await box.link();
+ const status = await box.cli('status');
+ assert.equal(status.code, 0);
+ assertPaused(status.document);
+ const pausedLink = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ assert.deepEqual(Object.keys(pausedLink.baselinePause).sort(), ['code', 'message', 'status'],
+ 'a small refused baseline persists only its bounded safe diagnostic');
+ assert.equal(pausedLink.baselinePause.status, 400);
+ assert.ok(pausedLink.baselinePause.message.length <= 240);
+ assert.doesNotMatch(JSON.stringify(pausedLink.baselinePause), /(?:ps|pa)_[A-Za-z0-9_-]{20,}/u);
+ assert.equal(pausedLink.snapshot, undefined, 'refused ciphertext is discarded so recovery seals current local state');
+ const diagnosed = await box.cli('doctor');
+ assert.ok([0, 1].includes(diagnosed.code));
+ assertPaused(diagnosed.document);
+
+ symlinkSync(resolve(import.meta.dirname, '../bin/pullboard.js'), join(box.env.PATH, 'pullboard'));
+ const staged = spawnSync('git', ['add', '-A'], { cwd: box.root, env: box.env, encoding: 'utf8' });
+ assert.equal(staged.status, 0, staged.stderr);
+ const seeded = spawnSync('git', ['commit', '-m', 'chore(test): seed relay pause fixture'], { cwd: box.root, env: box.env, encoding: 'utf8' });
+ assert.equal(seeded.status, 0, seeded.stderr);
+ const agentRoot = join(box.root, '..', 'relay-stuck-upload-agent');
+ const worktree = spawnSync('git', ['worktree', 'add', '-b', 'fixture-relay-stuck-agent', agentRoot, 'HEAD'], {
+ cwd: box.root, env: box.env, encoding: 'utf8',
+ });
+ assert.equal(worktree.status, 0, worktree.stderr);
+
+ const joined = await box.cliAt(agentRoot, 'join', buildLane);
+ assert.equal(joined.code, 0);
+ assertPaused(joined.document);
+ const claimed = await box.cliAt(agentRoot, 'claim', String(item));
+ assert.equal(claimed.code, 0, `the linked agent claims locally while no relay baseline exists; result=${JSON.stringify(claimed.document)}`);
+ assertPaused(claimed.document);
+
+ mkdirSync(join(agentRoot, 'src'), { recursive: true });
+ writeFileSync(join(agentRoot, 'src', 'relay-pause-fixture.js'), 'export const relayPauseFixture = true;\n');
+ const stagedChange = spawnSync('git', ['add', 'src/relay-pause-fixture.js'], { cwd: agentRoot, env: box.env, encoding: 'utf8' });
+ assert.equal(stagedChange.status, 0, stagedChange.stderr);
+ const committed = spawnSync('git', ['commit', '-m', 'feat(fixture-build): complete relay pause fixture [G1]'], { cwd: agentRoot, env: box.env, encoding: 'utf8' });
+ assert.equal(committed.status, 0, committed.stderr);
+ const submitted = await box.cliAt(agentRoot, 'submit', String(item));
+ assert.equal(submitted.code, 0, 'the linked agent submits locally while the baseline is refused');
+ assertPaused(submitted.document);
+ const shouted = await box.cliAt(agentRoot, 'shout', 'coordinator', 'Relay pause fixture remains available');
+ assert.equal(shouted.code, 0, 'the linked agent shouts locally while the baseline is refused');
+ assertPaused(shouted.document);
+
+ box.rejectSnapshots(null);
+ const resumed = await box.cliAt(agentRoot, 'status');
+ assert.equal(resumed.code, 0);
+ assert.doesNotMatch((resumed.document.diagnostics ?? []).join('\n'), /relay paused/u, 'a fitting snapshot clears the pause');
+ assert.equal(box.moveAcks.length, 0, 'no paused local move was sent before its baseline existed');
+ const baseline = await uploadedState(box);
+ assert.equal(baseline.sequence, 0);
+ assert.equal(baseline.document.tables.item.find(row => row.item_id === item).item_status, 'submitted',
+ 'the accepted fresh baseline includes the local claim and submission');
+ assert.ok(baseline.document.tables.shout.some(row => row.shout_text === 'Relay pause fixture remains available'),
+ 'the fresh baseline retains the local shout');
+ assert.ok(baseline.document.tables.agent.some(row => row.agent_path === agentRoot),
+ 'the fresh baseline retains the locally enrolled agent');
+ const ordered = await box.cliAt(agentRoot, 'shout', 'coordinator', 'The relay baseline has resumed');
+ assert.equal(ordered.code, 0);
+ assert.doesNotMatch((ordered.document.diagnostics ?? []).join('\n'), /relay paused/u);
+ assert.deepEqual(box.moveAcks.map(row => row.event_id), [1],
+ 'the real relay ACK places the first post-recovery native move immediately after its baseline');
+ const final = await uploadedState(box);
+ assert.equal(final.sequence, 1, 'the native checkpoint covers the post-recovery move');
+ assert.ok(final.document.tables.shout.some(row => row.shout_text === 'The relay baseline has resumed'));
+
+
+ /** Each internal move in a long-running command retains its own loud pause notice. */
+ await t.test('multiple local moves in one command each name the refused baseline [H16,B26]', async subtest => {
+ const repeated = await relayClientFixture(subtest);
+ repeated.rejectSnapshots({ status: 400, code: 'BAD_REQUEST', message: 'the body exceeds 14000000 bytes; send a smaller snapshot' });
+ await repeated.link();
+ const before = repeated.calls.filter(call => call.method === 'PUT' && call.path.endsWith('/state')).length;
+ const result = await repeated.script(`
+ const { syncRelay, relayOperation } = await import(${JSON.stringify(new URL('../src/relay.js', import.meta.url).href)});
+ const diagnostics = [];
+ const io = { /** Retain safe diagnostic lines for exact per-move counts. */ err: line => diagnostics.push(line) };
+ try {
+ await syncRelay(process.cwd(), io);
+ await relayOperation(process.cwd(), 'shout', [{ from: 'coordinator', to: 'all', lanes: [], text: 'first internal paused move' }], io);
+ await relayOperation(process.cwd(), 'shout', [{ from: 'coordinator', to: 'all', lanes: [], text: 'second internal paused move' }], io);
+ await syncRelay(process.cwd(), io);
+ process.stdout.write(JSON.stringify({ diagnostics }));
+ } catch (error) { process.stdout.write(JSON.stringify({ error: { code: error.code, message: error.message } })); process.exitCode = 1; }
+ `);
+ assert.equal(result.code, 0);
+ assert.equal(result.document.diagnostics.filter(line => /relay paused for /u.test(line)).length, 2,
+ 'each move gets one notice, with no duplicate preflight or postflight notice');
+ assert.equal(repeated.calls.filter(call => call.method === 'PUT' && call.path.endsWith('/state')).length - before, 1,
+ 'one command attempts only one fresh baseline despite multiple local moves');
+ assert.equal(repeated.moveAcks.length, 0, 'unaccepted local moves never become sequence-one uploads');
+ });
+
+ /** Two authenticated device sessions contend for one real SQLite baseline slot. */
+ await t.test('concurrent initial baseline uploads accept exactly one device [H16]', async subtest => {
+ const race = await relayClientFixture(subtest);
+ race.rejectSnapshots({ status: 400, code: 'BAD_UPLOAD', message: 'fixture retains two native baseline candidates' });
+ await race.link();
+ const first = JSON.parse(race.transit.find(row => row.method === 'PUT' && row.path.endsWith('/state')).request.toString('utf8'));
+ assert.equal((await race.cli('add', race.lane, 'local work in the second baseline candidate')).code, 0);
+ assert.equal((await race.cli('status')).code, 0);
+ const second = JSON.parse(race.transit.filter(row => row.method === 'PUT' && row.path.endsWith('/state')).at(-1).request.toString('utf8'));
+ assert.notEqual(first.sealed, second.sealed);
+ race.rejectSnapshots(null);
+ const state = JSON.parse(readFileSync(race.linkFile, 'utf8'));
+ const secondSession = await privatePersonSession(race);
+ const candidates = [first, second];
+ const sessions = [state.token, secondSession];
+ const replies = await Promise.all(candidates.map((candidate, index) => fetch(race.origin + '/api/v1/boards/' + state.board + '/state', {
+ method: 'PUT', headers: { authorization: 'Bearer ' + sessions[index], 'content-type': 'application/json',
+ 'x-pullboard-engine': String(ENGINE_VERSION), 'if-none-match': '*' }, body: JSON.stringify(candidate),
+ })));
+ assert.deepEqual(replies.map(reply => reply.status).sort(), [200, 412], 'one atomic baseline creator wins and one receives a precondition refusal');
+ const loser = replies.find(reply => reply.status === 412);
+ assert.equal((await loser.json()).error.code, 'BASELINE_EXISTS');
+ const winnerIndex = replies.findIndex(reply => reply.status === 200);
+ assert.equal((await uploadedState(race)).sealed, candidates[winnerIndex].sealed, 'the winning ciphertext is never replaced by the loser');
+ const replacement = candidates[1 - winnerIndex];
+ const checkpoint = await fetch(race.origin + '/api/v1/boards/' + state.board + '/state', {
+ method: 'PUT', headers: { authorization: 'Bearer ' + state.token, 'content-type': 'application/json',
+ 'x-pullboard-engine': String(ENGINE_VERSION) }, body: JSON.stringify(replacement),
+ });
+ assert.equal(checkpoint.status, 200, 'ordinary later snapshots remain replaceable at their covered sequence');
+ assert.equal((await uploadedState(race)).sealed, replacement.sealed);
+ });
+
+ /** A competing native snapshot arrives after absence was checked but before the client PUT. */
+ await t.test('a baseline race fences the native retry without discarding local work [H16]', async subtest => {
+ const race = await relayClientFixture(subtest);
+ race.rejectSnapshots({ status: 400, code: 'BAD_UPLOAD', message: 'fixture baseline pause before a competing device' });
+ await race.link();
+ const competing = JSON.parse(race.transit.find(row => row.method === 'PUT' && row.path.endsWith('/state')).request.toString('utf8'));
+ assert.equal((await race.cli('add', race.lane, 'preserved unaccepted local work')).code, 0);
+ race.rejectSnapshots(null);
+ const state = JSON.parse(readFileSync(race.linkFile, 'utf8'));
+ const secondSession = await privatePersonSession(race);
+ let conditional;
+ let competingStatus;
+ race.beforeNextSnapshot(async headers => {
+ conditional = headers['if-none-match'];
+ const reply = await fetch(race.origin + '/api/v1/boards/' + state.board + '/state', {
+ method: 'PUT', headers: { authorization: 'Bearer ' + secondSession, 'content-type': 'application/json',
+ 'x-pullboard-engine': String(ENGINE_VERSION), 'if-none-match': '*' }, body: JSON.stringify(competing),
+ });
+ competingStatus = reply.status;
+ await reply.arrayBuffer();
+ race.rejectStateReads({ status: 503, code: 'RELAY_UNAVAILABLE' });
+ });
+ const blocked = await race.cli('add', race.lane, 'must not overwrite the competing baseline');
+ assert.equal(competingStatus, 200);
+ assert.equal(conditional, '*', 'the real native client asks for an atomic initial upload');
+ assert.equal(blocked.code, 1);
+ assert.equal(blocked.document.error.code, 'RELAY_BASELINE_EXISTS');
+ assert.equal(JSON.parse(readFileSync(race.linkFile, 'utf8')).baselineConflict, true, 'the atomic conflict is durable even when a following state read would fail');
+ race.rejectStateReads(null);
+ const remote = await uploadedState(race);
+ assert.equal(remote.sealed, competing.sealed);
+ assert.equal(remote.document.tables.item.some(row => row.item_title === 'preserved unaccepted local work'), false);
+ const local = await race.cli('export');
+ assert.ok(local.document.tables.item.some(row => row.item_title === 'preserved unaccepted local work'), 'the conflicting local work survives for export');
+ assert.equal(local.document.tables.item.some(row => row.item_title === 'must not overwrite the competing baseline'), false);
+ assert.equal(race.moveAcks.length, 0);
+ });
+
+ /** Prove that malformed permanent refusals pause and recover from a fresh snapshot. */
+ await t.test('malformed baseline refusals carry their reason and recover [H16]', async (subtest) => {
+ const malformed = await relayClientFixture(subtest);
+ malformed.rejectSnapshots({ status: 400, code: 'BAD_UPLOAD', message: 'send only a sequence and sealed payload' });
+ await malformed.link();
+ const paused = await malformed.cli('status');
+ assert.equal(paused.code, 0);
+ const notice = (paused.document.diagnostics ?? []).join('\n');
+ assert.match(notice, /BAD_UPLOAD/u);
+ assert.match(notice, /send only a sequence and sealed payload/u);
+ assert.match(notice, /upgrade pullboard|pullboard relay on/u, 'the malformed-upload notice gives its recovery step');
+ malformed.rejectSnapshots(null);
+ const recovered = await malformed.cli('status');
+ assert.equal(recovered.code, 0);
+ assert.doesNotMatch((recovered.document.diagnostics ?? []).join('\n'), /relay paused/u);
+ });
+
+ /** Preserve ordinary retry behavior for every retryable HTTP response status. */
+ for (const status of [408, 425, 429, 503]) {
+ await t.test(`transient snapshot HTTP ${status} keeps retry behavior [H16]`, async (subtest) => {
+ const transient = await relayClientFixture(subtest);
+ transient.rejectSnapshots({ status, code: 'RELAY_UNAVAILABLE', message: `fixture snapshot HTTP ${status}` });
+ await transient.link();
+ const title = `not applied before baseline HTTP ${status}`;
+ const refused = await transient.cli('add', transient.lane, title);
+ assert.equal(refused.code, 1, 'a retryable outage still refuses the linked move');
+ assert.equal(refused.document.error.code, 'RELAY_UNAVAILABLE');
+ assert.doesNotMatch((refused.document.diagnostics ?? []).join('\n'), /relay paused/u,
+ 'retryable statuses never activate the permanent baseline pause');
+ transient.rejectSnapshots(null);
+ const retried = await transient.cli('add', transient.lane, title);
+ assert.equal(retried.code, 0, 'the same command succeeds after the transient failure clears');
+ });
+ }
+
+ /** A durable pre-ACK local intent cannot prove that the remote board is empty. */
+ for (const sequence of [0, 1]) {
+ await t.test(`an existing remote baseline at sequence ${sequence} never pauses locally [H16]`, async subtest => {
+ const existing = await relayClientFixture(subtest);
+ await existing.link();
+ const first = JSON.parse(readFileSync(existing.linkFile, 'utf8'));
+ const response = await fetch(existing.origin + '/api/v1/boards/' + first.board + '/state', {
+ headers: { authorization: 'Bearer ' + first.token, 'x-pullboard-engine': String(ENGINE_VERSION) },
+ });
+ assert.equal(response.status, 200);
+ const original = (await response.json()).state;
+ if (sequence === 1) assert.equal((await existing.cli('add', existing.lane, 'live remote prefix before new local intent')).code, 0);
+ // This is exactly a durable initial upload intent before the native client received its ACK.
+ const interrupted = JSON.parse(readFileSync(existing.linkFile, 'utf8'));
+ interrupted.baselineAccepted = false;
+ interrupted.snapshot = { sequence: 0, sealed: original.sealed };
+ writeFileSync(existing.linkFile, JSON.stringify(interrupted) + '\n', { mode: 0o600 });
+ existing.rejectSnapshots({ status: 400, code: 'BAD_UPLOAD', message: 'fixture permanently refused retry' });
+ const movesBefore = existing.moveAcks.length;
+ const blocked = await existing.cli('add', existing.lane, 'must never diverge into local fallback');
+ assert.equal(blocked.code, 1, 'an existing authenticated remote snapshot prevents local fallback');
+ assert.equal(blocked.document.error.code, 'RELAY_BASELINE_EXISTS');
+ assert.match(blocked.document.error.message, /protect.*ordered history/u);
+ const durable = JSON.parse(readFileSync(existing.linkFile, 'utf8'));
+ assert.equal(durable.baselinePause, undefined, 'no never-accepted claim is persisted for an existing remote baseline');
+ assert.equal(existing.moveAcks.length, movesBefore, 'the refused command emits no divergent ordered move');
+ const exported = await existing.cli('export');
+ assert.equal(exported.code, 0);
+ assert.equal(exported.document.tables.item.some(row => row.item_title === 'must never diverge into local fallback'), false,
+ 'the guarded command never applies locally either');
+ assert.equal((await uploadedState(existing)).sequence, sequence, 'the actual stored remote prefix remains intact');
+ const beforeRestart = await uploadedState(existing);
+ existing.rejectSnapshots(null);
+ const restarted = await existing.cli('add', existing.lane, 'never overwrite a conflicting baseline after restart');
+ assert.equal(restarted.code, 1, 'fresh commands remain fenced even when the snapshot refusal clears');
+ assert.equal(restarted.document.error.code, 'RELAY_BASELINE_EXISTS');
+ assert.deepEqual(await uploadedState(existing), beforeRestart, 'the remote baseline remains byte-for-byte intact');
+ assert.equal(existing.moveAcks.length, movesBefore);
+ assert.equal(JSON.parse(readFileSync(existing.linkFile, 'utf8')).baselineConflict, true);
+ for (const command of ['status', 'doctor']) {
+ const reported = await existing.cli(command);
+ assert.match((reported.document.diagnostics ?? []).join('\n'), /RELAY_BASELINE_EXISTS.*pullboard export.*pullboard relay off/u);
+ }
+ const relink = await existing.cli('relay', 'on', '--url', existing.origin);
+ assert.equal(relink.code, 1, 'plain relay on refuses the durable conflict before sign-in or snapshot upload');
+ assert.equal(relink.document.error.code, 'RELAY_BASELINE_EXISTS');
+ assert.deepEqual(await uploadedState(existing), beforeRestart);
+ const restartExport = await existing.cli('export');
+ assert.equal(restartExport.document.tables.item.some(row => row.item_title === 'never overwrite a conflicting baseline after restart'), false);
+ });
+ }
+
+ /** A remote baseline appearing after a durable pause must end local-only fallback. */
+ for (const sequence of [0, 1]) {
+ await t.test(`a previously paused board with remote sequence ${sequence} never diverges locally [H16]`, async subtest => {
+ const existing = await relayClientFixture(subtest);
+ existing.rejectSnapshots({ status: 400, code: 'BAD_UPLOAD', message: 'fixture refused initial baseline' });
+ await existing.link();
+ const paused = readFileSync(existing.linkFile, 'utf8');
+ assert.ok(JSON.parse(paused).baselinePause);
+ existing.rejectSnapshots(null);
+ const advanced = sequence === 0 ? await existing.cli('status')
+ : await existing.cli('add', existing.lane, 'actual native remote prefix');
+ assert.equal(advanced.code, 0);
+ assert.equal((await uploadedState(existing)).sequence, sequence);
+ // Model a restarted client's still-durable pause after the remote accepted another upload.
+ writeFileSync(existing.linkFile, paused, { mode: 0o600 });
+ const putsBeforeConflict = existing.calls.filter(call => call.method === 'PUT' && call.path.endsWith('/state')).length;
+ const beforeConflict = await uploadedState(existing);
+ const blocked = await existing.cli('add', existing.lane, 'never apply a divergent paused local move');
+ assert.equal(blocked.code, 1);
+ assert.equal(blocked.document.error.code, 'RELAY_BASELINE_EXISTS');
+ assert.equal(existing.calls.filter(call => call.method === 'PUT' && call.path.endsWith('/state')).length, putsBeforeConflict,
+ 'a remote baseline appearing during pause is checked before any recovered upload can overwrite it');
+ assert.deepEqual(await uploadedState(existing), beforeConflict);
+ const durable = JSON.parse(readFileSync(existing.linkFile, 'utf8'));
+ assert.equal(durable.baselineAccepted, true, 'remote presence is durable evidence against future local fallback');
+ assert.equal(durable.baselinePause, undefined);
+ const exported = await existing.cli('export');
+ assert.equal(exported.code, 0);
+ assert.equal(exported.document.tables.item.some(row => row.item_title === 'never apply a divergent paused local move'), false);
+ assert.equal((await uploadedState(existing)).sequence, sequence);
+ const beforeRestart = await uploadedState(existing);
+ const movesBeforeRestart = existing.moveAcks.length;
+ existing.rejectSnapshots(null);
+ const restarted = await existing.cli('add', existing.lane, 'never overwrite a resumed conflicting baseline');
+ assert.equal(restarted.code, 1, 'the durable remote-presence fence survives a fresh CLI invocation');
+ assert.equal(restarted.document.error.code, 'RELAY_BASELINE_EXISTS');
+ assert.deepEqual(await uploadedState(existing), beforeRestart);
+ assert.equal(existing.moveAcks.length, movesBeforeRestart);
+ assert.equal(JSON.parse(readFileSync(existing.linkFile, 'utf8')).baselineConflict, true);
+ for (const command of ['status', 'doctor']) {
+ const reported = await existing.cli(command);
+ assert.match((reported.document.diagnostics ?? []).join('\n'), /RELAY_BASELINE_EXISTS.*pullboard export.*pullboard relay off/u);
+ }
+ const relink = await existing.cli('relay', 'on', '--url', existing.origin);
+ assert.equal(relink.code, 1, 'plain relay on refuses the durable conflict before sign-in or snapshot upload');
+ assert.equal(relink.document.error.code, 'RELAY_BASELINE_EXISTS');
+ assert.deepEqual(await uploadedState(existing), beforeRestart);
+ const restartExport = await existing.cli('export');
+ assert.equal(restartExport.document.tables.item.some(row => row.item_title === 'never overwrite a resumed conflicting baseline'), false);
+ });
+ }
+
+ /** Only authenticated absence may authorize a local move, including after a failed preflight. */
+ for (const refusal of [
+ { label: 'unknown', status: 404, code: 'UNKNOWN_STATE' },
+ { label: 'auth', status: 401, code: 'AUTH_REQUIRED' },
+ { label: 'unavailable', status: 503, code: 'RELAY_UNAVAILABLE' },
+ { label: 'wrong-version', status: 404, code: 'NO_BOARD', version: 2 },
+ { label: 'unavailable-absence', status: 503, code: 'NO_BOARD' },
+ { label: 'auth-absence', status: 401, code: 'NO_SNAPSHOT' },
+ ]) {
+ await t.test(`uncertain ${refusal.label} remote state never authorizes local fallback [H16]`, async subtest => {
+ const uncertain = await relayClientFixture(subtest);
+ uncertain.rejectSnapshots({ status: 400, code: 'BAD_UPLOAD', message: 'fixture refused initial baseline' });
+ await uncertain.link();
+ assert.ok(JSON.parse(readFileSync(uncertain.linkFile, 'utf8')).baselinePause);
+ uncertain.rejectStateReads(refusal);
+ const blocked = await uncertain.cli('add', uncertain.lane, 'never apply a move after uncertain preflight');
+ assert.equal(blocked.code, 1, 'a failed remote check cannot become local fallback in the same command');
+ assert.equal(blocked.document.error.code, refusal.code);
+ assert.equal(uncertain.moveAcks.length, 0);
+ const exported = await uncertain.cli('export');
+ assert.equal(exported.code, 0);
+ assert.equal(exported.document.tables.item.some(row => row.item_title === 'never apply a move after uncertain preflight'), false);
+ });
+ }
+
+ /** A refused checkpoint after an accepted baseline does not switch moves to local-only mode. */
+ await t.test('a refused later checkpoint keeps ordered moves [H16]', async (subtest) => {
+ const accepted = await relayClientFixture(subtest);
+ await accepted.link();
+ accepted.rejectSnapshots({ status: 400, code: 'BAD_UPLOAD', message: 'fixture checkpoint refusal' });
+ const first = await accepted.cli('add', accepted.lane, 'ordered move before checkpoint refusal');
+ assert.equal(first.code, 0, 'the move remains ordered after baseline acceptance');
+ const second = await accepted.cli('add', accepted.lane, 'ordered move during checkpoint refusal');
+ assert.equal(second.code, 0, 'a permanent later checkpoint refusal does not pause ordered moves');
+ assert.doesNotMatch((second.document.diagnostics ?? []).join('\n'), /relay paused/u);
+ const link = JSON.parse(readFileSync(accepted.linkFile, 'utf8'));
+ const response = await fetch(`${accepted.origin}/api/v1/boards/${link.board}/events?after=0`, {
+ headers: { authorization: `Bearer ${link.token}`, 'x-pullboard-engine': String(ENGINE_VERSION) },
+ });
+ assert.equal(response.status, 200);
+ const events = (await response.json()).events;
+ assert.deepEqual(events.map(event => event.event_id), [1, 2], 'both post-baseline moves keep their relay positions');
+ });
+});
+
+/** Require the one-line durable baseline pause notice on a local move. */
+function assertPaused(document) {
+ const notices = (document.diagnostics ?? []).filter(line => /relay paused/u.test(line));
+ assert.equal(notices.length, 1, `each move names the paused relay upload and recovery path in one line; diagnostics=${JSON.stringify(document.diagnostics ?? [])}`);
+ assert.match(notices[0], /BAD_REQUEST/u, 'the notice keeps the relay refusal code');
+ assert.match(notices[0], /body exceeds 14000000 bytes/u, 'the notice keeps the relay refusal reason');
+ assert.match(notices[0], /snapshot.*fits/u, 'the notice says how automatic recovery proceeds');
+}
+
+/** Authenticate the actual relay checkpoint, accepting both supported plaintext snapshot formats. */
+async function uploadedState(box) {
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', {
+ headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) },
+ });
+ assert.equal(response.status, 200);
+ const row = (await response.json()).state;
+ const plain = await unseal(decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim()),
+ Buffer.from(row.sealed, 'base64url'), { boardId: link.board, kind: 'snapshot', sequence: row.sequence });
+ const bytes = plain[0] === 0x1f && plain[1] === 0x8b ? gunzipSync(plain) : plain;
+ return { sequence: row.sequence, sealed: row.sealed, document: JSON.parse(new TextDecoder().decode(bytes)) };
+}
+
+/** Obtain a second real OAuth session in RAM without changing the native device's stored link. */
+async function privatePersonSession(box) {
+ const start = await fetch(box.origin + '/auth/github/start', { redirect: 'manual' });
+ const binding = start.headers.getSetCookie()[0].split(';')[0];
+ const grant = await fetch(start.headers.get('location'), { redirect: 'manual' });
+ const signed = await fetch(grant.headers.get('location'), { redirect: 'manual', headers: { cookie: binding } });
+ assert.equal(signed.status, 303);
+ const cookie = signed.headers.getSetCookie().find(value => value.startsWith('pb_session='));
+ return cookie.split(';')[0].slice('pb_session='.length);
+}