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
test(relay): prove timeout checkpoint coverage [H16,C7]
Corey Olsona394c0626e5d
diff --git a/test/chrome-fixture.js b/test/chrome-fixture.jsindex 84fe4e63..c3e0cdc7 100644--- a/test/chrome-fixture.js+++ b/test/chrome-fixture.js@@ -125,6 +125,7 @@ export async function startChrome({'--use-mock-keychain', '--password-store=basic', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'];let launched;let socket;+ let loopDelay;let id = 0;const pending = new Map();try {@@ -133,7 +134,7 @@ export async function startChrome({const port = await readDevToolsPort(profile, launched, deadline);const target = await createPageTarget(port, deadline);socket = await connectDevTools(target.webSocketDebuggerUrl, deadline);- const loopDelay = monitorEventLoopDelay({ resolution: 10 });+ loopDelay = monitorEventLoopDelay({ resolution: 10 });loopDelay.enable();const relayRequests = new Set();const send = createSender(socket, pending, () => ++id, commandTimeoutMs, loopDelay, relayRequests);@@ -148,8 +149,12 @@ export async function startChrome({async function waitFor(expression, timeoutMs = commandTimeoutMs, label = 'wait for page condition') {const waitDeadline = Date.now() + timeoutMs;while (Date.now() < waitDeadline) {- if (await evaluate(expression, label)) return;- await pause(50);+ try {+ if (await evaluate(expression, label, waitDeadline - Date.now())) return;+ } catch (error) {+ if (error.code !== 'CDP_TIMEOUT' || Date.now() < waitDeadline) throw error;+ }+ await pause(Math.max(0, Math.min(50, waitDeadline - Date.now())));}throw new Error(`Browser condition "${label}" did not arrive within ${timeoutMs}ms.`);}@@ -177,8 +182,9 @@ export async function startChrome({/** Poll asynchronous page work while each DevTools command stays short. */async function pollTask(taskId, timeoutMs = taskTimeoutMs, label = 'poll page operation') {const key = JSON.stringify(taskId);+ const deadline = Date.now() + timeoutMs;await waitFor(`window[${key}] !== null && window[${key}] !== undefined`, timeoutMs, label);- const result = await evaluate(`window[${key}]`, label + ' result');+ const result = await evaluate(`window[${key}]`, label + ' result', deadline - Date.now());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;@@ -196,10 +202,10 @@ export async function startChrome({await launched.close();if (ownedProfile) rmSync(profile, { recursive: true, force: true });}- 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');+ await send('Network.enable', {}, 'enable network diagnostics', deadline - Date.now());+ await send('Page.enable', {}, 'enable page diagnostics', deadline - Date.now());+ await send('Runtime.enable', {}, 'enable runtime diagnostics', deadline - Date.now());+ await send('Page.navigate', { url }, 'open initial page', deadline - Date.now());const launchDurationMs = launched.launchDurationMs;process.stderr.write(`Chrome ready in ${launchDurationMs}ms (${startupTimeoutMs}ms DevTools budget)\n`);return {@@ -216,6 +222,7 @@ export async function startChrome({close,};} catch (error) {+ loopDelay?.disable();socket?.close();rejectPending(pending, 'Isolated Chrome stopped before startup completed.');const launchDurationMs = launched?.launchDurationMs ?? 0;@@ -293,7 +300,7 @@ function createSender(socket, pending, nextId, timeoutMs, loopDelay, relayRequeselse waiter.resolve(message.result);}socket.addEventListener('message', onMessage);- return (method, params = {}, label = method) => new Promise((resolveResult, rejectResult) => {+ return (method, params = {}, label = method, remainingMs = timeoutMs) => new Promise((resolveResult, rejectResult) => {const requestId = nextId();const startedAt = Date.now();const maxDelayAtSend = loopDelay.max;@@ -303,8 +310,10 @@ function createSender(socket, pending, nextId, timeoutMs, loopDelay, relayReques};const timer = setTimeout(() => {pending.delete(requestId);- rejectResult(new Error(timeoutMessage()));- }, timeoutMs);+ const error = new Error(timeoutMessage());+ error.code = 'CDP_TIMEOUT';+ rejectResult(error);+ }, Math.max(1, Math.min(timeoutMs, remainingMs)));pending.set(requestId, { resolve: resolveResult, reject: rejectResult, timer, method, label });try { socket.send(JSON.stringify({ id: requestId, method, params })); }catch {@@ -317,8 +326,8 @@ function createSender(socket, pending, nextId, timeoutMs, loopDelay, relayReques/** Evaluate a page expression by value and retain bounded diagnostics for page exceptions. */function createEvaluator(send) {- return async (expression, label = 'evaluate page expression') => {- const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, label);+ return async (expression, label = 'evaluate page expression', remainingMs) => {+ const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, label, remainingMs);if (result.exceptionDetails) {const details = result.exceptionDetails;const exception = details.exception;diff --git a/test/chrome-fixture.test.js b/test/chrome-fixture.test.jsindex e6f8ddc8..69e09152 100644--- a/test/chrome-fixture.test.js+++ b/test/chrome-fixture.test.js@@ -4,7 +4,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, wrimport { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';-import { launchChromeProcess, startChrome } from './chrome-fixture.js';+import { findChromeExecutable, launchChromeProcess, startChrome } from './chrome-fixture.js';/** Pause between checks while waiting for a fixture helper's readiness marker. */function pause(ms) {@@ -121,8 +121,9 @@ test('Chrome close releases inherited stderr after its owned process group exitsconst chrome = launchChromeProcess({ executable: process.execPath, args: ['-e', leader, holder, ready] });let holderPid;t.after(async () => {- if (holderPid) { try { process.kill(holderPid, 'SIGKILL'); } catch { /* The private stand-in already stopped. */ } }try { await chrome.close(); } catch { /* Retain the original close assertion on a broken implementation. */ }+ if (!holderPid && existsSync(ready)) holderPid = Number(readFileSync(ready, 'utf8'));+ if (holderPid) { try { process.kill(holderPid, 'SIGKILL'); } catch { /* The private stand-in already stopped. */ } }rmSync(directory, { recursive: true, force: true });});await waitForFile(ready);@@ -170,3 +171,16 @@ test('a failed browser evaluation names what the page threw [C7]', async () => {await chrome.close();}});++/** Prove a page condition cannot spend the much longer general command allowance. */+test('a stalled condition uses its remaining operation budget [C7]', {+ skip: !findChromeExecutable() && 'Chrome is not installed',+}, async t => {+ const chrome = await startChrome();+ t.after(() => chrome.close());+ const started = Date.now();+ await assert.rejects(chrome.waitFor('new Promise(() => {})', 250, 'bounded condition'),+ /Browser condition "bounded condition" did not arrive within 250ms/u);+ assert.ok(Date.now() - started < 10_000, 'the 250ms operation never consumes the 15000ms command allowance');+ assert.equal(await chrome.evaluate('1 + 1'), 2, 'timing out one command leaves the real DevTools connection usable');+});diff --git a/test/relay-browser-fixture.test.js b/test/relay-browser-fixture.test.jsindex cb919888..22cae731 100644--- a/test/relay-browser-fixture.test.js+++ b/test/relay-browser-fixture.test.js@@ -36,20 +36,33 @@ test('paired Chrome excludes idle event streams and reports only held state requskip: !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({ commandTimeoutMs: 15000 });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) + ')', relayWorkBudgetMs());- await chrome.waitForRelayIdle();+ // A static same-origin document has no cockpit refresh timer to start ordinary reads mid-probe.+ await chrome.navigate(box.origin + '/view.css');+ await chrome.waitFor('document.readyState === "complete"');+ const stateResponse = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', {+ headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) },+ });+ assert.equal(stateResponse.status, 200);+ const snapshot = (await stateResponse.json()).state;+ const streamPath = '/api/v1/boards/' + link.board + '/events?after=' + snapshot.sequence;+ const streamTask = await chrome.startTask(`fetch(${JSON.stringify(streamPath)}, {+ credentials: 'same-origin', headers: { 'x-pullboard-engine': ${ENGINE_VERSION}, accept: 'text/event-stream' }+ }).then(response => { window.__diagnosticStream = response.body.getReader();+ return { status: response.status, type: response.headers.get('content-type') }; })`, 'authenticated idle event stream');+ const stream = await chrome.pollTask(streamTask);+ assert.equal(stream.status, 200);+ assert.match(stream.type, /text\/event-stream/);+ assert.ok(box.calls.some(call => call.path === streamPath && call.accept === 'text/event-stream'),+ 'the real relay accepted the idle event stream before the stalled probe');+ await assert.doesNotReject(chrome.waitForRelayIdle(), 'a real idle event stream is excluded from ordinary pending requests');await stalledCommand(chrome, 'idle paired stream probe', false);const before = box.stateReadStarted();diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 12de7f37..c3845414 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -14,12 +14,9 @@ import { createRelayAuth } from '../relay/auth.js';import { createRelayHandler } from '../relay/service.js';import { createGitHubClient } from '../relay/github.js';import { githubFixture } from './relay-fixture.js';-import { RELAY_REQUEST_BOUND_MS, NATIVE_COMMAND_BOUND_MS, FIXTURE_SCHEDULING_MARGIN_MS, MAX_SNAPSHOT_ATTEMPTS } from './relay-budget.js';+import { relayWorkBudgetMs, MAX_SNAPSHOT_ATTEMPTS } from './relay-budget.js';const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');-const CLI_PRODUCT_DEADLINE_MS = NATIVE_COMMAND_BOUND_MS;-const SNAPSHOT_UPLOAD_BOUND_MS = RELAY_REQUEST_BOUND_MS;-const CLI_DEADLINE_MARGIN_MS = FIXTURE_SCHEDULING_MARGIN_MS;const MAX_OBSERVED_SNAPSHOT_UPLOADS = MAX_SNAPSHOT_ATTEMPTS;const DEFAULT_SNAPSHOT_UPLOADS = 3;@@ -27,25 +24,40 @@ const DEFAULT_SNAPSHOT_UPLOADS = 3;export function cliChildDeadlineMs(observedUploads) {assert.ok(Number.isSafeInteger(observedUploads) && observedUploads >= 0 && observedUploads <= MAX_OBSERVED_SNAPSHOT_UPLOADS,'observed snapshot upload count is within the finite fixture bound');- return Math.max(CLI_PRODUCT_DEADLINE_MS, observedUploads * SNAPSHOT_UPLOAD_BOUND_MS) + CLI_DEADLINE_MARGIN_MS;+ return relayWorkBudgetMs(observedUploads);}-/** Count durable checkpoints, permitting only byte-identical retries of aborted PUTs. */+/** Count exact checkpoints; a newer acknowledged snapshot may cover a superseded timeout. */export function assertSnapshotCheckpoints(trace, expected) {- const checkpoints = new Map();- for (const write of trace) {- assert.ok(Number.isSafeInteger(write.sequence) && /^[0-9a-f]{64}$/u.test(write.ciphertext ?? ''), 'checkpoint metadata is complete');- const previous = checkpoints.get(write.sequence);- if (previous) {- assert.equal(write.ciphertext, previous.ciphertext, 'a retried sequence preserves its exact ciphertext');- assert.equal(previous.abort?.name, 'TimeoutError', 'only a timed-out PUT can add a transport attempt');- assert.ok(write.callers.some(caller => caller.includes('async [email protected]:')), 'syncRelay retries the persisted checkpoint');+ try {+ const checkpoints = new Map();+ let priorSequence = -1;+ for (const write of trace) {+ assert.ok(Number.isSafeInteger(write.sequence) && /^[0-9a-f]{64}$/u.test(write.ciphertext ?? ''), 'checkpoint metadata is complete');+ assert.ok(write.sequence >= priorSequence, 'checkpoint attempts never regress the covered sequence');+ priorSequence = write.sequence;+ const previous = checkpoints.get(write.sequence);+ if (previous) {+ assert.equal(write.ciphertext, previous.ciphertext, 'a retried sequence preserves its exact ciphertext');+ assert.equal(previous.abort?.name, 'TimeoutError', 'only a timed-out PUT can add a transport attempt');+ assert.ok(write.callers.some(caller => caller.includes('async [email protected]:')), 'syncRelay retries the persisted checkpoint');+ }+ checkpoints.set(write.sequence, write);}- checkpoints.set(write.sequence, write);+ assert.equal(checkpoints.size, expected, 'the flow publishes its exact number of distinct checkpoints');+ if (expected === 0) return checkpoints.size;+ const latest = trace.at(-1);+ assert.equal(latest?.status, 200, 'the latest checkpoint receives an acknowledgement');+ for (const write of checkpoints.values()) {+ if (write.status === 200) continue;+ assert.equal(write.abort?.name, 'TimeoutError', 'only a timed-out checkpoint can be superseded');+ assert.ok(latest.sequence > write.sequence, 'the acknowledged checkpoint covers the superseded sequence');+ }+ return checkpoints.size;+ } catch (error) {+ error.message += '; sanitized checkpoint fetches: ' + JSON.stringify(trace);+ throw error;}- assert.equal(checkpoints.size, expected, 'the flow publishes its exact number of distinct checkpoints');- assert.ok([...checkpoints.values()].every(write => write.status === 200), 'every checkpoint eventually receives an acknowledgement');- return checkpoints.size;}/** Capture a real child result without exposing its private output in failure diagnostics. */diff --git a/test/relay-person-actions.test.js b/test/relay-person-actions.test.jsindex db2a1db5..24665d60 100644--- a/test/relay-person-actions.test.js+++ b/test/relay-person-actions.test.js@@ -46,7 +46,7 @@ async function personAction(chrome, board, move) {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)})`;- // Product checkpoint work is bounded at 15 seconds; ten seconds remain for scheduling and polling.+ // Share the native command, bounded snapshot attempts and scheduling allowance.const task = await chrome.startTask(`(async () => {const deadline = Date.now() + ${relayWorkBudgetMs()};while (Date.now() < deadline) {@@ -172,7 +172,7 @@ test('a person action completes with late native snapshots after 8 seconds [H12,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.error, undefined, 'the real native CLI completes within its upload-derived fixture budget');assert.equal(status.result.code, 0, 'the real native CLI reports success');const delays = box.snapshotWriteDelays().slice(delayedBefore);assertSnapshotCheckpoints(status.result.snapshotTrace, 3);diff --git a/test/relay-person-requests.test.js b/test/relay-person-requests.test.jsindex fcdf4823..bf9a7edf 100644--- a/test/relay-person-requests.test.js+++ b/test/relay-person-requests.test.js@@ -1,10 +1,10 @@/** A paired browser seals person intent; only native Pullboard executes it [H12,H16,B26]. */import assert from 'node:assert/strict';-import { randomUUID } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';import { readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { test } from 'node:test';-import { decodeBoardKey, seal } from '../src/seal.js';+import { decodeBoardKey, seal, unseal } from '../src/seal.js';import { ENGINE_VERSION } from '../src/machine.js';import { findChromeExecutable, relayWorkBudgetMs, startChrome } from './relay-browser-fixture.js';import { assertSnapshotCheckpoints, cliChildDeadlineMs, relayClientFixture } from './relay-client-fixture.js';@@ -55,7 +55,7 @@ async function signIn(chrome, box) {assert.equal(result.success, true, 'the real person session is installed in the isolated browser');}-/** Pair a real browser, then create the same transport module used by the relay cockpit. */+/** Pair a real browser and retain the transport already owned by its cockpit. */async function pairedTransport(chrome, box, title) {const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));const encoded = readFileSync(box.keyFile, 'utf8').trim();@@ -344,7 +344,7 @@ test('coordinator decline resolves a paired approval request with a reason and lbox.assertCliChildrenComplete();});-+/** Exercise the real product abort and require the persisted checkpoint to keep its sealed bytes. */test('a timed-out checkpoint PUT retries identical ciphertext through the native status flow [H16,C7]', async t => {const box = await relayClientFixture(t);await box.link();@@ -381,3 +381,54 @@ test('a timed-out checkpoint PUT retries identical ciphertext through the nativeassert.equal(exported.tables.shout.filter(row => row.shout_text === 'RETRY_CHECKPOINT_CONTROL').length, 1,'the identical checkpoint retry does not execute the person intent twice');});++/** Prove that a newer committed snapshot covers a timed-out earlier projection. */+test('a newer acknowledged checkpoint covers an earlier timed-out PUT [H16,C7]', async t => {+ const box = await relayClientFixture(t);+ await box.link();+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());+ const intent = { version: 1, type: 'person-request', id: randomUUID(),+ move: { verb: 'shout', args: { to: 'coordinator', text: 'COVERED_CHECKPOINT_CONTROL' } } };+ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(intent)), {+ boardId: link.board, kind: 'request', sequence: 1,+ })).toString('base64url');+ const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/requests', {+ method: 'POST', headers: { authorization: 'Bearer ' + link.token,+ 'x-pullboard-engine': String(ENGINE_VERSION), 'content-type': 'application/json' },+ body: JSON.stringify({ sequence: 1, sealed }),+ });+ assert.equal(response.status, 200);+ const before = box.snapshotWriteRecords().length;+ // The initial checkpoint times out before newer committed receipt checkpoints replace it.+ box.delaySnapshotWriteOnce(1, 10100);+ const result = await box.cliWithSnapshotTrace(3, 'status');+ assert.equal(result.code, 0);+ const trace = result.snapshotTrace;+ t.diagnostic('controlled superseded checkpoint: ' + JSON.stringify({ fetches: trace,+ relayReceives: box.snapshotWriteRecords().slice(before) }));+ assertSnapshotCheckpoints(trace, 3);+ assert.equal(trace.length, 3, 'a newer committed checkpoint supersedes the timed-out projection');+ assert.equal(trace[0].abort?.name, 'TimeoutError');+ assert.ok(trace[0].elapsedMs >= 9900, 'the actual ten-second product request bound expired');+ assert.ok(trace[1].sequence > trace[0].sequence);+ assert.ok(trace[2].sequence > trace[1].sequence);+ assert.equal(trace[2].status, 200);+ assert.equal(result.snapshotDeadlineMs, cliChildDeadlineMs(trace.length));+ const stateResponse = await fetch(box.origin + '/api/v1/boards/' + link.board + '/state', {+ headers: { authorization: 'Bearer ' + link.token, 'x-pullboard-engine': String(ENGINE_VERSION) },+ });+ assert.equal(stateResponse.status, 200);+ const saved = (await stateResponse.json()).state;+ assert.equal(saved.sequence, trace.at(-1).sequence, 'the relay retains the newest acknowledged checkpoint');+ assert.equal(createHash('sha256').update(saved.sealed).digest('hex'), trace.at(-1).ciphertext);+ const restored = JSON.parse(new TextDecoder().decode(await unseal(key, Buffer.from(saved.sealed, 'base64url'), {+ boardId: link.board, kind: 'snapshot', sequence: saved.sequence,+ })));+ const exported = (await box.cli('export')).document;+ assert.equal(Number(exported.tables.board_meta.find(row => row.meta_key === 'relay_applied_sequence').meta_value), saved.sequence);+ assert.equal(Number(restored.tables.board_meta.find(row => row.meta_key === 'relay_applied_sequence').meta_value), saved.sequence);+ assert.equal(restored.tables.shout.filter(row => row.shout_text === 'COVERED_CHECKPOINT_CONTROL').length, 1);+ assert.equal(exported.tables.shout.filter(row => row.shout_text === 'COVERED_CHECKPOINT_CONTROL').length, 1,+ 'the covering checkpoint does not execute the person intent twice');+});