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): on-demand relay study measurements [H5,H17]
Corey Olsonf266e1fa4a22
diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 2446b5cb..92512e7f 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -243,6 +243,7 @@ globalThis.fetch = function tracedFetch(input, init) {let stateReadStarted = 0;let refuseSnapshotWrites = false;let stallApi = false;+ let studyApiFault = null;let holdPublishes = false;const heldPublishes = [];let holdProbes = false;@@ -393,6 +394,16 @@ globalThis.fetch = function tracedFetch(input, init) {recordResponse({ method: req.method, path: req.url, request: Buffer.concat(requestChunks), response: Buffer.concat(responseChunks) });});calls.push(call);+ if (studyApiFault && (req.url ?? '').startsWith('/api/')) {+ const fault = studyApiFault;+ if (fault.delayMs) await new Promise(resolve => setTimeout(resolve, fault.delayMs));+ if (fault.status) {+ request.resume();+ res.writeHead(fault.status, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ version: 1, error: { code: fault.code, message: 'private study fault' } }));+ return;+ }+ }if (stallApi && (req.url ?? '').startsWith('/api/')) { request.resume(); await new Promise(() => {}); }// A held API2 checkpoint publish waits until released, so a test can act while an upload is in flight (#1014).if (holdPublishes && req.method === 'POST' && /^\/api\/v2\/boards\/[0-9a-f]{32}\/uploads\/[^/]+\/publish$/u.test(req.url ?? '')) {@@ -808,6 +819,13 @@ globalThis.fetch = function tracedFetch(input, init) {refuseSnapshotWrites(value) { refuseSnapshotWrites = value; },/** Leave every board API request unanswered until its client times out, like an overloaded relay. */stallApi(value = true) { stallApi = value; },+ /** Apply a private study's real HTTP fault to both snapshot protocol versions. */+ studyApiFault(value = null) {+ assert.ok(value === null || Number.isSafeInteger(value.delayMs) && value.delayMs >= 0 && value.delayMs <= 5000+ && (value.status === null || [409, 503].includes(value.status))+ && (value.status === null || ['ENGINE_VERSION', 'RELAY_UNAVAILABLE'].includes(value.code)));+ studyApiFault = value;+ },/** Hold every API2 checkpoint publish until called with false, which releases the held ones. */holdPublishes(value = true) {holdPublishes = value;diff --git a/test/relay-study-delta.test.js b/test/relay-study-delta.test.jsnew file mode 100644index 00000000..f1c20442--- /dev/null+++ b/test/relay-study-delta.test.js@@ -0,0 +1,61 @@+/** Measured change-based sync against whole checkpoints, for the private relay study [H5,H17]. */+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { performance } from 'node:perf_hooks';+import { test } from 'node:test';+import * as store from '../src/board.js';+import { ENGINE_VERSION } from '../src/machine.js';+import { relayClientFixture } from './relay-client-fixture.js';+import { readRelay } from './relay-study-fixture.js';++const STUDY = process.env.PULLBOARD_RELAY_STUDY === '1';++/** Sum the request or response bytes of transit rows that match one route. */+function bytes(rows, pick, side) {+ return rows.filter(pick).reduce((sum, row) => sum + row[side].byteLength, 0);+}++test('relay study measures one sealed move against its checkpoint at 10k and 50k events [H5,H17]', {+ timeout: 300_000, skip: !STUDY && 'a measurement: set PULLBOARD_RELAY_STUDY=1 to run it',+}, async t => {+ const box = await relayClientFixture(t);+ await box.link();+ const board = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ t.after(() => store.closeBoard(board));+ for (const target of [10_000, 50_000]) {+ let events = board.db.prepare('SELECT COUNT(*) AS n FROM event').get().n;+ store.atomic(board, () => {+ while (events < target) {+ const text = 'Study event ' + events + ' ' + createHash('sha256').update(String(events)).digest('hex');+ store.shout(board, { from: 'coordinator', to: 'all', text, lanes: [box.lane] });+ events++;+ }+ });+ assert.equal((await box.cli('status')).code, 0, 'the seeded scale is published before the probe move');+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const before = box.transit.length;+ const started = performance.now();+ const move = await box.cli('shout', 'all', 'delta probe at ' + target);+ const moveMs = performance.now() - started;+ assert.equal(move.code, 0, 'the probe move is recorded through the linked CLI');+ const rows = box.transit.slice(before);+ const isMove = row => row.method === 'POST' && /\/api\/v1\/boards\/[0-9a-f]{32}\/moves$/u.test(row.path);+ const isUpload = row => ['PUT', 'POST'].includes(row.method) && row.path.startsWith('/api/v2/');+ const headers = { authorization: 'Bearer ' + state.token, 'x-pullboard-engine': String(ENGINE_VERSION) };+ const deltaStarted = performance.now();+ const delta = await fetch(box.origin + '/api/v1/boards/' + state.board + '/events?after=' + state.sequence, { headers });+ const deltaBody = Buffer.from(await delta.arrayBuffer());+ const deltaReadMs = performance.now() - deltaStarted;+ const full = await readRelay(box);+ t.diagnostic(JSON.stringify({ phase: 'delta-versus-checkpoint', events: target + 1, node: process.versions.node,+ moveMs, movePosts: rows.filter(isMove).length, moveRequestBytes: bytes(rows, isMove, 'request'),+ checkpointRequests: rows.filter(isUpload).length, checkpointRequestBytes: bytes(rows, isUpload, 'request'),+ allRequestBytes: bytes(rows, () => true, 'request'), allResponseBytes: bytes(rows, () => true, 'response'),+ deltaReadStatus: delta.status, deltaReadBytes: deltaBody.byteLength, deltaReadMs,+ fullReadRequests: full.requests, fullReadBytes: full.receivedBytes, fullReadMs: full.readMs,+ scope: 'Private loopback relay, foreground checkpoint (PULLBOARD_RELAY_CHECKPOINT_BACKGROUND=0), one shout move.' }));+ assert.equal(delta.status, 200, 'the relay serves the sealed moves after the reader cursor');+ }+});diff --git a/test/relay-study-failure.test.js b/test/relay-study-failure.test.jsnew file mode 100644index 00000000..c3fd44df--- /dev/null+++ b/test/relay-study-failure.test.js@@ -0,0 +1,49 @@+/** Measured real HTTP fault behavior for the private relay study [H5,H17]. */+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { performance } from 'node:perf_hooks';+import { test } from 'node:test';+import * as store from '../src/board.js';+import { relayClientFixture } from './relay-client-fixture.js';++const SKIP = process.env.PULLBOARD_RELAY_STUDY !== '1' && 'a measurement: set PULLBOARD_RELAY_STUDY=1 to run it';++test('relay study measures native reads and local moves across private transport failures [H5,H17]', { timeout: 300_000, skip: SKIP }, async t => {+ for (const fault of ['down', 'slow-5s', '5xx', 'stale-engine']) {+ const box = await relayClientFixture(t);+ await box.link();+ if (fault === 'down') await box.stopRelay();+ else box.studyApiFault({ delayMs: fault === 'slow-5s' ? 5000 : 0,+ status: fault === '5xx' ? 503 : fault === 'stale-engine' ? 409 : null,+ code: fault === 'stale-engine' ? 'ENGINE_VERSION' : 'RELAY_UNAVAILABLE' });+ const before = box.calls.length;+ const started = performance.now();+ const status = await box.cli('status');+ const statusMs = performance.now() - started;+ const writeStarted = performance.now();+ const title = 'Study move during ' + fault;+ let move, censored = false;+ try { move = await box.cli('add', box.lane, title); }+ catch (error) {+ if (!/upload-derived child deadline 55000ms exceeded/u.test(error.message)) throw error;+ censored = true;+ move = { code: null, document: null };+ }+ const moveMs = performance.now() - writeStarted;+ const board = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ let recorded;+ try { recorded = store.listItems(board, { all: true }).filter(item => item.item_title === title).length; }+ finally { store.closeBoard(board); }+ const saved = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ t.diagnostic(JSON.stringify({ phase: 'native-transport-failure', fault, statusMs, statusExit: status.code,+ statusErrorCode: status.document?.error?.code ?? null, moveMs, moveExit: move.code,+ moveErrorCode: move.document?.error?.code ?? null, censoredAtExistingFixtureDeadline: censored,+ requestedMoveRecorded: recorded,+ queuedMoves: saved.outbox?.moves?.length ?? 0, pending: Boolean(saved.pending),+ requests: box.calls.slice(before).map(call => ({ method: call.method, path: call.path })),+ limitation: fault === 'stale-engine' ? 'Injected real HTTP409 ENGINE_VERSION response; current CLI binary itself remains current.'+ : 'Private real HTTP failure; this stage measures native CLI only, not browser behavior.' }));+ box.studyApiFault();+ if (fault === 'down') await box.restartRelay();+ }+});diff --git a/test/relay-study-fixture.js b/test/relay-study-fixture.jsnew file mode 100644index 00000000..b55a2dd6--- /dev/null+++ b/test/relay-study-fixture.js@@ -0,0 +1,57 @@+/** Shared authenticated readers for the measured private relay study [H5,H17]. */+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { performance } from 'node:perf_hooks';+import { ENGINE_VERSION } from '../src/machine.js';+import { decodeBoardKey } from '../src/seal.js';+import { openPagedSnapshot } from '../src/relay-page-layout.js';++/** Compare every JSON field, retaining paths but never printing board contents or credentials. */+export function differences(left, right, path = '$', found = []) {+ if (Object.is(left, right)) return found;+ if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object'+ || Array.isArray(left) !== Array.isArray(right)) {+ found.push(path);+ return found;+ }+ for (const name of new Set([...Object.keys(left), ...Object.keys(right)])) {+ const next = path + '[' + JSON.stringify(name) + ']';+ if (!Object.hasOwn(left, name) || !Object.hasOwn(right, name)) found.push(next);+ else differences(left[name], right[name], next, found);+ }+ return found;+}++/** Read the actual private API2 root and ciphertext pages through the production decoder. */+export async function readRelay(box) {+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const headers = { authorization: 'Bearer ' + state.token, 'x-pullboard-engine': String(ENGINE_VERSION) };+ let requests = 0, receivedBytes = 0;+ /** Count actual HTTP response bytes before decoding their JSON, without logging secrets. */+ async function request(path) {+ const response = await fetch(box.origin + path, { headers });+ const bytes = Buffer.from(await response.arrayBuffer());+ requests++; receivedBytes += bytes.byteLength;+ assert.equal(response.status, 200, 'the private relay accepted its authenticated read');+ return JSON.parse(bytes.toString('utf8'));+ }+ const started = performance.now();+ const response = await request('/api/v2/boards/' + state.board + '/state');+ const saved = response.state;+ assert.equal(response.apiVersion, 2);+ assert.equal(saved.apiVersion, 2, 'measure the current paged protocol');+ const page = await openPagedSnapshot(saved.root, {+ key: decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim()), boardId: state.board, sequence: saved.sequence,+ /** Follow only the server-pinned opaque page graph, exactly as the production reader does. */+ async get(id, parents) {+ const result = await request('/api/v2/boards/' + state.board + '/objects/' + id+ + '?pin=' + encodeURIComponent(saved.read.id) + '&via=' + parents.join(','));+ assert.equal(result.apiVersion, 2);+ assert.equal(result.page.id, id);+ return Buffer.from(result.page.sealed, 'base64url');+ },+ }, { maxEngine: ENGINE_VERSION });+ const document = await page.native();+ return { document, requests, receivedBytes, readMs: performance.now() - started };+}+diff --git a/test/relay-study-moves.test.js b/test/relay-study-moves.test.jsnew file mode 100644index 00000000..43325601--- /dev/null+++ b/test/relay-study-moves.test.js@@ -0,0 +1,144 @@+/** Exercise native move effects before comparing the actual relay's complete decoded projection [H5,H17]. */+import assert from 'node:assert/strict';+import { createHash, randomUUID } from 'node:crypto';+import { join } from 'node:path';+import { test } from 'node:test';+import * as store from '../src/board.js';+import * as milestones from '../src/milestones.js';+import { MOVE_OPERATIONS } from '../src/move-registry.js';+import { relaySnapshot } from '../src/relay-presentation.js';+import { relayClientFixture } from './relay-client-fixture.js';+import { differences, readRelay } from './relay-study-fixture.js';+import { submitFixture } from './board-submit-fixture.js';+import { syntheticFlakeObservation } from './flake-observation-fixture.js';++const SKIP = process.env.PULLBOARD_RELAY_STUDY !== '1' && 'a measurement: set PULLBOARD_RELAY_STUDY=1 to run it';++test('relay study compares each exercised move effect through the real API2 reader [H5,H17]', { timeout: 180_000, skip: SKIP }, async t => {+ const box = await relayClientFixture(t);+ await box.link();+ const board = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ t.after(() => store.closeBoard(board));+ const covered = new Set(), setupRefusals = [];+ t.after(() => t.diagnostic(JSON.stringify({ phase: 'move-effect-parity', node: process.versions.node,+ coveredMoves: [...covered], setupRefusals, uncoveredMoves: MOVE_OPERATIONS.filter(operation => !covered.has(operation)),+ limitation: 'Native board-state fixtures with actual API2 transport; synthetic submit is explicitly not a gate proof. Only successful event-producing calls counted.' })));+ /** Only successful native calls count as covered; a refused setup never supplies parity evidence. */+ async function exercise(operation, work) {+ const before = board.db.prepare('SELECT COALESCE(MAX(event_id),0) AS n FROM event').get().n;+ let result;+ try { result = work(); }+ catch (error) {+ if (!error.code) throw error;+ setupRefusals.push({ operation, code: error.code });+ return null;+ }+ if (board.db.prepare('SELECT COALESCE(MAX(event_id),0) AS n FROM event').get().n === before) {+ setupRefusals.push({ operation, code: 'NO_MUTATION' });+ return result;+ }+ const published = await box.cli('status');+ assert.equal(published.code, 0, 'the actual CLI publishes after ' + operation);+ const expected = relaySnapshot(box.root);+ const read = await readRelay(box);+ assert.deepEqual(differences(expected.presentation, read.document.presentation), [], operation + ' full presentation');+ assert.deepEqual(differences(expected.tables, read.document.tables), [], operation + ' native tables');+ covered.add(operation);+ return result;+ }+ const agent = await exercise('register', () => store.register(board, { lane: box.lane, path: join(box.root, 'study-worker'), parentDigest: 'a'.repeat(64) }));+ const reviewer = store.register(board, { lane: 'tests', path: join(box.root, 'study-reviewer'), parentDigest: 'b'.repeat(64) });+ const item = await exercise('addItem', () => store.addItem(board, { by: 'coordinator', lane: box.lane,+ title: 'Lifecycle study', criterion: 'A seeded lifecycle.', brief: 'Seeded brief.' }));+ await exercise('editItem', () => store.editItem(board, item, { agentId: 'coordinator', brief: 'Changed brief.', reason: 'study' }));+ await exercise('appendFact', () => store.appendFact(board, item, { agentId: 'coordinator', kind: 'measurement', text: 'Seeded fact.' }));+ const shout = await exercise('shout', () => store.shout(board, { from: agent, to: 'coordinator', text: 'Study question?', lanes: [box.lane], decision: true }));+ await exercise('passDecision', () => store.passDecision(board, shout, { agentId: 'coordinator', note: 'Study pass.', lanes: [box.lane] }));+ const answerable = store.shout(board, { from: agent, to: 'coordinator', text: 'Separate answerable question?', lanes: [box.lane], decision: true });+ await exercise('answerDecision', () => store.answerDecision(board, answerable, { agentId: 'coordinator', text: 'Study answer.', lanes: [box.lane] }));+ await exercise('holdItem', () => store.holdItem(board, item, { agentId: 'coordinator', reason: 'Study hold.' }));+ await exercise('releaseItemHold', () => store.releaseItemHold(board, item, { agentId: 'coordinator' }));+ await exercise('holdLane', () => store.holdLane(board, box.lane, { agentId: 'coordinator', reason: 'Study hold.' }));+ await exercise('releaseLane', () => store.releaseLane(board, box.lane, { agentId: 'coordinator' }));+ await exercise('declareJob', () => store.declareJob(board, { agentId: 'coordinator', name: 'study-job', every: '10m', owner: agent }));+ await exercise('recordJobRun', () => store.recordJobRun(board, { agentId: agent, name: 'study-job' }));+ await exercise('setLineSetting', () => store.setLineSetting(board, { agentId: 'coordinator', key: 'order', value: true, reason: 'Study projection.', window: { samples: 1 } }));+ await exercise('setBarReady', () => store.setBarReady(board, { agentId: 'coordinator', enabled: true }));+ await exercise('setBarReady', () => store.setBarReady(board, { agentId: 'coordinator', enabled: false }));+ await exercise('addMilestone', () => milestones.addMilestone(board, { agentId: 'coordinator', name: 'Study A', items: [item] }));+ const other = store.addItem(board, { by: 'coordinator', lane: box.lane, title: 'Second study item', criterion: 'Second seed.' });+ await exercise('editMilestoneItems', () => milestones.editMilestoneItems(board, 'Study A', { agentId: 'coordinator', add: [other] }));+ await exercise('orderMilestoneItems', () => milestones.orderMilestoneItems(board, 'Study A', { agentId: 'coordinator', items: [other, item] }));+ await exercise('editMilestone', () => milestones.editMilestone(board, 'Study A', { agentId: 'coordinator', note: 'Changed roadmap note.', target: '2026-12-01' }));+ milestones.addMilestone(board, { agentId: 'coordinator', name: 'Study B' });+ await exercise('moveMilestone', () => milestones.moveMilestone(board, 'Study B', { agentId: 'coordinator', before: 'Study A' }));+ await exercise('shipMilestone', () => milestones.shipMilestone(board, 'Study B', { agentId: 'coordinator', commit: 'a'.repeat(40) }));+ milestones.addMilestone(board, { agentId: 'coordinator', name: 'Study removable' });+ await exercise('removeMilestone', () => milestones.removeMilestone(board, 'Study removable', { agentId: 'coordinator' }));+ const claim = { agentId: agent, lane: box.lane, leaseMs: 3600000,+ freeze: () => ({ text: '{"rows":[]}', digest: 'study-frozen' }) };+ await exercise('claim', () => store.claim(board, item, claim));+ await exercise('recordAttempt', () => store.recordAttempt(board, item, { agentId: agent, n: 1, seconds: 1, result: 'red' }));+ await exercise('release', () => store.release(board, item, agent, 'Study release.'));+ await exercise('refreeze', () => store.refreeze(board, item, { agentId: 'coordinator', freeze: claim.freeze }));+ store.claim(board, item, claim);+ await exercise('submit', () => submitFixture(board, item, { agentId: agent, commit: 'a'.repeat(40), tree: 'b'.repeat(40) }));+ await exercise('reopen', () => store.reopen(board, item, { agentId: 'coordinator', note: 'Study submitted-item return.' }));+ if (store.getItem(board, item).item_status === 'open') {+ store.claim(board, item, claim);+ submitFixture(board, item, { agentId: agent, commit: 'c'.repeat(40), tree: 'b'.repeat(40) });+ }+ await exercise('reserveReview', () => store.reserveReview(board, item, { agentId: reviewer, lane: 'tests', leaseMs: 3600000, policy: 'any' }));+ await exercise('reserveNextReview', () => store.reserveNextReview(board, { agentId: reviewer, lane: 'tests', leaseMs: 3600000, policy: 'any' }));+ await exercise('verify', () => store.verify(board, item, { agentId: reviewer, decision: 'ACCEPT', head: 'c'.repeat(40),+ digest: 'study-frozen', policy: 'any', note: 'Synthetic native state only; no gate execution claimed.' }));+ await exercise('merged', () => store.merged(board, item, { agentId: 'coordinator', commit: 'c'.repeat(40) }));+ await exercise('withdraw', () => store.withdraw(board, other, { agentId: 'coordinator', reason: 'Study withdrawal.' }));+ const watch = await exercise('proposeSentinel', () => store.proposeSentinel(board, { agentId: agent,+ row: { name: 'study-watch', check: 'true', every: 'hourly', owner: 'coordinator' } }));+ if (watch) {+ await exercise('decideSentinel', () => store.decideSentinel(board, { agentId: 'person', channel: 'terminal',+ name: watch.name, digest: watch.digest, decision: 'approve' }));+ await exercise('beginSentinelRun', () => store.beginSentinelRun(board, { agentId: agent, name: watch.name, digest: watch.digest, run: 'study-run' }));+ await exercise('finishSentinelRun', () => store.finishSentinelRun(board, { agentId: agent, name: watch.name, digest: watch.digest,+ run: 'study-run', result: { green: true, code: 0, timedOut: false, signal: null, aborted: false, durationMs: 1, output: 'Synthetic watch receipt, no command execution claimed.' } }));+ }+ await exercise('recordHealthFindings', () => store.recordHealthFindings(board, { agentId: 'coordinator',+ observedRevision: board.db.prepare('SELECT MAX(event_id) AS n FROM event').get().n,+ findings: [{ key: 'study-fixture', cause: 'STUDY_FIXTURE', subject: agent, title: 'Synthetic projection observation',+ since: board.clock.now().toISOString(), why: 'Private state fixture, not a real health finding', next: 'Read study metadata', item: null }] }));+ await exercise('recordFlakeObservation', () => store.recordFlakeObservation(board, { agentId: 'coordinator',+ lane: box.lane, observation: syntheticFlakeObservation('study-synthetic-unclassified') }));+ const outsideText = '{"rows":[]}';+ const outside = await exercise('intakeOutside', () => store.intakeOutside(board, { agentId: 'coordinator',+ source: { kind: 'pull-request', repository: 'fixture/repository', number: 1281, author: 'study-contributor',+ state: 'open', maintainerReplied: false, commit: 'd'.repeat(40), tree: 'e'.repeat(40), base: 'f'.repeat(40),+ files: ['synthetic-study.txt'], sensitive: true },+ item: { lane: box.lane, title: 'Synthetic outside state', criterion: 'State projection only.', route: 'strong' },+ frozen: { text: outsideText, digest: createHash('sha256').update(outsideText).digest('hex') } }));+ if (outside) await exercise('approveOutside', () => store.approveOutside(board, outside, { agentId: 'person' }));+ await exercise('recordPublishFinding', () => store.recordPublishFinding(board, { agentId: 'coordinator', item,+ repository: 'fixture/repository', pull: 1281, head: 'c'.repeat(40),+ failures: [{ id: 1281, name: 'Synthetic state only, not a CI failure', url: 'https://example.invalid/study', files: ['synthetic-study.txt'] }] }));+ const command = 'node -e "process.exit(0)"';+ const pending = { command, main: 'a'.repeat(40), request: randomUUID(), result: 'pending' };+ const baselineItem = store.addItem(board, { by: 'coordinator', lane: box.lane, title: 'Unavailable baseline state',+ criterion: 'State projection only.', check: command, checkBaseline: pending });+ await exercise('completeCheckBaseline', () => store.completeCheckBaseline(board, baselineItem, { agentId: 'coordinator', expected: pending,+ baseline: { ...pending, result: 'unavailable', reason: 'Synthetic native-state fixture; no baseline execution claimed.' } }));+ await exercise('acceptCheck', () => store.acceptCheck(board, baselineItem, { agentId: 'person', channel: 'terminal',+ digest: createHash('sha256').update(command).digest('hex') }));+ const answered = board.db.prepare("SELECT MAX(event_id) AS n FROM event WHERE event_kind='answer'").get().n;+ const through = board.db.prepare('SELECT MAX(event_id) AS n FROM event').get().n;+ await exercise('recordActivityDelivery', () => store.recordActivityDelivery(board, { agentId: agent, through, digestThrough: through,+ interrupts: answered ? [{ id: 'event:' + answered, eventId: answered, reason: 'answered' }] : [] }));+ if (answered) await exercise('actOnActivity', () => store.actOnActivity(board, { agentId: agent, ids: ['event:' + answered] }));+ await exercise('draftSpecRow', () => store.draftSpecRow(board, { agentId: agent,+ row: { id: 'Z1281', text: 'Study row.', gate: 'review', tier: 'must', section: 'Study', target: 'spec' } }));+ const row = { kind: 'spec', id: 'Z1281', file: 'SPEC.md', source: '- Z1281 [draft, must] Study row. | gate: review',+ replacement: '- Z1281 [approved, must] Study row. | gate: review', text: 'Study row.', decision: 'approve' };+ const decisions = await exercise('recordRowDecisions', () => store.recordRowDecisions(board, { agentId: 'person', channel: 'terminal', decisions: [row] }));+ if (decisions) await exercise('applyRowDecisions', () => store.applyRowDecisions(board, { agentId: 'coordinator', events: decisions.map(value => value.event) }));+ const handoff = await exercise('openHandoff', () => store.openHandoff(board, { agentId: agent }));+ if (handoff) await exercise('takeHandoff', () => store.takeHandoff(board, { agentId: reviewer, item: handoff.item }));+});diff --git a/test/relay-study.test.js b/test/relay-study.test.jsnew file mode 100644index 00000000..c4ff1f87--- /dev/null+++ b/test/relay-study.test.js@@ -0,0 +1,110 @@+/** A measured private relay study, with explicit coverage limits rather than inferred parity [H5,H17]. */+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { performance } from 'node:perf_hooks';+import { test } from 'node:test';+import * as store from '../src/board.js';+import { ENGINE_VERSION } from '../src/machine.js';+import { MOVE_OPERATIONS } from '../src/move-registry.js';+import { relaySnapshot } from '../src/relay-presentation.js';+import { relayClientFixture } from './relay-client-fixture.js';+import { differences, readRelay } from './relay-study-fixture.js';++const SKIP = process.env.PULLBOARD_RELAY_STUDY !== '1' && 'a measurement: set PULLBOARD_RELAY_STUDY=1 to run it';++test('relay study measures seeded native and API2 reader parity [H5,H17]', { timeout: 180_000, skip: SKIP }, async t => {+ const box = await relayClientFixture(t);+ await box.link();+ const board = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ t.after(() => store.closeBoard(board));+ const item = store.addItem(board, { by: 'coordinator', lane: box.lane, title: 'Study seeded item',+ criterion: 'Full detail survives relay paging.', brief: 'A seeded detail field.', specIds: [] });+ store.editItem(board, item, { agentId: 'coordinator', brief: 'Changed seeded detail.', reason: 'study seed' });+ store.appendFact(board, item, { agentId: 'coordinator', kind: 'measurement', text: 'Measured seed observation.' });+ const decision = store.shout(board, { from: 'coordinator', to: 'all', text: 'Seeded decision?', lanes: [box.lane], decision: true });+ store.shout(board, { from: 'coordinator', to: 'all', text: 'Seeded answer.', lanes: [box.lane], answers: decision });+ const uploadStart = box.transit.length;+ const started = performance.now();+ const published = await box.cli('status');+ assert.equal(published.code, 0, 'the real linked CLI publishes the seeded board');+ const publishMs = performance.now() - started;+ const expected = relaySnapshot(box.root);+ const read = await readRelay(box);+ const full = differences(expected.presentation, read.document.presentation);+ const tables = differences(expected.tables, read.document.tables);+ const writes = box.transit.slice(uploadStart).filter(row => ['PUT', 'POST'].includes(row.method));+ const covered = ['addItem', 'editItem', 'appendFact', 'shout'];+ t.diagnostic(JSON.stringify({ phase: 'initial-api2-parity', engine: ENGINE_VERSION,+ node: process.versions.node, platform: process.platform, arch: process.arch,+ events: expected.tables.event.length, publishMs, uploadRequests: writes.length,+ uploadBytes: writes.reduce((sum, row) => sum + row.request.byteLength, 0),+ readMs: read.readMs, readRequests: read.requests, readBytes: read.receivedBytes,+ projectionDifferences: full, tableDifferences: tables, coveredMoves: covered,+ uncoveredMoves: MOVE_OPERATIONS.filter(operation => !covered.includes(operation)),+ limitation: 'Private loopback relay, initial seed only; not every move, throughput ceiling or failure study yet.' }));+ assert.equal(tables.length, 0, 'the measured relay restores every native table field');+ assert.equal(full.length, 0, 'the measured relay restores every full presentation field');+});++test('relay study measures 1k 10k and 50k native-event sync and private request saturation [H5,H17]', { timeout: 300_000, skip: SKIP }, async t => {+ const box = await relayClientFixture(t);+ await box.link();+ const board = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ t.after(() => store.closeBoard(board));+ for (const target of [1000, 10_000, 50_000]) {+ let events = board.db.prepare('SELECT COUNT(*) AS n FROM event').get().n;+ const seedStart = performance.now();+ store.atomic(board, () => {+ while (events < target) {+ const text = 'Study event ' + events + ' ' + createHash('sha256').update(String(events)).digest('hex');+ store.shout(board, { from: 'coordinator', to: 'all', text, lanes: [box.lane] });+ events++;+ }+ });+ const seedMs = performance.now() - seedStart;+ assert.equal(board.db.prepare('SELECT COUNT(*) AS n FROM event').get().n, target);+ const uploadStart = box.transit.length;+ const publishStart = performance.now();+ const result = await box.cli('status');+ assert.equal(result.code, 0, 'the actual CLI syncs the measured event scale');+ const publishMs = performance.now() - publishStart;+ const expected = relaySnapshot(box.root);+ const read = await readRelay(box);+ const projection = differences(expected.presentation, read.document.presentation);+ const tables = differences(expected.tables, read.document.tables);+ const writes = box.transit.slice(uploadStart).filter(row => ['PUT', 'POST'].includes(row.method));+ t.diagnostic(JSON.stringify({ phase: 'event-scale', events: target, seedMs, publishMs,+ nativeJsonBytes: Buffer.byteLength(JSON.stringify(expected)),+ uploadRequests: writes.length, uploadBytes: writes.reduce((sum, row) => sum + row.request.byteLength, 0),+ readMs: read.readMs, readRequests: read.requests, readBytes: read.receivedBytes,+ projectionDifferences: projection, tableDifferences: tables,+ workload: 'One private loopback API2 relay; unique SHA256-tagged shouts, batched native writes; not 50k independently synced moves.' }));+ assert.equal(projection.length, 0);+ assert.equal(tables.length, 0);+ }+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));+ const headers = { authorization: 'Bearer ' + state.token, 'x-pullboard-engine': String(ENGINE_VERSION) };+ for (const concurrency of [1, 4, 16, 64, 256, 1024]) {+ const times = [], statuses = {};+ const started = performance.now();+ /** Use real authenticated root reads, including each response body and the server's pinned-reader allocation. */+ async function read() {+ const begin = performance.now();+ const response = await fetch(box.origin + '/api/v2/boards/' + state.board + '/state', { headers });+ await response.arrayBuffer();+ times.push(performance.now() - begin);+ statuses[response.status] = (statuses[response.status] ?? 0) + 1;+ }+ for (let wave = 0; wave < 3; wave++) await Promise.all(Array.from({ length: concurrency }, read));+ const wallMs = performance.now() - started;+ times.sort((a, b) => a - b);+ const p95Ms = times[Math.ceil(times.length * 0.95) - 1];+ t.diagnostic(JSON.stringify({ phase: 'private-root-request-rate', concurrency, requests: times.length,+ wallMs, requestsPerSecond: times.length * 1000 / wallMs, p95Ms, statuses,+ scope: 'Same-process private loopback authenticated API2 root reads, three waves, no TLS; not external production capacity.' }));+ if (p95Ms > 500 || Object.keys(statuses).some(status => status !== '200')) break;+ }+});+