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
fix(relay): bound person flow waits [H16,C7]
Corey Olson3452598cd997
diff --git a/test/chrome-fixture.js b/test/chrome-fixture.jsindex 68169df7..399c9e08 100644--- a/test/chrome-fixture.js+++ b/test/chrome-fixture.js@@ -2,6 +2,7 @@import { spawn } from 'node:child_process';import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';+import { monitorEventLoopDelay } from 'node:perf_hooks';import { join, resolve } from 'node:path';const STARTUP_TIMEOUT_MS = 30_000;@@ -128,34 +129,60 @@ export async function startChrome({const port = await readDevToolsPort(profile, launched, deadline);const target = await createPageTarget(port, deadline);socket = await connectDevTools(target.webSocketDebuggerUrl, deadline);- const send = createSender(socket, pending, () => ++id, commandTimeoutMs);+ const loopDelay = monitorEventLoopDelay({ resolution: 10 });+ loopDelay.enable();+ const relayRequests = new Set();+ const send = createSender(socket, pending, () => ++id, commandTimeoutMs, loopDelay, relayRequests);const evaluate = createEvaluator(send);let closed = false;+ let taskSequence = 0;/** Navigate the existing isolated browser profile to a local or test-owned URL. */async function navigate(nextUrl) {- await send('Page.navigate', { url: nextUrl });+ await send('Page.navigate', { url: nextUrl }, 'navigate page');}/** Wait until a page expression becomes truthy before its command deadline. */- async function waitFor(expression, timeoutMs = commandTimeoutMs) {+ async function waitFor(expression, timeoutMs = commandTimeoutMs, label = 'wait for page condition') {const waitDeadline = Date.now() + timeoutMs;while (Date.now() < waitDeadline) {- if (await evaluate(expression)) return;+ if (await evaluate(expression, label)) return;await pause(50);}- throw new Error('Browser condition did not arrive before its deadline.');+ throw new Error(`Browser condition "${label}" did not arrive within ${timeoutMs}ms.`);+ }+ /** Start asynchronous page work without holding a CDP Runtime.evaluate command open. */+ async function startTask(expression, label) {+ const taskId = '__pullboardFixtureTask' + ++taskSequence;+ const key = JSON.stringify(taskId);+ await evaluate(`(() => { window[${key}] = null; Promise.resolve().then(() => (${expression}))+ .then(value => { window[${key}] = { value }; }, error => { window[${key}] = { error: { code: error?.code ?? null, message: error?.message ?? 'page operation failed' } }; }); return true; })()`, label);+ return taskId;+ }+ /** Poll asynchronous page work while each DevTools command stays short. */+ async function pollTask(taskId, timeoutMs = 25_000, label = 'poll page operation') {+ const key = JSON.stringify(taskId);+ await waitFor(`window[${key}] !== null && window[${key}] !== undefined`, timeoutMs, label);+ const result = await evaluate(`window[${key}]`, label + ' result');+ if (result?.error) {+ const error = new Error(`${label} failed${result.error.code ? ' [' + result.error.code + ']' : ''}: ${result.error.message}`);+ if (result.error.code) error.code = result.error.code;+ throw error;+ }+ return result?.value;}/** Close once; remove an owned profile only after the full Chrome process group is gone. */async function close() {if (closed) return;closed = true;try { socket.close(); } catch { /* The DevTools socket already closed. */ }+ loopDelay.disable();rejectPending(pending, 'Isolated Chrome closed before a command completed.');await launched.close();if (ownedProfile) rmSync(profile, { recursive: true, force: true });}- await send('Page.enable');- await send('Runtime.enable');- await send('Page.navigate', { url });+ await send('Network.enable', {}, 'enable network diagnostics');+ await send('Page.enable', {}, 'enable page diagnostics');+ await send('Runtime.enable', {}, 'enable runtime diagnostics');+ await send('Page.navigate', { url }, 'open initial page');const launchDurationMs = launched.launchDurationMs;process.stderr.write(`Chrome ready in ${launchDurationMs}ms (${startupTimeoutMs}ms DevTools budget)\n`);return {@@ -165,6 +192,8 @@ export async function startChrome({navigate,evaluate,waitFor,+ startTask,+ pollTask,send,close,};@@ -222,11 +251,22 @@ async function connectDevTools(debuggerUrl, deadline) {}/** Create a CDP command sender that correlates responses and bounds every request. */-function createSender(socket, pending, nextId, timeoutMs) {+function createSender(socket, pending, nextId, timeoutMs, loopDelay, relayRequests) {/** Resolve or reject the request matching one CDP response without logging its payload. */function onMessage(event) {let message;try { message = JSON.parse(String(event.data)); } catch { return; }+ if (message.method === 'Page.frameNavigated' && !message.params?.frame?.parentId) relayRequests.clear();+ if (message.method === 'Network.requestWillBeSent') {+ const request = message.params?.request;+ const url = request?.url ?? '';+ const eventStream = /\/api\/v1\/boards\/[0-9a-f]{32}\/events(?:\?|$)/.test(url)+ && /text\/event-stream/i.test(request?.headers?.Accept ?? request?.headers?.accept ?? '');+ if (/\/api\/v1\/boards\//.test(url) && !eventStream) relayRequests.add(message.params.requestId);+ }+ if (['Network.loadingFinished', 'Network.loadingFailed'].includes(message.method)) {+ relayRequests.delete(message.params?.requestId);+ }const waiter = pending.get(message.id);if (!waiter) return;pending.delete(message.id);@@ -235,13 +275,19 @@ function createSender(socket, pending, nextId, timeoutMs) {else waiter.resolve(message.result);}socket.addEventListener('message', onMessage);- return (method, params = {}) => new Promise((resolveResult, rejectResult) => {+ return (method, params = {}, label = method) => new Promise((resolveResult, rejectResult) => {const requestId = nextId();+ const startedAt = Date.now();+ const maxDelayAtSend = loopDelay.max;+ const timeoutMessage = () => {+ const maxDelayRise = Math.max(0, loopDelay.max - maxDelayAtSend);+ return `DevTools ${method} "${label}" timed out after ${Date.now() - startedAt}ms; maximum event-loop delay ${Math.round(maxDelayRise / 1e6)}ms; relay request pending: ${relayRequests.size > 0}.`;+ };const timer = setTimeout(() => {pending.delete(requestId);- rejectResult(new Error(`DevTools command timed out: ${method}.`));+ rejectResult(new Error(timeoutMessage()));}, timeoutMs);- pending.set(requestId, { resolve: resolveResult, reject: rejectResult, timer, method });+ pending.set(requestId, { resolve: resolveResult, reject: rejectResult, timer, method, label });try { socket.send(JSON.stringify({ id: requestId, method, params })); }catch {clearTimeout(timer);@@ -253,8 +299,8 @@ function createSender(socket, pending, nextId, timeoutMs) {/** Evaluate a page expression by value, without including page content in failures. */function createEvaluator(send) {- return async (expression) => {- const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });+ return async (expression, label = 'evaluate page expression') => {+ const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, label);if (result.exceptionDetails) throw new Error('Browser evaluation failed.');return result.result?.value;};diff --git a/test/relay-browser-fixture.test.js b/test/relay-browser-fixture.test.jsnew file mode 100644index 00000000..0f42b3e0--- /dev/null+++ b/test/relay-browser-fixture.test.js@@ -0,0 +1,66 @@+/** Real Chrome fixture diagnostics and timeout boundary [H16,C7]. */+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { test } from 'node:test';+import { ENGINE_VERSION } from '../src/machine.js';+import { relayClientFixture } from './relay-client-fixture.js';+import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';++/** Assert the fixed CDP bound reports its command context and relay-request state. */+async function stalledCommand(chrome, label, pending) {+ await assert.rejects(+ chrome.evaluate('new Promise(resolve => setTimeout(resolve, 16000))', label),+ error => {+ assert.match(error.message, /Runtime\.evaluate/);+ assert.match(error.message, new RegExp(label));+ assert.match(error.message, /timed out after 1[45]\d{3}ms/);+ assert.match(error.message, /maximum event-loop delay \d+ms/);+ assert.match(error.message, new RegExp('relay request pending: ' + pending));+ return true;+ },+ );+}++test('real Chrome names the stalled command when a 16-second page promise exceeds the CDP bound [H16,C7]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const chrome = await startChrome();+ t.after(() => chrome.close());+ await stalledCommand(chrome, '16-second stalled-command probe', false);+ const task = await chrome.startTask('new Promise(resolve => setTimeout(resolve, 16000))', 'navigation cleanup probe');+ await chrome.navigate('about:blank');+ await assert.rejects(chrome.pollTask(task, 250, 'task lost to navigation'), /did not arrive within 250ms/);+});++test('paired Chrome excludes idle event streams and reports only held state requests [H16,C7]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const title = 'RELAY_BROWSER_PENDING_DIAGNOSTIC';+ assert.equal((await box.cli('add', box.lane, title)).code, 0);+ await box.link();+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const key = readFileSync(box.keyFile, 'utf8').trim();+ const chrome = await startChrome();+ t.after(() => chrome.close());+ const cookie = await chrome.send('Network.setCookie', {+ name: 'pb_session', value: link.token, url: box.origin, httpOnly: true, sameSite: 'Lax',+ });+ assert.equal(cookie.success, true);+ await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + key);+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');+ await stalledCommand(chrome, 'idle paired stream probe', false);++ const before = box.stateReadStarted();+ box.delayStateReads(30000);+ const stateTask = await chrome.startTask(`fetch(${JSON.stringify('/api/v1/boards/' + link.board + '/state')}, { credentials: 'same-origin', headers: { 'x-pullboard-engine': ${ENGINE_VERSION} } })+ .then(response => response.status)`, 'held paired state read');+ const deadline = Date.now() + 5000;+ while (box.stateReadStarted() === before && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 20));+ assert.ok(box.stateReadStarted() > before, 'the authenticated state request reached the private relay');+ await stalledCommand(chrome, 'held paired state probe', true);+ await chrome.navigate('about:blank');+ box.delayStateReads(0);+ await stalledCommand(chrome, 'navigation-cleared paired request probe', false);+ await assert.rejects(chrome.pollTask(stateTask, 250, 'state task lost to navigation'), /did not arrive within 250ms/);+});diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 8c125544..6e50e882 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -14,19 +14,35 @@ import { createGitHubClient } from '../relay/github.js';import { githubFixture } from './relay-fixture.js';const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');+const CLI_PRODUCT_DEADLINE_MS = 15_000;+const SNAPSHOT_UPLOAD_BOUND_MS = 10_000;+const STATUS_SNAPSHOT_UPLOADS = 3;+const CLI_DEADLINE_MARGIN_MS = 10_000;++/** Derive a private CLI child deadline from the product bound and its asserted upload count. */+export function cliChildDeadlineMs(snapshotUploads) {+ assert.ok(Number.isSafeInteger(snapshotUploads) && snapshotUploads >= 0, 'snapshot upload count is a nonnegative integer');+ return Math.max(CLI_PRODUCT_DEADLINE_MS, snapshotUploads * SNAPSHOT_UPLOAD_BOUND_MS) + CLI_DEADLINE_MARGIN_MS;+}/** Capture a real child result without exposing its private output in failure diagnostics. */-function childResult(root, env, argv) {+function childResult(root, env, argv, snapshotUploads = STATUS_SNAPSHOT_UPLOADS) {return new Promise((resolveResult, reject) => {+ const startedAt = Date.now();+ const command = argv[0] === CLI ? (argv[1] ?? 'CLI') : (argv[0] ?? 'script');+ const childDeadlineMs = cliChildDeadlineMs(snapshotUploads);const child = spawn(process.execPath, argv, { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });let stdout = '';- const timer = setTimeout(() => child.kill('SIGKILL'), 25000);+ let exceededDeadline = false;+ const timer = setTimeout(() => { exceededDeadline = true; child.kill('SIGKILL'); }, childDeadlineMs);child.stdout.setEncoding('utf8').on('data', part => { stdout += part; });child.stderr.resume();child.once('error', error => { clearTimeout(timer); reject(error); });child.once('close', (code, signal) => {clearTimeout(timer);- if (signal) return reject(new Error('private relay fixture child exceeded its deadline'));+ if (signal) return reject(new Error(exceededDeadline+ ? `Private relay fixture ${command} exceeded its ${childDeadlineMs}ms deadline after ${Date.now() - startedAt}ms.`+ : `Private relay fixture ${command} ended with signal ${signal} after ${Date.now() - startedAt}ms.`));let document;try { document = JSON.parse(stdout); }catch { return reject(new Error('private relay fixture child did not return JSON')); }@@ -36,7 +52,7 @@ function childResult(root, env, argv) {}/** Start an isolated board with fallback-file keys and a real authorized loopback relay. */-export async function relayClientFixture(t) {+export async function relayClientFixture(t, { cliChildren } = {}) {const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-relay-cleanup-')));const root = join(scratch, 'repo');const home = join(scratch, 'home');@@ -64,6 +80,14 @@ export async function relayClientFixture(t) {let override = null;let mintFailures = 0;let refuseEventReads = false;+ const injectedSnapshotWriteDelayMs = Number(process.env.PULLBOARD_TEST_SNAPSHOT_WRITE_DELAY_MS ?? 0);+ assert.ok(Number.isSafeInteger(injectedSnapshotWriteDelayMs) && injectedSnapshotWriteDelayMs >= 0 && injectedSnapshotWriteDelayMs <= 15000,+ 'injected snapshot delay is within the product wait bound');+ let snapshotWriteDelayMs = 0;+ let snapshotWriteCount = 0;+ const snapshotWriteDelays = [];+ let stateReadDelayMs = 0;+ let stateReadStarted = 0;let refuseSnapshotWrites = false;let refuseRequestWrites = false;let signIn;@@ -74,6 +98,7 @@ export async function relayClientFixture(t) {const privateKeys = new Set();let keyLeaked = false;const server = createServer(async (req, res) => {+ if (req.method === 'PUT' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) snapshotWriteCount += 1;const requestChunks = [];const responseChunks = [];const request = new Transform({@@ -132,6 +157,17 @@ export async function relayClientFixture(t) {res.end(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture snapshot outage' } }));return;}+ const stateSnapshotDelayMs = Math.max(snapshotWriteDelayMs, injectedSnapshotWriteDelayMs);+ if (stateSnapshotDelayMs && req.method === 'PUT' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) {+ const delay = stateSnapshotDelayMs;+ const delayedAt = Date.now();+ await new Promise(resolveDelay => setTimeout(resolveDelay, delay));+ snapshotWriteDelays.push(Date.now() - delayedAt);+ }+ if (stateReadDelayMs && req.method === 'GET' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) {+ stateReadStarted += 1;+ await new Promise(resolveDelay => setTimeout(resolveDelay, stateReadDelayMs));+ }if (await signIn(request, res)) return;await api(request, res);});@@ -167,7 +203,39 @@ export async function relayClientFixture(t) {});}/** Invoke the production CLI in this private repository. */- async function cli(...args) { return childResult(root, env, [CLI, ...args, '--json']); }+ let cliChildIndex = 0;+ /** Verify and consume the next optional test-flow child descriptor. */+ function plannedSnapshotUploads(args) {+ if (!cliChildren) return undefined;+ const step = cliChildren[cliChildIndex++];+ assert.ok(step, `unexpected private CLI child: ${args.slice(0, 2).join(' ')}`);+ assert.deepEqual(args.slice(0, step.command.length), step.command, `private CLI child ${cliChildIndex} matches its budget descriptor`);+ return step.snapshotUploads;+ }+ /** Run one CLI child and verify its observed uploads against the plan when the test supplied one. */+ async function runCliChild(args, requestedUploads) {+ const plannedUploads = plannedSnapshotUploads(args);+ const snapshotUploads = plannedUploads ?? requestedUploads;+ const writesBefore = snapshotWriteCount;+ const result = await childResult(root, env, [CLI, ...args, '--json'], snapshotUploads);+ if (cliChildren) {+ assert.equal(snapshotWriteCount - writesBefore, snapshotUploads,+ `private CLI child ${cliChildIndex} uploads its declared number of snapshots`);+ }+ if (cliChildren && requestedUploads !== undefined) {+ assert.equal(requestedUploads, snapshotUploads, `private CLI child ${cliChildIndex} uses its declared upload count`);+ }+ return result;+ }+ /** Invoke the production CLI in this private repository under its planned budget, when present. */+ async function cli(...args) {+ return runCliChild(args);+ }+ /** Bound a CLI child using the exact snapshot count asserted by its fixture flow. */+ async function cliWithSnapshotUploads(snapshotUploads, ...args) {+ cliChildDeadlineMs(snapshotUploads);+ return runCliChild(args, snapshotUploads);+ }assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: root, env }).status, 0);writeFileSync(join(root, 'README.md'), 'private relay fixture project\n', { mode: 0o600 });assert.equal(spawnSync('git', ['add', 'README.md'], { cwd: root, env }).status, 0);@@ -266,11 +334,29 @@ export async function relayClientFixture(t) {}return {transit, relayDirectory: join(scratch, 'relay'), authDatabase, otherDeviceJoin,- root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, link, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,+ root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, cliWithSnapshotUploads, link, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,+ /** Assert the test consumed every declared child budget, with no hidden CLI calls. */+ assertCliChildrenComplete() {+ if (cliChildren) assert.equal(cliChildIndex, cliChildren.length, 'every planned private CLI child ran exactly once');+ },advance(days) { time = Date.now() + days * 86400000; },overrideDelete(value) { override = value; },failTokenMints(count) { mintFailures = count; },refuseSnapshotWrites(value) { refuseSnapshotWrites = value; },+ /** Delay each real relay snapshot upload until disabled to model late native checkpoints. */+ delaySnapshotWrites(ms) {+ assert.ok(Number.isSafeInteger(ms) && ms >= 0 && ms <= 15000, 'snapshot delay is within the product wait bound');+ snapshotWriteDelayMs = ms;+ },+ /** Return observed delays for the fixture's real snapshot endpoint. */+ snapshotWriteDelays() { return [...snapshotWriteDelays]; },+ /** Hold real state reads long enough to observe their pending-request diagnostic. */+ delayStateReads(ms) {+ assert.ok(Number.isSafeInteger(ms) && ms >= 0 && ms <= 30000, 'state read hold is bounded');+ stateReadDelayMs = ms;+ },+ /** Return how many state reads reached the private relay. */+ stateReadStarted() { return stateReadStarted; },refuseRequestWrites(value) { refuseRequestWrites = value; },mainURL: new URL('../src/cli.js', import.meta.url).href,keyInRequest() { return keyLeaked; },diff --git a/test/relay-person-actions.test.js b/test/relay-person-actions.test.jsindex 75a762a5..b9446e14 100644--- a/test/relay-person-actions.test.js+++ b/test/relay-person-actions.test.js@@ -28,45 +28,46 @@ async function pairedTransport(chrome, box, title) {await signIn(chrome, box);await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + key);await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');- await chrome.evaluate(`(async () => {+ const task = await chrome.startTask(`(async () => {const { createTransport } = await import('/relay/client.js');window.__personActionTransport = await createTransport({ onUpdate: () => {} });return true;- })()`);+ })()`, 'initialize paired person transport');+ await chrome.pollTask(task, 25000, 'initialize paired person transport');return link;}/** Submit literal person intent through the browser-owned transport. */async function personAction(chrome, board, move) {- return chrome.evaluate('window.__personActionTransport.request('- + JSON.stringify('/api/v1/boards/' + board + '/moves') + ',' + JSON.stringify(move) + ')');+ const task = await chrome.startTask('window.__personActionTransport.request('+ + JSON.stringify('/api/v1/boards/' + board + '/moves') + ',' + JSON.stringify(move) + ')', 'send person action');+ return chrome.pollTask(task, 25000, 'send person action');}-/** Poll checkpoint completion separately from CDP's 15-second per-evaluation deadline. */+/** Poll checkpoint completion separately from CDP's bounded evaluation deadline. */async function waitRequest(chrome, board, id, status) {const path = '/api/v1/boards/' + board + '/state';const predicate = `value.state?.personRequests?.some(entry => entry.id === ${JSON.stringify(id)} && entry.status === ${JSON.stringify(status)})`;- // A serialized stream task may wait up to 15 seconds for a checkpoint. Let the page finish- // that task and perform another state read, while each CDP evaluation remains synchronous.- await chrome.evaluate(`(() => {- window.__personActionReceipt = null;- (async () => {- const deadline = Date.now() + 30000;+ // Product checkpoint work is bounded at 15 seconds; ten seconds remain for scheduling and polling.+ const task = await chrome.startTask(`(async () => {+ const deadline = Date.now() + 25000;while (Date.now() < deadline) {try {const value = await window.__personActionTransport.request(${JSON.stringify(path)});- if (${predicate}) { window.__personActionReceipt = { value }; return; }+ if (${predicate}) return value;} catch { /* A checkpoint still being uploaded leaves the request waiting. */ }await new Promise(resolve => setTimeout(resolve, 50));}- window.__personActionReceipt = { error: 'The native request status did not reach the paired browser.' };- })();- return true;- })()`);- await chrome.waitFor('window.__personActionReceipt !== null', 45000);- const receipt = await chrome.evaluate('window.__personActionReceipt');- assert.equal(receipt.error, undefined, receipt.error);- return receipt.value;+ throw new Error('The native request status did not reach the paired browser.');+ })()`, 'wait for native person request status');+ return chrome.pollTask(task, 30000, 'wait for native person request status');+}++/** Read the final relay state without holding Runtime.evaluate open across network work. */+async function finalState(chrome, board) {+ const task = await chrome.startTask('window.__personActionTransport.request('+ + JSON.stringify('/api/v1/boards/' + board + '/state') + ')', 'read final person-action state');+ return chrome.pollTask(task, 25000, 'read final person-action state');}test('real paired person adds, answers a person decision, and holds then releases a lane [H12,H16,B26]', {@@ -136,7 +137,7 @@ test('real paired person adds, answers a person decision, and holds then release});assert.equal((await box.cli('status')).code, 0);await waitRequest(chrome, link.board, invalid.result.request.id, 'refused');- const state = await chrome.evaluate('window.__personActionTransport.request(' + JSON.stringify('/api/v1/boards/' + link.board + '/state') + ')');+ const state = await finalState(chrome, link.board);const refusal = state.state.personRequests.find(row => row.id === invalid.result.request.id).error;assert.equal(refusal.code, 'NO_LANE');exported = (await box.cli('export')).document;@@ -144,7 +145,7 @@ test('real paired person adds, answers a person decision, and holds then releaseconst brief = 'Files:\n- ../foreign.js\nTest:\n- Keep the file in its own lane';const foreign = await personAction(chrome, link.board, { verb: 'add', args: { lane: box.lane, title: 'PERSON_ACTION_FOREIGN_BRIEF', brief } });assert.equal((await box.cli('status')).code, 0);- const rejected = (await chrome.evaluate('window.__personActionTransport.request(' + JSON.stringify('/api/v1/boards/' + link.board + '/state') + ')')).state.personRequests.find(row => row.id === foreign.result.request.id);+ const rejected = (await finalState(chrome, link.board)).state.personRequests.find(row => row.id === foreign.result.request.id);assert.equal(rejected.status, 'refused');assert.equal(rejected.error.code, 'BRIEF_LANE');const terminal = await box.cli('add', box.lane, 'PERSON_ACTION_FOREIGN_BRIEF', '--brief', brief);@@ -153,6 +154,37 @@ test('real paired person adds, answers a person decision, and holds then release});+test('a person action completes with late native snapshots after 8 seconds [H12,H16]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const box = await relayClientFixture(t);+ const title = 'PERSON_ACTION_LATE_SNAPSHOT_READY';+ assert.equal((await box.cli('add', box.lane, title)).code, 0);+ await box.link();+ const chrome = await startChrome();+ t.after(() => chrome.close());+ const link = await pairedTransport(chrome, box, title);+ const action = await personAction(chrome, link.board, {+ verb: 'shout', args: { to: 'coordinator', text: 'PERSON_ACTION_LATE_SNAPSHOT' },+ });+ assert.equal(action.result.request.status, 'waiting');++ const delayedBefore = box.snapshotWriteDelays().length;+ box.delaySnapshotWrites(8000);+ const native = box.cliWithSnapshotUploads(3, 'status').then(result => ({ result }), error => ({ error }));+ const status = await native;+ box.delaySnapshotWrites(0);+ assert.equal(status.error, undefined, 'the real native CLI completes within its product deadline plus margin');+ assert.equal(status.result.code, 0, 'the real native CLI reports success');+ const delays = box.snapshotWriteDelays().slice(delayedBefore);+ assert.equal(delays.length, 3, 'this three-upload status flow uploads exactly three snapshots');+ assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds');+ const completed = await waitRequest(chrome, link.board, action.result.request.id, 'done');+ assert.equal(completed.state.personRequests.find(row => row.id === action.result.request.id).status, 'done');+ const exported = (await box.cli('export')).document;+ assert.equal(exported.tables.shout.filter(row => row.shout_text === 'PERSON_ACTION_LATE_SNAPSHOT').length, 1);+});+test('local view attribution is person-only and an agent token cannot seal person-attributed holds [H12,H16,B26]', async t => {const box = await relayClientFixture(t);const localHold = await executeMove(box.root, { verb: 'hold', args: { lane: box.lane, reason: 'LOCAL_PERSON_HOLD_FIXTURE' } }, main);diff --git a/test/relay-person-outbox.test.js b/test/relay-person-outbox.test.jsindex cc028ec9..fc771495 100644--- a/test/relay-person-outbox.test.js+++ b/test/relay-person-outbox.test.js@@ -27,11 +27,36 @@ async function pairedTransport(chrome, box, title) {/** Initialize the real transport on the currently loaded document. */async function installTransport(chrome) {- await chrome.evaluate(`(async () => {+ const task = await chrome.startTask(`(async () => {const { createTransport } = await import('/relay/client.js');window.__personOutboxTransport = await createTransport({ onUpdate: () => {} });return true;- })()`);+ })()`, 'initialize person outbox transport');+ await chrome.pollTask(task, 25000, 'initialize person outbox transport');+}++/** Read a final state without keeping a single DevTools evaluation open during relay work. */+async function finalState(chrome, board) {+ const task = await chrome.startTask('window.__personOutboxTransport.request('+ + JSON.stringify('/api/v1/boards/' + board + '/state') + ')', 'read person outbox state');+ return chrome.pollTask(task, 25000, 'read person outbox state');+}++/** Poll the device-decrypted outbox receipt while native status publishes its snapshot. */+async function waitForRequest(chrome, board, id, status) {+ const path = '/api/v1/boards/' + board + '/state';+ const task = await chrome.startTask(`(async () => {+ const deadline = Date.now() + 25000;+ while (Date.now() < deadline) {+ try {+ const state = await window.__personOutboxTransport.request(${JSON.stringify(path)});+ if (state.state?.personRequests?.some(entry => entry.id === ${JSON.stringify(id)} && entry.status === ${JSON.stringify(status)})) return state;+ } catch { /* The native snapshot may still be in flight. */ }+ await new Promise(resolve => setTimeout(resolve, 50));+ }+ throw new Error('The person outbox receipt did not reach its expected status.');+ })()`, 'wait for person outbox receipt');+ return chrome.pollTask(task, 30000, 'wait for person outbox receipt');}test('real Chrome keeps an interrupted person request sealed and retries it once after reload [H12,H16,H17]', {@@ -48,10 +73,13 @@ test('real Chrome keeps an interrupted person request sealed and retries it onceconst outboxPrefix = 'pullboard.relay.requests.v1.' + link.board + '.';box.refuseRequestWrites(true);- const interrupted = await chrome.evaluate(`window.__personOutboxTransport.request(+ const interruptedTask = await chrome.startTask(`window.__personOutboxTransport.request(${JSON.stringify('/api/v1/boards/' + link.board + '/moves')},${JSON.stringify({ verb: 'shout', args: { to: 'coordinator', text } })}- ).then(() => ({ code: null }), error => ({ code: error.code }))`);+ )`, 'submit interrupted person request');+ let interrupted;+ try { interrupted = await chrome.pollTask(interruptedTask, 25000, 'submit interrupted person request'); }+ catch (error) { interrupted = { code: error.code }; }assert.equal(interrupted.code, 'RELAY_UNAVAILABLE');let outbox = await chrome.evaluate(`(() => {const keys = Array.from({ length: localStorage.length }, (_, i) => localStorage.key(i)).filter(key => key?.startsWith(${JSON.stringify(outboxPrefix)}));@@ -71,8 +99,7 @@ test('real Chrome keeps an interrupted person request sealed and retries it onceawait chrome.navigate(box.origin);await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');await installTransport(chrome);- const statePath = '/api/v1/boards/' + link.board + '/state';- const state = await chrome.evaluate('window.__personOutboxTransport.request(' + JSON.stringify(statePath) + ')');+ const state = await finalState(chrome, link.board);const requestId = outbox[0].record.id;const receipt = state.state.personRequests.find(row => row.id === requestId);assert.equal(receipt?.status, 'waiting', 'a read flushes the saved request after the service recovers');@@ -81,11 +108,22 @@ test('real Chrome keeps an interrupted person request sealed and retries it once.filter(key => key?.startsWith(${JSON.stringify(outboxPrefix)})))()`);assert.deepEqual(outbox, [], 'the relay acknowledgement removes the device outbox entry');- assert.equal((await box.cli('status')).code, 0, 'the native linked machine executes the recovered request');+ const delayedBefore = box.snapshotWriteDelays().length;+ box.delaySnapshotWrites(8000);+ const native = box.cliWithSnapshotUploads(3, 'status').then(result => ({ result }), error => ({ error }));+ const status = await native;+ box.delaySnapshotWrites(0);+ assert.equal(status.error, undefined, 'the native linked machine executes the recovered request');+ assert.equal(status.result.code, 0, 'the native linked machine reports success');+ const delays = box.snapshotWriteDelays().slice(delayedBefore);+ assert.equal(delays.length, 3, 'this three-upload status flow uploads exactly three snapshots');+ assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds');+ const completed = await waitForRequest(chrome, link.board, requestId, 'done');const exported = (await box.cli('export')).document;const shouts = exported.tables.shout.filter(row => row.shout_from === 'person' && row.shout_text === text);assert.equal(shouts.length, 1, 'one recovered intent creates exactly one authored person shout');- const repeatedState = await chrome.evaluate('window.__personOutboxTransport.request(' + JSON.stringify(statePath) + ')');+ assert.equal(completed.state.personRequests.find(row => row.id === requestId).status, 'done');+ const repeatedState = await finalState(chrome, link.board);assert.equal(repeatedState.state.personRequests.find(row => row.id === requestId).status, 'done');assert.equal((await box.cli('status')).code, 0, 'repeated native replay stays idempotent');const repeatedExport = (await box.cli('export')).document;diff --git a/test/relay-person-requests.test.js b/test/relay-person-requests.test.jsindex 7e6686e3..5b792522 100644--- a/test/relay-person-requests.test.js+++ b/test/relay-person-requests.test.js@@ -7,7 +7,44 @@ import { test } from 'node:test';import { decodeBoardKey, seal } from '../src/seal.js';import { ENGINE_VERSION } from '../src/machine.js';import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';-import { relayClientFixture } from './relay-client-fixture.js';+import { cliChildDeadlineMs, relayClientFixture } from './relay-client-fixture.js';++const CHROME_START_BUDGET_MS = 30_000;+const CLI_SETUP_MARGIN_MS = 20_000;+const FIXTURE_SETUP_CLI_CHILDREN = [+ { command: ['init'], snapshotUploads: 0 },+ { command: ['add'], snapshotUploads: 0 },+ { command: ['export'], snapshotUploads: 0 },+];+const APPROVAL_FLOW_CLI_CHILDREN = [+ ...FIXTURE_SETUP_CLI_CHILDREN,+ { command: ['add'], snapshotUploads: 0 },+ { command: ['relay', 'on'], snapshotUploads: 1 },+ { command: ['status'], snapshotUploads: 4 },+ { command: ['export'], snapshotUploads: 0 },+ { command: ['resume'], snapshotUploads: 0 },+ { command: ['spec', 'apply'], snapshotUploads: 1 },+ { command: ['answer'], snapshotUploads: 1 },+ { command: ['status'], snapshotUploads: 3 },+ { command: ['export'], snapshotUploads: 0 },+ { command: ['add'], snapshotUploads: 0 },+ { command: ['export'], snapshotUploads: 0 },+];+const DECLINE_FLOW_CLI_CHILDREN = [+ ...FIXTURE_SETUP_CLI_CHILDREN,+ { command: ['add'], snapshotUploads: 0 },+ { command: ['relay', 'on'], snapshotUploads: 1 },+ { command: ['status'], snapshotUploads: 4 },+ { command: ['answer'], snapshotUploads: 1 },+ { command: ['answer'], snapshotUploads: 1 },+ { command: ['resume'], snapshotUploads: 0 },+];++/** Budget all actual CLI children in a flow, plus one Chrome launch and stated setup margin. */+function approvalFlowTimeoutMs(cliChildren) {+ const childrenBudgetMs = cliChildren.reduce((total, child) => total + cliChildDeadlineMs(child.snapshotUploads), 0);+ return CHROME_START_BUDGET_MS + childrenBudgetMs + CLI_SETUP_MARGIN_MS;+}/** Install the fixture's person session without exposing its cookie in browser diagnostics. */async function signIn(chrome, box) {@@ -31,26 +68,46 @@ async function pairedTransport(chrome, box, title) {/** Attach a transport handle for the existing test actions after either pairing or a reload. */async function installRequestTransport(chrome) {- await chrome.evaluate(`(async () => {+ const task = await chrome.startTask(`(async () => {const { createTransport } = await import('/relay/client.js');window.__personRequestTransport = await createTransport({ onUpdate: () => {} });return true;- })()`);+ })()`, 'initialize person request transport');+ await chrome.pollTask(task, 25000, 'initialize person request transport');}/** Send one exact person intent through the browser transport rather than constructing a move. */async function sendPersonIntent(chrome, board, move) {const path = '/api/v1/boards/' + board + '/moves';- return chrome.evaluate('window.__personRequestTransport.request('- + JSON.stringify(path) + ',' + JSON.stringify(move) + ')');+ const task = await chrome.startTask('window.__personRequestTransport.request('+ + JSON.stringify(path) + ',' + JSON.stringify(move) + ')', 'send person request');+ return chrome.pollTask(task, 25000, 'send person request');}/** Poll the browser's authenticated, device-decrypted presentation for one durable receipt. */async function waitForRequest(chrome, board, id, status, requireCoordinatorRequest = false) {const path = '/api/v1/boards/' + board + '/state';const predicate = `(() => { const row = documentValue.state?.personRequests?.find(entry => entry.id === ${JSON.stringify(id)}); return row?.status === ${JSON.stringify(status)}${requireCoordinatorRequest ? ' && Number.isSafeInteger(row.coordinatorRequest)' : ''}; })()`;- await chrome.waitFor(`(async () => { try { const documentValue = await window.__personRequestTransport.request(${JSON.stringify(path)}); return ${predicate}; } catch { return false; } })()`);- return chrome.evaluate('window.__personRequestTransport.request(' + JSON.stringify(path) + ')');+ // Native processing can take 15 seconds; allow ten seconds for relay transport and polling.+ const task = await chrome.startTask(`(async () => {+ const deadline = Date.now() + 25000;+ while (Date.now() < deadline) {+ try {+ const documentValue = await window.__personRequestTransport.request(${JSON.stringify(path)});+ if (${predicate}) return documentValue;+ } catch { /* The native checkpoint may still be arriving. */ }+ await new Promise(resolve => setTimeout(resolve, 50));+ }+ throw new Error('The native person request did not reach the expected status.');+ })()`, 'wait for person request status');+ return chrome.pollTask(task, 30000, 'wait for person request status');+}++/** Read final request state by starting the fetch in the page and polling its completion. */+async function finalState(chrome, board) {+ const task = await chrome.startTask('window.__personRequestTransport.request('+ + JSON.stringify('/api/v1/boards/' + board + '/state') + ')', 'read final person request state');+ return chrome.pollTask(task, 25000, 'read final person request state');}/** Add a private pending spec row without changing shared or submitted repository files. */@@ -62,7 +119,7 @@ function addPendingSpecRow(box, id) {return { path, original };}-test('real paired Chrome transports one person shout, and native status makes one authored shout [H12,H16]', {+test('real paired Chrome transports a person shout while its native snapshot is 8 seconds late [H12,H16]', {skip: !findChromeExecutable() && 'Chrome is not installed',}, async t => {const box = await relayClientFixture(t);@@ -100,7 +157,16 @@ test('real paired Chrome transports one person shout, and native status makes on'the device-local request id survives a page reload without storing its text');await installRequestTransport(chrome);- assert.equal((await box.cli('status')).code, 0, 'the next native status receives and executes the queued intent');+ const delayedBefore = box.snapshotWriteDelays().length;+ box.delaySnapshotWrites(8000);+ const native = box.cliWithSnapshotUploads(3, 'status').then(result => ({ result }), error => ({ error }));+ const status = await native;+ box.delaySnapshotWrites(0);+ assert.equal(status.error, undefined, 'the next native status receives and executes the queued intent');+ assert.equal(status.result.code, 0, 'the next native status reports success');+ const delays = box.snapshotWriteDelays().slice(delayedBefore);+ assert.equal(delays.length, 3, 'this three-upload status flow uploads exactly three snapshots');+ assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds');const latest = await waitForRequest(chrome, link.board, receipt.result.request.id, 'done');assert.equal(await chrome.evaluate("document.querySelector('#relay-notice').textContent"), '','the completed local request no longer appears as waiting');@@ -112,8 +178,9 @@ test('real paired Chrome transports one person shout, and native status makes ontest('real paired Chrome approval remains pending until coordinator applies and answers; invalid add keeps its CLI refusal [H12,H16,B26]', {skip: !findChromeExecutable() && 'Chrome is not installed',+ timeout: approvalFlowTimeoutMs(APPROVAL_FLOW_CLI_CHILDREN),}, async t => {- const box = await relayClientFixture(t);+ const box = await relayClientFixture(t, { cliChildren: APPROVAL_FLOW_CLI_CHILDREN });const title = 'PERSON_REQUEST_APPROVAL_FIXTURE';const id = 'G98';const row = addPendingSpecRow(box, id);@@ -127,7 +194,15 @@ test('real paired Chrome approval remains pending until coordinator applies andconst approval = await sendPersonIntent(chrome, link.board, { verb: 'spec-approve', args: { ids: id } });assert.equal(approval.result.request.status, 'waiting');assert.deepEqual(approval.result.request.move, { verb: 'spec-approve', args: { ids: id } });- assert.equal((await box.cli('status')).code, 0);+ const delayedBefore = box.snapshotWriteDelays().length;+ box.delaySnapshotWrites(8000);+ const native = await box.cliWithSnapshotUploads(4, 'status').then(result => ({ result }), error => ({ error }));+ box.delaySnapshotWrites(0);+ assert.equal(native.error, undefined, 'the four-upload approval status fits its derived deadline');+ assert.equal(native.result.code, 0);+ const delays = box.snapshotWriteDelays().slice(delayedBefore);+ assert.equal(delays.length, 4, 'the approval status flow uploads exactly four snapshots');+ assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every approval snapshot by 8 seconds');const pendingState = await waitForRequest(chrome, link.board, approval.result.request.id, 'waiting', true);assert.equal(readFileSync(row.path, 'utf8'), before, 'the received approval records a row decision but does not edit SPEC.md');const decisionEvents = (await box.cli('export')).document.tables.event.filter(event => event.event_kind === 'row_decision' && event.event_by === 'person');@@ -162,6 +237,7 @@ test('real paired Chrome approval remains pending until coordinator applies andconst local = (await box.cli('export')).document;assert.equal(local.tables.item.some(item => item.item_title === 'PERSON_REQUEST_INVALID_SPEC'), false);assert.equal(local.tables.event.some(event => event.event_kind === 'row_decision' && JSON.parse(event.event_detail).record.id === 'G999'), false);+ box.assertCliChildrenComplete();});test('an agent-sealed row approval is refused before any row receipt or spec edit [H12,H16,B26]', async t => {@@ -205,8 +281,9 @@ test('an agent-sealed row approval is refused before any row receipt or spec editest('coordinator decline resolves a paired approval request with a reason and leaves repo files unchanged [H12,H16,B26]', {skip: !findChromeExecutable() && 'Chrome is not installed',+ timeout: approvalFlowTimeoutMs(DECLINE_FLOW_CLI_CHILDREN),}, async t => {- const box = await relayClientFixture(t);+ const box = await relayClientFixture(t, { cliChildren: DECLINE_FLOW_CLI_CHILDREN });const row = addPendingSpecRow(box, 'G96');const before = readFileSync(row.path, 'utf8');const title = 'PERSON_REQUEST_DECLINE_FIXTURE';@@ -216,9 +293,16 @@ test('coordinator decline resolves a paired approval request with a reason and lt.after(() => chrome.close());const link = await pairedTransport(chrome, box, title);const queued = await sendPersonIntent(chrome, link.board, { verb: 'spec-approve', args: { ids: 'G96' } });- assert.equal((await box.cli('status')).code, 0);- const statePath = '/api/v1/boards/' + link.board + '/state';- const pending = (await chrome.evaluate('window.__personRequestTransport.request(' + JSON.stringify(statePath) + ')')).state.personRequests.find(record => record.id === queued.result.request.id);+ const delayedBefore = box.snapshotWriteDelays().length;+ box.delaySnapshotWrites(8000);+ const native = await box.cliWithSnapshotUploads(4, 'status').then(result => ({ result }), error => ({ error }));+ box.delaySnapshotWrites(0);+ assert.equal(native.error, undefined, 'the four-upload decline status fits its derived deadline');+ assert.equal(native.result.code, 0);+ const delays = box.snapshotWriteDelays().slice(delayedBefore);+ assert.equal(delays.length, 4, 'the decline status flow uploads exactly four snapshots');+ assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every decline snapshot by 8 seconds');+ const pending = (await finalState(chrome, link.board)).state.personRequests.find(record => record.id === queued.result.request.id);assert.equal(pending.status, 'waiting');assert.ok(Number.isSafeInteger(pending.coordinatorRequest));const missingReason = await box.cli('answer', String(pending.coordinatorRequest), 'declined');@@ -226,9 +310,10 @@ test('coordinator decline resolves a paired approval request with a reason and lassert.equal(missingReason.document.error.code, 'REQUEST_OUTCOME');const reason = 'Waiting for a revised requirement';assert.equal((await box.cli('answer', String(pending.coordinatorRequest), 'declined ' + reason)).code, 0);- const completed = (await chrome.evaluate('window.__personRequestTransport.request(' + JSON.stringify(statePath) + ')')).state.personRequests.find(record => record.id === queued.result.request.id);+ const completed = (await finalState(chrome, link.board)).state.personRequests.find(record => record.id === queued.result.request.id);assert.equal(completed.status, 'refused');assert.deepEqual(completed.error, { code: 'REQUEST_DECLINED', message: reason, next: 'Read the coordinator reason and send a revised request from the view.' });assert.equal(readFileSync(row.path, 'utf8'), before, 'declining the repository request does not edit any row');assert.deepEqual((await box.cli('resume')).document.requests, [], 'the declined request leaves the open coordinator queue');+ box.assertCliChildrenComplete();});