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
chore(relay): integrate accepted ordered engine [H3,H16]
Corey Olson53e8d7061515
diff --cc test/relay-browser.test.jsindex d4f53807,00000000..2732080fmode 100644,000000..100644--- a/test/relay-browser.test.js+++ b/test/relay-browser.test.js@@@ -1,294 -1,0 +1,301 @@@+/** Real Chrome reads and follows device-sealed boards; the relay never receives its key [H5,H15,H18]. */+import assert from 'node:assert/strict';+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { test } from 'node:test';+import { snapshotState, presentationState } from '../relay/browser-model.js';+import { decodeBoardKey, seal, unseal } from '../src/seal.js';+import { relaySnapshot } from '../src/relay-presentation.js';++import { addItem, closeBoard, openBoard } from '../src/board.js';+import { relayClientFixture } from './relay-client-fixture.js';+import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';++/** Sign a browser in with the real stand-in device grant, without exposing its credential. */+async function signIn(chrome, box) {+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const result = await chrome.send('Network.setCookie', {+ name: 'pb_session', value: state.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ });+ assert.equal(result.success, true, 'the real authorized person session is installed in this private browser');+ return state;+}++test('older native snapshots project into read-only API state and reject wrong board/version [H5,H15]', async t => {+ const box = await relayClientFixture(t);+ const id = box.before.tables.board_meta.find(row => row.meta_key === 'board_id').meta_value;+ 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' });+});++test('conditional sealed snapshots reauthorize before 304 and refresh spec-only presentation [H5,H15]', async t => {+ const box = await relayClientFixture(t);+ await box.link();+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const endpoint = box.origin + '/api/v1/boards/' + link.board + '/state';+ const headers = { authorization: 'Bearer ' + link.token };+ const first = await fetch(endpoint, { headers });+ assert.equal(first.status, 200);+ const tag = first.headers.get('etag');+ assert.equal(typeof tag, 'string');+ const body = await first.json();+ const unchanged = await fetch(endpoint, { headers: { ...headers, 'if-none-match': tag } });+ assert.equal(unchanged.status, 304);+ const unauthorized = await fetch(endpoint, { headers: { 'if-none-match': tag } });+ assert.equal(unauthorized.status, 401, 'a cached ciphertext tag never grants access');+ writeFileSync(join(box.root, 'SPEC.md'), '# Browser fixture spec\n\n## G · Goals\n\n- G1 [draft, must] SPEC_PRESENTATION_ONLY_108 | gate: review\n');+ assert.equal((await box.cli('status')).code, 0, 'a board read publishes changed spec presentation without a move');+ const changed = await fetch(endpoint, { headers: { ...headers, 'if-none-match': tag } });+ assert.equal(changed.status, 200);+ assert.equal(changed.headers.get('etag') === tag, false);+ const 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 })));+ assert.equal(document.presentation.state.spec.some(rule => rule.text === 'SPEC_PRESENTATION_ONLY_108'), true);+});++test('real Chrome pairs, retains its device key, follows SSE without polling and shows inactivity [H5,H15,H18]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ 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);+ assert.equal(signInPage.includes(firstTitle), false);+ assert.equal(signInPage.includes(encoded), false);++ const chrome = await startChrome();+ t.after(() => chrome.close());+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', {+ source: 'window.setInterval = () => 0;',+ });+ await signIn(chrome, box);+ const beforeUnpaired = box.calls.length;+ await chrome.navigate(box.origin);+ await chrome.waitFor("document.querySelector('#relay-notice')?.textContent.includes('pair this browser')");+ assert.equal(await chrome.evaluate('document.body.textContent.includes(' + JSON.stringify(firstTitle) + ')'), false);+ assert.equal(box.calls.slice(beforeUnpaired).some(call => /\/(state|events)(?:\?|$)/.test(call.path)), false,+ 'a browser without the key sees only authorized board names and pairing guidance');++ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + encoded);+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(firstTitle) + ')');+ assert.equal(await chrome.evaluate('location.hash === ""'), true, 'the pairing key is removed from browser history');+ 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) + ')');+ assert.equal(await chrome.evaluate("document.querySelector('#relay-notice').textContent.includes('Acting from the relay is coming')"), true);+ await chrome.navigate(box.origin);+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(liveTitle) + ')');+ assert.equal(await chrome.evaluate('location.hash === ""'), true, 'a later visit needs no new pairing link');+ 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) + ')');+});++/** Append an authenticated synthetic sealed move without writing it to the private local board. */+async function appendEngineMove(box, link, key, sequence, engine, presentation) {+ const event = { event_id: sequence, event_kind: 'add', event_by: 'fixture', event_at: new Date().toISOString(), event_detail: '{}' };+ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify({ version: 1, engine, event, ...(presentation ? { presentation } : {}) })), {+ boardId: link.board, kind: 'move', sequence,+ })).toString('base64url');+ const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/moves', {+ method: 'POST', headers: { authorization: 'Bearer ' + link.token, 'content-type': 'application/json' },+ body: JSON.stringify({ sequence, sealed }),+ });+ assert.equal(response.status, 200, 'the private stand-in accepts the synthetic sealed sequence');+ return response.json();+}++test('real Chrome refuses a newer engine in the initial replay without exposing board contents [H5,H15]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const privateTitle = 'ENGINE_TWO_PRIVATE_108';+ assert.equal((await box.cli('add', box.lane, privateTitle)).code, 0);+ await box.link();+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const presentation = relaySnapshot(box.root).presentation;+ presentation.state.items[0].title = privateTitle;+ await appendEngineMove(box, link, key, 1, 2, presentation);++ const chrome = await startChrome();+ t.after(() => chrome.close());+ await signIn(chrome, box);+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + readFileSync(box.keyFile, 'utf8').trim());+ await chrome.waitFor("document.querySelector('#relay-notice')?.textContent.includes('This board needs engine 2')");+ assert.equal(await chrome.evaluate('document.body.textContent.includes(' + JSON.stringify(privateTitle) + ')'), false,+ 'an unsupported initial event cannot install its attached presentation');+});++test('real Chrome refuses a newer engine delivered over the live stream [H5,H15]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const initialTitle = 'ENGINE_ONE_INITIAL_108';+ const privateTitle = 'ENGINE_TWO_LIVE_PRIVATE_108';+ assert.equal((await box.cli('add', box.lane, initialTitle)).code, 0);+ await box.link();+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const chrome = await startChrome();+ t.after(() => chrome.close());+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: 'window.setInterval = () => 0;' });+ await signIn(chrome, box);+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + readFileSync(box.keyFile, 'utf8').trim());+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(initialTitle) + ')');+ const presentation = relaySnapshot(box.root).presentation;+ presentation.state.items[0].title = privateTitle;+ await appendEngineMove(box, link, key, 1, 2, presentation);+ await chrome.waitFor("document.querySelector('#relay-notice')?.textContent.includes('This board needs engine 2')");+ assert.equal(await chrome.evaluate('document.body.textContent.includes(' + JSON.stringify(privateTitle) + ')'), false,+ 'a newer live engine is refused before its presentation changes the page');+});++test('real Chrome waits for and installs the late snapshot that compacts a legacy move [H5,H15]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const initialTitle = 'LATE_SNAPSHOT_INITIAL_108';+ const finalTitle = 'LATE_SNAPSHOT_REPAIRED_108';+ assert.equal((await box.cli('add', box.lane, initialTitle)).code, 0);+ await box.link();+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const chrome = await startChrome();+ t.after(() => chrome.close());+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: 'window.setInterval = () => 0;' });+ await signIn(chrome, box);+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + readFileSync(box.keyFile, 'utf8').trim());+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(initialTitle) + ')');++ await appendEngineMove(box, link, key, 1, 1);+ await new Promise(resolveLate => setTimeout(resolveLate, 350));+ assert.equal(await chrome.evaluate('document.body.textContent.includes(' + JSON.stringify(finalTitle) + ')'), false,+ 'the event position is not consumed while the current snapshot is behind it');++ const checkpoint = relaySnapshot(box.root);+ checkpoint.tables.item[0].item_title = finalTitle;+ checkpoint.presentation.state.items[0].title = finalTitle;+ const bytes = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(checkpoint)), {+ boardId: link.board, kind: 'snapshot', sequence: 1,+ })).toString('base64url');+ const uploaded = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', {+ method: 'PUT', headers: { authorization: 'Bearer ' + link.token, 'content-type': 'application/json' },+ body: JSON.stringify({ sequence: 1, sealed: bytes }),+ });+ assert.equal(uploaded.status, 200, 'the stand-in acknowledges a snapshot covering the move');+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(finalTitle) + ')');+ const replay = await fetch(box.origin + '/api/v1/boards/' + link.board + '/events?after=0', { headers: { authorization: 'Bearer ' + link.token } });+ assert.equal(replay.status, 409, 'the relay compacted the covered event and requires the new snapshot cursor');+ assert.equal(box.keyInRequest(), false, 'the key remains absent from browser requests');+});++test('an unauthenticated pairing link stays device-only through sign-in and a wrong key shows no contents [H5,H15]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const marker = 'PRIVATE_BOARD_WITH_PAIRING_108';+ assert.equal((await box.cli('add', box.lane, marker)).code, 0);+ await box.link();+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const encoded = readFileSync(box.keyFile, 'utf8').trim();+ const chrome = await startChrome();+ t.after(() => chrome.close());+ 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 chrome.navigate(box.origin + '/auth/github/start');+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(marker) + ')');++ const wrong = await startChrome();+ t.after(() => wrong.close());+ await signIn(wrong, box);+ await wrong.navigate(box.origin + '/#board=' + link.board + '&key=' + 'A'.repeat(43));+ await wrong.waitFor("document.querySelector('#relay-notice')?.textContent.includes('Could not open')");+ 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. */++/** A pre-ordered mirror's durable local outbox keeps its final browser projection recoverable. */+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);++ // Recreate the historical pre-161 link metadata, then commit two local-first rows directly.++ link.cursor = box.before.tables.event.at(-1)?.event_id ?? 0;++ delete link.mode;++ delete link.presentationDigest;++ writeFileSync(box.linkFile, JSON.stringify(link) + '\n', { mode: 0o600 });++ const board = openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));++ try {++ addItem(board, { by: 'coordinator', lane: box.lane, title: 'FIRST_QUEUED_108' });++ addItem(board, { by: 'coordinator', lane: box.lane, title: 'SECOND_QUEUED_108' });++ } finally { closeBoard(board); }+ box.refuseSnapshotWrites(true);+ const status = await box.cli('status');+ assert.equal(status.code, 0);+ assert.equal((status.document.diagnostics ?? []).some(line => line.includes('[RELAY_UNAVAILABLE]')), true,+ 'a refused snapshot keeps the final projection pending for retry');+ assert.equal(box.calls.filter(call => call.method === 'POST' && /\/moves$/.test(call.path)).length, 2, 'both queued moves reached the real stand-in route');+ assert.equal(box.moveAcks.length, 2, 'both encrypted move acknowledgements were captured before snapshot compaction');+ const pendingLink = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ assert.equal(pendingLink.needsPresentation, true);+ assert.equal(Boolean(pendingLink.snapshot), true);+ const oldState = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', { headers: { authorization: 'Bearer ' + link.token } });+ assert.equal((await oldState.json()).state.sequence, 0, 'the relay did not acknowledge the refused checkpoint');++ box.refuseSnapshotWrites(false);+ const retried = await box.cli('status');+ assert.equal(retried.code, 0);+ assert.equal(retried.document.diagnostics?.length ?? 0, 0, 'the saved checkpoint retries without re-sending acknowledged moves');+ assert.equal(box.moveAcks.length, 2);+ const completedLink = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ assert.equal(completedLink.needsPresentation, false, 'only a matching snapshot acknowledgement clears the pending presentation');+ assert.equal(Boolean(completedLink.snapshot), false);+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const moves = await Promise.all(box.moveAcks.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);+ const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', { headers: { authorization: 'Bearer ' + link.token } });+ 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 })));+ 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 } });+ assert.equal(compacted.status, 409, 'the relay compacted the moves only after acknowledging their final checkpoint');+});diff --cc test/relay-client.test.jsindex 0c46a2c6,b1129089..e5330240--- a/test/relay-client.test.js+++ b/test/relay-client.test.js@@@ -268,3 -296,358 +296,368 @@@ test('[H1,H3,H7,H15,H16] relay on snapsassert.equal(relay.calls.length, afterOffCalls, 'unlinked commands stop connecting immediately');assert.equal(existsSync(keyFile), false, 'successful off removes this device copy of the board key');});++ test('[H3,H16] two cloned linked replicas order competing claims and retain the same refusal receipt', { timeout: 240_000 }, async (t) => {+ const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-relay-clone-race-')));+ const seed = join(scratch, 'seed');+ const clones = [join(scratch, 'clone-a'), join(scratch, 'clone-b')];+ const worktrees = [join(scratch, 'work-a'), join(scratch, 'work-b')];+ const homes = [join(scratch, 'home-a'), join(scratch, 'home-b')];+ const privateBin = join(scratch, 'path');+ const relayDirectory = join(scratch, 'relay');+ mkdirSync(seed);+ mkdirSync(privateBin, { mode: 0o700 });+ for (const home of homes) mkdirSync(home, { mode: 0o700 });+ const gitBinary = process.env.PATH.split(delimiter).map((entry) => join(entry, 'git')).find(existsSync);+ assert.ok(gitBinary, 'the fixture PATH contains git');+ symlinkSync(realpathSync(gitBinary), join(privateBin, 'git'));+ symlinkSync(realpathSync(process.execPath), join(privateBin, 'node'));+ const envs = homes.map((home) => {+ const env = { ...process.env, HOME: home, USERPROFILE: home, PULLBOARD_HOME: join(home, '.pullboard'), PATH: privateBin };+ for (const key of Object.keys(env)) if (key.startsWith('GIT_')) delete env[key];+ Object.assign(env, {+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Relay Clone Test', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Relay Clone Test', GIT_COMMITTER_EMAIL: '[email protected]',+ });+ return env;+ });++ /** Run fixture Git with an isolated identity and report its stderr on failure. */+ function gitAt(root, env, ...args) {+ const result = spawnSync('git', args, { cwd: root, env, encoding: 'utf8' });+ assert.equal(result.status, 0, `git ${args.join(' ')}: ${result.stderr}`);+ return result.stdout.trim();+ }++ /** Resolve the common Git directory used by a clone and its worktree. */+ function commonDir(root, env) {+ return resolve(root, gitAt(root, env, 'rev-parse', '--git-common-dir'));+ }++ t.after(() => rmSync(scratch, { recursive: true, force: true }));+ gitAt(seed, envs[0], 'init', '-q', '-b', 'main');+ writeFileSync(join(seed, 'pullboard.json'), JSON.stringify({+ gate: 'true', lanes: { web: { owns: ['web/'], specs: ['G'] } },+ }, null, 2) + '\n');+ writeFileSync(join(seed, 'SPEC.md'), '# Spec\n\n## G · Goals: relay claim fixture\n- G1 [approved, must] A linked claim is applied once in relay order. | gate: review\n');+ writeFileSync(join(seed, 'PRACTICE.md'), readFileSync(resolve(import.meta.dirname, '../PRACTICE.md')));+ mkdirSync(join(seed, 'web'));+ writeFileSync(join(seed, 'web', 'README.md'), 'relay claim fixture\n');+ gitAt(seed, envs[0], 'add', '-A');+ gitAt(seed, envs[0], 'commit', '-q', '-m', 'test: seed relay claim fixture');++ for (const clone of clones) gitAt(scratch, envs[0], 'clone', '-q', seed, clone);+ for (let index = 0; index < clones.length; index += 1) {+ gitAt(clones[index], envs[index], 'remote', 'set-url', 'origin', '[email protected]:fixture/repository.git');+ gitAt(clones[index], envs[index], 'worktree', 'add', '-q', '-b', `web/race-${index + 1}`, worktrees[index], 'main');+ }++ const seedBoard = store.openBoard(join(commonDir(seed, envs[0]), 'pullboard', 'board.sqlite'));+ let boardId;+ let snapshot;+ try {+ store.register(seedBoard, { lane: 'coordinator', path: seed });+ for (let index = 0; index < worktrees.length; index += 1) {+ store.register(seedBoard, { lane: 'web', path: worktrees[index], route: 'light' });+ }+ for (let id = 1; id <= 20; id += 1) {+ store.addItem(seedBoard, {+ by: 'coordinator', lane: 'web', title: `Concurrent claim ${id}`,+ criterion: 'one clone claims this item once', specIds: ['G1'],+ brief: 'Files: web/README.md\nTest: exactly one ordered claim event is recorded.', route: 'light', check: 'true',+ });+ }+ boardId = store.boardId(seedBoard);+ checkpointSequence(seedBoard, 0);+ snapshot = exportBoard(seedBoard);+ } finally { store.closeBoard(seedBoard); }++ for (let index = 0; index < clones.length; index += 1) {+ const replica = store.openBoard(join(commonDir(clones[index], envs[index]), 'pullboard', 'board.sqlite'));+ try { importBoard(replica, snapshot); } finally { store.closeBoard(replica); }+ }++ const provider = await githubFixture(t);+ const auth = createRelayAuth({ database: join(scratch, 'auth.sqlite'), github: createGitHubClient(provider.config) });+ t.after(() => auth.close());+ const relay = await relayServer(t, relayDirectory, auth);+ const flow = auth.beginWeb();+ const authorization = await fetch(flow.authorizationURL, { redirect: 'manual' });+ const callback = new URL(authorization.headers.get('location'));+ const person = await auth.finishWeb(callback.searchParams.get('state'), callback.searchParams.get('code'), flow.binding);+ await auth.linkBoard(person.token, boardId, 'fixture/repository');++ const key = await generateBoardKey();+ const savedPath = process.env.PATH;+ const savedHome = process.env.PULLBOARD_HOME;+ try {+ process.env.PATH = privateBin;+ for (let index = 0; index < clones.length; index += 1) {+ process.env.PULLBOARD_HOME = envs[index].PULLBOARD_HOME;+ assert.equal(storeBoardKey(boardId, key), 'file', 'the isolated PATH forces the private file fallback');+ const keyFile = join(envs[index].PULLBOARD_HOME, 'relay-keys', `${boardId}.key`);+ assert.equal(statSync(keyFile).mode & 0o777, 0o600);+ const state = {+ version: 1, mode: 'ordered', board: boardId, url: relay.origin, repository: 'fixture/repository',+ token: person.token, tokenId: person.id, keyStorage: 'file', sequence: 0,+ cursor: snapshot.tables.event.at(-1)?.event_id ?? 0,+ };+ const linkFile = join(commonDir(clones[index], envs[index]), 'pullboard', 'relay.json');+ writeFileSync(linkFile, JSON.stringify(state) + '\n', { mode: 0o600 });+ chmodSync(linkFile, 0o600);+ }+ } finally {+ if (savedPath === undefined) delete process.env.PATH; else process.env.PATH = savedPath;+ if (savedHome === undefined) delete process.env.PULLBOARD_HOME; else process.env.PULLBOARD_HOME = savedHome;+ }++ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(snapshot)), {+ boardId, kind: 'snapshot', sequence: 0,+ })).toString('base64url');+ const uploaded = await fetch(`${relay.origin}/api/v1/boards/${boardId}/state`, {+ method: 'PUT', headers: { authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },+ body: JSON.stringify({ sequence: 0, sealed }),+ });+ assert.equal(uploaded.status, 200, await uploaded.text());++ const refusals = new Map();+ for (let id = 1; id <= 20; id += 1) {+ const [left, right] = await Promise.all([+ cliResult(worktrees[0], envs[0], 'claim', String(id)),+ cliResult(worktrees[1], envs[1], 'claim', String(id)),+ ]);+ const attempts = [left, right];+ assert.equal(attempts.filter((result) => result.status === 0).length, 1, `one clone claims #${id}`);+ const winner = attempts.findIndex((result) => result.status === 0);+ const loser = attempts[1 - winner];+ assert.equal(loser.status, 1, `the competing claim for #${id} is refused`);+ assert.equal(loser.document.error.code, 'HELD');+ assert.equal(typeof loser.document.error.message, 'string');+ assert.equal(typeof loser.document.error.next, 'string');+ refusals.set(id, loser.document.error);+ const released = await cliResult(worktrees[winner], envs[winner], 'release', String(id));+ assert.equal(released.status, 0, `the winner releases #${id} before the next round`);+ }++ const synced = await Promise.all(clones.map((clone, index) => cliResult(worktrees[index], envs[index], 'status')));+ assert.ok(synced.every((result) => result.status === 0), 'both replicas finish by applying the same relay prefix');++ /** Read replay receipts without changing either replica's event cursor. */+ function receipts(file) {+ const db = new DatabaseSync(file, { readOnly: true });+ try {+ return db.prepare("SELECT meta_value FROM board_meta WHERE meta_key LIKE 'relay_receipt_%'")+ .all().map(({ meta_value }) => JSON.parse(meta_value));+ } finally { db.close(); }+ }++ const replicaFiles = clones.map((clone, index) => join(commonDir(clone, envs[index]), 'pullboard', 'board.sqlite'));+ const eventRows = replicaFiles.map((file) => localEvents(file));+ const receiptRows = replicaFiles.map(receipts);+ for (let id = 1; id <= 20; id += 1) {+ for (const events of eventRows) {+ assert.equal(events.filter((event) => event.item_id === id && event.event_kind === 'claim').length, 1,+ `item #${id} has exactly one applied claim event on each clone`);+ }+ for (const rows of receiptRows) {+ const claims = rows.map((receipt) => ({ receipt, move: JSON.parse(receipt.move) }))+ .filter(({ move }) => move.operation === 'claim' && move.args[0] === id);+ assert.equal(claims.length, 2, `both ordered claim descriptors for #${id} have durable receipts`);+ const denied = claims.filter(({ receipt }) => receipt.outcome.error);+ assert.equal(denied.length, 1, `exactly one durable claim receipt for #${id} is a refusal`);+ assert.deepEqual(denied[0].receipt.outcome.error, {+ code: refusals.get(id).code, message: refusals.get(id).message, next: refusals.get(id).next,+ }, `the durable refusal for #${id} matches the losing CLI result exactly`);+ }+ }+ assert.equal(receiptRows[0].length, receiptRows[1].length, 'both cloned boards retain the same number of applied operation receipts');++ relay.failMoves(true);+ const beforeWorktreeFailure = localEvents(replicaFiles[0]);+ const beforeWorktrees = gitAt(clones[0], envs[0], 'worktree', 'list', '--porcelain');+ const failedWorktree = await cliResult(clones[0], envs[0], 'worktree', 'web');+ assert.equal(failedWorktree.status, 1);+ assert.equal(failedWorktree.document.error.code, 'TEMPORARY');+ assert.equal(gitAt(clones[0], envs[0], 'worktree', 'list', '--porcelain'), beforeWorktrees,+ 'a refused relay registration removes only its newly-created clean worktree');+ assert.equal(spawnSync('git', ['show-ref', '--verify', '--quiet', 'refs/heads/web/1'], {+ cwd: clones[0], env: envs[0],+ }).status, 1, 'the unregistered new branch is removed too');+ assert.deepEqual(localEvents(replicaFiles[0]), beforeWorktreeFailure, 'registration never runs locally before sequencing');+ relay.failMoves(false);+ await cli(clones[0], envs[0], 'status');++ const beforeInit = localEvents(replicaFiles[0]);+ const initializedClone = await cli(clones[0], envs[0], 'init');+ assert.equal(initializedClone.root, clones[0]);+ assert.deepEqual(localEvents(replicaFiles[0]), beforeInit, 'repeated init cannot bypass relay ordering to rewrite coordinator registration');++ const board = store.openBoard(replicaFiles[0]);+ let earlier;+ let next;+ try {+ next = appliedSequence(board) + 1;+ earlier = prepareEngineMove(board, 'addItem', [{ by: 'coordinator', lane: 'web', title: 'Earlier remote item' }]);+ } finally { store.closeBoard(board); }+ const earlierSealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(earlier)), {+ boardId, kind: 'move', sequence: next,+ })).toString('base64url');+ const headers = { authorization: `Bearer ${person.token}`, 'content-type': 'application/json' };+ assert.equal((await fetch(`${relay.origin}/api/v1/boards/${boardId}/moves`, {+ method: 'POST', headers, body: JSON.stringify({ sequence: next, sealed: earlierSealed }),+ })).status, 200);++ /** Run the actual local API command under this clone's isolated device credentials. */+ async function apiCommand(argv, io) {+ const names = ['PATH', 'HOME', 'PULLBOARD_HOME', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM'];+ const previous = new Map(names.map((name) => [name, process.env[name]]));+ try {+ for (const name of names) process.env[name] = envs[0][name];+ return await main(argv, io);+ } finally {+ for (const [name, value] of previous) {+ if (value === undefined) delete process.env[name]; else process.env[name] = value;+ }+ }+ }+ const localApi = await serveApi({ runCommand: apiCommand, projects: () => [{ root: clones[0], name: 'Clone API' }] });+ try {+ const address = new URL(localApi.url);+ const response = await fetch(`${address.origin}/api/v1/boards/${boardId}/moves`, {+ method: 'POST', headers: { 'x-pullboard-key': address.searchParams.get('k'), 'content-type': 'application/json' },+ body: JSON.stringify({ verb: 'add', args: { lane: 'web', title: 'This API item' } }),+ });+ const result = await response.json();+ assert.equal(response.status, 200, JSON.stringify(result));+ assert.equal(result.event.event_kind, 'add');+ assert.equal(result.event.item_id, result.result.item.item_id, 'the API returns its own event despite catching up an earlier add');+ assert.equal(result.result.item.item_title, 'This API item');+ } finally { await localApi.close(); }++ await Promise.all(worktrees.map((root, index) => cli(root, envs[index], 'status')));+ const updated = store.openBoard(replicaFiles[0]);+ let future;+ try {+ next = appliedSequence(updated) + 1;+ future = { ...prepareEngineMove(updated, 'addItem', [{ by: 'coordinator', lane: 'web', title: 'Future engine item' }]), engine: ENGINE_VERSION + 1 };+ } finally { store.closeBoard(updated); }+ const futureSealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(future)), {+ boardId, kind: 'move', sequence: next,+ })).toString('base64url');+ assert.equal((await fetch(`${relay.origin}/api/v1/boards/${boardId}/moves`, {+ method: 'POST', headers, body: JSON.stringify({ sequence: next, sealed: futureSealed }),+ })).status, 200);+ const beforeFuture = replicaFiles.map(localEvents);+ const incompatible = await Promise.all(clones.map((root, index) => cliResult(root, envs[index], 'add', 'web', 'Must not apply')));+ for (const result of incompatible) {+ assert.equal(result.status, 1);+ assert.equal(result.document.error.code, 'ENGINE_VERSION');+ assert.match(result.document.error.message, new RegExp(`engine version ${ENGINE_VERSION + 1}.*engine version ${ENGINE_VERSION}`));+ assert.match(result.document.error.next, /upgrade/);+ }+ assert.deepEqual(replicaFiles.map(localEvents), beforeFuture, 'neither clone applies a future engine or its own later move');++ });++ /** Exercise migration of an old local-first mirror queue into the ordered native checkpoint. */+ async function legacyMirrorQueueFragment({+ relay, root, relayEnv, boardFile, linkFile, lane, lanes, boardId, key, currentPersonToken,+ localEvents, cli, store, unseal,+ }) {+ const priorRows = localEvents(boardFile);+ const link = JSON.parse(readFileSync(linkFile, 'utf8'));+ assert.equal(link.mode, 'ordered');+ link.cursor = priorRows.at(-1)?.event_id ?? 0;++ // Model the pre-161 local-first outbox: old link metadata plus local rows committed before upload.+ delete link.mode;+ delete link.presentationDigest;+ writeFileSync(linkFile, JSON.stringify(link) + '\n', { mode: 0o600 });++ const board = store.openBoard(boardFile);+ try {+ store.addItem(board, {+ by: 'coordinator', lane, title: 'legacy queued item', criterion: 'queued before ordered mode',+ });+ store.shout(board, {+ from: 'coordinator', to: 'person', text: 'legacy queued shout', lanes,+ });+ } finally { store.closeBoard(board); }++ const queuedRows = localEvents(boardFile);+ const queuedEvents = queuedRows.slice(priorRows.length);+ assert.deepEqual(queuedEvents.map((event) => event.event_kind), ['add', 'shout']);+ const initialUploadCount = relay.uploads.length;+ const expectedBehind = queuedEvents.length;++ relay.failMoves(true);+ const offline = await cli(root, relayEnv, 'status');+ assert.equal(offline.relay.behind, expectedBehind, 'the legacy local rows remain in the durable queue');+ assert.deepEqual(localEvents(boardFile), queuedRows, 'a failed migration leaves local rows untouched');+ assert.equal(relay.uploads.length, initialUploadCount, 'refused uploads are not acknowledged');++ const pendingLegacy = JSON.parse(readFileSync(linkFile, 'utf8'));++ assert.equal(pendingLegacy.pending.sequence, link.sequence + 1);++ assert.equal(pendingLegacy.pending.needsPresentation, true, 'the first legacy row has no projection covering its position');++ relay.failMoves(false);+ const resumed = await cli(root, relayEnv, 'status');+ assert.equal(resumed.relay.behind, 0, 'the next reachable command drains the queued legacy rows');+ assert.deepEqual(localEvents(boardFile), queuedRows, 'migration checkpoints existing rows instead of replaying them');- assert.deepEqual(relay.uploads.slice(initialUploadCount).map((upload) => upload.sequence), [4, 5]);++ const legacyUploads = relay.uploads.slice(initialUploadCount);++ assert.deepEqual(legacyUploads.map((upload) => upload.sequence), [4, 5]);++ const openedLegacy = await Promise.all(legacyUploads.map(async (upload) => JSON.parse(new TextDecoder().decode(await unseal(++ key, Buffer.from(upload.sealed, 'base64url'), { boardId, kind: 'move', sequence: upload.sequence },++ )))));++ assert.equal(openedLegacy[0].presentation, undefined, 'the historical first move cannot attest the later row');++ assert.equal(openedLegacy[1].presentation.state.events[0].event_id, queuedEvents.at(-1).event_id, 'the final legacy move carries only its matching projection');++ const authorization = { authorization: `Bearer ${currentPersonToken}` };+ const stateResponse = await fetch(`${relay.origin}/api/v1/boards/${boardId}/state`, { headers: authorization });+ 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(+ 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'));++ const repeated = await cli(root, relayEnv, 'status');+ assert.equal(repeated.relay.behind, 0);+ assert.deepEqual(localEvents(boardFile), queuedRows, 'a repeated sync does not execute legacy rows again');+ assert.equal(relay.uploads.length, initialUploadCount + 2, 'a repeated sync does not append duplicate uploads');+ const unchangedResponse = await fetch(`${relay.origin}/api/v1/boards/${boardId}/state`, { headers: authorization });+ assert.equal((await unchangedResponse.json()).state.sealed, stateDocument.state.sealed,+ 'a repeated sync leaves the acknowledged native checkpoint unchanged');+ }++ /** Confirm migration refuses an unrecognized remote prefix before executing another local move. */+ async function legacyForeignPrefixFragment({+ relay, root, relayEnv, boardFile, linkFile, lane, boardId, currentPersonToken, localEvents, cliResult,+ }) {+ const originalLink = readFileSync(linkFile, 'utf8');+ const link = JSON.parse(originalLink);+ assert.equal(link.mode, 'ordered');+ link.cursor = localEvents(boardFile).at(-1)?.event_id ?? 0;+ delete link.mode;+ delete link.presentationDigest;+ writeFileSync(linkFile, JSON.stringify(link) + '\n', { mode: 0o600 });++ const foreign = await fetch(`${relay.origin}/api/v1/boards/${boardId}/moves`, {+ method: 'POST',+ headers: { authorization: `Bearer ${currentPersonToken}`, 'content-type': 'application/json' },+ body: JSON.stringify({ sequence: link.sequence + 1, sealed: 'AQ' }),+ });+ assert.equal(foreign.status, 200, await foreign.text());++ const beforeAttempt = localEvents(boardFile);+ const refused = await cliResult(root, relayEnv, 'add', lane, 'must not follow a foreign prefix');+ assert.equal(refused.status, 1);+ assert.equal(refused.document.error.code, 'RELAY_DIVERGED');+ assert.match(refused.document.error.message, new RegExp(`relay sequence ${link.sequence + 1}.*local sequence ${link.sequence}`));+ assert.match(refused.document.error.next, /relay off.*relay on.*pairing/);+ assert.deepEqual(localEvents(boardFile), beforeAttempt, 'a foreign prefix is refused before the CLI move applies');++ writeFileSync(linkFile, originalLink, { mode: 0o600 });+ }