Skip to content

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.

chore(merge): integrate accepted per-agent relay tokens [H2,H9]

Corey Olson5e0ac6a9bc8b
diff --cc src/api-http.js
index 3b938ba3,fa4518d3..2644298b
--- a/src/api-http.js
+++ b/src/api-http.js
@@@ -104,27 -104,23 +104,36 @@@ export function createApiHandler(adapte
try {
let url;
try { url = new URL(req.url ?? '/', 'http://127.0.0.1'); } catch { throw new Refused('BAD_REQUEST', 'use a valid path under /api/v1/boards'); }
- const route = /^\/api\/v1\/boards\/([^/]+)\/(state|events|moves|requests|code)$/.exec(url.pathname);
+ const route = /^\/api\/v1\/boards\/([^/]+)\/(state|events|moves|requests|code|tokens)$/.exec(url.pathname);
- const who = await adapter.authenticate(req, { board: route?.[1] ?? null, write: req.method === 'POST' });
+ const shoutRoute = /^\/api\/v1\/boards\/([^/]+)\/shouts\/([^/]+)$/.exec(url.pathname);
+ const boardId = route?.[1] ?? shoutRoute?.[1] ?? null;
+ const who = await adapter.authenticate(req, { board: boardId, write: req.method === 'POST' });
if (req.method === 'GET' && url.pathname === '/api/v1/boards') {
const listing = await adapter.boards(who);
return json(res, 200, Array.isArray(listing) ? { boards: listing } : listing);
}
- if (!route) return json(res, 404, refusal(new Refused('NO_ENDPOINT', 'no API v1 endpoint here; use /api/v1/boards and a board state, code, events, moves or requests path')));
- const board = await adapter.board(route[1], who);
+ if (!route && !shoutRoute) return json(res, 404, refusal(new Refused('NO_ENDPOINT', 'no API v1 endpoint here; use /api/v1/boards and a board state, shout, code, events, moves or requests path')));
+ const board = await adapter.board(boardId, who);
+ if (req.method === 'GET' && shoutRoute) {
+ const rawId = shoutRoute[2];
+ if (!/^[1-9]\d*$/.test(rawId) || !Number.isSafeInteger(Number(rawId))) throw new Refused('BAD_REQUEST', 'shout needs a positive integer id; use the id from the event or recent state');
+ if (typeof adapter.shout !== 'function') throw new Refused('SHOUT_NOT_AVAILABLE', 'this API adapter does not provide addressed shout reads');
+ return json(res, 200, { shout: await adapter.shout(board, Number(rawId), who) });
+ }
+ if (shoutRoute) throw new Refused('BAD_REQUEST', 'read an addressed shout with GET; use a board move to create or answer shouts');
+ if (route[2] === 'tokens') {
+ if (typeof adapter.tokens !== 'function' || typeof adapter.revokeToken !== 'function') {
+ throw new Refused('TOKENS_NOT_AVAILABLE', "manage this board's agent tokens in its local view or signed-in relay account");
+ }
+ if (req.method === 'GET') return json(res, 200, { tokens: await adapter.tokens(board, who) });
+ if (req.method === 'POST') {
+ const body = await readBody(req);
+ if (Object.keys(body).some((key) => key !== 'id') || typeof body.id !== 'string') {
+ throw new Refused('BAD_REQUEST', "token revocation takes only the opaque id from this board's token list");
+ }
+ return json(res, 200, await adapter.revokeToken(board, body.id, who));
+ }
+ }
if (req.method === 'GET' && route[2] === 'state') {
const seen = url.searchParams.has('seen') ? seenCursor(url.searchParams.get('seen')) : null;
const state = await adapter.state(board, who, seen);
diff --cc src/cli.js
index 1b4bfdba,bd621475..dd20b1d0
--- a/src/cli.js
+++ b/src/cli.js
@@@ -56,7 -61,8 +61,8 @@@ import { proofStats } from './stats.js'
import { exportBoard, importBoard } from './exchange.js';
import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';
import { loadMachineSettings, setGateSlots } from './settings.js';
- import { relayLinked, relayOff, relayOn, relayOperation, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';
-import { relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecovered, relayStatus, syncRelay } from './relay.js';
++import { relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';
+ import { executePersonRequests } from './relay-request-execution.js';
const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
export const VERSION = PACKAGE.version;
@@@ -1976,22 -2388,9 +2395,22 @@@ async function runCommand(argv, io)
if (command === 'hook') return await hookCommand(io, args);
if (command === 'settings') return settingsCommand(io, args);
if (command === 'relay') {
+ if (['tokens', 'revoke'].includes(first)) {
+ if (rest.length || values.url || (first === 'tokens' && second) || (first === 'revoke' && !second)) {
+ throw new Refused('USAGE', 'pullboard relay tokens, or pullboard relay revoke <token-id>');
+ }
+ const ctx = context(io);
+ const result = first === 'tokens' ? await relayTokens(ctx.info.root, io) : await relayRevoke(ctx.info.root, second, io);
+ io.result?.(result);
+ if (first === 'tokens') {
+ if (!result.tokens.length) io.say('no agent tokens on this board');
+ for (const row of result.tokens) io.say(row.id + ' ' + row.agent + ' ' + (row.revoked ? 'revoked' : 'expires ' + new Date(row.expires).toISOString()));
+ } else io.say('revoked token ' + result.id + '; other agent tokens are unchanged');
+ return 0;
+ }
if (second || rest.length || (first && !['on', 'off'].includes(first)) || (values.url && first !== 'on')) throw new Refused('USAGE', 'pullboard relay [on|off] [--url <address>]');
const ctx = context(io);
- if (!first) await syncRelay(ctx.info.root, io);
+ if (!first) { await syncRelay(ctx.info.root, io); await executePersonRequests(ctx.info.root, io, main); }
const result = first === 'on' ? await relayOn(ctx.info.root, values.url, io)
: first === 'off' ? await relayOff(ctx.info.root, io) : relayStatus(ctx.info.root);
io.result?.(result);
diff --cc src/relay.js
index c74fcc4c,853fa7a3..0d0f4e90
--- a/src/relay.js
+++ b/src/relay.js
@@@ -4,7 -4,7 +4,8 @@@ import { existsSync, lstatSync, mkdirSy
import { dirname, join } from 'node:path';
import * as store from './board.js';
import { exportBoard, restoreRelaySnapshot } from './exchange.js';
- import { appliedSequence, applyEngineMove, checkpointSequence, engineReceipt, engineActor, prepareEngineMove, startRelayEpoch } from './engine.js';
+ import { appliedSequence, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, requireSupportedEngine, startRelayEpoch } from './engine.js';
++import { relayMoveActor } from './relay-sender.js';
import { ENGINE_VERSION } from './machine.js';
import { presentationDigest, relayPresentation, relaySnapshot } from './relay-presentation.js';
import { repoInfo, tryGit } from './git.js';
@@@ -121,7 -119,7 +124,7 @@@ async function request(state, path, { m
try {
response = await fetch(relayOrigin(state.url) + path, {
method, redirect: 'error', signal: AbortSignal.timeout(10000),
- headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
- headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(state.token ? { authorization: 'Bearer ' + state.token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
++ headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(token ? { authorization: 'Bearer ' + token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
} catch { throw new Refused('RELAY_UNAVAILABLE', `the relay ${state.url} did not answer; read the local board offline, then retry this move when the relay is reachable`); }
@@@ -322,8 -362,7 +368,8 @@@ async function sendPending(root, file,
for (let tries = 0; state.pending && tries < 100; tries += 1) {
const pending = state.pending;
try {
- const transport = await actorTransport(root, file, state, engineActor(pending.move.operation, pending.move.args), io);
- const reply = await request(state, '/api/v1/boards/' + state.board + '/moves', { method: 'POST', body: { sequence: pending.sequence, sealed: pending.sealed } }, io);
++ const transport = await actorTransport(root, file, state, credentialActor(pending.move), io);
+ const reply = await request(transport, '/api/v1/boards/' + state.board + '/moves', { method: 'POST', body: { sequence: pending.sequence, sealed: pending.sealed } }, io);
if (reply.event?.event_id !== pending.sequence || reply.event.sealed !== pending.sealed) throw new Refused('RELAY_RESPONSE', 'the relay acknowledgement differs from this executable send; fetch the configured relay');
} catch (error) {
if (!['SEQUENCE_REPEAT', 'SEQUENCE_GAP'].includes(error.code)) throw error;
@@@ -340,46 -379,40 +386,87 @@@
if (state.pending) throw new Refused('RELAY_BUSY', 'the relay order stayed busy; retry this command after other clients finish');
}
++/** Choose credentials only; main's relay sender policy remains the sole replay authorization. */
++function credentialActor(move) {
++ const args = move.args;
++ if (move.personRequest || ['register', 'ensureCoordinator', 'recordRowDecisions'].includes(move.operation)
++ || move.operation === 'answerDecision' && args[1]?.asPerson
++ || move.operation === 'shout' && args[0]?.request) return 'person';
++ return relayMoveActor(move);
++}
++
+/** Select one scoped credential without renewing a revoked or expired agent cache. */
+async function actorTransport(root, file, state, actor, io) {
+ if (typeof actor !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/.test(actor)) {
+ throw new Refused('RELAY_ACTOR', 'name the registered agent performing this move before sending it');
+ }
++ if (actor === 'person') {
++ if (!state.token.startsWith('ps_')) throw new Refused('HUMAN_REQUIRED', 'sign in as a person to enroll an agent or answer as the person');
++ return state;
++ }
+ const supplied = process.env.PULLBOARD_RELAY_TOKEN;
+ if (supplied !== undefined) {
+ if (!/^pa_[A-Za-z0-9_-]{43}$/.test(supplied)) throw new Refused('AUTH_REQUIRED', 'supply a current scoped board token, without including it in command arguments');
+ const transport = { ...state, token: supplied, agent: actor };
+ const identity = await request(transport, '/auth/session?board=' + state.board, {}, io);
+ if (identity.session?.kind !== 'board' || identity.session.agent !== actor) throw new Refused('RELAY_ACTOR', 'use the scoped token belonging to this move’s registered agent');
+ return transport;
+ }
- if (actor === 'person') {
- if (!state.token.startsWith('ps_')) throw new Refused('HUMAN_REQUIRED', 'sign in as a person to enroll an agent or answer as the person');
- return state;
- }
+ if (state.token.startsWith('pa_')) {
+ const identity = await request(state, '/auth/session?board=' + state.board, {}, io);
+ if (identity.session?.agent !== actor) throw new Refused('RELAY_ACTOR', 'use the scoped token belonging to this move’s registered agent');
+ return { ...state, agent: actor };
+ }
+ state.agentTokens ??= {};
+ if (!state.agentTokens[actor]) {
+ if (!localRecords(root, (board) => store.listAgents(board).some((agent) => agent.agent_id === actor))) {
+ throw new Refused('RELAY_ACTOR', 'register this agent in the ordered board before obtaining its scoped token');
+ }
+ const issued = await request(state, '/auth/tokens', { method: 'POST', body: { board: state.board, agent: actor } }, io);
+ if (!/^pa_[A-Za-z0-9_-]{43}$/.test(issued.token) || issued.board !== state.board || issued.agent !== actor ||
+ typeof issued.id !== 'string' || !Number.isSafeInteger(issued.expires)) {
+ throw new Refused('RELAY_RESPONSE', 'the relay did not issue this agent’s scoped credential; ask the person to retry enrollment');
+ }
+ state.agentTokens[actor] = { id: issued.id, token: issued.token, expires: issued.expires };
+ saveLink(file, state);
+ }
+ return { ...state, token: state.agentTokens[actor].token, agent: actor };
+}
+
+ /** Compare caller intent without executing frozen callbacks or allocating another operation id. */
+ function operationIntent(operation, args) {
+ const values = Array.isArray(args) ? args.map((value, index) => {
+ if (!['claim', 'refreeze'].includes(operation) || index !== 1 || !value || typeof value !== 'object') return value;
+ const options = { ...value };
+ delete options.freeze;
+ delete options.frozen;
+ delete options.freezeError;
+ return options;
+ }) : args;
+ return JSON.stringify({ operation, args: values }, (_key, value) => typeof value === 'function' ? undefined : value);
+ }
+
+ /** Keep a recovered outcome until its caller repeats the interrupted operation to receive it. */
+ function recoveredMove(root, state, operation, args, command) {
+ if (!state.recovered) return null;
+ const recovered = state.recovered;
+ const intent = recovered.intent ?? operationIntent(recovered.move.operation, recovered.move.args);
+ const matches = recovered.commandIntent === undefined
+ ? intent === operationIntent(operation, args)
+ : recovered.move.operation === operation && recovered.commandIntent === operationIntent('cli:' + command?.cliOperation, command);
+ if (!matches) {
+ throw new Refused('RELAY_RETRY_PENDING', 'the previous move reached the relay; repeat that interrupted command to receive its original outcome before sending a different move');
+ }
+ const receipt = localRecords(root, (board) => engineReceipt(board, recovered.move.id));
+ if (!receipt) throw new Refused('RELAY_RESPONSE', 'the recovered operation has no replay receipt; fetch a consistent relay snapshot before retrying');
+ if (receipt.move !== JSON.stringify(recovered.move)) {
+ throw new Refused('RELAY_MOVE', 'the recovered operation differs from its durable receipt; restore consistent relay metadata before retrying');
+ }
+ return recovered.move;
+ }
+
/** Send one board operation before executing it locally, and report its canonical engine result. */
- export async function relayOperation(root, operation, args, io) {
+ export async function relayOperation(root, operation, args, io, command) {
const file = linkFile(root);
return locked(file, async () => {
const state = loadLink(file);
@@@ -390,14 -423,38 +477,39 @@@
delete state.pending;
saveLink(file, state);
}
- const move = localRecords(root, (board) => prepareEngineMove(board, operation, args, { actor: engineActor(operation, args) }));
- await actorTransport(root, file, state, move.actor, io);
- const sequence = state.sequence + 1;
- state.pending = { move, sequence, sealed: await sealedRecord(readBoardKey(state.board), move, state, 'move', sequence) };
- saveLink(file, state);
- await sendPending(root, file, state, io);
+ const previousReceipt = io.personRequestMoveId && localRecords(root, board => engineReceipt(board, io.personRequestMoveId));
+ if (previousReceipt) {
+ if (state.recovered?.move?.id === io.personRequestMoveId) {
+ delete state.recovered;
+ saveLink(file, state);
+ }
+ if (previousReceipt.outcome.error) throw new Refused(previousReceipt.outcome.error.code, previousReceipt.outcome.error.message);
+ for (const event of previousReceipt.outcome.events ?? []) io.onEvent?.(event);
+ return previousReceipt.outcome.result;
+ }
+ let move = recoveredMove(root, state, operation, args, command);
+ if (!move) {
+ move = localRecords(root, (board) => prepareEngineMove(board, operation, args, io.personRequestMoveId ? { id: io.personRequestMoveId } : {}));
+ if (io.personRequest) move.personRequest = structuredClone(io.personRequest);
++ move.actor = relayMoveActor(move) ?? credentialActor(move);
++ await actorTransport(root, file, state, credentialActor(move), io);
+ const sequence = state.sequence + 1;
+ state.pending = { move, intent: operationIntent(operation, args),
+ ...(command ? { command, commandIntent: operationIntent('cli:' + command.cliOperation, command) } : {}), sequence,
+ sealed: await sealedRecord(readBoardKey(state.board), move, state, 'move', sequence) };
+ saveLink(file, state);
+ try { await sendPending(root, file, state, io); }
+ catch (error) {
+ if (!['RELAY_UNAVAILABLE', 'RELAY_RESPONSE'].includes(error.code)) throw error;
+ // A lost acknowledgement can be recovered now without asking the caller to retry side effects.
+ try { await catchUp(root, file, state, io); } catch { throw error; }
+ if (!localRecords(root, (board) => engineReceipt(board, move.id))) throw error;
+ }
+ }
-
const receipt = localRecords(root, (board) => engineReceipt(board, move.id));
if (!receipt) throw new Refused('RELAY_RESPONSE', 'the acknowledged operation has no replay receipt; fetch a consistent relay snapshot');
+ delete state.recovered;
+ saveLink(file, state);
// A phone can read a compacted checkpoint; failed presentation uploads do not undo the move.
try { await publishCheckpoint(root, file, state, io); }
catch (error) { if (!(error instanceof Refused)) throw error; io.err(`pullboard: ${error.message}`); }
@@@ -441,54 -497,48 +553,95 @@@ export async function syncRelay(root, i
});
}
+/** Return token-management context without opening a board-key pairing link or exposing any credential. */
+function tokenContext(state) {
+ return { linked: true, board: state.board, url: state.url, link: '', sequence: state.sequence, behind: 0 };
+}
+
+/** Require the signed-in person's existing link before listing or revoking scoped agent credentials. */
+function managementLink(file) {
+ const state = loadLink(file);
+ if (!state || state.unlinking) throw new Refused('RELAY_OFF', 'link this board with pullboard relay on before managing its agent tokens');
+ return state;
+}
+
+/** List only this person's current board-token metadata, never bearer values or the board key. */
+export async function relayTokens(root, io) {
+ const file = linkFile(root);
+ return locked(file, async () => {
+ const state = managementLink(file);
+ const listed = await request(state, '/auth/tokens?board=' + state.board, {}, io);
+ if (!Array.isArray(listed.tokens) || listed.tokens.some((row) => !row || row.board !== state.board ||
+ typeof row.id !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(row.id) ||
+ typeof row.agent !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/.test(row.agent) ||
+ !Number.isSafeInteger(row.expires) || (row.created !== null && !Number.isSafeInteger(row.created)) ||
+ typeof row.revoked !== 'boolean')) throw new Refused('RELAY_RESPONSE', 'the relay token inventory is invalid; retry its configured address');
+ const tokens = listed.tokens.map(({ id, board, agent, created, expires, revoked }) => ({ id, board, agent, created, expires, revoked }));
+ return { ...tokenContext(state), tokens };
+ });
+}
+
+/** Revoke one credential listed on this board while retaining its cache so it cannot be silently reminted. */
+export async function relayRevoke(root, id, io) {
+ if (typeof id !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id)) {
+ throw new Refused('TOKEN_NOT_OWNED', 'name an opaque token id from pullboard relay tokens, never a credential value');
+ }
+ const file = linkFile(root);
+ return locked(file, async () => {
+ const state = managementLink(file);
+ const listed = await request(state, '/auth/tokens?board=' + state.board, {}, io);
+ if (!Array.isArray(listed.tokens) || !listed.tokens.some((row) => row.id === id)) {
+ throw new Refused('TOKEN_NOT_OWNED', 'choose a token listed on this board by pullboard relay tokens');
+ }
+ const result = await request(state, '/auth/tokens/revoke', { method: 'POST', body: { id } }, io);
+ if (result.id !== id || result.revoked !== true) throw new Refused('RELAY_RESPONSE', 'the relay did not acknowledge this token revocation; retry its opaque id');
+ for (const credential of Object.values(state.agentTokens ?? {})) if (credential.id === id) credential.revoked = true;
+ saveLink(file, state);
+ return { ...tokenContext(state), id: result.id, revoked: result.revoked };
+ });
+}
+
+ /** Read an acknowledged exact CLI result before changed spec, brief or Git refs can block it. */
+ export async function relayCommandReceipt(root, command) {
+ if (!command) return null;
+ const file = linkFile(root);
+ return locked(file, async () => {
+ const state = loadLink(file);
+ if (!state || state.unlinking) return null;
+ const recovered = state.recovered;
+ if (!recovered || recovered.commandIntent !== operationIntent('cli:' + command.cliOperation, command)) return null;
+ if (recovered.commandIntent !== operationIntent('cli:' + recovered.command?.cliOperation, recovered.command)) {
+ throw new Refused('RELAY_STORAGE', 'restore the interrupted command metadata before retrying');
+ }
+ const expected = { add: 'addItem', edit: 'editItem', merged: 'merged' }[command.cliOperation];
+ if (!recovered.move || recovered.move.operation !== expected) throw new Refused('RELAY_STORAGE', 'restore the interrupted command metadata before retrying');
+ const move = recoveredMove(root, state, recovered.move.operation, recovered.move.args, command);
+ const receipt = localRecords(root, board => engineReceipt(board, move.id));
+ if (receipt.outcome.error) {
+ delete state.recovered;
+ saveLink(file, state);
+ throw new Refused(receipt.outcome.error.code, receipt.outcome.error.message);
+ }
+ return { result: receipt.outcome.result, events: receipt.outcome.events ?? [], move };
+ });
+ }
+
+ /** Consume the exact cached result after its original CLI outcome has been formatted. */
+ export async function relayCommandReceiptReported(root, moveId) {
+ const file = linkFile(root);
+ return locked(file, async () => {
+ const state = loadLink(file);
+ if (state?.recovered?.move?.id === moveId) {
+ delete state.recovered;
+ saveLink(file, state);
+ }
+ });
+ }
+
+ /** Expose only an unreported operation descriptor so CLI preconditions cannot strand its outcome. */
+ export function relayRecovered(root) {
+ return loadLink(linkFile(root))?.recovered?.move ?? null;
+ }
-
/** Read the local link and lag without opening a network connection or revealing its relay token. */
export function relayStatus(root) { return summary(root, loadLink(linkFile(root))); }
diff --cc test/engine.test.js
index d18e59eb,c541b85a..5f468393
--- a/test/engine.test.js
+++ b/test/engine.test.js
@@@ -58,75 -59,135 +59,221 @@@ function boardRows(board, itemId)
};
}
+test('authenticated relay senders bind every move and refusals preserve replica prefixes [H2,H9,H3,H16]', (t) => {
+ const { copies, item } = engineCopies(t);
+ const [one, two] = copies;
+ const claim = claimMove(one, item, 'web-1');
+ const actorlessClaim = { ...claim, id: 'actorless-person-claim' };
+ delete actorlessClaim.actor;
- const mismatchedArgs = prepareEngineMove(one, 'claim', claim.args, {
- id: 'sealed-actor-mismatch', actor: 'web-2',
++ const mismatchedArgs = prepareEngineMove(one, 'claim', [item, { ...claim.args[1], agentId: 'web-2' }], {
++ id: 'sealed-actor-mismatch', actor: 'web-1',
+ });
+ const personalAnswer = prepareEngineMove(one, 'answerDecision', [1, {
+ asPerson: true, agentId: 'coordinator', text: 'fixture answer', lanes: ['web'],
+ }], { id: 'agent-person-answer' });
+ const cases = [
- { move: actorlessClaim, sender: { kind: 'person', userId: 'fixture-user' } },
++ { move: actorlessClaim, sender: undefined, expected: 'RELAY_SENDER' },
+ { move: claim, sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-2' } },
+ { move: mismatchedArgs, sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' } },
+ { move: prepareEngineMove(one, 'register', [{ lane: 'web', path: '/fixture/enroll' }], { id: 'agent-enrollment' }), sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' } },
- { move: personalAnswer, sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' } },
++ { move: personalAnswer, sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' }, expected: 'RELAY_PERSON_ONLY' },
+ { move: prepareEngineMove(one, 'shout', [{ from: 'web-2', agentId: 'web-1', to: 'all', text: 'spoof', lanes: ['web'] }], { id: 'shadowed-shout', actor: 'web-1' }), sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' } },
+ { move: prepareEngineMove(one, 'addItem', [{ by: 'coordinator', agentId: 'web-1', lane: 'web', title: 'spoof' }], { id: 'shadowed-add', actor: 'web-1' }), sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' } },
+ ];
+
- cases.forEach(({ move, sender }, index) => {
++ cases.forEach(({ move, sender, expected = 'RELAY_SENDER_MISMATCH' }, index) => {
+ const sequence = index + 1;
+ for (const board of copies) {
+ const before = boardRows(board, item);
- const outcome = applyEngineMove(board, move, { sequence, at: CLAIM_AT, sender });
- assert.equal(outcome.error?.code, 'RELAY_ACTOR', `case ${index + 1} must refuse before native writes`);
- assert.deepEqual(boardRows(board, item), before, `case ${index + 1} leaves native rows/events unchanged`);
++ const outcome = applyRelayMove(board, move, { sequence, at: CLAIM_AT, kind: 'move', sender });
++ assert.equal(outcome.error?.code, expected, `case ${index + 1} must refuse before native writes`);
++ const after = boardRows(board, item);
++ assert.deepEqual(after.item, before.item, `case ${index + 1} leaves native item rows unchanged`);
++ assert.deepEqual(after.events.slice(0, -1), before.events, `case ${index + 1} preserves every prior event`);
++ assert.equal(after.events.length, before.events.length + 1, 'only the mandated refusal event is appended');
++ assert.equal(after.events.at(-1).event_kind, 'relay_refused');
++ assert.equal(after.events.at(-1).event_by, sender?.kind === 'agent' ? sender.agent : 'relay');
+ assert.equal(replayCursor(board), sequence, `case ${index + 1} commits the refusal prefix`);
+ }
+ });
+
+ const validClaim = { ...claim, id: 'valid-claim-after-refusals' };
+ const agent = { kind: 'agent', userId: 'fixture-user', agent: 'web-1' };
- const claimOne = applyEngineMove(one, validClaim, { sequence: cases.length + 1, at: CLAIM_AT, sender: agent });
- const claimTwo = applyEngineMove(two, validClaim, { sequence: cases.length + 1, at: CLAIM_AT, sender: agent });
++ const claimOne = applyRelayMove(one, validClaim, { sequence: cases.length + 1, at: CLAIM_AT, kind: 'move', sender: agent });
++ const claimTwo = applyRelayMove(two, validClaim, { sequence: cases.length + 1, at: CLAIM_AT, kind: 'move', sender: agent });
+ assert.deepEqual(claimOne, claimTwo);
+ assert.equal(store.getItem(one, item).item_owner, 'web-1');
+
+ const shout = prepareEngineMove(one, 'shout', [{ from: 'web-1', to: 'all', text: 'authenticated fixture', lanes: ['web'] }], { id: 'valid-shout-after-refusals' });
- const shoutOne = applyEngineMove(one, shout, { sequence: cases.length + 2, at: CLAIM_AT, sender: agent });
- const shoutTwo = applyEngineMove(two, shout, { sequence: cases.length + 2, at: CLAIM_AT, sender: agent });
++ const shoutOne = applyRelayMove(one, shout, { sequence: cases.length + 2, at: CLAIM_AT, kind: 'move', sender: agent });
++ const shoutTwo = applyRelayMove(two, shout, { sequence: cases.length + 2, at: CLAIM_AT, kind: 'move', sender: agent });
+ assert.deepEqual(shoutOne, shoutTwo);
+ assert.deepEqual(boardRows(one, item), boardRows(two, item), 'valid claim and shout replay identically after refusal prefix');
+ assert.equal(replayCursor(one), cases.length + 2);
+ assert.equal(replayCursor(two), cases.length + 2);
+});
+
++test('person sessions delegate native agent moves under the shared sender policy [H2,H9,H16]', (t) => {
++ const { copies, item } = engineCopies(t);
++ const move = claimMove(copies[0], item, 'web-1');
++ delete move.actor;
++ const outcomes = copies.map(board => applyRelayMove(board, move, {
++ sequence: 1, at: CLAIM_AT, kind: 'move', sender: { kind: 'person', userId: 'fixture-user' },
++ }));
++ assert.deepEqual(outcomes[0], outcomes[1]);
++ assert.equal(outcomes[0].error, undefined);
++ for (const board of copies) assert.equal(store.getItem(board, item).item_owner, 'web-1');
++});
++
+test('authenticated coordinator milestones replay and reject foreign sender identity [H2,H9,H3,H16]', (t) => {
+ const { copies, item } = engineCopies(t);
+ const [one, two] = copies;
+ const move = prepareEngineMove(one, 'addMilestone', [{ agentId: 'coordinator', name: 'Fixture milestone', items: [item] }], { id: 'coordinator-milestone', actor: 'coordinator' });
+ for (const board of copies) {
+ const before = store.milestones(board);
- const refused = applyEngineMove(board, move, { sequence: 1, at: CLAIM_AT, sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' } });
- assert.equal(refused.error?.code, 'RELAY_ACTOR');
++ const refused = applyRelayMove(board, move, { sequence: 1, at: CLAIM_AT, kind: 'move', sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' } });
++ assert.equal(refused.error?.code, 'RELAY_SENDER_MISMATCH');
+ assert.deepEqual(store.milestones(board), before, 'a foreign scoped token cannot change milestone metadata');
+ }
+ const valid = { ...move, id: 'valid-coordinator-milestone' };
+ const sender = { kind: 'agent', userId: 'fixture-user', agent: 'coordinator' };
- const outcomes = copies.map((board) => applyEngineMove(board, valid, { sequence: 2, at: CLAIM_AT, sender }));
++ const outcomes = copies.map((board) => applyRelayMove(board, valid, { sequence: 2, at: CLAIM_AT, kind: 'move', sender }));
+ assert.deepEqual(outcomes[0], outcomes[1]);
+ assert.equal(outcomes[0].error, undefined, 'the coordinator scoped token binds the native milestone actor');
+ assert.deepEqual(store.milestones(one), [{ name: 'Fixture milestone', note: null, items: [item] }]);
+ assert.deepEqual(store.milestones(one), store.milestones(two));
+ assert.deepEqual(store.events(one), store.events(two));
+});
+
+ test('person answer channel replays identically on agent and plain replicas [B26,H16]', t => {
+ const questions = [];
+ const { copies } = engineCopies(t, source => {
+ questions.push(...['view', 'terminal', 'legacy'].map(channel => store.shout(source, {
+ from: 'coordinator', to: 'person', text: 'Private engine fixture ' + channel,
+ decision: true, lanes: ['web'],
+ })));
+ });
+ const [one, two] = copies;
+ const markers = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'AI_AGENT', 'CODEX_THREAD_ID', 'CODEX_SESSION_ID', 'CODEX_CI', 'CODEX_SHELL'];
+ const original = markers.map(name => [name, process.env[name]]);
+ try {
+ questions.forEach((id, index) => {
+ const channel = ['view', 'terminal', undefined][index];
+ const move = prepareEngineMove(one, 'answerDecision', [id, {
+ agentId: 'coordinator', text: 'Approved private fixture', lanes: ['web'], asPerson: true,
+ ...(channel ? { channel } : {}),
+ }]);
+ for (const name of markers) process.env[name] = 'fixture-agent';
+ const agentReceipt = applyEngineMove(one, move, { sequence: index + 1, at: CLAIM_AT });
+ for (const name of markers) delete process.env[name];
+ const plainReceipt = applyEngineMove(two, move, { sequence: index + 1, at: CLAIM_AT });
+ assert.equal(Boolean(agentReceipt.error), false);
+ assert.deepEqual(agentReceipt, plainReceipt, 'replica execution ignores sender-shell markers');
+ assert.equal(JSON.parse(agentReceipt.events[0].event_detail).channel, channel ?? 'terminal');
+ });
+ assert.deepEqual(exportBoard(one).tables, exportBoard(two).tables);
+ } finally {
+ for (const [name, value] of original) {
+ if (value === undefined) delete process.env[name];
+ else process.env[name] = value;
+ }
+ }
+ });
+
+ test('missing relay senders are refused deterministically without poisoning a later legitimate move id [H2,H16]', t => {
+ const { copies, item } = engineCopies(t);
+ const [one, two] = copies;
+ const move = claimMove(one, item, 'web-1');
+ for (const board of copies) {
+ const before = store.getItem(board, item);
+ const refused = applyRelayMove(board, move, { sequence: 1, at: CLAIM_AT, kind: 'request' });
+ assert.equal(refused.error.code, 'RELAY_SENDER');
+ assert.deepEqual(store.getItem(board, item), before);
+ assert.equal(appliedSequence(board), 1);
+ assert.equal(engineReceipt(board, move.id), null, 'a forged move id cannot reserve a legitimate operation receipt');
+ assert.equal(store.events(board).at(-1).event_kind, 'relay_refused');
+ assert.equal(store.events(board).at(-1).event_by, 'relay');
+ const accepted = applyRelayMove(board, move, { sequence: 2, at: CLAIM_AT, kind: 'move', sender: { kind: 'agent', userId: 'fixture-user', agent: 'web-1' } });
+ assert.equal(Boolean(accepted.error), false);
+ assert.equal(store.getItem(board, item).item_owner, 'web-1');
+ const after = exportBoard(board);
+ assert.deepEqual(applyRelayMove(board, move, { sequence: 1, at: CLAIM_AT, kind: 'request' }), refused);
+ assert.deepEqual(exportBoard(board), after, 'repeated refusal returns its own receipt without moving the cursor backwards');
+ }
+ assert.deepEqual(exportBoard(one).tables, exportBoard(two).tables);
+ });
+
+ test('sealed shouts cannot bypass addressee, already answered or person decision rules [H16,B26]', t => {
+ const questions = [];
+ const { copies } = engineCopies(t, source => {
+ const lanes = ['web'];
+ questions.push(store.shout(source, { from: 'coordinator', to: 'person', text: 'Person decision', decision: true, lanes }));
+ questions.push(store.shout(source, { from: 'coordinator', to: 'web-2', text: 'Another agent decision', decision: true, lanes }));
+ const closed = store.shout(source, { from: 'coordinator', to: 'web-1', text: 'Already answered decision', decision: true, lanes });
+ store.answerDecision(source, closed, { agentId: 'web-1', text: 'Original answer', lanes });
+ questions.push(closed);
+ questions.push(store.shout(source, { from: 'web-1', to: 'coordinator', text: 'Needs passing', decision: true, lanes }));
+ });
+ for (const board of copies) {
+ const original = exportBoard(board);
+ let sequence = 0;
+ for (const sender of [{ kind: 'agent', userId: 'fixture-user', agent: 'web-1' }, { kind: 'person', userId: 'fixture-user' }]) {
+ for (const answers of questions.slice(0, 3)) {
+ const move = prepareEngineMove(board, 'shout', [{ from: 'web-1', to: 'coordinator', text: 'Bypass attempted', answers, lanes: ['web'] }], { id: 'bypass-' + ++sequence });
+ const refused = applyRelayMove(board, move, { sequence, at: CLAIM_AT, kind: 'move', sender });
+ assert.equal(refused.error?.code, 'RELAY_ANSWER');
+ assert.match(refused.error.next, /pullboard answer.*pullboard pass/);
+ assert.deepEqual(exportBoard(board).tables.shout, original.tables.shout);
+ assert.deepEqual(exportBoard(board).tables.item, original.tables.item);
+ }
+ }
+ const agentSender = { kind: 'agent', userId: 'fixture-user', agent: 'web-1' };
+ for (const [index, expected] of ['NOT_YOUR_DECISION', 'NOT_YOUR_DECISION', 'ALREADY_ANSWERED'].entries()) {
+ const move = prepareEngineMove(board, 'answerDecision', [questions[index], { agentId: 'web-1', text: 'Guarded attempt', lanes: ['web'] }], { id: 'answer-' + ++sequence });
+ assert.equal(applyRelayMove(board, move, { sequence, at: CLAIM_AT, kind: 'move', sender: agentSender }).error.code, expected);
+ assert.deepEqual(exportBoard(board).tables.shout, original.tables.shout);
+ }
+ assert.deepEqual(store.openDecisions(board, 'person').map(row => row.shout_id), [questions[0]]);
+ const permitted = prepareEngineMove(board, 'answerDecision', [questions[0], { agentId: 'coordinator', asPerson: true, text: 'Person answered', lanes: ['web'], channel: 'view' }], { id: 'person-answer' });
+ assert.equal(Boolean(applyRelayMove(board, permitted, { sequence: ++sequence, at: CLAIM_AT, kind: 'move', sender: { kind: 'person', userId: 'fixture-user' } }).error), false);
+ assert.deepEqual(store.openDecisions(board, 'person'), []);
+ const personSender = { kind: 'person', userId: 'fixture-user' };
+ const pass = prepareEngineMove(board, 'passDecision', [questions[3], { agentId: 'coordinator', note: 'Needs the person', lanes: ['web'] }], { id: 'guarded-pass' });
+ const passed = applyRelayMove(board, pass, { sequence: ++sequence, at: CLAIM_AT, kind: 'move', sender: personSender });
+ assert.equal(Boolean(passed.error), false);
+ assert.deepEqual(store.openDecisions(board, 'person').map(row => row.shout_id), [passed.result]);
+ const response = prepareEngineMove(board, 'answerDecision', [passed.result, { agentId: 'coordinator', asPerson: true, text: 'Passed decision answered', lanes: ['web'] }], { id: 'passed-answer' });
+ assert.equal(Boolean(applyRelayMove(board, response, { sequence: ++sequence, at: CLAIM_AT, kind: 'move', sender: personSender }).error), false);
+ assert.deepEqual(store.openDecisions(board, 'person'), []);
+ assert.deepEqual(store.openDecisions(board, 'coordinator'), []);
+ assert.ok(exportBoard(board).tables.shout.some(row => row.shout_answers === questions[3] && row.shout_from === 'person'), 'guarded person answers reach the original asker');
+ }
+ assert.deepEqual(exportBoard(copies[0]).tables, exportBoard(copies[1]).tables);
+ });
+
+ test('future engine relay records stop before every sender shape without changing a replica [H16]', t => {
+ const { copies, item } = engineCopies(t);
+ const move = { ...claimMove(copies[0], item, 'web-1'), engine: ENGINE_VERSION + 1 };
+ for (const sender of [undefined, {}, { kind: 'person', userId: 'fixture-user' }, { kind: 'agent', userId: 'fixture-user', agent: 'web-2' }]) {
+ for (const board of copies) {
+ const before = exportBoard(board);
+ assert.throws(() => applyRelayMove(board, move, { sequence: 1, at: CLAIM_AT, kind: 'request', sender }), error => error.code === 'ENGINE_VERSION');
+ assert.deepEqual(exportBoard(board), before);
+ assert.equal(appliedSequence(board), 0);
+ }
+ }
+ });
+
+ test('a relay refusal receipt failure rolls back its log and cursor together [H2,H16]', t => {
+ const { copies, item } = engineCopies(t);
+ const board = copies[0];
+ const before = exportBoard(board);
+ board.db.exec("CREATE TEMP TRIGGER refuse_receipt BEFORE INSERT ON board_meta WHEN NEW.meta_key LIKE 'relay_refusal_%' BEGIN SELECT RAISE(ABORT, 'refusal receipt rollback'); END");
+ assert.throws(() => applyRelayMove(board, claimMove(board, item, 'web-1'), { sequence: 1, at: CLAIM_AT, kind: 'move' }), /refusal receipt rollback/);
+ assert.deepEqual(exportBoard(board), before);
+ assert.equal(appliedSequence(board), 0);
+ });
+
test('the same sealed claim replays to identical rows and sequence retries are idempotent [H3,H16]', (t) => {
const { copies, item } = engineCopies(t);
const [one, two] = copies;
diff --cc test/relay-agent.test.js
index 66829dc2,00000000..93f8e128
mode 100644,000000..100644
--- a/test/relay-agent.test.js
+++ b/test/relay-agent.test.js
@@@ -1,313 -1,0 +1,321 @@@
+/** Private end-to-end proof for ordered agent enrollment and scoped relay credentials [H2,H9,A4]. */
+import assert from 'node:assert/strict';
+import { spawn, spawnSync } from 'node:child_process';
++import { createHash } from 'node:crypto';
+import { DatabaseSync } from 'node:sqlite';
+import { chmodSync, existsSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from 'node:fs';
+import { basename, dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { test } from 'node:test';
+import { claim as claimStoredItem, closeBoard, openBoard, register as registerStoredAgent, submit as submitStoredItem } from '../src/board.js';
+import { serveApi } from '../src/api.js';
+import { main } from '../src/cli.js';
++import { ENGINE_VERSION } from '../src/machine.js';
+import { decodeBoardKey, unseal } from '../src/seal.js';
+import { frozenCriterion, parseSpec } from '../src/spec.js';
+import { relayClientFixture } from './relay-client-fixture.js';
+
+/** Invoke one real CLI command without retaining stderr or exposing private command output. */
+function runCli(root, env, cli, args) {
+ return new Promise((resolveResult, reject) => {
+ const child = spawn(process.execPath, [cli, ...args, '--json'], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });
+ let stdout = '';
+ const timer = setTimeout(() => child.kill('SIGKILL'), 25000);
+ child.stdout.setEncoding('utf8').on('data', (part) => { stdout += part; });
+ child.stderr.resume();
+ child.once('error', (error) => { clearTimeout(timer); reject(error); });
+ child.once('close', (code, signal) => {
+ clearTimeout(timer);
+ if (signal) return reject(new Error('private agent CLI exceeded its deadline'));
+ try { resolveResult({ code, document: JSON.parse(stdout) }); }
+ catch { reject(new Error(`private agent CLI ${args[0]} did not return JSON (exit ${code ?? 'signal'})`)); }
+ });
+ });
+}
+
+/** Run Git in a private fixture and keep all diagnostics credential-free. */
+function git(root, env, args) {
+ const result = spawnSync('git', args, { cwd: root, env, encoding: 'utf8' });
+ assert.equal(result.status, 0, `private Git fixture ${args[0]} succeeds: ${result.stderr}`);
+}
+
+/** Return private Git output for a structural assertion without surfacing command diagnostics. */
+function gitText(root, env, args) {
+ const result = spawnSync('git', args, { cwd: root, env, encoding: 'utf8' });
+ assert.equal(result.status, 0, `private Git fixture ${args[0]} succeeds`);
+ return result.stdout;
+}
+
+/** Read durable local event attribution without opening a writable SQLite handle. */
+function nativeEvents(path) {
+ const db = new DatabaseSync(path, { readOnly: true });
+ try { return db.prepare('SELECT event_by, event_kind, item_id FROM event ORDER BY event_id').all(); }
+ finally { db.close(); }
+}
+
+/** Read durable verdict identity without opening a writable SQLite handle. */
+function nativeVerdicts(path) {
+ const db = new DatabaseSync(path, { readOnly: true });
+ try { return db.prepare('SELECT verdict_by, verdict_decision, item_id, verdict_commit FROM verdict ORDER BY verdict_id').all(); }
+ finally { db.close(); }
+}
+
+/** Read only the canonical registered identity for a private worktree path. */
+function registeredAgent(path, worktree) {
+ const db = new DatabaseSync(path, { readOnly: true });
+ try { return db.prepare('SELECT agent_id FROM agent WHERE agent_path = ?').get(worktree)?.agent_id ?? null; }
+ finally { db.close(); }
+}
+
+/** Load a cached scoped token for private transport setup without writing it to diagnostics. */
+function scopedToken(linkFile, agent) {
+ return JSON.parse(readFileSync(linkFile, 'utf8')).agentTokens[agent].token;
+}
+
+/** Assert a response contains only metadata and none of the fixture's private credentials. */
+function assertMetadataOnly(value, credentials, message) {
+ const serialized = JSON.stringify(value);
+ for (const credential of credentials) assert.equal(serialized.includes(credential), false, message);
+ for (const row of value.tokens ?? []) assert.equal(Object.hasOwn(row, 'token'), false, message);
+}
+
+test('ordered agent joins mint scoped tokens and retain authenticated native actors [H2,H9]', async (t) => {
+ const box = await relayClientFixture(t);
+ const cli = join(dirname(fileURLToPath(import.meta.url)), '../bin/pullboard.js');
+ const shim = join(box.env.PATH, 'pullboard');
+ writeFileSync(shim, `#!/bin/sh\nexec node "${cli}" "$@"\n`, { mode: 0o700 });
+ chmodSync(shim, 0o700);
+ const boardFile = join(box.root, '.git', 'pullboard', 'board.sqlite');
+ const oneItem = await box.cli('add', box.lane, 'agent one private review', '--criterion', 'the first verifier records its own decision');
+ const twoItem = await box.cli('add', box.lane, 'agent two private review', '--criterion', 'the second verifier records its own decision');
+ const workItem = await box.cli('add', box.lane, 'token-only agent work');
+ assert.equal(oneItem.code, 0);
+ assert.equal(twoItem.code, 0);
+ assert.equal(workItem.code, 0);
+
+ git(box.root, box.env, ['add', '-A']);
+ git(box.root, box.env, ['commit', '-q', '-m', 'test: prepare private agent fixture']);
+ const submittedHead = gitText(box.root, box.env, ['rev-parse', 'HEAD']).trim();
+ const submittedTree = gitText(box.root, box.env, ['rev-parse', 'HEAD^{tree}']).trim();
+ const seed = openBoard(boardFile);
+ try {
+ const spec = parseSpec(readFileSync(join(box.root, 'SPEC.md'), 'utf8'));
- const freezer = (item) => frozenCriterion(spec, item);
++ const config = JSON.parse(readFileSync(join(box.root, 'pullboard.json'), 'utf8'));
++ const freezer = (item) => {
++ const criterion = JSON.parse(frozenCriterion(spec, item).text);
++ const policy = { version: 1, commit: submittedHead, verify: { policy: config.verify.policy, family: config.verify.family } };
++ const text = JSON.stringify({ ...criterion, policy });
++ return { text, digest: createHash('sha256').update(text).digest('hex') };
++ };
+ for (const [row, builderPath] of [[oneItem.document.item, '/private/relay-builder-one'], [twoItem.document.item, '/private/relay-builder-two']]) {
+ const builder = registerStoredAgent(seed, { lane: box.lane, path: builderPath });
+ claimStoredItem(seed, row.item_id, { agentId: builder, lane: box.lane, leaseMs: 60 * 60 * 1000, freeze: freezer, head: submittedHead });
+ submitStoredItem(seed, row.item_id, { agentId: builder, commit: submittedHead, tree: submittedTree });
+ }
+ } finally { closeBoard(seed); }
+ const firstRoot = join(dirname(box.root), 'agent-one');
+ const secondRoot = join(dirname(box.root), 'agent-two');
+ git(box.root, box.env, ['worktree', 'add', '-q', '-b', 'core/private-agent-one', firstRoot, 'HEAD']);
+ git(box.root, box.env, ['worktree', 'add', '-q', '-b', 'core/private-agent-two', secondRoot, 'HEAD']);
+
+ await box.link();
+ const firstStart = box.calls.length;
+ const firstJoin = await runCli(firstRoot, box.env, cli, ['join', box.lane, '--family', 'codex-fixture']);
+ assert.equal(firstJoin.code, 0, 'the first worktree joins through the real linked CLI');
+ const firstAgent = firstJoin.document.agent;
+ const firstCalls = box.calls.slice(firstStart);
+ const firstRegistration = firstCalls.findIndex((call) => call.method === 'POST' && call.path.endsWith('/moves'));
+ const firstMint = firstCalls.findIndex((call) => call.method === 'POST' && call.path === '/auth/tokens');
+ assert.ok(firstRegistration >= 0 && firstMint > firstRegistration, 'the first token is minted after ordered registration');
+
+ const secondStart = box.calls.length;
+ const secondJoin = await runCli(secondRoot, box.env, cli, ['join', box.lane, '--family', 'codex-fixture']);
+ assert.equal(secondJoin.code, 0, 'the second worktree joins through the real linked CLI');
+ const secondAgent = secondJoin.document.agent;
+ const secondCalls = box.calls.slice(secondStart);
+ const secondRegistration = secondCalls.findIndex((call) => call.method === 'POST' && call.path.endsWith('/moves'));
+ const secondMint = secondCalls.findIndex((call) => call.method === 'POST' && call.path === '/auth/tokens');
+ assert.ok(secondRegistration >= 0 && secondMint > secondRegistration, 'the second token is minted after ordered registration');
+ assert.notEqual(firstAgent, secondAgent);
+
+ const firstToken = scopedToken(box.linkFile, firstAgent);
+ const secondToken = scopedToken(box.linkFile, secondAgent);
+ const list = await box.cli('relay', 'tokens');
+ assert.equal(list.code, 0);
+ assert.deepEqual(list.document.tokens.map((row) => row.agent).sort(), [firstAgent, secondAgent].sort());
+ const personState = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const boardKey = readFileSync(box.keyFile, 'utf8').trim();
+ assertMetadataOnly(list.document, [firstToken, secondToken, personState.token, boardKey], 'CLI inventory exposes only scoped token metadata');
+ const firstTokenRow = list.document.tokens.find((row) => row.agent === firstAgent);
+ const secondTokenRow = list.document.tokens.find((row) => row.agent === secondAgent);
+ assert.ok(firstTokenRow?.id && secondTokenRow?.id);
+
+ const localApi = await serveApi({
+ runCommand: main,
+ projects: () => [{ root: box.root, name: 'private relay fixture', project: 'fixture/repository', added: '2026-10-07T00:00:00.000Z' }],
+ });
+ t.after(() => localApi.close());
+ const tokenUrl = new URL(`/api/v1/boards/${personState.board}/tokens`, localApi.url);
+ tokenUrl.searchParams.set('k', new URL(localApi.url).searchParams.get('k'));
+ const apiHeaders = { 'content-type': 'application/json' };
+ const apiListResponse = await fetch(tokenUrl, { headers: apiHeaders });
+ assert.equal(apiListResponse.status, 200, 'local API reads the real relay token inventory');
+ const apiList = await apiListResponse.json();
+ assert.deepEqual(apiList.tokens.map((row) => row.agent).sort(), [firstAgent, secondAgent].sort());
+ assertMetadataOnly(apiList, [firstToken, secondToken, personState.token, boardKey], 'local API exposes only token metadata');
+
+ const realGit = realpathSync(join(box.env.PATH, 'git'));
+ const pushLog = join(dirname(box.root), 'private-git-push.log');
+ unlinkSync(join(box.env.PATH, 'git'));
+ writeFileSync(join(box.env.PATH, 'git'), `#!/bin/sh\nif [ "$1" = push ]; then printf 'blocked\\n' >> "${pushLog}"; exit 1; fi\nexec "${realGit}" "$@"\n`, { mode: 0o700 });
+ chmodSync(join(box.env.PATH, 'git'), 0o700);
+ const deniedPush = spawnSync('git', ['push'], { cwd: firstRoot, env: box.env, encoding: 'utf8' });
+ assert.equal(deniedPush.status, 1, 'the private fixture refuses every Git push before a remote can be contacted');
+ assert.equal(readFileSync(pushLog, 'utf8'), 'blocked\n', 'the refusing Git shim records the attempted push without arguments');
+
+ const firstVerify = await runCli(firstRoot, { ...box.env, PULLBOARD_RELAY_TOKEN: firstToken }, cli,
+ ['verify', String(oneItem.document.item.item_id), 'accept', '--note', 'checked the private submitted proof']);
+ assert.equal(firstVerify.code, 0, `the first agent gives an ACCEPT verdict using only its scoped token (${firstVerify.document.error?.code ?? 'no refusal'})`);
+ const secondVerify = await runCli(secondRoot, { ...box.env, PULLBOARD_RELAY_TOKEN: secondToken }, cli,
+ ['verify', String(twoItem.document.item.item_id), 'accept', '--note', 'checked the other private submitted proof']);
+ assert.equal(secondVerify.code, 0, `the second agent gives an ACCEPT verdict using only its scoped token (${secondVerify.document.error?.code ?? 'no refusal'})`);
+
+ const revoke = await box.cli('relay', 'revoke', firstTokenRow.id);
+ assert.equal(revoke.code, 0, 'CLI revokes one listed opaque token id');
+ const apiRevokeResponse = await fetch(tokenUrl, {
+ method: 'POST', headers: apiHeaders, body: JSON.stringify({ id: firstTokenRow.id }),
+ });
+ assert.equal(apiRevokeResponse.status, 200, 'local API accepts the opaque id-only revocation body');
+ const apiRevoke = await apiRevokeResponse.json();
+ assert.equal(apiRevoke.id, firstTokenRow.id);
+ assert.equal(apiRevoke.revoked, true);
+ assertMetadataOnly(apiRevoke, [firstToken, secondToken, personState.token, boardKey], 'local API revocation response contains no credential');
+
+ // Capture authenticated journal records before a person command checkpoints their prefix.
+ const remoteState = await fetch(`${box.origin}/api/v1/boards/${personState.board}/state`, {
- headers: { authorization: `Bearer ${secondToken}` },
++ headers: { authorization: `Bearer ${secondToken}`, 'x-pullboard-engine': String(ENGINE_VERSION) },
+ });
+ assert.equal(remoteState.status, 200, 'the second scoped token can read the sealed relay snapshot');
+ const relayState = await remoteState.json();
+ const remote = await fetch(`${box.origin}/api/v1/boards/${personState.board}/events?after=${relayState.state.sequence}`, {
- headers: { authorization: `Bearer ${secondToken}` },
++ headers: { authorization: `Bearer ${secondToken}`, 'x-pullboard-engine': String(ENGINE_VERSION) },
+ });
+ assert.equal(remote.status, 200, 'the second scoped token can read the ordered relay events');
+ const remoteEvents = (await remote.json()).events;
+
+ const cachedMintCount = box.calls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length;
+ const beforeCachedRefusal = nativeEvents(boardFile);
+ const cachedRefusal = await runCli(firstRoot, box.env, cli, ['shout', 'all', 'revoked cache must stay revoked']);
+ assert.equal(cachedRefusal.code, 1, 'a cached revoked credential refuses even while the person session remains valid');
+ assert.equal(cachedRefusal.document.error.code, 'AUTH_REQUIRED');
+ assert.deepEqual(nativeEvents(boardFile), beforeCachedRefusal, 'revoked cached credentials cannot write native board events');
+ assert.equal(box.calls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length, cachedMintCount,
+ 'a valid person session never silently re-mints its revoked agent cache');
+
+ const linkAfterRevoke = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const personRevoked = await fetch(box.origin + '/auth/tokens/revoke', {
+ method: 'POST', headers: { authorization: `Bearer ${linkAfterRevoke.token}`, 'content-type': 'application/json' },
+ body: JSON.stringify({ id: linkAfterRevoke.tokenId }),
+ });
+ assert.equal(personRevoked.status, 200, 'the private person session is revoked before token-only access');
+ const deadSession = await fetch(box.origin + '/auth/session', { headers: { authorization: `Bearer ${linkAfterRevoke.token}` } });
+ assert.equal(deadSession.status, 401);
+ assert.equal((await deadSession.json()).error.code, 'AUTH_REQUIRED');
+
+ const mintCount = box.calls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length;
+ const firstEnv = { ...box.env, PULLBOARD_RELAY_TOKEN: firstToken };
+ const revokedMove = await runCli(firstRoot, firstEnv, cli, ['add', box.lane, 'must not use revoked token']);
+ assert.equal(revokedMove.code, 1);
+ assert.equal(revokedMove.document.error.code, 'AUTH_REQUIRED');
+ assert.equal(box.calls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length, mintCount,
+ 'a revoked credential is not silently re-minted');
+
+ const secondEnv = { ...box.env, PULLBOARD_RELAY_TOKEN: secondToken };
+ const tokenOnlyRead = await runCli(secondRoot, secondEnv, cli, ['list', '--all']);
+ assert.equal(tokenOnlyRead.code, 0, 'the other agent reads through its scoped token after person revocation');
+ const tokenOnlyWrite = await runCli(secondRoot, secondEnv, cli, ['claim', String(workItem.document.item.item_id)]);
+ assert.equal(tokenOnlyWrite.code, 0, 'the other agent writes through its scoped token after person revocation');
+
+ const native = nativeEvents(boardFile);
+ assert.ok(native.some((row) => row.event_by === secondAgent && row.event_kind === 'claim' && row.item_id === workItem.document.item.item_id),
+ 'the second agent claim is recorded in the native SQLite event log');
+ const verdicts = nativeVerdicts(boardFile);
+ assert.ok(verdicts.some((row) => row.verdict_by === firstAgent && row.verdict_decision === 'ACCEPT' && row.item_id === oneItem.document.item.item_id && row.verdict_commit === submittedHead),
+ 'the first submitted-item ACCEPT is recorded under the first agent in native SQLite');
+ assert.ok(verdicts.some((row) => row.verdict_by === secondAgent && row.verdict_decision === 'ACCEPT' && row.item_id === twoItem.document.item.item_id && row.verdict_commit === submittedHead),
+ 'the second submitted-item ACCEPT is recorded under the second agent in native SQLite');
+
+ const otherBoard = (personState.board[0] === '0' ? '1' : '0') + personState.board.slice(1);
+ const crossBoard = await fetch(`${box.origin}/api/v1/boards/${otherBoard}/events?after=0`, {
- headers: { authorization: `Bearer ${secondToken}` },
++ headers: { authorization: `Bearer ${secondToken}`, 'x-pullboard-engine': String(ENGINE_VERSION) },
+ });
+ assert.equal(crossBoard.status, 403, 'an agent token cannot cross to another board');
+ assert.equal((await crossBoard.json()).error.code, 'TOKEN_BOARD');
+
+ assert.ok(remoteEvents.some((event) => event.sender?.kind === 'agent' && event.sender.agent === firstAgent),
+ 'relay metadata attributes the first native move to its authenticated agent');
+ assert.ok(remoteEvents.some((event) => event.sender?.kind === 'agent' && event.sender.agent === secondAgent),
+ 'relay metadata attributes the second native move to its authenticated agent');
+
+ const openedEvents = await Promise.all(remoteEvents.map(async (record) => ({ record, opened: JSON.parse(new TextDecoder().decode(await unseal(
+ decodeBoardKey(boardKey), Buffer.from(record.sealed, 'base64url'),
+ { boardId: personState.board, kind: record.kind, sequence: record.event_id },
+ ))) })));
+ assert.ok(openedEvents.some(({ record, opened }) => record.sender?.agent === firstAgent && opened.operation === 'verify' && opened.args[0] === oneItem.document.item.item_id),
+ 'the relay carries the first agent verification under its authenticated sender metadata');
+ assert.ok(openedEvents.some(({ record, opened }) => record.sender?.agent === secondAgent && opened.operation === 'verify' && opened.args[0] === twoItem.document.item.item_id),
+ 'the relay carries the second agent verification under its authenticated sender metadata');
+
+ const firstEventRecord = openedEvents.find((event) => event.record.sender?.agent === firstAgent)?.opened;
+ assert.equal(firstEventRecord.actor, firstAgent, 'the authenticated relay principal matches the sealed native actor');
+ assertMetadataOnly(remoteEvents.map(({ event_id, event_at, kind, sender }) => ({ event_id, event_at, kind, sender })),
+ [firstToken, secondToken, personState.token, boardKey], 'relay event metadata never exposes credentials');
+});
+
+test('a token mint failure after registration preserves the agent for one clean retry [H2,H9]', async (t) => {
+ const box = await relayClientFixture(t);
+ const cli = join(dirname(fileURLToPath(import.meta.url)), '../bin/pullboard.js');
+ const shim = join(box.env.PATH, 'pullboard');
+ writeFileSync(shim, `#!/bin/sh\nexec node "${cli}" "$@"\n`, { mode: 0o700 });
+ chmodSync(shim, 0o700);
+ const boardFile = join(box.root, '.git', 'pullboard', 'board.sqlite');
+ const item = await box.cli('add', box.lane, 'retry registered agent token fixture');
+ assert.equal(item.code, 0);
+ git(box.root, box.env, ['add', '-A']);
+ git(box.root, box.env, ['commit', '-q', '-m', 'test: prepare token retry fixture']);
+ await box.link();
+ box.failTokenMints(1);
+
+ const firstStart = box.calls.length;
+ const failedCreate = await box.cli('worktree', box.lane, '--family', 'codex-fixture');
+ assert.equal(failedCreate.code, 1, 'the injected token service failure is reported after the real worktree registration');
+ const firstCalls = box.calls.slice(firstStart);
+ assert.equal(firstCalls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length, 1);
+ const agentRoot = join(dirname(box.root), `${basename(box.root)}-${box.lane}-1`);
+ const agent = registeredAgent(boardFile, agentRoot);
+ assert.ok(agent, 'successful ordered registration remains canonical after token mint failure');
+ assert.equal(existsSync(agentRoot), true, 'the registered worktree is retained for retry');
+ const worktrees = gitText(box.root, box.env, ['worktree', 'list', '--porcelain']);
+ assert.ok(worktrees.includes(agentRoot), 'Git still records the retained worktree');
+ assert.match(worktrees, new RegExp(`branch refs/heads/${box.lane}/1`), 'the registered branch is retained too');
+ const joinRows = nativeEvents(boardFile).filter((row) => row.event_by === agent && row.event_kind === 'join');
+ assert.equal(joinRows.length, 1, 'the failed mint does not undo or duplicate ordered registration');
+
+ const retryStart = box.calls.length;
+ const retry = await runCli(agentRoot, box.env, cli, ['join', box.lane, '--family', 'codex-fixture']);
+ assert.equal(retry.code, 0, 'the same registered worktree can retry token minting');
+ assert.equal(retry.document.agent, agent);
+ assert.equal(box.calls.slice(retryStart).filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length, 1);
+ assert.equal(nativeEvents(boardFile).filter((row) => row.event_by === agent && row.event_kind === 'join').length, 1);
+
+ const linkState = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ assert.deepEqual(Object.keys(linkState.agentTokens), [agent], 'the private link cache holds one usable token for the registered agent');
+ const token = scopedToken(box.linkFile, agent);
+ const listed = await box.cli('relay', 'tokens');
+ assert.equal(listed.code, 0);
+ assert.deepEqual(listed.document.tokens.map((row) => row.agent), [agent]);
+ assertMetadataOnly(listed.document, [token, linkState.token], 'retry inventory exposes metadata only');
+ const usable = await runCli(agentRoot, { ...box.env, PULLBOARD_RELAY_TOKEN: token }, cli,
+ ['claim', String(item.document.item.item_id)]);
+ assert.equal(usable.code, 0, 'the single token from the successful retry authorizes an agent action');
+});
diff --cc test/relay-client-fixture.js
index 246f75c2,f6aaa548..edf76998
--- a/test/relay-client-fixture.js
+++ b/test/relay-client-fixture.js
@@@ -54,24 -54,39 +54,47 @@@ export async function relayClientFixtur
GIT_AUTHOR_NAME: 'Relay Fixture', GIT_AUTHOR_EMAIL: '[email protected]',
GIT_COMMITTER_NAME: 'Relay Fixture', GIT_COMMITTER_EMAIL: '[email protected]',
};
+ for (const name of ['PULLBOARD_RELAY_KEY', 'PULLBOARD_RELAY_TOKEN']) delete env[name];
const provider = await githubFixture(t);
provider.state.deviceAuthorized = true;
- const auth = createRelayAuth({ database: join(scratch, 'auth.sqlite'), github: createGitHubClient(provider.config) });
+ let auth;
let time = Date.now();
let override = null;
+ let mintFailures = 0;
+ let refuseEventReads = false;
+ let refuseSnapshotWrites = false;
+ let refuseRequestWrites = false;
let signIn;
let api;
const calls = [];
+ const moveAcks = [];
+ const privateKeys = new Set();
+ let keyLeaked = false;
const server = createServer(async (req, res) => {
- calls.push({ method: req.method, path: req.url });
+ const end = res.end.bind(res);
+ res.end = (chunk, ...args) => {
+ if (req.method === 'POST' && /\/api\/v1\/boards\/[0-9a-f]{32}\/moves$/.test(req.url ?? '') && (typeof chunk === 'string' || Buffer.isBuffer(chunk))) {
+ try {
+ const response = JSON.parse(Buffer.isBuffer(chunk) ? chunk.toString('utf8') : chunk);
+ if (typeof response.event?.sealed === 'string') moveAcks.push(response.event);
+ } catch { /* Capture only valid move acknowledgements; the production response remains unchanged. */ }
+ }
+ return end(chunk, ...args);
+ };
+ calls.push({ method: req.method, path: req.url, accept: req.headers.accept ?? '', engine: req.headers['x-pullboard-engine'] });
+ if ([...privateKeys].some(key => JSON.stringify({ url: req.url, headers: req.headers }).includes(key))) keyLeaked = true;
+ if (mintFailures > 0 && req.method === 'POST' && req.url === '/auth/tokens') {
+ mintFailures -= 1;
+ req.resume();
+ res.writeHead(503, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ version: 1, error: { code: 'TEMPORARY', message: 'fixture refusal' } }));
+ return;
+ }
+ if (refuseEventReads && req.method === 'GET' && /\/events(?:\?|$)/.test(req.url)) {
+ res.writeHead(503, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ version: 1, error: { code: 'RELAY_UNAVAILABLE', message: 'fixture read outage' } }));
+ return;
+ }
if (override && req.method === 'DELETE') {
res.writeHead(override.status, { 'content-type': 'application/json' });
res.end(JSON.stringify({ version: override.version ?? 1, error: { code: override.code, message: 'fixture refusal' } }));
@@@ -130,10 -201,15 +209,16 @@@
return childResult(root, env, ['--input-type=module', '-e', source]);
}
return {
- root, env, origin, lane, before, linkFile, keyFile, calls, cli, link, otherDeviceOff, script,
+ root, env, origin, lane, before, linkFile, keyFile, calls, moveAcks, cli, link, requireEngineThree, otherDeviceOff, additionalBoard, script, stopRelay, restartRelay,
advance(days) { time = Date.now() + days * 86400000; },
overrideDelete(value) { override = value; },
+ failTokenMints(count) { mintFailures = count; },
+ refuseSnapshotWrites(value) { refuseSnapshotWrites = value; },
+ refuseRequestWrites(value) { refuseRequestWrites = value; },
mainURL: new URL('../src/cli.js', import.meta.url).href,
+ keyInRequest() { return keyLeaked; },
+ /** Revoke the actual synthetic person session, including its current live streams. */
+ revokeSession() { const state = JSON.parse(readFileSync(linkFile, 'utf8')); return auth.revoke(state.token, state.tokenId); },
+ refuseReads(value) { refuseEventReads = value; },
};
}
diff --cc test/relay-client.test.js
index 8b4942f7,e91b3020..4ad5fd2e
--- a/test/relay-client.test.js
+++ b/test/relay-client.test.js
@@@ -503,8 -551,7 +551,8 @@@ test('[H3,H16] three cloned linked repl
const earlierSealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(earlier)), {
boardId, kind: 'move', sequence: next,
})).toString('base64url');
- const headers = { 'x-pullboard-engine': '3', authorization: `Bearer ${person.token}`, 'content-type': 'application/json' };
+ const coordinatorCredential = await auth.issueToken(person.token, { board: boardId, agent: 'coordinator' });
- const headers = { authorization: 'Bearer ' + coordinatorCredential.token, 'content-type': 'application/json' };
++ const headers = { 'x-pullboard-engine': '3', authorization: 'Bearer ' + coordinatorCredential.token, 'content-type': 'application/json' };
assert.equal((await fetch(`${relay.origin}/api/v1/boards/${boardId}/moves`, {
method: 'POST', headers, body: JSON.stringify({ sequence: next, sealed: earlierSealed }),
})).status, 200);
diff --cc test/relay-credential.test.js
index 00000000,00000000..f1dabf35
new file mode 100644
--- /dev/null
+++ b/test/relay-credential.test.js
@@@ -1,0 -1,0 +1,72 @@@
++/** Real transport proves credential selection follows every public operation class [H2,H9,H16]. */
++import assert from 'node:assert/strict';
++import { readFileSync } from 'node:fs';
++import { test } from 'node:test';
++import { ENGINE_OPERATIONS } from '../src/engine.js';
++import { decodeBoardKey, unseal } from '../src/seal.js';
++import { relayClientFixture } from './relay-client-fixture.js';
++
++test('every current operation selects its native actor credential without a second authorization policy [H2,H9,H16]', async (t) => {
++ const box = await relayClientFixture(t);
++ await box.link();
++ const actor = 'coordinator';
++ const options = { agentId: actor, lane: box.lane, leaseMs: 3600000, reason: 'credential fixture', note: 'credential fixture', text: 'fixture', kind: 'observation', head: 'a'.repeat(40), frozen: { text: '{"rows":[]}', digest: 'f'.repeat(64) } };
++ const cases = ENGINE_OPERATIONS.map(operation => {
++ let args = [999999, options];
++ let kind = 'agent';
++ if (operation === 'register') { args = [{ lane: box.lane, path: '/private/credential-enrollment' }]; kind = 'person'; }
++ if (operation === 'ensureCoordinator') { args = [box.root]; kind = 'person'; }
++ if (operation === 'addItem') args = [{ by: actor, lane: box.lane, title: 'credential actor fixture' }];
++ if (operation === 'shout') args = [{ from: actor, to: 'all', text: 'credential actor fixture', lanes: [box.lane] }];
++ if (operation === 'release') args = [999999, actor];
++ if (['claim', 'refreeze'].includes(operation)) args = [box.before.tables.item[0].item_id, options];
++ if (operation === 'reserveNextReview') args = [options];
++ if (operation === 'addMilestone') args = [{ agentId: actor, name: 'Credential fixture', items: [] }];
++ if (['holdLane', 'releaseLane'].includes(operation)) args = [box.lane, options];
++ if (operation === 'applyRowDecisions') args = [{ agentId: actor, events: [] }];
++ if (operation === 'recordRowDecisions') { args = [{ agentId: 'person', channel: 'terminal', decisions: [] }]; kind = 'person'; }
++ return { operation, args, kind };
++ });
++ cases.push(
++ { operation: 'answerDecision', args: [999999, { ...options, asPerson: true, channel: 'terminal' }], kind: 'person' },
++ { operation: 'holdLane', args: [box.lane, { ...options, asPerson: true, channel: 'terminal' }], kind: 'person' },
++ { operation: 'releaseLane', args: [box.lane, { ...options, asPerson: true, channel: 'terminal' }], kind: 'person' },
++ { operation: 'shout', args: [{ from: actor, to: 'all', text: 'person request fixture', lanes: [box.lane], request: true }], kind: 'person' },
++ { operation: 'applyRowDecisions', args: [{ agentId: actor, events: [] }], kind: 'person', personRequest: { id: 'credential-request', stage: 'apply' } },
++ );
++ const start = box.moveAcks.length;
++ const results = [];
++ // Each child keeps the fixture's existing deadline while all moves share one durable board.
++ for (let offset = 0; offset < cases.length; offset += 8) {
++ const batch = cases.slice(offset, offset + 8);
++ const result = await box.script(`
++ import { relayOperation } from ${JSON.stringify(new URL('../src/relay.js', import.meta.url).href)};
++ import { Refused } from ${JSON.stringify(new URL('../src/refused.js', import.meta.url).href)};
++ const cases = ${JSON.stringify(batch)};
++ const results = [];
++ for (const entry of cases) {
++ const io = { err() {}, onEvent() {}, ...(entry.personRequest ? { personRequest: entry.personRequest } : {}) };
++ try { await relayOperation(process.cwd(), entry.operation, entry.args, io); results.push(null); }
++ catch (error) { if (!(error instanceof Refused)) { results.push({ fatal: error.name, operation: entry.operation, stack: error.stack?.split('\\n').slice(1, 3).join('\\n') }); break; } results.push(error.code); }
++ }
++ console.log(JSON.stringify({ results }));
++ `);
++ assert.equal(result.code, 0, 'every operation reaches the real transport and deterministic replay');
++ assert.equal(result.document.results.some(value => value?.fatal), false, JSON.stringify(result.document.results.filter(value => value?.fatal)));
++ assert.equal(result.document.results.length, batch.length);
++ results.push(...result.document.results);
++ }
++ const records = box.moveAcks.slice(start);
++ assert.equal(records.length, cases.length, 'each operation is acknowledged once even when native preconditions refuse it');
++ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());
++ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));
++ for (const [index, entry] of cases.entries()) {
++ const record = records[index];
++ const move = JSON.parse(new TextDecoder().decode(await unseal(key, Buffer.from(record.sealed, 'base64url'), { boardId: state.board, kind: record.kind, sequence: record.event_id })));
++ assert.equal(move.operation, entry.operation);
++ assert.equal(record.sender.kind, entry.kind, `${entry.operation} selects the correct authenticated credential`);
++ if (entry.kind === 'agent') assert.equal(record.sender.agent, actor, 'the scoped credential belongs to the native actor');
++ assert.ok(!['RELAY_ACTOR', 'RELAY_SENDER', 'RELAY_SENDER_MISMATCH', 'RELAY_PERSON_ONLY'].includes(results[index]),
++ `${entry.operation} passes main's shared sender policy`);
++ }
++});
diff --cc test/relay.test.js
index 2e5cf607,51e11f06..2fe77723
--- a/test/relay.test.js
+++ b/test/relay.test.js
@@@ -4,7 -4,7 +4,8 @@@ import { existsSync, mkdtempSync, readF
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { test } from 'node:test';
+import { DatabaseSync } from 'node:sqlite';
+ import { ENGINE_VERSION } from '../src/machine.js';
import { createGitHubClient } from '../relay/github.js';
import { createRelayAuth, ACCESS_WINDOW_MS } from '../relay/auth.js';
import { serveRelay } from '../relay/service.js';
@@@ -482,6 -447,94 +484,94 @@@ test('unlinked board commands attempt z
assert.ok(result.document.codes.every(code => code === 0), 'all ordinary local board commands succeed without transport');
});
+
+ test('offline linked reads use the local board, moves refuse, and the same relay resumes [H10]', async (t) => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const boardFile = join(box.root, '.git', 'pullboard', 'board.sqlite');
+ const beforeBytes = readFileSync(boardFile);
+ const beforeTables = (await box.cli('export')).document.tables;
+ const beforeEvents = beforeTables.event;
+ const oldEnvironment = new Map(['HOME', 'PULLBOARD_HOME', 'PULLBOARD_MACHINE_HOME']
+ .map(name => [name, process.env[name]]));
+ for (const name of oldEnvironment.keys()) process.env[name] = box.env[name];
+ let view;
+ try {
+ view = await serveView({ port: 0 });
+ const page = await fetch(view.url);
+ assert.equal(page.status, 200, 'the real local view page remains available');
+ assert.match(page.headers.get('content-type') ?? '', /text\/html/);
+
+ await box.stopRelay();
+ const status = await box.cli('status');
+ const listed = await box.cli('list', '--all');
+ const shown = await box.cli('show', '1');
+ assert.equal(status.code, 0, 'status reads its local board while disconnected');
+ assert.equal(listed.code, 0, 'list reads its local board while disconnected');
+ assert.ok(listed.document.items.some(item => item.item_title === 'private cleanup fixture item'));
+ assert.equal(shown.code, 0, 'show reads its local board while disconnected');
+ assert.equal(shown.document.item_title, 'private cleanup fixture item');
+
+ const viewKey = new URL(view.url).searchParams.get('k');
+ const localBoardsUrl = new URL('/api/v1/boards', view.url);
+ localBoardsUrl.searchParams.set('k', viewKey);
+ const localBoardsResponse = await fetch(localBoardsUrl);
+ assert.equal(localBoardsResponse.status, 200, 'the local view API remains available offline');
+ const localBoards = await localBoardsResponse.json();
+ const localBoard = localBoards.boards.find(board => board.root === box.root);
+ assert.ok(localBoard, 'the local view still lists the linked project from its local registry');
+ const localStateUrl = new URL(`/api/v1/boards/${localBoard.id}/state`, view.url);
+ localStateUrl.searchParams.set('k', viewKey);
+ const localStateResponse = await fetch(localStateUrl);
+ assert.equal(localStateResponse.status, 200);
+ const localState = await localStateResponse.json();
+ assert.ok(localState.state.items.some(item => item.title === 'private cleanup fixture item'),
+ 'the local view reads the same private board contents while the relay is stopped');
+
+ for (const args of [
+ ['add', box.lane, 'refused offline add'],
+ ['shout', 'coordinator', 'refused offline shout'],
+ ]) {
+ const refused = await box.cli(...args);
+ assert.equal(refused.code, 1);
+ assert.equal(refused.document.error.code, 'RELAY_UNAVAILABLE');
+ assert.ok(refused.document.error.message.includes(box.origin), 'the refusal names the address attempted');
+ assert.match(refused.document.error.message, /retry this move when the relay is reachable/);
+ }
+ const viewMoveUrl = new URL(`/api/v1/boards/${localBoard.id}/moves`, view.url);
+ viewMoveUrl.searchParams.set('k', viewKey);
+ const viewMove = await fetch(viewMoveUrl, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ verb: 'add', args: { lane: box.lane, title: 'refused offline view move' } }),
+ });
+ assert.equal(viewMove.status, 409, 'the local view API uses the linked move refusal path');
+ assert.equal((await viewMove.json()).error.code, 'RELAY_UNAVAILABLE');
+
+ assert.deepEqual(readFileSync(boardFile), beforeBytes, 'offline reads and refused moves leave the native board bytes unchanged');
+ assert.deepEqual((await box.cli('export')).document.tables, beforeTables, 'no speculative local move or event was applied');
+
+ await box.restartRelay();
+ const resumed = await box.cli('add', box.lane, 'move after relay returns');
+ assert.equal(resumed.code, 0, 'the relay resumes without relay off/on repair');
+ assert.equal(resumed.document.item.item_title, 'move after relay returns');
+ const afterTables = (await box.cli('export')).document.tables;
+ assert.equal(afterTables.event.length, beforeEvents.length + 1, 'only the acknowledged recovery move is recorded locally');
+ assert.equal(afterTables.event.at(-1).event_kind, 'add');
+ const remoteStateResponse = await fetch(`${box.origin}/api/v1/boards/${link.board}/state`, {
- headers: { authorization: `Bearer ${link.token}` },
++ headers: { authorization: `Bearer ${link.token}`, 'x-pullboard-engine': String(ENGINE_VERSION) },
+ });
+ assert.equal(remoteStateResponse.status, 200);
+ assert.equal((await remoteStateResponse.json()).state.sequence, 1, 'the resumed move has exactly one relay position');
+ } finally {
+ if (view) await view.close();
+ for (const [name, value] of oldEnvironment) {
+ if (value === undefined) delete process.env[name];
+ else process.env[name] = value;
+ }
+ }
+ });
+
test('plain relay off explains an already-deleted board without printing credentials [H1,H18]', async (t) => {
const box = await relayClientFixture(t);
await box.link();