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): bind live presentation to its ordered prefix [H5,H15]

Corey Olsona8e558ebcd6c
diff --git a/relay/browser-client.js b/relay/browser-client.js
index 1afd55a7..22a49683 100644
--- a/relay/browser-client.js
+++ b/relay/browser-client.js
@@ -64,6 +64,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
accessLost = true;
for (const entry of paired.values()) { entry.stream?.close(); entry.state = null; }
paired.clear();
+ document.querySelector('main')?.replaceChildren();
location.replace('/');
}
@@ -114,6 +115,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
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 state = snapshotState(value, entry.id);
+ if (accessLost) throw new Error('Sign in again to read this board.');
entry.snapshotTag = response.headers.get('etag');
if (row.sequence >= entry.cursor) {
entry.state = state;
@@ -133,6 +135,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
}
const plain = await unseal(entry.key, transportBytes(row.sealed), { boardId: entry.id, kind: row.kind, sequence: row.event_id });
const move = JSON.parse(new TextDecoder().decode(plain));
+ if (accessLost) throw new Error('Sign in again to read this board.');
if (move.version !== 1 || !Number.isSafeInteger(move.engine) || move.engine < 1) throw new Error('This sealed move has an unsupported format. Refresh it from a linked machine.');
if (move.engine !== 1) throw new Error('This board needs engine ' + move.engine + '; this browser reads engine 1. Upgrade the browser client.');
if (move.presentation) {
@@ -140,7 +143,9 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
entry.cursor = row.event_id;
} else {
await snapshot(entry);
- if (entry.cursor < row.event_id) throw new Error('This move needs a refreshed presentation from a linked machine. Run pullboard status there.');
+ // Earlier records in a legacy batch have no complete projection. Consume their position
+ // without exposing later local moves; its final record/checkpoint supplies the presentation.
+ if (entry.cursor < row.event_id) entry.cursor = row.event_id;
}
}
@@ -199,7 +204,7 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
const visible = new Set(available.map(board => board.id));
for (const [id, entry] of paired) if (!visible.has(id)) { entry.stream?.close(); paired.delete(id); }
for (const board of available) {
- if (paired.has(board.id)) continue;
+ if (paired.has(board.id) && pair?.board !== board.id) continue;
Object.assign(keys, stored(localStorage, KEYS, {}));
const encoded = pair?.board === board.id ? pair.key : keys[board.id];
if (!encoded) continue;
@@ -207,6 +212,8 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
const entry = { id: board.id, key: decodeBoardKey(encoded), cursor: -1, state: null };
await snapshot(entry);
await catchUp(entry);
+ if (accessLost) throw new Error('Sign in again to read this board.');
+ paired.get(board.id)?.stream?.close();
paired.set(board.id, entry);
keys[board.id] = encoded;
try { localStorage.setItem(KEYS, JSON.stringify({ ...stored(localStorage, KEYS, {}), [board.id]: encoded })); } catch { failure = 'This browser cannot save pairing. Use the pairing link again on your next visit.'; }
@@ -223,6 +230,12 @@ export async function createTransport({ onUpdate = () => {} } = {}) {
};
}
+ /** Pair a link opened in this already-loaded page as well as one opened on a fresh visit. */
+ async function pairingChanged() {
+ try { pair = rememberPairing() ?? pair; await listing(); onUpdate(); }
+ catch { failure = 'The pairing link is invalid. Get a new link from a linked machine.'; notice(); }
+ }
+ addEventListener('hashchange', pairingChanged);
addEventListener('pagehide', () => { for (const entry of paired.values()) entry.stream?.close(); });
await listing();
return {
diff --git a/relay/browser-model.js b/relay/browser-model.js
index e4750b5e..1454929c 100644
--- a/relay/browser-model.js
+++ b/relay/browser-model.js
@@ -24,7 +24,7 @@ export function snapshotState(document, boardId) {
const verdicts = tables.verdict.filter(row => row.item_id === item.item_id).map(verdict);
return {
id: item.item_id, title: item.item_title, lane: item.item_lane, status: item.item_status,
- route: item.item_route, owner: item.item_owner, reviewer: item.item_review_by,
+ route: item.item_route, owner: item.item_owner, reviewer: item.item_status === 'submitted' && item.item_review_by && item.item_review_until > new Date().toISOString() ? item.item_review_by : null,
reviewUntil: item.item_review_until, builtBy: item.item_built_by, verifiedBy: item.item_verified_by,
specs: item.item_spec_ids ? item.item_spec_ids.split(',') : [], criterion: item.item_criterion,
brief: item.item_brief, commit: item.item_commit, merged: item.item_merged_commit,
@@ -35,7 +35,7 @@ export function snapshotState(document, boardId) {
}),
agents: tables.agent.map(agent => ({ ...agent, lastMoveAt: log.filter(event => event.event_by === agent.agent_id).at(-1)?.event_at ?? null })),
shouts, decisions: decisions.filter(row => row.shout_to === 'person'), asked: decisions.filter(row => row.shout_to !== 'person'),
- events: log.slice(-80).reverse(), holds: tables.lane_hold ?? [], spec: [], practice: [], products: [], unseen: null,
+ events: log.slice(-80).reverse(), holds: tables.hold ?? [], spec: [], practice: [], products: [], unseen: null,
};
}
diff --git a/src/relay.js b/src/relay.js
index 68e3659d..b5871489 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -193,8 +193,10 @@ async function flush(root, file, state, io) {
for (const event of rows) {
if (!state.pending) {
const sequence = state.sequence + 1;
- const presentation = relayPresentation(root);
- state.pending = { localEvent: event.event_id, sequence, presentationDigest: presentationDigest(presentation),
+ const current = relayPresentation(root);
+ // Only a projection ending at this local record belongs to its relay position.
+ const presentation = current.state.events[0]?.event_id === event.event_id ? current : undefined;
+ state.pending = { localEvent: event.event_id, sequence, ...(presentation ? { presentationDigest: presentationDigest(presentation) } : {}),
sealed: await sealedRecord(key, { version: 1, engine: 1, event, presentation }, state, 'move', sequence) };
saveLink(file, state);
}
@@ -203,7 +205,7 @@ async function flush(root, file, state, io) {
if (reply.event?.event_id !== sequence || reply.event.sealed !== sealed) throw new Refused('RELAY_RESPONSE', 'the relay acknowledgement does not match the queued record; retry after checking the relay');
state.sequence = sequence;
state.cursor = event.event_id;
- state.presentationDigest = state.pending.presentationDigest;
+ if (state.pending.presentationDigest) state.presentationDigest = state.pending.presentationDigest;
delete state.pending;
saveLink(file, state);
}
@@ -211,6 +213,7 @@ async function flush(root, file, state, io) {
const digest = presentationDigest(presentation);
if (state.presentationDigest !== digest) {
const document = relaySnapshot(root);
+ if ((document.tables.event.at(-1)?.event_id ?? 0) !== state.cursor) throw new Refused('RELAY_PRESENTATION_PENDING', 'new local moves arrived while syncing; run pullboard status again before publishing their presentation');
state.snapshot = { sequence: state.sequence, sealed: await sealedRecord(key, document, state, 'snapshot', state.sequence) };
state.presentationDigest = presentationDigest(document.presentation);
saveLink(file, state);
diff --git a/test/relay-browser.test.js b/test/relay-browser.test.js
index 9819edf7..fddbe114 100644
--- a/test/relay-browser.test.js
+++ b/test/relay-browser.test.js
@@ -24,6 +24,12 @@ test('older native snapshots project into read-only API state and reject wrong b
const state = snapshotState(box.before, id);
assert.equal(state.items[0].title, box.before.tables.item[0].item_title);
assert.equal(Array.isArray(state.products), true);
+ const held = structuredClone(box.before);
+ held.tables.hold = [{ hold_lane: box.lane, hold_reason: 'fixture hold', hold_by: 'coordinator', hold_at: '2026-01-01T00:00:00.000Z' }];
+ Object.assign(held.tables.item[0], { item_status: 'submitted', item_review_by: 'expired-reviewer', item_review_until: '2000-01-01T00:00:00.000Z' });
+ const projected = snapshotState(held, id);
+ assert.deepEqual(projected.holds, held.tables.hold);
+ assert.equal(projected.items[0].reviewer, null);
assert.throws(() => snapshotState(box.before, '0'.repeat(32)), { code: 'RELAY_SNAPSHOT' });
assert.throws(() => snapshotState({ ...box.before, version: 2 }, id), { code: 'RELAY_SNAPSHOT' });
assert.throws(() => presentationState({ version: 2, state }, id), { code: 'RELAY_PRESENTATION' });
@@ -62,10 +68,12 @@ test('real Chrome pairs, retains its device key, follows SSE without polling and
const box = await relayClientFixture(t);
const firstTitle = 'SEALED_BROWSER_INITIAL_108';
const liveTitle = 'SEALED_BROWSER_LIVE_108';
+ const secondTitle = 'SECOND_LINKED_BOARD_108';
assert.equal((await box.cli('add', box.lane, firstTitle)).code, 0);
await box.link();
const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
const encoded = readFileSync(box.keyFile, 'utf8').trim();
+ const second = await box.additionalBoard(secondTitle);
const unauthenticated = await fetch(box.origin + '/');
const signInPage = await unauthenticated.text();
assert.equal(signInPage.includes('Sign in with GitHub'), true);
@@ -91,6 +99,14 @@ test('real Chrome pairs, retains its device key, follows SSE without polling and
assert.equal(await chrome.evaluate("JSON.parse(localStorage.getItem('pullboard.relay.keys.v1'))[" + JSON.stringify(link.board) + '].length === 43'), true);
assert.equal(await chrome.evaluate("getComputedStyle(document.querySelector('#new-item')).display === 'none'"), true, 'the relay page hides action controls');
assert.equal(box.calls.some(call => call.accept.includes('text/event-stream')), true, 'the page opened a real authorized event stream');
+ await chrome.navigate(box.origin + '/#board=' + second.id + '&key=' + second.encoded);
+ await chrome.waitFor("document.querySelectorAll('#proj-list .proj.repo').length === 2");
+ assert.equal(await chrome.evaluate("Object.keys(JSON.parse(localStorage.getItem('pullboard.relay.keys.v1'))).length === 2"), true,
+ 'pairing another board retains both device-only keys');
+ const firstSelector = '#proj-list .proj.repo[data-root="' + link.board + '"]';
+ await chrome.evaluate('document.querySelector(' + JSON.stringify(firstSelector) + ').click()');
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(firstTitle) + ')');
+
assert.equal((await box.cli('add', box.lane, liveTitle)).code, 0);
await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(liveTitle) + ')');
@@ -101,6 +117,8 @@ test('real Chrome pairs, retains its device key, follows SSE without polling and
box.advance(80);
await chrome.waitFor("document.querySelector('#relay-notice')?.textContent.includes('BOARD_INACTIVE') && document.querySelector('#relay-notice').textContent.includes('10 days left')");
assert.equal(box.keyInRequest(), false, 'the key was never in an HTTP URL or header');
+ await box.revokeSession();
+ await chrome.waitFor("document.body.textContent.includes('Sign in with GitHub') && !document.body.textContent.includes(" + JSON.stringify(liveTitle) + ')');
});
test('an unauthenticated pairing link stays device-only through sign-in and a wrong key shows no contents [H5,H15]', {
@@ -117,8 +135,7 @@ test('an unauthenticated pairing link stays device-only through sign-in and a wr
await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + encoded);
await chrome.waitFor("document.body.textContent.includes('Sign in with GitHub') && location.hash === ''");
assert.equal(await chrome.evaluate('document.body.textContent.includes(' + JSON.stringify(marker) + ')'), false);
- await signIn(chrome, box);
- await chrome.navigate(box.origin);
+ await chrome.navigate(box.origin + '/auth/github/start');
await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(marker) + ')');
const wrong = await startChrome();
@@ -129,3 +146,24 @@ test('an unauthenticated pairing link stays device-only through sign-in and a wr
assert.equal(await wrong.evaluate('document.body.textContent.includes(' + JSON.stringify(marker) + ')'), false);
assert.equal(box.keyInRequest(), false);
});
+
+/** A read outage can accumulate moves before any exact pending record has been sealed. */
+test('legacy queued presentations never disclose later unacknowledged moves [H5,H15]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ box.refuseReads(true);
+ assert.equal((await box.cli('add', box.lane, 'FIRST_QUEUED_108')).code, 0);
+ assert.equal((await box.cli('add', box.lane, 'SECOND_QUEUED_108')).code, 0);
+ box.refuseReads(false);
+ assert.equal((await box.cli('status')).code, 0);
+ const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/events?after=0', { headers: { authorization: 'Bearer ' + link.token } });
+ assert.equal(response.status, 200);
+ const rows = (await response.json()).events;
+ assert.equal(rows.length, 2);
+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());
+ const moves = await Promise.all(rows.map(async row => JSON.parse(new TextDecoder().decode(await unseal(key, Buffer.from(row.sealed, 'base64url'), { boardId: link.board, kind: row.kind, sequence: row.event_id })))));
+ assert.equal(moves[0].presentation, undefined, 'the earlier record cannot attest the already-advanced whole board');
+ assert.equal(moves[1].presentation.state.events[0].event_id, moves[1].event.event_id);
+ assert.equal(moves[1].presentation.state.items.some(item => item.title === 'SECOND_QUEUED_108'), true);
+});
diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.js
index 91379f5d..4f2db1f6 100644
--- a/test/relay-client-fixture.js
+++ b/test/relay-client-fixture.js
@@ -54,19 +54,26 @@ export async function relayClientFixture(t) {
GIT_AUTHOR_NAME: 'Relay Fixture', GIT_AUTHOR_EMAIL: '[email protected]',
GIT_COMMITTER_NAME: 'Relay Fixture', GIT_COMMITTER_EMAIL: '[email protected]',
};
+ for (const name of ['PULLBOARD_RELAY_KEY', 'PULLBOARD_RELAY_TOKEN']) delete env[name];
const provider = await githubFixture(t);
provider.state.deviceAuthorized = true;
- const auth = createRelayAuth({ database: join(scratch, 'auth.sqlite'), github: createGitHubClient(provider.config) });
+ let auth;
let time = Date.now();
let override = null;
+ let refuseEventReads = false;
let signIn;
let api;
const calls = [];
- let privateKey = '';
+ const privateKeys = new Set();
let keyLeaked = false;
const server = createServer(async (req, res) => {
calls.push({ method: req.method, path: req.url, accept: req.headers.accept ?? '' });
- if (privateKey && JSON.stringify({ url: req.url, headers: req.headers }).includes(privateKey)) keyLeaked = true;
+ if ([...privateKeys].some(key => JSON.stringify({ url: req.url, headers: req.headers }).includes(key))) keyLeaked = true;
+ if (refuseEventReads && req.method === 'GET' && /\/events(?:\?|$)/.test(req.url)) {
+ res.writeHead(503, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture read outage' } }));
+ return;
+ }
if (override && req.method === 'DELETE') {
res.writeHead(override.status, { 'content-type': 'application/json' });
res.end(JSON.stringify({ version: override.version ?? 1, error: { code: override.code, message: 'fixture refusal' } }));
@@ -78,6 +85,7 @@ export async function relayClientFixture(t) {
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const origin = 'http://127.0.0.1:' + server.address().port;
+ auth = createRelayAuth({ database: join(scratch, 'auth.sqlite'), github: createGitHubClient({ ...provider.config, callbackURL: origin + '/auth/github/callback' }) });
signIn = createAuthHandler({ auth, publicOrigin: origin });
api = createRelayHandler({ directory: join(scratch, 'relay'), auth, publicOrigin: origin, pollMs: 10, maintenanceMs: 0, now: () => time });
t.after(async () => {
@@ -103,7 +111,7 @@ export async function relayClientFixture(t) {
/** Start a saved real relay link without exposing the pairing fragment. */
async function link() {
assert.equal((await cli('relay', 'on', '--url', origin)).code, 0, 'real device sign-in links the board');
- privateKey = readFileSync(keyFile, 'utf8').trim();
+ privateKeys.add(readFileSync(keyFile, 'utf8').trim());
}
/** Pair and unlink from a second real repository with its own private device home and key. */
async function otherDeviceOff() {
@@ -123,15 +131,37 @@ export async function relayClientFixture(t) {
assert.equal((await run('relay', 'on', '--url', origin)).code, 0, 'second device signs in independently');
return (await run('relay', 'off')).code;
}
+ /** Link another independently initialized synthetic board through the same real person account. */
+ async function additionalBoard(title) {
+ const nextRoot = join(scratch, 'additional-board');
+ const nextHome = join(scratch, 'additional-home');
+ mkdirSync(nextRoot);
+ mkdirSync(nextHome, { mode: 0o700 });
+ const nextEnv = { ...env, HOME: nextHome, PULLBOARD_HOME: join(nextHome, '.pullboard') };
+ /** Run this separate board without retaining credentials in diagnostic output. */
+ const run = (...args) => childResult(nextRoot, nextEnv, [CLI, ...args, '--json']);
+ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: nextRoot, env: nextEnv }).status, 0);
+ assert.equal((await run('init')).code, 0);
+ assert.equal(spawnSync('git', ['remote', 'add', 'origin', '[email protected]:fixture/repository.git'], { cwd: nextRoot, env: nextEnv }).status, 0);
+ assert.equal((await run('add', lane, title)).code, 0);
+ assert.equal((await run('relay', 'on', '--url', origin)).code, 0);
+ const state = JSON.parse(readFileSync(join(nextRoot, '.git', 'pullboard', 'relay.json'), 'utf8'));
+ const encoded = readFileSync(join(nextEnv.PULLBOARD_HOME, 'relay-keys', state.board + '.key'), 'utf8').trim();
+ privateKeys.add(encoded);
+ return { id: state.board, encoded, cli: run };
+ }
/** Run multiple production commands in one process, emitting only safe counters. */
async function script(source) {
return childResult(root, env, ['--input-type=module', '-e', source]);
}
return {
- root, env, origin, lane, before, linkFile, keyFile, calls, cli, link, otherDeviceOff, script,
+ root, env, origin, lane, before, linkFile, keyFile, calls, cli, link, otherDeviceOff, additionalBoard, script,
advance(days) { time = Date.now() + days * 86400000; },
overrideDelete(value) { override = value; },
mainURL: new URL('../src/cli.js', import.meta.url).href,
keyInRequest() { return keyLeaked; },
+ /** Revoke the actual synthetic person session, including its current live streams. */
+ revokeSession() { const state = JSON.parse(readFileSync(linkFile, 'utf8')); return auth.revoke(state.token, state.tokenId); },
+ refuseReads(value) { refuseEventReads = value; },
};
}
diff --git a/test/relay-client.test.js b/test/relay-client.test.js
index a0ec76af..0c46a2c6 100644
--- a/test/relay-client.test.js
+++ b/test/relay-client.test.js
@@ -229,7 +229,10 @@ test('[H1,H7,H15] relay on snapshots and mirrors ciphertext, retries local moves
key, Buffer.from(queued.sealed, 'base64url'), { boardId, kind: 'move', sequence },
)));
assert.deepEqual({ version: openedQueued.version, engine: openedQueued.engine, event: openedQueued.event }, { version: 1, engine: 1, event: allNewRows[offset + 2] }, 'queued records retain their local order');
- assert.equal(openedQueued.presentation.version, 1);
+ if (openedQueued.presentation) {
+ assert.equal(openedQueued.presentation.version, 1);
+ assert.equal(openedQueued.presentation.state.events[0].event_id, openedQueued.event.event_id, 'a queued projection never contains later unacknowledged local moves');
+ }
}
relay.dropNextReply();
await cli(root, relayEnv, 'add', lane, 'committed reply lost');