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.

fix(relay): renew expired agent sign-ins once [H16,H5]

Corey Olson367afa945330
diff --git a/src/relay.js b/src/relay.js
index 54693e7f..3c6d1868 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -32,6 +32,9 @@ const CHECKPOINT_NOTICES = new WeakMap();
const CHECKPOINT_MOVES = new WeakMap();
const BASELINE_LOCAL_MOVES = new WeakSet();
const BASELINE_FAILURES = new WeakMap();
+const AUTH_NOTICES = new WeakSet();
+const ORDERED_MOVE_COMMANDS = new Set(['add', 'edit', 'fact', 'escalate', 'run', 'sweep', 'next', 'claim', 'hold', 'release',
+ 'submit', 'done', 'verify', 'merged', 'withdraw', 'refreeze', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget', 'join', 'worktree']);
/** Require a trusted origin; HTTP exists only for loopback development and test relays. */
export function relayOrigin(address) {
@@ -233,6 +236,32 @@ function safePauseMessage(error) {
return message.slice(0, 240) || 'the relay refused the baseline upload';
}
+/** Whether the CLI command will make an ordered move whose refusal should be reported at dispatch. */
+function orderedMoveCommand(io) {
+ const command = io.relayCommand;
+ if (command?.cliOperation === 'spec') return ['approve', 'decline', 'apply'].includes(command.positionals?.[0]);
+ return ORDERED_MOVE_COMMANDS.has(command?.cliOperation);
+}
+
+/** Give a local read a single safe explanation when its signed relay read is refused. */
+function reportExpiredSignIn(state, io) {
+ if (AUTH_NOTICES.has(io)) return;
+ AUTH_NOTICES.add(io);
+ const fix = process.env.PULLBOARD_RELAY_TOKEN !== undefined
+ ? 'unset PULLBOARD_RELAY_TOKEN to use this machine credential or supply a current PULLBOARD_RELAY_TOKEN'
+ : 'run pullboard relay on to sign in again or pullboard relay off to stop syncing';
+ io.err(`pullboard: [AUTH_REQUIRED] relay sign-in expired or was revoked for board ${state.board}; ${fix}`);
+}
+
+/** Preserve the ordered-move refusal while naming this board and both recovery choices. */
+function expiredSignInMoveRefusal(state, error) {
+ const reason = safePauseMessage(error);
+ if (process.env.PULLBOARD_RELAY_TOKEN !== undefined) {
+ return new Refused('AUTH_REQUIRED', `the supplied PULLBOARD_RELAY_TOKEN was refused for board ${state.board}: ${reason}; unset PULLBOARD_RELAY_TOKEN to use this machine credential or supply a current PULLBOARD_RELAY_TOKEN`);
+ }
+ return new Refused('AUTH_REQUIRED', `relay sign-in expired or was revoked for board ${state.board}: ${reason}; run pullboard relay on to give this machine a credential or pullboard relay off to stop syncing`);
+}
+
/** Pause only definitive baseline 4xx refusals; throttling and transient errors retain retries. */
function permanentBaselineRefusal(error) {
return Number.isInteger(error?.httpStatus) && error.httpStatus >= 400 && error.httpStatus < 500 &&
@@ -667,6 +696,7 @@ async function catchUp(root, file, state, io) {
/** Finish a durable executable send; a collision reseals its unchanged id after applying the winner. */
async function sendPending(root, file, state, io) {
+ let renewedAgentToken = false;
for (let tries = 0; state.pending && tries < 100; tries += 1) {
const pending = state.pending;
try {
@@ -674,6 +704,16 @@ async function sendPending(root, file, state, 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) {
+ const actor = credentialActor(pending.move);
+ if (error.code === 'AUTH_REQUIRED' && !renewedAgentToken && actor !== 'machine' && actor !== 'person'
+ && process.env.PULLBOARD_RELAY_TOKEN === undefined && state.token?.startsWith('pm_') && state.agentTokens?.[actor]?.token) {
+ // A revoked/expired PA cache can be replaced once by this board's existing PM credential.
+ delete state.agentTokens[actor];
+ saveLink(file, state);
+ renewedAgentToken = true;
+ await actorTransport(root, file, state, actor, io);
+ continue;
+ }
if (!['SEQUENCE_REPEAT', 'SEQUENCE_GAP'].includes(error.code)) throw error;
await catchUp(root, file, state, io);
if (state.pending) {
@@ -698,7 +738,7 @@ function credentialActor(move) {
return relayMoveActor(move);
}
-/** Select one scoped credential without renewing a revoked or expired agent cache. */
+/** Select a scoped credential; sendPending alone may renew a failed cached token once. */
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');
@@ -785,60 +825,69 @@ export async function relayOperation(root, operation, args, io, command, applyLo
const applyPausedMoveLocally = () => typeof applyLocally === 'function'
? applyLocally()
: localRecords(root, (board) => store[operation](board, ...args));
- if (!await ensureOrdered(root, file, state, io)) {
- // Preflight's notice covers the first move; long-running commands still name every later move.
- if (BASELINE_LOCAL_MOVES.has(io)) BASELINE_NOTICES.delete(io);
- reportBaselinePause(state, io);
- BASELINE_LOCAL_MOVES.add(io);
- return applyPausedMoveLocally();
- }
- await catchUp(root, file, state, io);
- if (state.pending) {
- delete state.pending;
- saveLink(file, state);
- }
- const previousReceipt = io.personRequestMoveId && localRecords(root, board => engineReceipt(board, io.personRequestMoveId));
- if (previousReceipt) {
- if (state.recovered?.move?.id === io.personRequestMoveId) {
- delete state.recovered;
+ try {
+ if (!await ensureOrdered(root, file, state, io)) {
+ // Preflight's notice covers the first move; long-running commands still name every later move.
+ if (BASELINE_LOCAL_MOVES.has(io)) BASELINE_NOTICES.delete(io);
+ reportBaselinePause(state, io);
+ BASELINE_LOCAL_MOVES.add(io);
+ return applyPausedMoveLocally();
+ }
+ await catchUp(root, file, state, io);
+ if (state.pending) {
+ delete state.pending;
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);
- const problem = move.personRequest && localRecords(root, board => requestMoveProblem(board, move, { checkExecutorLease: false }));
- if (problem) throw problem;
- 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) };
+ 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);
+ const problem = move.personRequest && localRecords(root, board => requestMoveProblem(board, move, { checkExecutorLease: false }));
+ if (problem) throw problem;
+ 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);
- try { await sendPending(root, file, state, io); }
+ // 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 (!['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;
+ if (!(error instanceof Refused)) throw error;
+ if (error.code === 'AUTH_REQUIRED') reportExpiredSignIn(state, io);
+ else io.err(`pullboard: ${error.message}`);
}
+ if (receipt.outcome.error) throw new Refused(receipt.outcome.error.code, receipt.outcome.error.message);
+ if (['register', 'ensureCoordinator'].includes(operation)) await actorTransport(root, file, state, receipt.outcome.result, io);
+ for (const event of receipt.outcome.events ?? []) io.onEvent?.(event);
+ return receipt.outcome.result;
+ } catch (error) {
+ if (error instanceof Refused && error.code === 'AUTH_REQUIRED') throw expiredSignInMoveRefusal(state, error);
+ 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}`); }
- if (receipt.outcome.error) throw new Refused(receipt.outcome.error.code, receipt.outcome.error.message);
- if (['register', 'ensureCoordinator'].includes(operation)) await actorTransport(root, file, state, receipt.outcome.result, io);
- for (const event of receipt.outcome.events ?? []) io.onEvent?.(event);
- return receipt.outcome.result;
});
}
@@ -874,6 +923,8 @@ export async function syncRelay(root, io) {
KEY_WARNED_COMMANDS.add(io);
io.err(`pullboard: ${error.message}; moves are off until the key is reachable`);
}
+ } else if (error.code === 'AUTH_REQUIRED') {
+ if (!orderedMoveCommand(io)) reportExpiredSignIn(state, io);
} else io.err(`pullboard: ${error.message}; run pullboard status to see pending uploads`);
return { linked: true, board: state.board, url: state.url, sequence: state.sequence,
behind: (state.mode === 'ordered' ? Number(Boolean(state.pending)) : behind(root, state)) + Number(Boolean(state.snapshot || state.checkpoint)) };
diff --git a/test/relay-agent.test.js b/test/relay-agent.test.js
index 325da448..9ebad4e7 100644
--- a/test/relay-agent.test.js
+++ b/test/relay-agent.test.js
@@ -336,13 +336,17 @@ test('ordered agent joins mint scoped tokens and retain authenticated native act
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 while the paired phone remains available');
- 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 machine credential never silently re-mints its revoked agent cache');
+ const cachedMoveCount = box.calls.filter((call) => call.method === 'POST' && call.path.endsWith('/moves')).length;
+ const beforeCachedRenewal = nativeEvents(boardFile);
+ const cachedRenewal = await runCli(firstRoot, box.env, cli, ['shout', 'all', 'renew the revoked agent cache once']);
+ assert.equal(cachedRenewal.code, 0, cachedRenewal.failure ?? 'the valid machine credential replaces one revoked cached agent token');
+ assert.equal(box.calls.filter((call) => call.method === 'POST' && call.path === '/auth/tokens').length, cachedMintCount + 1,
+ 'one revoked cache causes exactly one replacement scoped token to be minted');
+ assert.equal(box.calls.filter((call) => call.method === 'POST' && call.path.endsWith('/moves')).length, cachedMoveCount + 2,
+ 'the refused ordered send is retried exactly once with the replacement credential');
+ const afterCachedRenewal = nativeEvents(boardFile);
+ assert.equal(afterCachedRenewal.length, beforeCachedRenewal.length + 1,
+ 'the authenticated retry writes exactly one native board event');
const linkAfterRevoke = JSON.parse(readFileSync(box.linkFile, 'utf8'));
const machineRevoked = await fetch(box.origin + '/auth/tokens/revoke', {
diff --git a/test/relay-auth-expired.test.js b/test/relay-auth-expired.test.js
new file mode 100644
index 00000000..121fc9cb
--- /dev/null
+++ b/test/relay-auth-expired.test.js
@@ -0,0 +1,207 @@
+/** Expired relay credentials retain local reads and ordered, actor-scoped moves [H16,H5]. */
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { relayClientFixture } from './relay-client-fixture.js';
+import { runFixtureGit } from './fixture-child.js';
+
+/** Revoke one private fixture credential through the real relay authorization endpoint. */
+async function revokeCredential(box, id) {
+ const phone = await box.phoneSession();
+ const response = await fetch(box.origin + '/auth/tokens/revoke', {
+ method: 'POST',
+ headers: { authorization: 'Bearer ' + phone.token, 'content-type': 'application/json' },
+ body: JSON.stringify({ id }),
+ });
+ assert.equal(response.status, 200, 'the fixture revokes the selected opaque credential');
+}
+
+/** Read one real CLI result and check its single board-named local fallback diagnostic. */
+async function assertLocalRead(box, board, ...args) {
+ const result = await box.cli(...args);
+ assert.equal(result.code, 0, result.failure ?? `${args[0]} answers from the local board`);
+ assert.equal(result.document.diagnostics?.length, 1, `${args[0]} prints one auth-expiry line`);
+ assert.match(result.document.diagnostics[0], new RegExp(board));
+ assert.match(result.document.diagnostics[0], /sign-in expired or was revoked/u);
+ assert.match(result.document.diagnostics[0], /pullboard relay on.*pullboard relay off/u);
+ return result;
+}
+
+test('reads and status answer when the relay sign-in expired [H16,H5]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const seed = await box.cli('add', box.lane, 'local read fixture');
+ assert.equal(seed.code, 0, seed.failure ?? 'the private real relay accepts a fixture move');
+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ await revokeCredential(box, state.tokenId);
+
+ const board = state.board;
+ await assertLocalRead(box, board, 'status');
+ await assertLocalRead(box, board, 'spec', 'check');
+ await assertLocalRead(box, board, 'show', String(seed.document.item.item_id));
+ await assertLocalRead(box, board, 'list', '--all');
+ await assertLocalRead(box, board, 'decisions');
+ await assertLocalRead(box, board, 'inbox');
+ await assertLocalRead(box, board, 'log');
+ const view = await assertLocalRead(box, board, 'view', '--export', join(box.root, 'local-view.html'));
+ assert.equal(existsSync(view.document.path), true, 'the local view export is available after relay auth refusal');
+});
+
+test('a move renews its agent token from the machine credential [H16,H5]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const seed = await box.cli('add', box.lane, 'seed agent credential');
+ assert.equal(seed.code, 0, seed.failure ?? 'the initial move registers the coordinator token');
+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const agent = state.agentTokens.coordinator;
+ assert.ok(agent?.id, 'the board link caches a scoped coordinator credential');
+ await revokeCredential(box, agent.id);
+
+ const mintsBefore = box.calls.filter(call => call.method === 'POST' && call.path === '/auth/tokens').length;
+ const sendsBefore = box.calls.filter(call => call.method === 'POST' && call.path.endsWith('/moves')).length;
+ const acksBefore = box.moveAcks.length;
+ const moved = await box.cli('add', box.lane, 'move after agent-token renewal');
+ assert.equal(moved.code, 0, moved.failure ?? 'the machine credential renews the revoked scoped token');
+ assert.equal(box.calls.filter(call => call.method === 'POST' && call.path === '/auth/tokens').length, mintsBefore + 1,
+ 'one machine-authenticated request mints one replacement agent token');
+ assert.equal(box.calls.filter(call => call.method === 'POST' && call.path.endsWith('/moves')).length, sendsBefore + 2,
+ 'the refused move is retried exactly once with the replacement token');
+ assert.equal(box.moveAcks.length, acksBefore + 1, 'the ordered relay acknowledges exactly one move');
+ const rows = (await box.cli('export')).document.tables.item;
+ assert.equal(rows.filter(row => row.item_title === 'move after agent-token renewal').length, 1,
+ 'the retried ordered move has one local effect');
+ const beforeSecondRefusal = (await box.cli('export')).document.tables;
+ const cached = JSON.parse(readFileSync(box.linkFile, 'utf8')).agentTokens.coordinator;
+ await revokeCredential(box, cached.id);
+ let refusedSends = 0;
+ /** Revoke each actual scoped credential just before its real HTTP send. */
+ async function revokeAtSend() {
+ const current = JSON.parse(readFileSync(box.linkFile, 'utf8')).agentTokens.coordinator;
+ await revokeCredential(box, current.id);
+ refusedSends += 1;
+ if (refusedSends === 1) box.beforeNextMove(revokeAtSend);
+ }
+ box.beforeNextMove(revokeAtSend);
+ const mintsBeforeRefusal = box.calls.filter(call => call.method === 'POST' && call.path === '/auth/tokens').length;
+ const failed = await box.cli('add', box.lane, 'a second refusal must not retry forever');
+ assert.equal(failed.code, 1, 'a replacement token refused again stops this command');
+ assert.equal(failed.document.error.code, 'AUTH_REQUIRED');
+ assert.equal(refusedSends, 2, 'there is one original send and one retry');
+ assert.equal(box.calls.filter(call => call.method === 'POST' && call.path === '/auth/tokens').length, mintsBeforeRefusal + 1,
+ 'a second refusal never causes a second mint');
+ assert.deepEqual((await box.cli('export')).document.tables, beforeSecondRefusal,
+ 'neither refused send can change the local ordered board');
+});
+
+test('a move without a machine credential refuses with the fix [H16,H5]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const seed = await box.cli('add', box.lane, 'seed revoked machine fixture');
+ assert.equal(seed.code, 0, seed.failure ?? 'the initial move registers a scoped credential');
+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const cliPath = fileURLToPath(new URL('../bin/pullboard.js', import.meta.url));
+ writeFileSync(join(box.env.PATH, 'pullboard'), `#!/bin/sh\nexec node "${cliPath}" "$@"\n`, { mode: 0o700 });
+ runFixtureGit(['add', '-A'], { cwd: box.root, env: box.env });
+ runFixtureGit(['commit', '-q', '-m', 'test: prepare private ordered claim'], { cwd: box.root, env: box.env });
+ const agentRoot = join(box.root, '..', 'claim-agent');
+ runFixtureGit(['worktree', 'add', '-q', '-b', 'core/auth-claim', agentRoot], { cwd: box.root, env: box.env });
+ const joined = await box.cliAt(agentRoot, 'join', box.lane);
+ assert.equal(joined.code, 0, joined.failure ?? 'a real agent joins before the credentials are revoked');
+ await revokeCredential(box, state.agentTokens.coordinator.id);
+ const before = (await box.cli('export')).document.tables;
+ const mintsBeforeExplicit = box.calls.filter(call => call.method === 'POST' && call.path === '/auth/tokens').length;
+ const sendsBeforeExplicit = box.calls.filter(call => call.method === 'POST' && call.path.endsWith('/moves')).length;
+
+ box.env.PULLBOARD_RELAY_TOKEN = state.agentTokens.coordinator.token;
+ try {
+ const explicit = await box.cli('add', box.lane, 'explicit revoked token is not replaced');
+ assert.equal(explicit.code, 1);
+ assert.equal(explicit.document.error.code, 'AUTH_REQUIRED');
+ assert.match(explicit.document.error.message, /supplied PULLBOARD_RELAY_TOKEN was refused/u);
+ assert.match(explicit.document.error.message, /unset PULLBOARD_RELAY_TOKEN.*supply a current PULLBOARD_RELAY_TOKEN/u);
+ assert.equal(box.calls.filter(call => call.method === 'POST' && call.path === '/auth/tokens').length, mintsBeforeExplicit,
+ 'an explicit revoked token is never replaced from the machine credential');
+ assert.equal(box.calls.filter(call => call.method === 'POST' && call.path.endsWith('/moves')).length, sendsBeforeExplicit,
+ 'the explicit-token refusal never reaches the relay move endpoint');
+ assert.deepEqual((await box.cli('export')).document.tables, before,
+ 'an explicit revoked token is preserved as the caller identity and cannot apply a local move');
+ } finally { delete box.env.PULLBOARD_RELAY_TOKEN; }
+
+ await revokeCredential(box, state.tokenId);
+ const refused = await box.cli('add', box.lane, 'must stay ordered without machine auth');
+ assert.equal(refused.code, 1);
+ assert.equal(refused.document.error.code, 'AUTH_REQUIRED');
+ assert.equal(refused.document.error.message.split('\n').length, 1, 'the refusal stays on one line');
+ assert.match(refused.document.error.message, new RegExp(state.board));
+ assert.match(refused.document.error.message, /expired or was revoked/u);
+ assert.match(refused.document.error.message, /pullboard relay on.*pullboard relay off/u);
+ assert.deepEqual((await box.cli('export')).document.tables, before, 'a move without renewable machine authority is never applied locally out of order');
+ const next = await box.cliAt(agentRoot, 'next', '--build');
+ assert.equal(next.code, 1, 'next is an ordered claim/reservation move, not an offline read');
+ assert.equal(next.document.error.code, 'AUTH_REQUIRED');
+ assert.match(next.document.error.message, /pullboard relay on.*pullboard relay off/u);
+ assert.deepEqual((await box.cli('export')).document.tables, before, 'an unauthenticated next cannot reserve locally out of order');
+ const textRefusal = await box.script(`
+ const { main } = await import(${JSON.stringify(box.mainURL)});
+ let stdout = '', stderr = '';
+ const code = await main(['join', ${JSON.stringify(box.lane)}], {
+ cwd: ${JSON.stringify(agentRoot)}, stdout: { write(value) { stdout += value; } }, stderr: { write(value) { stderr += value; } },
+ });
+ console.log(JSON.stringify({ code, stdout, stderr }));
+ `);
+ assert.equal(textRefusal.code, 0, 'the private production CLI capture completes');
+ assert.equal(textRefusal.document.code, 1);
+ const refusalLines = textRefusal.document.stderr.trim().split('\n');
+ assert.equal(refusalLines.length, 1, 'text registration reports exactly one refusal line');
+ assert.match(refusalLines[0], new RegExp(state.board));
+ assert.match(refusalLines[0], /pullboard relay on.*pullboard relay off/u);
+ const rejoin = await box.cliAt(agentRoot, 'join', box.lane);
+ assert.equal(rejoin.code, 1);
+ assert.equal(rejoin.document.error.code, 'AUTH_REQUIRED');
+ assert.equal((rejoin.document.diagnostics ?? []).length, 0, 'registration reports only its refusal, without a read fallback first');
+ assert.equal(rejoin.document.error.message.split('\n').length, 1);
+ assert.match(rejoin.document.error.message, new RegExp(state.board));
+ assert.match(rejoin.document.error.message, /pullboard relay on.*pullboard relay off/u);
+
+ const phone = await box.phoneSession();
+ for (const token of [state.agentTokens.coordinator.token, phone.token, undefined]) {
+ const legacy = { ...JSON.parse(readFileSync(box.linkFile, 'utf8')), token };
+ delete legacy.tokenId;
+ delete legacy.agentTokens;
+ writeFileSync(box.linkFile, JSON.stringify(legacy) + '\n', { mode: 0o600 });
+ const oldRead = await assertLocalRead(box, state.board, 'status');
+ assert.equal(oldRead.code, 0);
+ const oldMove = await box.cli('add', box.lane, 'old links cannot apply out of order');
+ assert.equal(oldMove.code, 1);
+ assert.equal(oldMove.document.error.code, 'AUTH_REQUIRED');
+ assert.equal((oldMove.document.diagnostics ?? []).length, 0);
+ assert.equal(oldMove.document.error.message.split('\n').length, 1);
+ assert.match(oldMove.document.error.message, new RegExp(state.board));
+ assert.match(oldMove.document.error.message, /pullboard relay on.*pullboard relay off/u);
+ assert.deepEqual((await box.cli('export')).document.tables, before, 'old PA, PS and tokenless links retain the local board');
+ }
+});
+
+test('relay off keeps a board out of auto-link [H1,H7,H16]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const machineFile = join(box.env.PULLBOARD_HOME, 'relay-machine', 'state.json');
+ const machine = JSON.parse(readFileSync(machineFile, 'utf8'));
+ machine.autoLink = true;
+ writeFileSync(machineFile, JSON.stringify(machine) + '\n', { mode: 0o600 });
+
+ const off = await box.cli('relay', 'off');
+ assert.equal(off.code, 0, off.failure ?? 'relay off always completes local unlink');
+ assert.equal(existsSync(box.linkFile), false, 'relay off removes the local link immediately');
+ const excluded = JSON.parse(readFileSync(machineFile, 'utf8')).excluded;
+ assert.ok(excluded.includes(box.root), 'relay off durably records the local opt-out');
+
+ const callsBeforeStatus = box.calls.length;
+ const status = await box.cli('status');
+ assert.equal(status.code, 0, status.failure ?? 'local status remains available after relay off');
+ assert.equal(status.document.relay.linked, false, 'the auto-link pass leaves the board unlinked');
+ assert.equal(box.calls.length, callsBeforeStatus, 'auto-link does not contact the relay or relink an excluded board');
+ assert.ok(JSON.parse(readFileSync(machineFile, 'utf8')).excluded.includes(box.root));
+});