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(relay): compress snapshots inside device seals [H5,H17]
Corey Olson4f52a053e81b
diff --git a/relay/browser-client.js b/relay/browser-client.jsindex 26b42cb1..0376a85b 100644--- a/relay/browser-client.js+++ b/relay/browser-client.js@@ -41,6 +41,23 @@ function transportBytes(value) {return Uint8Array.from(binary, character => character.charCodeAt(0));}+/** Inflate a new gzip snapshot or preserve the legacy JSON plaintext format. */+async function snapshotDocument(plain) {+ if (plain[0] === 0x1f && plain[1] === 0x8b) {+ if (typeof DecompressionStream !== 'function') throw new Error('This browser cannot read gzip snapshots. Upgrade the browser client.');+ try {+ const stream = new Blob([plain]).stream().pipeThrough(new DecompressionStream('gzip'));+ return JSON.parse(await new Response(stream).text());+ } catch { throw new Refused('SNAPSHOT_FORMAT', 'The sealed gzip snapshot is invalid. Refresh it from a linked machine.'); }+ }+ if (plain[0] !== 0x7b) {+ const seen = [...plain.slice(0, 4)].map(value => value.toString(16).padStart(2, '0')).join('') || 'no bytes';+ throw new Refused('SNAPSHOT_FORMAT', `The sealed snapshot starts with ${seen}; expected gzip magic 1f8b or legacy JSON starting with 7b.`);+ }+ try { return JSON.parse(new TextDecoder().decode(plain)); }+ catch { throw new Refused('SNAPSHOT_FORMAT', 'The sealed legacy JSON snapshot is invalid. Refresh it from a linked machine.'); }+}+/** Fetch only same-origin API documents, retaining stable refusal guidance and no provider details. */async function documentAt(path, onDenied, options = {}) {const headers = new Headers(options.headers ?? {});@@ -124,7 +141,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {if (!row || !Number.isSafeInteger(row.sequence) || row.sequence < 0) throw new Error('The relay snapshot cursor is invalid. Refresh this board.');warning(row.warning, entry.id);const plain = await unseal(entry.key, transportBytes(row.sealed), { boardId: entry.id, kind: 'snapshot', sequence: row.sequence });- const value = JSON.parse(new TextDecoder().decode(plain));+ const value = await snapshotDocument(plain);const state = snapshotState(value, entry.id);if (accessLost) throw new Error('Sign in again to read this board.');entry.snapshotTag = response.headers.get('etag');diff --git a/src/cli.js b/src/cli.jsindex 37b56879..60b89164 100644--- a/src/cli.js+++ b/src/cli.js@@ -67,7 +67,7 @@ import { proofStats } from './stats.js';import { exportBoard, importBoard } from './exchange.js';import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';import { loadMachineSettings, setGateSlots } from './settings.js';-import { relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';+import { formatSnapshotLimit, pendingSnapshotSize, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';import { relayOnAll, revokeRelayDevice, unlinkedRelayProjects } from './relay-setup.js';import { readRelayMachine } from './relay-machine.js';import { relayJoin, relayPair } from './relay-pairing-client.js';@@ -1565,6 +1565,7 @@ function readCommands(io, { first, second, rest, values }) {return 0;}if (summary.relay.linked) io.say(`relay: sequence ${summary.relay.sequence}; ${summary.relay.behind} pending uploads`);+ if (summary.relay.oversizedSnapshot) io.say(formatSnapshotLimit(summary.relay.oversizedSnapshot));const { items, accepted, rejected } = summary.stats;io.say(`${summary.me.id}: ${summary.unread} unread shouts; holding ${summary.mine.map((item) => `#${item.item_id}`).join(', ') || 'nothing'}`);io.say(`board: ${items.open} open, ${items.claimed} claimed, ${items.submitted} awaiting verification, ${items.verified} verified, ${items.withdrawn} withdrawn`);@@ -1586,6 +1587,10 @@ function readCommands(io, { first, second, rest, values }) {}const ctx = context(io);const problems = [...doctorProblems(ctx.file, ctx.info.root, tryGit, ctx.config), ...doctrineProblems(ctx.info.root, ctx.config), ...unlinkedRelayProjects()];+ const oversizedSnapshot = pendingSnapshotSize(ctx.info.root);+ if (oversizedSnapshot) problems.push({ code: 'RELAY_SNAPSHOT_LIMIT',+ message: formatSnapshotLimit(oversizedSnapshot),+ next: 'reduce the sealed board snapshot below the relay limit, then run pullboard status' });io.result?.({ problems });if (!problems.length) {io.say('board is clean');diff --git a/src/relay.js b/src/relay.jsindex b84b5f09..47e08645 100644--- a/src/relay.js+++ b/src/relay.js@@ -2,6 +2,7 @@import { randomUUID } from 'node:crypto';import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { dirname, join } from 'node:path';+import { gunzipSync, gzipSync } from 'node:zlib';import * as store from './board.js';import { exportBoard, restoreRelaySnapshot } from './exchange.js';import { appliedSequence, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, requireSupportedEngine, startRelayEpoch } from './engine.js';@@ -18,6 +19,7 @@ import { readRelayMachine, updateRelayMachine, wrapForRecordedDevice } from './rimport { receivePersonRequest } from './relay-requests.js';export const DEFAULT_RELAY = 'https://app.pullboard.dev';+const SEALED_SNAPSHOT_LIMIT = 10_000_000;const LINK_FILES = new WeakMap();const WARNED_COMMANDS = new WeakSet();const KEY_WARNED_COMMANDS = new WeakSet();@@ -157,14 +159,40 @@ function summary(root, state, { pairing = false } = {}) {if (!state) return { linked: false, board: '', url: '', link: '', sequence: 0, behind: 0 };if (state.unlinking) return { linked: false, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0, cleanup: true };const fragment = pairing ? '&key=' + encodeBoardKey(readBoardKey(state.board)) : '';+ 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)) };+ sequence: state.sequence, behind: (state.mode === 'ordered' ? Number(Boolean(state.pending)) : behind(root, state)) + Number(Boolean(state.snapshot || state.checkpoint)),+ ...(oversizedSnapshot ? { oversizedSnapshot } : {}) };+}++/** Measure a pending sealed snapshot against the relay's decoded journal limit. */+function snapshotSize(state) {+ const sealed = state?.snapshot?.sealed ?? state?.checkpoint?.sealed;+ if (typeof sealed !== 'string') return null;+ const bytes = Buffer.from(sealed, 'base64url');+ if (bytes.toString('base64url') !== sealed || bytes.byteLength <= SEALED_SNAPSHOT_LIMIT) return null;+ return { board: state.board, sealedBytes: bytes.byteLength, limit: SEALED_SNAPSHOT_LIMIT };+}++/** Return the local pending snapshot's oversize details without contacting the relay. */+export function pendingSnapshotSize(root) {+ return snapshotSize(loadLink(linkFile(root)));+}++/** Format a shared status line for an oversized sealed snapshot. */+export function formatSnapshotLimit(problem, { paused = false } = {}) {+ const size = `${(problem.sealedBytes / 1_000_000).toFixed(1)} MB`;+ const limit = `${(problem.limit / 1_000_000).toFixed(1)} MB`;+ if (paused) return `relay paused for ${problem.board}: snapshot ${size} over the relay limit ${limit}; it resumes on its own once a snapshot fits`;+ return `relay snapshot for ${problem.board}: sealed snapshot ${size} over the relay limit ${limit}`;}/** Seal a client record at its proposed public sequence, with no board key in its envelope. */async function sealedRecord(key, value, state, kind, sequence) {- return Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(value)), { boardId: state.board, kind, sequence })).toString('base64url');+ const plain = Buffer.from(JSON.stringify(value));+ const content = kind === 'snapshot' ? gzipSync(plain) : plain;+ return Buffer.from(await seal(key, content, { boardId: state.board, kind, sequence })).toString('base64url');}/** Catch up in local order, retaining exact ciphertext so a lost response cannot duplicate a move. */@@ -259,8 +287,18 @@ async function decoded(key, record, state, kind, sequence) {const bytes = Buffer.from(record.sealed, 'base64url');if (!bytes.length || bytes.toString('base64url') !== record.sealed) throw new Refused('RELAY_RESPONSE', 'the relay returned invalid sealed bytes; fetch the board again');const plain = await unseal(key, bytes, { boardId: state.board, kind, sequence });- try { return JSON.parse(new TextDecoder().decode(plain)); }- catch { throw new Refused('RELAY_MOVE', 'the authenticated relay document is invalid; upgrade pullboard or restore a consistent snapshot'); }+ try {+ if (kind === 'snapshot') {+ if (plain[0] === 0x1f && plain[1] === 0x8b) return JSON.parse(gunzipSync(plain).toString('utf8'));+ if (plain[0] !== 0x7b) throw new Refused('SNAPSHOT_FORMAT', `the sealed snapshot starts with ${Buffer.from(plain.subarray(0, 4)).toString('hex') || 'no bytes'}; expected gzip magic 1f8b or legacy JSON starting with 7b`);+ }+ return JSON.parse(new TextDecoder().decode(plain));+ }+ catch (error) {+ if (error instanceof Refused) throw error;+ if (kind === 'snapshot') throw new Refused('SNAPSHOT_FORMAT', 'the sealed snapshot has gzip magic or legacy JSON bytes but cannot be read; refresh it from a linked machine');+ throw new Refused('RELAY_MOVE', 'the authenticated relay document is invalid; upgrade pullboard or restore a consistent snapshot');+ }}/** Persist the exact checkpoint before uploading, so a lost reply retries identical ciphertext. */diff --git a/test/relay-browser.test.js b/test/relay-browser.test.jsindex bd34273a..4d4b9c48 100644--- a/test/relay-browser.test.js+++ b/test/relay-browser.test.js@@ -5,6 +5,7 @@ import { createServer } from 'node:net';import { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';+import { gunzipSync } from 'node:zlib';import { snapshotState, presentationState } from '../relay/browser-model.js';import { decodeBoardKey, seal, unseal } from '../src/seal.js';import { relaySnapshot } from '../src/relay-presentation.js';@@ -13,6 +14,11 @@ import { addItem, closeBoard, openBoard } from '../src/board.js';import { relayClientFixture } from './relay-client-fixture.js';import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';+/** Read native gzip snapshots while retaining checks against historical uncompressed records. */+function snapshotDocument(plain) {+ return JSON.parse(Buffer.from(plain[0] === 0x1f && plain[1] === 0x8b ? gunzipSync(plain) : plain).toString('utf8'));+}+/** Write an executable that fails its first launch, then optionally delegates to real Chrome. */function writeLaunchWrapper(directory, { chrome, failEveryLaunch = false, publishPort }) {const counter = join(directory, 'launches');@@ -126,7 +132,7 @@ test('conditional sealed snapshots reauthorize before 304 and refresh spec-onlyconst row = (await changed.json()).state;assert.equal(row.sequence, body.state.sequence, 'spec refresh preserves the acknowledged move sequence');const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());- const document = JSON.parse(new TextDecoder().decode(await unseal(key, Buffer.from(row.sealed, 'base64url'), { boardId: link.board, kind: 'snapshot', sequence: row.sequence })));+ const document = snapshotDocument(await unseal(key, Buffer.from(row.sealed, 'base64url'), { boardId: link.board, kind: 'snapshot', sequence: row.sequence }));assert.equal(document.presentation.state.spec.some(rule => rule.text === 'SPEC_PRESENTATION_ONLY_108'), true);});@@ -366,7 +372,7 @@ test('legacy queued presentations never disclose later unacknowledged moves [H5,assert.equal(response.status, 200);const checkpoint = (await response.json()).state;assert.equal(checkpoint.sequence, box.moveAcks[1].event_id, 'the acknowledged final checkpoint covers the omitted presentation');- const document = JSON.parse(new TextDecoder().decode(await unseal(key, Buffer.from(checkpoint.sealed, 'base64url'), { boardId: link.board, kind: 'snapshot', sequence: checkpoint.sequence })));+ const document = snapshotDocument(await unseal(key, Buffer.from(checkpoint.sealed, 'base64url'), { boardId: link.board, kind: 'snapshot', sequence: checkpoint.sequence }));assert.equal(document.presentation.state.items.some(item => item.title === 'FIRST_QUEUED_108'), true);assert.equal(document.presentation.state.items.some(item => item.title === 'SECOND_QUEUED_108'), true);const compacted = await fetch(box.origin + '/api/v1/boards/' + link.board + '/events?after=0', { headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) } });diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 6e50e882..aa179ac8 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -305,7 +305,7 @@ export async function relayClientFixture(t, { cliChildren } = {}) {const envKey = { ...otherEnv, PULLBOARD_RELAY_KEY: environmentKey };return childResult(otherRoot, envKey, [CLI, ...args, '--json']);}- return { joined: document, exported: exported.document, syncWithEnvironmentKey,+ return { joined: document, exported: exported.document, cli: run, syncWithEnvironmentKey,/** Check that the paired clone still has no persisted board-key file. */keyFileExists() { return existsSync(otherKeyFile); } };}diff --git a/test/relay-client.test.js b/test/relay-client.test.jsindex ebdbf257..9dd7891b 100644--- a/test/relay-client.test.js+++ b/test/relay-client.test.js@@ -6,6 +6,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSynimport { delimiter, join, resolve } from 'node:path';import { tmpdir } from 'node:os';import { test } from 'node:test';+import { gunzipSync } from 'node:zlib';import { DatabaseSync } from 'node:sqlite';import { createAuthHandler } from '../relay/auth-http.js';import { createRelayAuth } from '../relay/auth.js';@@ -26,6 +27,11 @@ import { fetchFresh } from './http-fixture.js';const SIGN_INS = new Map();+/** Read native gzip snapshots while retaining checks against historical uncompressed records. */+function snapshotDocument(plain) {+ return JSON.parse(Buffer.from(plain[0] === 0x1f && plain[1] === 0x8b ? gunzipSync(plain) : plain).toString('utf8'));+}+/** Run the actual CLI asynchronously so this process can continue serving its HTTP requests. */function cliResult(root, env, ...args) {return new Promise((resolveResult, reject) => {@@ -220,9 +226,9 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offli}const remoteState = await get(`/api/v1/boards/${boardId}/state`);assert.equal(remoteState.status, 200);- const openedSnapshot = JSON.parse(new TextDecoder().decode(await unseal(+ const openedSnapshot = snapshotDocument(await unseal(key, Buffer.from(remoteState.body.state.sealed, 'base64url'), { boardId, kind: 'snapshot', sequence: 0 },- )));+ ));const linkedExport = await cli(root, env, 'export');assert.deepEqual(openedSnapshot.tables, linkedExport.tables, 'the first sealed record is the exact native board snapshot');assert.ok(openedSnapshot.presentation.state.items.some((item) => item.title === 'initial private item'));@@ -241,7 +247,7 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offliassert.deepEqual(firstMoves.map((row) => row.event_kind), ['add', 'shout']);const nativeAfterMoves = await get(`/api/v1/boards/${boardId}/state`);assert.equal(nativeAfterMoves.body.state.sequence, 2, 'the checkpoint covers both acknowledged operations');- const checkpoint = JSON.parse(new TextDecoder().decode(await unseal(key, Buffer.from(nativeAfterMoves.body.state.sealed, 'base64url'), { boardId, kind: 'snapshot', sequence: 2 })));+ const checkpoint = snapshotDocument(await unseal(key, Buffer.from(nativeAfterMoves.body.state.sealed, 'base64url'), { boardId, kind: 'snapshot', sequence: 2 }));assert.deepEqual(checkpoint.tables.event.slice(beforeLink.tables.event.length), firstMoves);assert.ok(checkpoint.presentation.state.items.some((item) => item.title === 'mirrored private move'));assert.equal(relay.uploads.length, 2);@@ -791,9 +797,9 @@ async function legacyMirrorQueueFragment({assert.equal(stateResponse.status, 200);const stateDocument = await stateResponse.json();assert.equal(stateDocument.state.sequence, 5, 'the native checkpoint covers the complete ordered prefix');- const checkpoint = JSON.parse(new TextDecoder().decode(await unseal(+ const checkpoint = snapshotDocument(await unseal(key, Buffer.from(stateDocument.state.sealed, 'base64url'), { boardId, kind: 'snapshot', sequence: 5 },- )));+ ));assert.deepEqual(checkpoint.tables.event.slice(priorRows.length), queuedEvents,'the source-native snapshot records both legacy rows in order');assert.ok(checkpoint.presentation.state.items.some((item) => item.title === 'legacy queued item'));diff --git a/test/relay-snapshot-size.test.js b/test/relay-snapshot-size.test.jsnew file mode 100644index 00000000..c3bd388d--- /dev/null+++ b/test/relay-snapshot-size.test.js@@ -0,0 +1,197 @@+/** Compression stays inside the device seal while both clients retain legacy snapshot reads [H5,H15,H17]. */+import assert from 'node:assert/strict';+import { createHash, randomBytes } from 'node:crypto';+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { gzipSync, gunzipSync } from 'node:zlib';+import { test } from 'node:test';+import * as store from '../src/board.js';+import { decodeBoardKey, seal, unseal } from '../src/seal.js';+import { ENGINE_VERSION } from '../src/machine.js';+import { presentationDigest, relaySnapshot } from '../src/relay-presentation.js';+import { relayClientFixture } from './relay-client-fixture.js';+import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';++const RELAY_LIMIT = 10_000_000;+const BODY_LIMIT = 14_000_000;++/** Preserve every SQLite value while normalizing row prototypes for JSON transport comparisons. */+function plainRows(rows) { return rows.map(row => ({ ...row })); }++/** Normalize all exported tables without dropping columns or changing their order. */+function plainTables(tables) { return Object.fromEntries(Object.entries(tables).map(([name, rows]) => [name, plainRows(rows)])); }++/** Run a real CLI text command inside the fixture process and return only its captured streams. */+async function textCommand(box, ...args) {+ const source = `+ import { main } from ${JSON.stringify(box.mainURL)};+ let stdout = '', stderr = '';+ const code = await main(${JSON.stringify(args)}, {+ cwd: process.cwd(),+ stdout: { write(value) { stdout += value; } },+ stderr: { write(value) { stderr += value; } },+ });+ console.log(JSON.stringify({ code, stdout, stderr }));+ `;+ return (await box.script(source)).document;+}++/** Seal a legacy plaintext snapshot at its current authenticated relay position. */+async function sealedSnapshot(box, document, sequence, compressed) {+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const json = Buffer.from(JSON.stringify(document));+ const plaintext = compressed ? gzipSync(json) : json;+ return Buffer.from(await seal(key, plaintext, { boardId: state.board, kind: 'snapshot', sequence })).toString('base64url');+}++test('a large board syncs to the relay compressed [H5,H15,H17]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ await box.link();++ // Pair a second native CLI while the board is small; it must later restore the relay snapshot.+ const pairing = await box.cli('relay', 'pair');+ const second = await box.otherDeviceJoin(pairing.document.code);++ // An ordinary older JSON snapshot remains readable by the CLI after the relay compacts it.+ assert.equal((await box.cli('add', box.lane, 'legacy snapshot cursor')).code, 0);+ let sourceState = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ let legacyDocument = relaySnapshot(box.root);+ const legacySealed = await sealedSnapshot(box, legacyDocument, sourceState.sequence, false);+ const legacyUpload = await fetch(box.origin + '/api/v1/boards/' + sourceState.board + '/state', {+ method: 'PUT',+ headers: { authorization: 'Bearer ' + sourceState.token, 'x-pullboard-engine': String(ENGINE_VERSION), 'content-type': 'application/json' },+ body: JSON.stringify({ sequence: sourceState.sequence, sealed: legacySealed }),+ });+ assert.equal(legacyUpload.status, 200, 'the relay continues accepting a stored legacy JSON snapshot');+ const legacyRead = await second.cli('status');+ assert.equal(legacyRead.code, 0, legacyRead.document?.error?.message);+ const legacyExport = await second.cli('export');+ assert.equal(legacyExport.code, 0);+ assert.deepEqual(plainRows(legacyExport.document.tables.item), plainRows(legacyDocument.tables.item), 'the CLI restored the legacy JSON snapshot from the relay');++ // The second CLI publishes its own current gzip checkpoint after restoring; replace it with the same legacy bytes before the browser reads.+ const browserLegacyUpload = await fetch(box.origin + '/api/v1/boards/' + sourceState.board + '/state', {+ method: 'PUT',+ headers: { authorization: 'Bearer ' + sourceState.token, 'x-pullboard-engine': String(ENGINE_VERSION), 'content-type': 'application/json' },+ body: JSON.stringify({ sequence: sourceState.sequence, sealed: legacySealed }),+ });+ assert.equal(browserLegacyUpload.status, 200);+ assert.equal((await browserLegacyUpload.json()).state.sealed, legacySealed, 'the browser starts with the exact stored uncompressed bytes');++ // The actual browser keeps reading a previously stored uncompressed JSON checkpoint too.+ const chrome = await startChrome();+ t.after(() => chrome.close());+ await chrome.send('Network.setCookie', {+ name: 'pb_session', value: sourceState.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ });+ const encodedKey = readFileSync(box.keyFile, 'utf8').trim();+ await chrome.navigate(box.origin + '/#board=' + sourceState.board + '&key=' + encodedKey);+ try {+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes('legacy snapshot cursor')");+ } catch (error) {+ t.diagnostic('legacy browser read: ' + JSON.stringify(await chrome.evaluate("({ title: document.title, notice: document.querySelector('#relay-notice')?.textContent.slice(0, 800), signIn: document.body.textContent.includes('Sign in with GitHub'), hasLegacy: document.body.textContent.includes('legacy snapshot cursor') })")));+ throw error;+ }+ t.diagnostic('legacy browser snapshot read passed');++ const marker = 'COMPRESSED_RELAY_SNAPSHOT_EXACT_340_';+ const longText = marker + 'q'.repeat(7_200_000);+ const native = store.openBoard(join(box.root, '.git/pullboard/board.sqlite'));+ try {+ store.shout(native, { from: 'coordinator', to: 'all', text: longText, lanes: [box.lane] });+ // The historical payload grows the native snapshot without sending a seven-megabyte paragraph to the recent UI feed.+ for (let index = 0; index < 100; index++) {+ store.shout(native, { from: 'coordinator', to: 'all', text: marker + 'recent ' + index, lanes: [box.lane] });+ }+ } finally { store.closeBoard(native); }+ const before = relaySnapshot(box.root);+ assert.ok(Buffer.byteLength(JSON.stringify(before)) > BODY_LIMIT, 'the uncompressed snapshot exceeds the unchanged relay body limit');+ const uncompressedSealed = await sealedSnapshot(box, before, JSON.parse(readFileSync(box.linkFile, 'utf8')).sequence, false);+ assert.ok(Buffer.from(uncompressedSealed, 'base64url').byteLength > BODY_LIMIT, 'the actual legacy sealed snapshot exceeds the relay body limit before base64 framing');++ assert.equal((await box.cli('status')).code, 0, 'the local CLI publishes a compressed pending snapshot');+ assert.equal((await box.cli('add', box.lane, 'advance compressed snapshot')).code, 0, 'an acknowledged move advances the relay snapshot cursor');+ const expected = relaySnapshot(box.root);+ const snapshotRequest = box.transit.filter(row => row.method === 'PUT' && row.path.endsWith('/state')).at(-1);+ assert.ok(snapshotRequest, 'the actual linked CLI uploaded a snapshot to the relay');+ const uploadBody = JSON.parse(snapshotRequest.request.toString('utf8'));+ const sealedBytes = Buffer.from(uploadBody.sealed, 'base64url');+ assert.ok(sealedBytes.byteLength < RELAY_LIMIT, 'the opaque compressed snapshot fits the decoded journal limit');+ assert.ok(snapshotRequest.request.byteLength < BODY_LIMIT, 'the base64 transport body fits the unchanged request limit');+ const boardKey = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const plaintext = await unseal(boardKey, sealedBytes, { boardId: JSON.parse(readFileSync(box.linkFile, 'utf8')).board, kind: 'snapshot', sequence: uploadBody.sequence });+ assert.deepEqual(plainTables(JSON.parse(gunzipSync(plaintext).toString('utf8')).tables), plainTables(expected.tables),+ 'the gzip payload inside the device seal is the exact native snapshot');+ assert.equal(snapshotRequest.request.includes(Buffer.from(marker)), false, 'the relay request contains no board plaintext');+ assert.equal(snapshotRequest.response.includes(Buffer.from(marker)), false, 'the relay response contains no board plaintext');++ // A second CLI that predates this checkpoint must restore the compressed snapshot exactly.+ assert.equal((await second.cli('status')).code, 0, 'the paired CLI restores the compressed snapshot');+ const restored = await second.cli('export');+ assert.equal(restored.code, 0);+ assert.deepEqual(plainTables(restored.document.tables), plainTables(expected.tables), 'the paired CLI reads back the exact compressed snapshot');++ // The actual Chrome client reads that same compressed checkpoint and renders the full shout text.+ sourceState = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ await chrome.navigate(box.origin);+ try {+ await chrome.waitFor("document.querySelector('#feed')?.textContent.includes(" + JSON.stringify(marker) + ") || document.querySelector('#relay-notice')?.textContent.includes('Could not open this board with its saved key')");+ } catch (error) {+ t.diagnostic('compressed browser read: ' + JSON.stringify(await chrome.evaluate("({ title: document.title, notice: document.querySelector('#relay-notice')?.textContent.slice(0, 800), signIn: document.body.textContent.includes('Sign in with GitHub'), hasMarker: document.body.textContent.includes('COMPRESSED_RELAY_SNAPSHOT_EXACT_340_') })")));+ throw error;+ }+ assert.equal(await chrome.evaluate("document.querySelector('#feed')?.textContent.includes(" + JSON.stringify(marker) + ') ?? false'), true, 'the production browser decoder reads the compressed checkpoint');+ const projection = { ...expected.presentation.state, root: sourceState.board };+ const projectionHash = createHash('sha256').update(JSON.stringify(projection)).digest('hex');+ const tablesHash = createHash('sha256').update(JSON.stringify(expected.tables)).digest('hex');+ const browserRead = await chrome.evaluate(`(async () => {+ const { createTransport } = await import('/relay/client.js');+ const transport = await createTransport();+ const document = await transport.request('/api/v1/boards/${sourceState.board}/state');+ const { decodeBoardKey, unseal } = await import('/relay/seal.js');+ const response = await fetch('/api/v1/boards/${sourceState.board}/state', { headers: { 'x-pullboard-engine': '${ENGINE_VERSION}' } });+ const envelope = (await response.json()).state;+ const encoded = envelope.sealed.replaceAll('-', '+').replaceAll('_', '/');+ const ciphertext = Uint8Array.from(atob(encoded + '='.repeat((4 - encoded.length % 4) % 4)), value => value.charCodeAt(0));+ const keys = JSON.parse(localStorage.getItem('pullboard.relay.keys.v1'));+ const plain = await unseal(decodeBoardKey(keys['${sourceState.board}']), ciphertext, { boardId: '${sourceState.board}', kind: 'snapshot', sequence: envelope.sequence });+ const stream = new Blob([plain]).stream().pipeThrough(new DecompressionStream('gzip'));+ const native = JSON.parse(await new Response(stream).text());+ /** Hash exact browser-decoded JSON without sending private contents into test diagnostics. */+ async function digest(value) {+ const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(value))));+ return [...bytes].map(value => value.toString(16).padStart(2, '0')).join('');+ }+ return { projectionHash: await digest(document.state), tablesHash: await digest(native.tables) };+ })()`, 'hash browser projection and native snapshot');+ assert.deepEqual(browserRead, { projectionHash, tablesHash }, 'the production browser client reads the exact projection and browser gzip retains every native table byte');++ // A valid but still-too-large gzip checkpoint remains pending and is named by both CLI readers.+ const oversizedDocument = relaySnapshot(box.root);+ const randomTitle = 'OVERSIZE_SNAPSHOT_340_' + randomBytes(5_050_000).toString('base64');+ const itemId = oversizedDocument.tables.item[0].item_id;+ oversizedDocument.tables.item.find(row => row.item_id === itemId).item_title = randomTitle;+ oversizedDocument.presentation.state.items.find(row => row.id === itemId).title = randomTitle;+ const oversizedGzip = await sealedSnapshot(box, oversizedDocument, sourceState.sequence, true);+ const oversizedBytes = Buffer.from(oversizedGzip, 'base64url').byteLength;+ assert.ok(oversizedBytes > RELAY_LIMIT, 'the compressed sealed snapshot still exceeds the relay journal limit');+ assert.ok(Buffer.byteLength(JSON.stringify({ sequence: sourceState.sequence, sealed: oversizedGzip })) < BODY_LIMIT,+ 'the oversized sealed snapshot remains below the unchanged HTTP body limit');+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const localDigest = presentationDigest(relaySnapshot(box.root).presentation);+ link.checkpoint = { sequence: sourceState.sequence, sealed: oversizedGzip };+ link.checkpointPresentationDigest = localDigest;+ writeFileSync(box.linkFile, JSON.stringify(link), { mode: 0o600 });++ const status = await textCommand(box, 'status');+ assert.match(status.stdout, new RegExp(`relay snapshot for ${sourceState.board}: sealed snapshot \\d+\\.\\d MB over the relay limit 10\\.0 MB`));+ const doctor = await textCommand(box, 'doctor');+ assert.equal(doctor.code, 1);+ const doctorJSON = await box.cli('doctor');+ assert.equal(doctorJSON.code, 1);+ assert.ok(doctorJSON.document.problems.some(problem => problem.code === 'RELAY_SNAPSHOT_LIMIT'), 'doctor JSON names the stable oversize rule');+ assert.match(doctor.stdout, new RegExp(`relay snapshot for ${sourceState.board}: sealed snapshot \\d+\\.\\d MB over the relay limit 10\\.0 MB`));+});