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): seed all native operations for reader parity [H5,H16,A2]
Corey Olsona2f299562c9d
diff --git a/src/api.js b/src/api.jsindex c9ef4165..920c2580 100644--- a/src/api.js+++ b/src/api.js@@ -91,6 +91,7 @@ function stateRevision(inputs) {* nextExpiry is the earliest live claim or review lease, when a lease turns over with no write.*/function localRevisionInputs(board, now) {+ board = Object.assign(Object.create(board), { clock: { ...board.clock, now: () => new Date(now) } });const leases = board.db.prepare('SELECT item_id, item_status, item_owner, item_lease_until, item_review_by, item_review_until FROM item ORDER BY item_id').all().map((item) => [item.item_id, item.item_status, item.item_owner, item.item_lease_until, item.item_review_by, item.item_review_until,@@ -121,12 +122,12 @@ function visibleMilestoneInputs(milestones, scoped) {}/** Capture the inexpensive inputs that can invalidate a complete board-state snapshot. */-function boardStateRevision(root, id, isMain, { projects = listApiProjects, scopeCommonDir = null } = {}) {+function boardStateRevision(root, id, isMain, { projects = listApiProjects, scopeCommonDir = null, observedAt = Date.now() } = {}) {const info = repoInfo(root);const config = loadConfig(info.root);const files = stateFileInputs(info.root, config).map(fileRevision);const local = withBoard(info.root, (board) => {- const inputs = localRevisionInputs(board, board.clock.now().toISOString());+ const inputs = localRevisionInputs(board, new Date(observedAt).toISOString());const hasExternalMilestones = inputs.milestones.some((milestone) => milestone.items.some((item) => typeof item !== 'number'));return { ...inputs, externalMilestones: hasExternalMilestones? scopeCommonDir === null@@ -827,11 +828,11 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =* input revision holds before and after the read, and building it again when one moved.*/function withSnapshot(board, read, observedAt = now()) {- const before = boardStateRevision(board.root, board.id, codeIsMain, { projects: apiProjects, scopeCommonDir });+ const before = boardStateRevision(board.root, board.id, codeIsMain, { projects: apiProjects, scopeCommonDir, observedAt });const cached = stateCache.get(before.cacheId);if (before.cacheable && cached?.revision === before.revision) {const result = read(cached, true);- const after = boardStateRevision(board.root, board.id, codeIsMain, { projects: apiProjects, scopeCommonDir });+ const after = boardStateRevision(board.root, board.id, codeIsMain, { projects: apiProjects, scopeCommonDir, observedAt });if (after.cacheable && after.revision === before.revision) {stateCache.delete(before.cacheId);stateCache.set(before.cacheId, cached);@@ -860,7 +861,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =itemMoveCounts: built.itemMoveCounts,});entry.cacheId = before.cacheId;- const after = boardStateRevision(board.root, board.id, codeIsMain, { projects: apiProjects, scopeCommonDir });+ const after = boardStateRevision(board.root, board.id, codeIsMain, { projects: apiProjects, scopeCommonDir, observedAt });// Missing Git objects can arrive without a board event or trunk move; retry that uncertainty.if (before.cacheable && after.cacheable && before.revision === after.revision &&!state.items.some(item => item.verdictState?.reason)) {diff --git a/test/relay-parity-extra-seeds.js b/test/relay-parity-extra-seeds.jsnew file mode 100644index 00000000..2fb4bf12--- /dev/null+++ b/test/relay-parity-extra-seeds.js@@ -0,0 +1,130 @@+/** Additional real native mutations for the complete reader inventory [H5,H16,A2]. */+import { createHash, randomUUID } from 'node:crypto';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { resolveCommit } from '../src/git.js';+import { tryGit } from '../src/git.js';+import { barReadiness } from '../src/bar-readiness.js';+import { revisionReference } from '../src/spec-revisions.js';+import { receiptBody } from '../src/gate-run-receipt.js';++/** Outside metadata is synthetic fixture input; these calls make no GitHub or owner-authentication assurance claim. */+export async function seedOutside(context) {+ const { board, box, store, exercise } = context;+ const text = '{"rows":[]}';+ const outside = await exercise('intakeOutside', () => store.intakeOutside(board, { agentId: 'coordinator',+ source: { kind: 'pull-request', repository: 'fixture/repository', number: 1282, author: 'parity-contributor',+ state: 'open', maintainerReplied: false, commit: 'd'.repeat(40), tree: 'e'.repeat(40), base: 'f'.repeat(40),+ files: ['synthetic-parity.txt'], sensitive: true },+ item: { lane: box.lane, title: 'Outside projection input', criterion: 'Complete readers retain outside metadata', check: 'true', route: 'strong' },+ frozen: { text, digest: createHash('sha256').update(text).digest('hex') } }));+ if (outside !== null) await exercise('approveOutside', () => store.approveOutside(board, outside, { agentId: 'person' }));+}++/** Preserve gate and landing receipt shapes without pretending that this state fixture executed those jobs. */+export async function seedLandingObservations(context) {+ const { board, box, store, exercise } = context;+ const command = 'synthetic projection receipt; no command executed';+ const head = resolveCommit(box.root, 'HEAD');+ const tree = tryGit(box.root, ['rev-parse', `${head}^{tree}`]).stdout.trim();+ const receipt = { version: 1, id: randomUUID(), kind: 'gate', head, main: head, tree,+ command: createHash('sha256').update(command).digest('hex'), green: false,+ failures: [{ file: 'test/parity-synthetic.test.js', name: 'Synthetic projection observation', durationMs: 1 }],+ at: board.clock.now().toISOString(), load: { average: [0, 0, 0], cpus: 1, freeMB: 100 } };+ const folder = join(box.root, '.git', 'pullboard', 'gate-receipts');+ mkdirSync(folder, { recursive: true });+ writeFileSync(join(folder, `${receipt.id}.json`), receiptBody(receipt));+ await exercise('recordGateRun', () => store.recordGateRun(board, { agentId: 'coordinator', receipt, lane: box.lane }));+ await exercise('recordLandingWaiver', () => store.recordLandingWaiver(board, { agentId: 'person', channel: 'terminal',+ id: 'parity-synthetic-waiver', test: 'test/parity-synthetic.test.js', until: '2099-01-01T00:00:00Z', reason: 'Synthetic projection fixture; no real test waiver' }));+ await exercise('recordLandingFlake', () => store.recordLandingFlake(board, { agentId: 'coordinator', test: 'test/parity-synthetic.test.js',+ hash: 'a'.repeat(64), names: ['Synthetic projection observation'], lane: box.lane, batchId: randomUUID() }));+ await exercise('recordLandingTestDefect', () => store.recordLandingTestDefect(board, { agentId: 'coordinator', test: 'test/parity-synthetic-defect.test.js',+ hash: 'b'.repeat(64), blob: head, trunkBlob: null, names: ['Synthetic projection defect'], lane: box.lane, batchId: randomUUID(), branch: 'refs/heads/main' }));+}++/** Membership data exercises projection only; key-handover signature verification is deliberately outside this fixture. */+export async function seedMembership(context) {+ const { board, store, exercise } = context;+ await exercise('setBoardMembers', () => store.setBoardMembers(board, { agentId: 'coordinator', document: {+ body: { v: 1, board: store.boardId(board), repository: 'fixture/repository', revision: 1, members: ['parity-member'] },+ by: 'parity-owner', signature: '-----BEGIN SSH SIGNATURE-----\nSynthetic projection fixture; not a verified signature\n-----END SSH SIGNATURE-----' } }));+}++/** Coordinator path upkeep and escalation both have real intermediate projection effects. */+export async function seedAdministrative(context) {+ const { board, box, store, exercise } = context;+ await exercise('ensureCoordinator', () => store.ensureCoordinator(board, join(box.root, 'moved-coordinator')));+ await exercise('ensureCoordinator', () => store.ensureCoordinator(board, box.root));+ const item = store.addItem(board, { by: 'coordinator', lane: box.lane, title: 'Escalated projection input', criterion: 'Route changes remain visible', route: 'mid' });+ await exercise('escalate', () => store.escalate(board, item, { agentId: 'coordinator', note: 'Synthetic projection escalation' }));+}++/** Complete a synthetic accepted-item batch through real recording operations, without pushing Git or claiming LAND. */+export async function seedBatch(context) {+ const { board, box, store, exercise, agent, reviewer, submitFixture } = context;+ const head = resolveCommit(box.root, 'HEAD');+ const tree = tryGit(box.root, ['rev-parse', `${head}^{tree}`]).stdout.trim();+ const frozen = { text: '{"rows":[]}', digest: 'parity-batch-frozen' };+ const item = store.addItem(board, { by: 'coordinator', lane: box.lane, title: 'Synthetic batch projection', criterion: 'Readers retain batch state' });+ store.claim(board, item, { agentId: agent, lane: box.lane, leaseMs: 3600000, head, freeze: () => frozen });+ submitFixture(board, item, { agentId: agent, commit: head, tree });+ store.reserveReview(board, item, { agentId: reviewer, lane: 'tests', leaseMs: 3600000, policy: 'any' });+ store.verify(board, item, { agentId: reviewer, decision: 'ACCEPT', head, digest: frozen.digest, policy: 'any', familyPolicy: 'off',+ note: 'Synthetic state only; no gate or independent assurance claimed.', review: { commit: head, head, trunk: head, paths: [] } });+ const batch = { version: 1, id: randomUUID(), state: 'pushed', base: head, tip: head, root: box.root,+ branch: 'refs/heads/main', owner: 'private-projection-fixture', logPath: join(box.root, 'synthetic-batch.log'),+ items: [{ id: item, commit: head, merge: head, reviewedCommit: head }] };+ await exercise('recordLandingBatch', () => store.recordLandingBatch(board, { agentId: 'coordinator', batch }));+ await exercise('finishLandingBatch', () => store.finishLandingBatch(board, { agentId: 'coordinator', id: batch.id, tip: head }));+}++/** Native takeover and lease records use explicitly synthetic private-fixture authority, not a live session claim. */+export async function seedCoordinatorAuthority(context) {+ const { board, store, exercise } = context;+ const previous = board.verifierStanding;+ board.verifierStanding = { lineage: 'parity-private-synthetic-lineage' };+ try {+ await exercise('takeCoordinator', () => store.takeCoordinator(board, { agentId: 'coordinator', machine: 'parity-fixture', name: 'Parity fixture' }));+ const token = randomUUID();+ const request = await exercise('landingLeaseMove', () => store.landingLeaseMove(board, { agentId: 'coordinator', action: 'request',+ token, branch: 'refs/heads/main', pid: process.pid }));+ if (request) await exercise('landingLeaseMove', () => store.landingLeaseMove(board, { agentId: 'coordinator', action: 'release', token,+ generation: request.generation, branch: 'refs/heads/main', pid: process.pid }));+ } finally { board.verifierStanding = previous; }+}+++/** Spec receipts retain exact immutable sources; fixture parent identities do not assert real-world independence. */+export async function seedSpecOutcomes(context) {+ const { board, store, exercise, agent, reviewer } = context;+ const row = { id: 'P1282', text: 'A projection-only draft.', gate: 'review', tier: 'must', section: 'P · Projection', target: 'spec' };+ store.draftSpecRow(board, { agentId: agent, row });+ await exercise('recordRowVerification', () => store.recordRowVerification(board, { agentId: reviewer,+ source: '- P1282 [draft, must] A projection-only draft. | gate: review', decision: 'accepted', reason: 'Synthetic projection receipt; no external assurance.' }));+ const revision = store.draftSpecRow(board, { agentId: agent, row: { id: 'P1283', target: 'spec', revises: 'P1284',+ text: 'Revised projection text.', gate: 'review', tier: 'must', section: 'P · Projection', status: 'approved', file: 'SPEC.md',+ source: '- P1284 [approved, must] Original projection text. | gate: review',+ replacement: '- P1284 [approved, must] Revised projection text. | gate: review', reason: 'Synthetic revision disposition.' } });+ await exercise('decideSpecRevisions', () => store.decideSpecRevisions(board, { agentId: 'person', channel: 'terminal', decisions: [{+ version: 1, type: 'row-decision', kind: 'spec', id: revision.revises, file: revision.file, source: revision.source,+ replacement: revision.replacement, text: revision.text, decision: 'decline', reason: 'Synthetic projection-only decline.', revision: revisionReference(revision) }] }));+}++/** A bar signature is synthetic projection input, with complete recorded readiness and explicit fixture identities. */+export async function seedBarSignature(context) {+ const { board, box, store, exercise, reviewer } = context;+ store.setBarReady(board, { agentId: 'coordinator', enabled: true });+ const head = resolveCommit(box.root, 'HEAD');+ const check = 'node --test --test-name-pattern "projection witness" test/projection.test.js';+ const item = store.addItem(board, { by: 'coordinator', lane: box.lane, title: 'Ready projection bar', route: 'mid',+ barActor: { session: 'a'.repeat(64), parent: 'a'.repeat(64) }, criterion: 'The projection witness names a mismatch', check,+ checkBaseline: { command: check, main: head, result: 'red', testEvidence: { failed: ['projection witness'], passed: [], noTestsMatched: false } },+ brief: 'Files: src/projection.js\nTest: projection witness asserts mismatch\nNamed test: projection witness\nMeasurements: no quantitative acceptance bounds\nReviewer edges: absent field and clock-only change' });+ const { revision } = barReadiness(board, store.getItem(board, item));+ await exercise('signBar', () => store.signBar(board, item, { agentId: reviewer,+ barActor: { session: 'b'.repeat(64), parent: 'b'.repeat(64) }, revision: revision.revision, digest: revision.digest,+ note: 'Synthetic readiness signature for state projection only.', coverage: { version: 1, sourceMain: head, policyKey: 'd'.repeat(64),+ sourceCheck: check, timeoutMs: 300000, runner: 'node --test', required: [], files: [] } }));+ store.setBarReady(board, { agentId: 'coordinator', enabled: false });+}diff --git a/test/relay-parity-fixture.js b/test/relay-parity-fixture.jsindex 11bcf5c6..04b0371b 100644--- a/test/relay-parity-fixture.js+++ b/test/relay-parity-fixture.js@@ -1,44 +1,17 @@/** Real loopback relay and complete native API observations for reader parity [H5,H15,H16,A2]. */import assert from 'node:assert/strict';-import { randomBytes } from 'node:crypto';-import { readFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { readFileSync, writeFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import * as store from '../src/board.js';-import { serveApi } from '../src/api.js';-import { main } from '../src/cli.js';import { decodeBoardKey } from '../src/seal.js';-import { ENGINE_VERSION } from '../src/machine.js';-import { openPagedSnapshot } from '../src/relay-page-layout.js';-import { snapshotState } from '../relay/browser-model.js';import { relayPresentation } from '../src/relay-presentation.js';import { presentationDigest } from '../src/relay-presentation.js';import { runFixtureChild } from './fixture-child.js';+export { assertReaderParity } from './relay-parity-reader.js';+import { createParityReader } from './relay-parity-reader.js';import { relayClientFixture } from './relay-client-fixture.js';-/** Only the native filesystem routing identity differs deliberately from the relay board identity. */-export const LOCAL_PARITY_FIELDS = Object.freeze([- { path: 'root', reason: 'Native routing uses a local repository directory; a relay reader routes by persistent board id.' },-]);--/** Report the first undeclared field difference with both actual values, including missing keys. */-export function assertReaderParity(native, relay, localFields = LOCAL_PARITY_FIELDS) {- const ignored = new Set(localFields.map(entry => entry.path));- assert.ok(localFields.every(entry => entry.path && entry.reason?.trim()), 'every local-only field has a reason');- /** Compare structure as well as values; a missing field is never equivalent to an explicit null. */- function compare(left, right, path) {- if (ignored.has(path)) return;- const label = value => value === undefined ? '<missing>' : JSON.stringify(value);- if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {- assert.deepEqual(left, right, `reader parity ${path}: native=${label(left)} relay=${label(right)}`);- return;- }- assert.equal(Array.isArray(left), Array.isArray(right), `reader parity ${path}: native=${label(left)} relay=${label(right)}`);- for (const key of new Set([...Object.keys(left), ...Object.keys(right)])) compare(left[key], right[key], path ? `${path}.${key}` : key);- }- compare(native, relay, '');-}-/** Seed actual native writes, keeping the operation receipts available for the fail-closed coverage inventory. */export function seedParityBoard(root, lane) {const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'));@@ -96,32 +69,10 @@ export async function parityRoundtrip(t, { foreign = false } = {}) {const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());const session = await box.phoneSession();- /** Request through a distinct authenticated person session, never a direct journal read. */- async function request(path) {- const response = await fetch(box.origin + path, { headers: { authorization: `Bearer ${session.token}`, 'x-pullboard-engine': String(ENGINE_VERSION) } });- assert.equal(response.status, 200, `relay parity reader GET ${path.split('?')[0]}`);- return response.json();- }- const document = await request(`/api/v2/boards/${link.board}/state`);- assert.equal(document.apiVersion, 2, 'current snapshot transport is exercised');- const saved = document.state;- const page = await openPagedSnapshot(saved.root, { key, boardId: link.board, sequence: saved.sequence,- /** Fetch only the pinned, reachable sealed object graph through its actual service boundary. */- async get(id, parents) {- const object = await request(`/api/v2/boards/${link.board}/objects/${id}?pin=${encodeURIComponent(saved.read.id)}&via=${parents.join(',')}`);- return Uint8Array.from(Buffer.from(object.page.sealed, 'base64url'));- },- }, { maxEngine: ENGINE_VERSION });- const restored = await page.native();- const relay = snapshotState(restored, link.board);- const observedAt = Date.parse(relay.observedAt);- assert.ok(Number.isSafeInteger(observedAt), 'the sealed projection carries its explicit observation clock');- const secret = randomBytes(24).toString('base64url');- const api = await serveApi({ secret, runCommand: main, projects: () => [{ root: box.root, name: 'parity' }, ...(other ? [other] : [])], isMain: true, stateDetail: 'full', scope: { projectRoot: box.root }, now: () => observedAt });- t.after(api.close);- const nativeResponse = await fetch(`http://127.0.0.1:${api.port}/api/v1/boards/${link.board}/state?detail=full`, { headers: { 'x-pullboard-key': secret } });- assert.equal(nativeResponse.status, 200, 'complete native API state is available');- const native = (await nativeResponse.json()).state;+ const reader = await createParityReader({ root: box.root, origin: box.origin, token: session.token, boardId: link.board, key,+ projects: () => [{ root: box.root, name: 'parity' }, ...(other ? [other] : [])] });+ t.after(reader.close);+ const { native, relay, restored } = await reader.read();if (other) {assert.ok(!JSON.stringify(restored).includes(other.secret), 'the actual sealed native snapshot never carries the foreign title');const scoped = relay.milestones.find(milestone => milestone.name === 'Cross-board privacy');@@ -129,5 +80,19 @@ export async function parityRoundtrip(t, { foreign = false } = {}) {assert.ok(JSON.stringify(scoped).includes('unavailable'), 'the external reference is an unavailable obligation');assert.ok(!JSON.stringify(scoped).includes('foreign-parity'), 'the external project reference remains redacted');}- return { native, relay, exercised: seeded.exercised };+ /** One genuine private-environment process retains native and HTTP clients for the full declared operation inventory. */+ async function exerciseOperations() {+ const module = new URL('./relay-parity-operations.js', import.meta.url).href;+ const parameters = { root: box.root, origin: box.origin, token: session.token, boardId: link.board, lane: box.lane, keyFile: box.keyFile };+ const file = join(box.root, '.git', 'pullboard', 'parity-reader-session.json');+ writeFileSync(file, JSON.stringify(parameters), { mode: 0o600 });+ try {+ const result = await box.script(`import { readFileSync } from 'node:fs';+import { exerciseOperationParity } from ${JSON.stringify(module)};+try { console.log(JSON.stringify(await exerciseOperationParity(JSON.parse(readFileSync(${JSON.stringify(file)}, 'utf8'))))); } catch (error) { console.log(JSON.stringify({ error: error.message })); process.exitCode = 1; }`);+ assert.equal(result.code, 0, `complete operation inventory: ${result.failure ?? result.document?.error ?? 'no result'}`);+ return result.document;+ } finally { rmSync(file, { force: true }); }+ }+ return { native, relay, exercised: seeded.exercised, exerciseOperations };}diff --git a/test/relay-parity-operations.js b/test/relay-parity-operations.jsnew file mode 100644index 00000000..ad44ccff--- /dev/null+++ b/test/relay-parity-operations.js@@ -0,0 +1,63 @@+/** Exercise every declared native operation through the complete current reader oracle [H5,H16,A2]. */+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import * as store from '../src/board.js';+import * as milestones from '../src/milestones.js';+import { MOVE_OPERATIONS } from '../src/move-registry.js';+import { publishLatestCheckpoint } from '../src/relay.js';+import { captureSpecApprovalBaseline } from '../src/spec-approval.js';+import { loadConfig } from '../src/config.js';+import { decodeBoardKey } from '../src/seal.js';+import { createParityReader, assertReaderParity } from './relay-parity-reader.js';+import { createStudyExercise, seedStudyState } from './relay-parity-seeds.js';+import { submitFixture } from './board-submit-fixture.js';+import { seedOutside, seedLandingObservations, seedMembership, seedAdministrative, seedBatch, seedCoordinatorAuthority, seedSpecOutcomes, seedBarSignature } from './relay-parity-extra-seeds.js';+import { syntheticFlakeObservation } from './flake-observation-fixture.js';++/** Run inside the existing private fixture's genuine environment, retaining one HTTP server and person session. */+export async function exerciseOperationParity({ root, origin, token, boardId, lane, keyFile }) {+ const key = decodeBoardKey(readFileSync(keyFile, 'utf8').trim());+ const reader = await createParityReader({ root, origin, token, boardId, key });+ const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'));+ const notices = [];+ const io = { say() {}, err(message) { notices.push(message); } };+ /** Publish with the actual production capture/seal/HTTP path, then compare both full readers before covering the move. */+ async function verifyAfterMutation({ operation, after }) {+ assert.equal(await publishLatestCheckpoint(root, io), true, `the ${operation} checkpoint is acknowledged`);+ const { native, relay } = await reader.read();+ assert.ok(native.sequence >= after, `the ${operation} observation includes its actual native event`);+ assertReaderParity(native, relay);+ }+ const tracking = createStudyExercise({ board, verifyAfterMutation });+ const context = { board, box: { root, lane }, store, milestones, ...tracking, submitFixture, syntheticFlakeObservation };+ try {+ const baseline = store.specApprovalBaseline(board);+ if (baseline) {+ // init records this immutable baseline before pairing is possible. Its actual event and the+ // first complete reader observation cover that bootstrap input; a no-op repeat never does.+ const event = store.events(board).find(event => event.event_kind === 'spec_approval_baseline');+ assert.ok(event, 'the initial baseline has a real native mutation receipt');+ await verifyAfterMutation({ operation: 'recordSpecApprovalBaseline', after: event.event_id });+ tracking.covered.add('recordSpecApprovalBaseline');+ } else {+ await tracking.exercise('recordSpecApprovalBaseline', () => store.recordSpecApprovalBaseline(board, {+ agentId: 'coordinator', baseline: captureSpecApprovalBaseline(root, loadConfig(root)) }));+ }+ await seedStudyState(context);+ await seedOutside(context);+ await seedLandingObservations(context);+ await seedMembership(context);+ await seedAdministrative(context);+ await seedBatch(context);+ await seedSpecOutcomes(context);+ await seedBarSignature(context);+ await seedCoordinatorAuthority(context);+ const missing = tracking.missing(MOVE_OPERATIONS);+ assert.deepEqual(missing, [], `every declared native operation must pass the complete oracle; setup refusals=${JSON.stringify(tracking.setupRefusals)}`);+ return { covered: [...tracking.covered].sort(), declared: [...MOVE_OPERATIONS].sort() };+ } finally {+ store.closeBoard(board);+ await reader.close();+ }+}diff --git a/test/relay-parity-reader.js b/test/relay-parity-reader.jsnew file mode 100644index 00000000..2870069e--- /dev/null+++ b/test/relay-parity-reader.js@@ -0,0 +1,66 @@+/** Complete authenticated HTTP and pinned API2 reader oracle [H5,H16,A2]. */+import assert from 'node:assert/strict';+import { randomBytes } from 'node:crypto';+import { serveApi } from '../src/api.js';+import { main } from '../src/cli.js';+import { ENGINE_VERSION } from '../src/machine.js';+import { openPagedSnapshot } from '../src/relay-page-layout.js';+import { snapshotState } from '../relay/browser-model.js';++/** Only the native filesystem routing identity differs deliberately from the relay board identity. */+export const LOCAL_PARITY_FIELDS = Object.freeze([+ { path: 'root', reason: 'Native routing uses a local repository directory; a relay reader routes by persistent board id.' },+]);++/** Report the first undeclared field difference with both actual values, including missing keys. */+export function assertReaderParity(native, relay, localFields = LOCAL_PARITY_FIELDS) {+ const ignored = new Set(localFields.map(entry => entry.path));+ assert.ok(localFields.every(entry => entry.path && entry.reason?.trim()), 'every local-only field has a reason');+ /** Compare structure as well as values; a missing field is never equivalent to an explicit null. */+ function compare(left, right, path) {+ if (ignored.has(path)) return;+ const label = value => value === undefined ? '<missing>' : JSON.stringify(value);+ if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {+ assert.deepEqual(left, right, `reader parity ${path}: native=${label(left)} relay=${label(right)}`);+ return;+ }+ assert.equal(Array.isArray(left), Array.isArray(right), `reader parity ${path}: native=${label(left)} relay=${label(right)}`);+ for (const key of new Set([...Object.keys(left), ...Object.keys(right)])) compare(left[key], right[key], path ? `${path}.${key}` : key);+ }+ compare(native, relay, '');+}++/** Retain both real service clients across native mutations without starting another CLI process. */+export async function createParityReader({ root, origin, token, boardId, key, projects = () => [{ root, name: 'parity' }] }) {+ let observedAt = Date.now();+ const secret = randomBytes(24).toString('base64url');+ const api = await serveApi({ secret, runCommand: main, projects, isMain: true, stateDetail: 'full', scope: { projectRoot: root }, now: () => observedAt });+ /** Read the current exact sealed clock, then ask the complete native HTTP API at that clock. */+ async function read() {+ /** Request through a distinct authenticated person session, never a direct journal read. */+ async function request(path) {+ const response = await fetch(origin + path, { headers: { authorization: `Bearer ${token}`, 'x-pullboard-engine': String(ENGINE_VERSION) } });+ assert.equal(response.status, 200, `relay parity reader GET ${path.split('?')[0]}`);+ return response.json();+ }+ const document = await request(`/api/v2/boards/${boardId}/state`);+ assert.equal(document.apiVersion, 2, 'current snapshot transport is exercised');+ const saved = document.state;+ const page = await openPagedSnapshot(saved.root, { key, boardId, sequence: saved.sequence,+ /** Fetch only the pinned, reachable sealed object graph through its actual service boundary. */+ async get(id, parents) {+ const object = await request(`/api/v2/boards/${boardId}/objects/${id}?pin=${encodeURIComponent(saved.read.id)}&via=${parents.join(',')}`);+ return Uint8Array.from(Buffer.from(object.page.sealed, 'base64url'));+ },+ }, { maxEngine: ENGINE_VERSION });+ const restored = await page.native();+ const relay = snapshotState(restored, boardId);+ observedAt = Date.parse(relay.observedAt);+ assert.ok(Number.isSafeInteger(observedAt), 'the sealed projection carries its explicit observation clock');+ const nativeResponse = await fetch(`http://127.0.0.1:${api.port}/api/v1/boards/${boardId}/state?detail=full`, { headers: { 'x-pullboard-key': secret } });+ assert.equal(nativeResponse.status, 200, 'complete native API state is available');+ const native = (await nativeResponse.json()).state;+ return { native, relay, restored };+ }+ return { read, close: api.close };+}diff --git a/test/relay-parity-seeds.js b/test/relay-parity-seeds.jsnew file mode 100644index 00000000..f1839dba--- /dev/null+++ b/test/relay-parity-seeds.js@@ -0,0 +1,200 @@+/** Native operation recipes extracted from study 7b08e883 for the complete reader oracle [H5,H16,A2].+ * Original recipes: whole ff/db757 material pool; integration/helper: whole420/475.+ * Synthetic receipts exercise projection only, never gate, CI, watch or provider-authority assurance.+ * Every covered operation must advance native events and pass the current complete reader oracle.+ */+import { createHash, randomUUID } from 'node:crypto';+import { join } from 'node:path';++/** Count only actual native mutations whose full current owner-supplied oracle succeeds.+ * work is synchronous, matching the original native-store recipe contract.+ * Coded refusals remain visible and uncovered; they never count as successful proof.+ */+export function createStudyExercise({ board, verifyAfterMutation, covered = new Set(), setupRefusals = [] }) {+ if (typeof verifyAfterMutation !== 'function') throw new TypeError('a complete current HTTP/pinned-API2 oracle is required');+ 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;+ }+ const after = board.db.prepare('SELECT COALESCE(MAX(event_id),0) AS n FROM event').get().n;+ if (after === before) {+ setupRefusals.push({ operation, code: 'NO_MUTATION' });+ return result;+ }+ await verifyAfterMutation({ operation, before, after, result });+ covered.add(operation);+ return result;+ }+ return { exercise, covered, setupRefusals,+ missing: operations => operations.filter(operation => !covered.has(operation)) };+}++/** seedIdentity uses real operations; synthetic records retain their original explicit labels. */+export async function seedIdentity(context) {+ const { board, box, store, milestones, exercise, submitFixture, syntheticFlakeObservation, other, claim } = context;+ 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.' }));+ Object.assign(context, { agent, reviewer, item });+ return context;+}++/** seedOrdinaryWork uses real operations; synthetic records retain their original explicit labels. */+export async function seedOrdinaryWork(context) {+ const { board, box, store, milestones, exercise, submitFixture, syntheticFlakeObservation, agent, reviewer, item, other, claim } = context;+ 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 }));+ return context;+}++/** seedMilestones uses real operations; synthetic records retain their original explicit labels. */+export async function seedMilestones(context) {+ const { board, box, store, milestones, exercise, submitFixture, syntheticFlakeObservation, agent, reviewer, item, claim } = context;+ 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' }));+ Object.assign(context, { other });+ return context;+}++/** seedLifecycle uses real operations; synthetic records retain their original explicit labels. */+export async function seedLifecycle(context) {+ const { board, box, store, milestones, exercise, submitFixture, syntheticFlakeObservation, agent, reviewer, item, other } = context;+ 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.' }));+ Object.assign(context, { claim });+ return context;+}++/** seedWatchReceipts uses real operations; synthetic records retain their original explicit labels. */+export async function seedWatchReceipts(context) {+ const { board, box, store, milestones, exercise, submitFixture, syntheticFlakeObservation, agent, reviewer, item, other, claim } = context;+ 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.' } }));+ }+ return context;+}++/** seedObservationReceipts uses real operations; synthetic records retain their original explicit labels. */+export async function seedObservationReceipts(context) {+ const { board, box, store, milestones, exercise, submitFixture, syntheticFlakeObservation, agent, reviewer, item, other, claim } = context;+ 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') }));+ return context;+}++/** seedPublishFinding uses real operations; synthetic records retain their original explicit labels. */+export async function seedPublishFinding(context) {+ const { board, box, store, milestones, exercise, submitFixture, syntheticFlakeObservation, agent, reviewer, item, other, claim } = context;+ 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'] }] }));+ return context;+}++/** seedBaselineReceipts uses real operations; synthetic records retain their original explicit labels. */+export async function seedBaselineReceipts(context) {+ const { board, box, store, milestones, exercise, submitFixture, syntheticFlakeObservation, agent, reviewer, item, other, claim } = context;+ 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') }));+ return context;+}++/** seedActivityReceipts uses real operations; synthetic records retain their original explicit labels. */+export async function seedActivityReceipts(context) {+ const { board, box, store, milestones, exercise, submitFixture, syntheticFlakeObservation, agent, reviewer, item, other, claim } = context;+ 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] }));+ return context;+}++/** seedSpecAndHandoff uses real operations; synthetic records retain their original explicit labels. */+export async function seedSpecAndHandoff(context) {+ const { board, box, store, milestones, exercise, submitFixture, syntheticFlakeObservation, agent, reviewer, item, other, claim } = context;+ 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 }));+ return context;+}++/** Optional original ordering. Owners may instead call individual phases with valid prerequisites. */+export async function seedStudyState(context) {+ await seedIdentity(context);+ await seedOrdinaryWork(context);+ await seedMilestones(context);+ await seedLifecycle(context);+ await seedWatchReceipts(context);+ await seedObservationReceipts(context);+ await seedPublishFinding(context);+ await seedBaselineReceipts(context);+ await seedActivityReceipts(context);+ await seedSpecAndHandoff(context);+ return context;+}diff --git a/test/relay-parity.test.js b/test/relay-parity.test.jsindex 85c6fcf1..4ad87270 100644--- a/test/relay-parity.test.js+++ b/test/relay-parity.test.js@@ -4,7 +4,7 @@ import { test } from 'node:test';import { parityRoundtrip, assertReaderParity } from './relay-parity-fixture.js';test('a field that differs between native and relay readers is refused, naming the field [H5,H16,A2]', { timeout: 60_000 }, async t => { // budget: criterion's sixty-second guard ceiling, including real local HTTP and cleanup.- const { native, relay } = await parityRoundtrip(t);+ const { native, relay, exerciseOperations } = await parityRoundtrip(t);const live = native.agents.find(agent => agent.heartbeatAt !== null);assert.ok(live, 'a real native heartbeat is present in the seed');const missingHeartbeat = structuredClone(native);@@ -12,6 +12,8 @@ test('a field that differs between native and relay readers is refused, naming tassert.throws(() => assertReaderParity(native, missingHeartbeat), error => /agents\.\d+\.heartbeatAt/u.test(error.message)&& error.message.includes('native=') && error.message.includes('relay=<missing>'), 'the deliberate heartbeat removal names its exact field and both values');assertReaderParity(native, relay);+ const inventory = await exerciseOperations();+ assert.deepEqual(inventory.covered, inventory.declared, 'every declared operation passes complete reader parity');});