Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(relay): share scoped state and observation clock [H5,H16,A2]
Corey Olson492440a3fd42
diff --git a/src/api.js b/src/api.jsindex 1fdc7d7a..c9ef4165 100644--- a/src/api.js+++ b/src/api.js@@ -1,5 +1,7 @@import { buildLocalBoardState } from './native-board-state.js';import { dependencyIds } from './native-board-state.js';+import { stateFileInputs } from './native-board-state.js';+import { fileRevision } from './native-board-state.js';/** The local API v1: the CLI's moves, persistent board identities and live events (A2). */import {createHash,@@ -20,7 +22,6 @@ import {import { displayAgentName } from './agent-names.js';import * as store from './board.js';import {- CONFIG_FILE,COORDINATOR,loadConfig,} from './config.js';@@ -60,13 +61,7 @@ import {projectItemSpecApprovals,specApprovalState,} from './spec-approval.js';-import {- fitFile,-} from './blueprint-fit.js';import { Refused } from './refused.js';-import {- BLOCKS_FILE,-} from './blocks.js';import { verdictProjector } from './verdict-freshness.js';import { trunkRevisionReader } from './trunk-revision.js';import {@@ -91,26 +86,6 @@ function stateRevision(inputs) {return JSON.stringify(STATE_REVISION_INPUTS.map((name) => [name, inputs[name]]));}-/** Name project and built-in files separately, even when their basenames collide. */-function stateFileInputs(root, config) {- return [- { name: `config:${CONFIG_FILE}`, path: join(root, CONFIG_FILE) },- { name: `spec:${config.spec}`, path: join(root, config.spec) },- { name: `practice:${config.practice}`, path: join(root, config.practice) },- { name: 'builtin:standard-doctrine.md', path: new URL('./standard-doctrine.md', import.meta.url) },- ...['signoffs.jsonl', 'signers', 'first-commit', 'signers.initial'].map(name => ({ name: `approval:${name}`, path: join(root, '.pullboard', name) })),- { name: 'fit:blueprint-fit.json', path: fitFile(repoInfo(root).commonDir) },- // A new block changes Needs you without a board move, so the ledger is a state input [C6].- { name: 'blocks:blocks.jsonl', path: join(repoInfo(root).commonDir, BLOCKS_FILE) },- ];-}--/** Hash the exact bytes of one named input, preserving a missing-file marker. */-function fileRevision(file) {- if (!existsSync(file.path)) return [file.name, null];- return [file.name, createHash('sha256').update(readFileSync(file.path)).digest('hex')];-}-/*** Read this board's own revision inputs from one open connection, for the cache and the watcher alike.* nextExpiry is the earliest live claim or review lease, when a lease turns over with no write.@@ -455,7 +430,7 @@ function snapshotEntry(revision, state, preparedFlow, { inputs = null, itemMeta}/** State fields every delta carries whole: this request's unread count and flow, and the small Needs-you lists. */-const DELTA_WHOLE = new Set(['unseen', 'proofStats', 'decisions', 'decisionQueue', 'holds', 'requests', 'personRequests']);+const DELTA_WHOLE = new Set(['observedAt', 'unseen', 'proofStats', 'decisions', 'decisionQueue', 'holds', 'requests', 'personRequests']);/** The state lists a delta merges entry by entry, and the field that names each entry. */const DELTA_KEYS = Object.freeze({ items: 'id', shouts: 'shout_id', asked: 'shout_id', events: 'event_id', agents: 'agent_id', spec: 'id', practice: 'id', milestones: 'name' });/** How many recent builds of each board a server keeps as possible delta bases. */@@ -521,23 +496,23 @@ function stateDelta(bases, current, state) {}/** Add the request-specific unread count without mutating the reusable snapshot. */-function stateForRequest(state, root, seen, preparedFlow, refreshFlow, isMain) {+function stateForRequest(state, root, seen, preparedFlow, refreshFlow, isMain, observedAt) {const projection = seen === null ? { unseen: null } : withBoard(root, (board) => ({unseen: { since: seen, count: board.db.prepare('SELECT COUNT(*) AS n FROM shout WHERE shout_id > ?').get(seen).n },}), isMain);if (refreshFlow && preparedFlow) {projection.proofStats = {...state.proofStats,- flow: projectFlowStats(preparedFlow, null, Date.now(), state.proofStats),+ flow: projectFlowStats(preparedFlow, null, observedAt, state.proofStats),};}- return { ...state, ...projection };+ return { ...state, ...projection, observedAt: new Date(observedAt).toISOString() };}/** Cache JSON fragments for state fields whose values stay fixed across a cache hit. */function prepareStateJson(state) {const fields = Object.entries(state).map(([key, value]) => {- if (key === 'unseen') return { dynamic: key };+ if (key === 'unseen' || key === 'observedAt') return { dynamic: key };if (key === 'proofStats') {const stats = Object.entries(value).filter(([name]) => name !== 'flow').map(([name, entry]) => jsonField(name, entry)).filter(Boolean);return { dynamic: key, stats };@@ -567,7 +542,7 @@ function serializeState(state, fields, reportJson) {if (!fields) return JSON.stringify(state);const encoded = fields.map((field) => {if (field.static !== undefined) return field.static;- if (field.dynamic === 'unseen') return jsonField('unseen', state.unseen);+ if (field.dynamic === 'unseen' || field.dynamic === 'observedAt') return jsonField(field.dynamic, state[field.dynamic]);if (field.dynamic === 'proofStats') {const value = state.proofStats?.flow;const flow = reportJson === undefined || !value ? jsonField('flow', value)@@ -788,9 +763,10 @@ function isLiteralIPv4(host) {}/** Share the local router with the person's view and other local transports; the standalone API explicitly denies person authority.- * @param {{ secret: string | Buffer, getPort: () => number, runCommand: Function, projects?: () => any[], scope?: { projectRoot: string }, isMain?: boolean, allowedOrigins?: string[], allowedHosts?: string[], onStateBuild?: Function, onItemBuild?: Function, personChannel?: string, stateDetail?: string, sessionCookie?: {name:string,value:string} }} [options]+ * @param {{ secret: string | Buffer, getPort: () => number, runCommand: Function, projects?: () => any[], scope?: { projectRoot: string }, isMain?: boolean, allowedOrigins?: string[], allowedHosts?: string[], onStateBuild?: Function, onItemBuild?: Function, personChannel?: string, stateDetail?: string, now?: () => number, sessionCookie?: {name:string,value:string} }} [options]*/-export function createLocalApiHandler({ secret, getPort, runCommand, projects = listApiProjects, scope, isMain, allowedOrigins = [], allowedHosts = [], onStateBuild, onItemBuild, personChannel = 'view', stateDetail = 'full', sessionCookie } = {}) {+export function createLocalApiHandler({ secret, getPort, runCommand, projects = listApiProjects, scope, isMain, allowedOrigins = [], allowedHosts = [], onStateBuild, onItemBuild, personChannel = 'view', stateDetail = 'full', sessionCookie, now = Date.now } = {}) {+ if (typeof now !== 'function') throw new TypeError('createLocalApiHandler needs an observation clock');if (typeof getPort !== 'function') throw new TypeError('createLocalApiHandler needs a bound-port getter');if (typeof runCommand !== 'function') throw new TypeError('createLocalApiHandler needs the actual CLI entry point as runCommand');// A page that still reads each item's detail from the state keeps full items until it opts in.@@ -850,7 +826,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =* Read the current board build through `read(entry, cached)`, reusing the cached build while every* input revision holds before and after the read, and building it again when one moved.*/- function withSnapshot(board, read) {+ function withSnapshot(board, read, observedAt = now()) {const before = boardStateRevision(board.root, board.id, codeIsMain, { projects: apiProjects, scopeCommonDir });const cached = stateCache.get(before.cacheId);if (before.cacheable && cached?.revision === before.revision) {@@ -875,6 +851,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =onItemBuild,projects: apiProjects,scopeCommonDir,+ observedAt,}), codeIsMain);const state = { ...built.state, sequence: built.sequence };const entry = snapshotEntry(before.revision, state, prepareFlowHistory(built.history), {@@ -896,15 +873,16 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =}/** Return item summaries or every item in full, as asked or by this server's default, and the JSON for either. */function localState(board, seen, { detail = null } = {}) {+ const observedAt = now();const full = (detail ?? stateDetail) === 'full';const sent = withSnapshot(board, (entry, cached) => {- const state = stateForRequest(full ? entry.state : entry.summary, board.root, seen, entry.preparedFlow, cached, codeIsMain);+ const state = stateForRequest(full ? entry.state : entry.summary, board.root, seen, entry.preparedFlow, cached, codeIsMain, observedAt);// Full fragments wait for the first full request, so a server sending summaries never builds them.const fields = full ? (entry.stateJsonFields ??= prepareStateJson(entry.state)) : entry.summaryFields;const reportValidator = reportValidation(entry);const validator = serializeState(state, fields, entry.reportValidator.json) + '\0report-expiry:' + reportValidator;return { state, json: serializeState(state, fields), validator, reportValidator, entry };- });+ }, observedAt);// Only the build actually returned is sent; a delta extends summaries, never a full state.if (!full) keepSentBase(sent.entry);return sent;@@ -915,9 +893,10 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =* names why instead of guessing; a delta's result is what the client then holds, so it is kept.*/function localDelta(board, seen, { since, eventLogVersion = null }) {+ const observedAt = now();/** One build's answer: its delta from the summary states sent at `since`, or a reset naming why there is none. */const answerFor = (entry, cached) => {- const state = stateForRequest(entry.summary, board.root, seen, entry.preparedFlow, cached, codeIsMain);+ const state = stateForRequest(entry.summary, board.root, seen, entry.preparedFlow, cached, codeIsMain, observedAt);const answer = { since, sequence: entry.sequence, eventLogVersion: store.EVENT_LOG_VERSION };const path = '/api/v1/boards/' + board.id + '/state';/** Tell the client to load a fresh snapshot, and why. */@@ -931,7 +910,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =if (!bases.length) return reset('BASE_NOT_KEPT', `this server keeps no snapshot it sent at event ${since}; use GET ${path} for a fresh snapshot`);return { ...answer, delta: stateDelta(bases, entry.print, state) };};- const sent = withSnapshot(board, (entry, cached) => ({ entry, answer: answerFor(entry, cached) }));+ const sent = withSnapshot(board, (entry, cached) => ({ entry, answer: answerFor(entry, cached) }), observedAt);if (sent.answer.delta) keepSentBase(sent.entry);return Object.defineProperty(sent.answer, 'reportValidator', { value: reportValidation(sent.entry) });}@@ -1078,11 +1057,11 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =* Serve the RFC 0002 API only on loopback, behind the same session-secret boundary as the view. Its* state sends item summaries unless asked for detail=full; each item's detail has its own path (A2).*/-export function serveApi({ port = 0, secret = randomBytes(18).toString('base64url'), runCommand, projects = listApiProjects, isMain, onStateBuild, onItemBuild, stateDetail = 'summary' } = {}) {+export function serveApi({ port = 0, secret = randomBytes(18).toString('base64url'), runCommand, projects = listApiProjects, isMain, onStateBuild, onItemBuild, stateDetail = 'summary', now = Date.now, scope } = {}) {if (typeof runCommand !== 'function') throw new TypeError('serveApi needs the actual CLI entry point as runCommand');let bound;// A serve key authenticates board access, never a person, even in an ordinary terminal.- const handler = createLocalApiHandler({ secret, getPort: () => bound, runCommand, projects, isMain, onStateBuild, onItemBuild, personChannel: 'api', stateDetail });+ const handler = createLocalApiHandler({ secret, getPort: () => bound, runCommand, projects, isMain, onStateBuild, onItemBuild, personChannel: 'api', stateDetail, now, scope });const server = createServer(handler);server.requestTimeout = 15_000;return new Promise((ready, fail) => {diff --git a/src/native-board-state.js b/src/native-board-state.jsindex dc8d69a9..bc30e7d9 100644--- a/src/native-board-state.js+++ b/src/native-board-state.js@@ -1,4 +1,11 @@/** One complete native state builder for local HTTP and sealed relay projections [A2,H5,H16]. */+import { createHash } from 'node:crypto';+import { existsSync } from 'node:fs';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { CONFIG_FILE } from './config.js';+import { fitFile } from './blueprint-fit.js';+import { BLOCKS_FILE } from './blocks.js';import * as store from './board.js';import { displayAgentName } from './agent-names.js';import { COORDINATOR } from './config.js';@@ -22,7 +29,9 @@ import { projectState } from './serve.js';import { personRequestStatuses } from './relay-requests.js';/** Build the complete local API state, including fields that the shared project snapshot omits. */-export function buildLocalBoardState(root, boardId, board, codeIsMain, { previous = null, fullItemRebuild = true, afterSequence = 0, changedLeases = new Set(), onItemBuild, projects = listApiProjects, scopeCommonDir = null } = {}) {+export function buildLocalBoardState(root, boardId, board, codeIsMain, { previous = null, fullItemRebuild = true, afterSequence = 0, changedLeases = new Set(), onItemBuild, projects = listApiProjects, scopeCommonDir = null, observedAt = Date.now() } = {}) {+ if (!Number.isSafeInteger(observedAt) || observedAt < 0) throw new TypeError('native projection needs an observation timestamp');+ board = Object.assign(Object.create(board), { clock: { ...board.clock, now: () => new Date(observedAt) } });board.db.exec('BEGIN');try {const sequence = board.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id;@@ -65,6 +74,7 @@ export function buildLocalBoardState(root, boardId, board, codeIsMain, { previou} });state.agents = state.agents.map((agent) => ({ ...agent, model: agent.agent_model ?? 'unknown', displayName: displayAgentName(agent, config.agents.names) }));state.board = boardId;+ state.observedAt = new Date(observedAt).toISOString();state.decisionQueue = store.openDecisions(board, COORDINATOR);const projectData = {requests: store.openRequests(board),@@ -73,7 +83,7 @@ export function buildLocalBoardState(root, boardId, board, codeIsMain, { previou? milestoneRoadmap(root, board): milestoneRoadmap(root, board, { projects, hideOutOfScope: true }),rowDecisions: store.rowDecisions(board),- proofStats: proofStats(board),+ proofStats: proofStats(board, { now: observedAt }),};state.proofStats = projectData.proofStats;state.requests = projectData.requests;@@ -119,3 +129,24 @@ export function dependencyIds(item) {return item.item_after ? item.item_after.split(',').map(Number) : [];}++/** Name project and built-in files separately, even when their basenames collide. */+export function stateFileInputs(root, config) {+ return [+ { name: `config:${CONFIG_FILE}`, path: join(root, CONFIG_FILE) },+ { name: `spec:${config.spec}`, path: join(root, config.spec) },+ { name: `practice:${config.practice}`, path: join(root, config.practice) },+ { name: 'builtin:standard-doctrine.md', path: new URL('./standard-doctrine.md', import.meta.url) },+ ...['signoffs.jsonl', 'signers', 'first-commit', 'signers.initial'].map(name => ({ name: `approval:${name}`, path: join(root, '.pullboard', name) })),+ { name: 'fit:blueprint-fit.json', path: fitFile(repoInfo(root).commonDir) },+ // A new block changes Needs you without a board move, so the ledger is a state input [C6].+ { name: 'blocks:blocks.jsonl', path: join(repoInfo(root).commonDir, BLOCKS_FILE) },+ ];+}++/** Hash the exact bytes of one named input, preserving a missing-file marker. */+export function fileRevision(file) {+ if (!existsSync(file.path)) return [file.name, null];+ return [file.name, createHash('sha256').update(readFileSync(file.path)).digest('hex')];+}+diff --git a/src/relay-presentation.js b/src/relay-presentation.jsindex 01f83f8b..a855e17e 100644--- a/src/relay-presentation.js+++ b/src/relay-presentation.js@@ -10,40 +10,43 @@ import {} from './git.js';import { Refused } from './refused.js';import { loadConfig } from './config.js';-import { projectState } from './serve.js';-import { personNeeds } from './needs.js';-import { personBlockWords } from './blocks.js';-import { personRequestStatuses } from './relay-requests.js';-import {- cachedVerdictStates,- verdictProjector,-} from './verdict-freshness.js';+import { buildLocalBoardState } from './native-board-state.js';+import { stateFileInputs } from './native-board-state.js';+import { fileRevision } from './native-board-state.js';+import { resolveCommit } from './git.js';import { trunkRevisionReader } from './trunk-revision.js';+// A comparison clock is an internal fingerprint input, never a displayed forecast or observation.+const COMPARISON_CLOCK = Date.UTC(2000, 0, 1);+/** Capture spec, doctrine, config and board presentation without sending plaintext to a relay. */-export function relayPresentation(root, { board: providedBoard = null } = {}) {- return withGitReadFacts(() => readRelayPresentation(root, providedBoard));+export function relayPresentation(root, { board: providedBoard = null, observedAt = Date.now() } = {}) {+ return withGitReadFacts(() => readRelayPresentation(root, providedBoard, observedAt));}-/** One presentation read, using the supplied staged board without sharing its derived cache. */-function readRelayPresentation(root, providedBoard) {+/** Build both clocks through the same pure projection; only the actual observation is emitted as state. */+function readRelayPresentation(root, providedBoard, observedAt) {const info = repoInfo(root);- const board = providedBoard ?? store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });+ const isMain = codeIsFromMain();+ const board = providedBoard ?? store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain });try {- const projected = projectState(root, { board });- // The sealed page's Needs you carries the person's blocks, in plain words with no local path [C6].- const blocks = personBlockWords(info.commonDir, (board.clock ?? store.systemClock).now());- const state = { ...projected, blocks, needs: personNeeds({ ...projected, blocks }) };- const freshness = providedBoard- ? verdictProjector(root, board, { main: trunkRevisionReader(info)() }).state- : cachedVerdictStates(root, board, info);- const derived = new Map(store.listItems(board, { all: true }).map(item => [item.item_id, freshness(item)]));- state.items = state.items.map(item => {- const verdictState = derived.get(item.id);- return verdictState ? { ...item, verdictState } : item;- });- return { version: 1, state: { ...store.projectItemThreads(board, state), personRequests: personRequestStatuses(board) }, config: loadConfig(root), shouts: store.allShouts(board) }; }- finally { if (!providedBoard) store.closeBoard(board); }+ const boardId = store.boardId(board);+ const config = loadConfig(root);+ const projects = () => [{ root: info.root, name: config.name, project: config.project }];+ /** Preserve a single authorized board, including existing unavailable external milestone entries. */+ const project = (clock) => {+ const built = buildLocalBoardState(root, boardId, board, isMain, { projects, scopeCommonDir: info.commonDir, observedAt: clock });+ return { ...built.state, sequence: built.sequence };+ };+ const state = project(observedAt);+ const comparison = project(COMPARISON_CLOCK);+ // exportBoard omits only derived proof counters and machine-local landing lease cache rows.+ // Exact source bytes also retain expired/hidden business inputs that a fixed-clock view may omit.+ const inputs = { native: exportBoard(board), files: stateFileInputs(root, config).map(fileRevision),+ head: resolveCommit(root, 'HEAD'), trunk: trunkRevisionReader(info)(), config };+ const changeFingerprint = createHash('sha256').update(JSON.stringify({ inputs, comparison })).digest('hex');+ return { version: 1, state, config, shouts: store.allShouts(board), changeFingerprint };+ } finally { if (!providedBoard) store.closeBoard(board); }}/** Resolve one shout from the complete history carried only inside the sealed presentation. */export function relayPresentationShout(root, id) {@@ -61,7 +64,9 @@ export function presentationShout(presentation, id) {/** Notice presentation-only changes, including a spec or doctrine edit without a board move. */export function presentationDigest(presentation) {- return createHash('sha256').update(JSON.stringify(presentation)).digest('hex');+ return /^[a-f0-9]{64}$/u.test(presentation?.changeFingerprint ?? '')+ ? presentation.changeFingerprint+ : createHash('sha256').update(JSON.stringify(presentation)).digest('hex');}/** Capture importable native tables beside matching API presentation, retrying a concurrent local move. */diff --git a/test/relay-parity-fixture.js b/test/relay-parity-fixture.jsindex 6151be2e..11bcf5c6 100644--- a/test/relay-parity-fixture.js+++ b/test/relay-parity-fixture.js@@ -1,7 +1,8 @@/** 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 } from 'node:fs';+import { readFileSync, 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';@@ -10,6 +11,9 @@ 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';import { relayClientFixture } from './relay-client-fixture.js';/** Only the native filesystem routing identity differs deliberately from the relay board identity. */@@ -50,19 +54,47 @@ export function seedParityBoard(root, lane) {} finally { store.closeBoard(board); }}+/** Clock advancement alone is not a board change, while a real native mutation always is. */+function assertPresentationChangeClock(root, item) {+ const first = relayPresentation(root, { observedAt: Date.UTC(2026, 0, 1) });+ const later = relayPresentation(root, { observedAt: Date.UTC(2026, 0, 2) });+ assert.notEqual(first.state.observedAt, later.state.observedAt, 'emitted observations retain their actual caller clock');+ assert.equal(presentationDigest(first), presentationDigest(later), 'an unchanged board does not publish merely because its clock advanced');+ const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'));+ try { store.editItem(board, item, { agentId: 'coordinator', brief: 'Business input changed after the clock-only observation.' }); }+ finally { store.closeBoard(board); }+ const changed = relayPresentation(root, { observedAt: Date.UTC(2026, 0, 2) });+ assert.notEqual(presentationDigest(later), presentationDigest(changed), 'a real business mutation changes the fingerprint at the same observation clock');+}++/** Give a scoped board a genuine foreign milestone target whose private title must stay outside its key. */+function foreignBoardFixture(t, box) {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-parity-foreign-'));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ assert.equal(runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: root, env: box.env, encoding: 'utf8' }).status, 0);+ mkdirSync(join(root, '.git', 'pullboard'), { recursive: true });+ const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'));+ const secret = 'Foreign board private title must never enter another board snapshot';+ let id;+ try {+ store.ensureCoordinator(board, root);+ id = store.addItem(board, { by: 'coordinator', lane: box.lane, title: secret, criterion: 'Private second-board work' });+ } finally { store.closeBoard(board); }+ const own = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));+ try { store.addMilestone(own, { agentId: 'coordinator', name: 'Cross-board privacy', items: [`foreign-parity#${id}`] }); }+ finally { store.closeBoard(own); }+ return { root, name: 'foreign-parity', secret };+}+/** Capture full API state and independently reconstruct the sealed API2 snapshot over actual authenticated HTTP. */-export async function parityRoundtrip(t) {+export async function parityRoundtrip(t, { foreign = false } = {}) {const box = await relayClientFixture(t);const seeded = seedParityBoard(box.root, box.lane);+ const other = foreign ? foreignBoardFixture(t, box) : null;+ assertPresentationChangeClock(box.root, seeded.item);await box.link();const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());- const secret = randomBytes(24).toString('base64url');- const api = await serveApi({ secret, runCommand: main, projects: () => [{ root: box.root, name: 'parity' }], isMain: true, stateDetail: 'full' });- 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 session = await box.phoneSession();/** Request through a distinct authenticated person session, never a direct journal read. */async function request(path) {@@ -82,5 +114,20 @@ export async function parityRoundtrip(t) {}, { 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;+ 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');+ assert.ok(scoped, 'the cross-board milestone remains visible');+ 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 };}diff --git a/test/relay-parity.test.js b/test/relay-parity.test.jsindex cb646fda..85c6fcf1 100644--- a/test/relay-parity.test.js+++ b/test/relay-parity.test.js@@ -13,3 +13,9 @@ test('a field that differs between native and relay readers is refused, naming t&& error.message.includes('native=') && error.message.includes('relay=<missing>'), 'the deliberate heartbeat removal names its exact field and both values');assertReaderParity(native, relay);});+++test('single-board parity never seals another board title through a milestone reference [H5,H16,A2]', { timeout: 60_000 }, async t => { // budget: the same real transport and cleanup ceiling as the parity guard.+ const { native, relay } = await parityRoundtrip(t, { foreign: true });+ assertReaderParity(native, relay);+});