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): retain pending moves after deletion [H17,E9]

Corey Olson3f5770df235a
diff --git a/docs/api.md b/docs/api.md
index 60e89989..ce483240 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -203,7 +203,7 @@ Phone enrollment uses a one-use `#device=<locator>.<secret>` fragment, removed b
`GET /auth/machines?board=<id>` returns `{version, machines: [{machine}]}` for the live computer credentials on that board, with duplicate computer ids listed once. It requires that board's machine credential or a person session with current repository write access; agent tokens and credentials from another board are refused. `relay off` excludes its own computer from the list and warns which joined computers lose the shared copy if the phone approves deletion. JSON also returns those ids in `affectedMachines`. Local unlink still succeeds when the relay cannot supply the list.
-After phone-approved deletion, a previously live scoped credential receives HTTP 410 / `RELAY_BOARD_DELETED` for that deleted copy. The relay retains only its hash, board id and original expiry as a deletion receipt, prunes expired receipts, and grants no access through them. Unknown, already revoked and already expired credentials receive `AUTH_REQUIRED` as before. Only a versioned deletion response naming this link's own board turns a joined computer back into a local board. The CLI removes the inert link and its device key, excludes the project from automatic relinking, and retains a private credential-free notice that the relay copy was deleted; native board contents remain local. A successful explicit `relay on` starts a new link and clears that notice. A network outage or ordinary credential refusal does not authorize this transition.
+After phone-approved deletion, a previously live scoped credential receives HTTP 410 / `RELAY_BOARD_DELETED` for that deleted copy. The relay retains only its hash, board id and original expiry as a deletion receipt, prunes expired receipts, and grants no access through them. Unknown, already revoked and already expired credentials receive `AUTH_REQUIRED` as before. Only a versioned deletion response naming this link's own board turns a joined computer back into a local board. The CLI removes the inert link and its device key, excludes the project from automatic relinking, and retains a private credential-free notice that the relay copy was deleted; native board contents remain local. A successful explicit `relay on` starts a new link and clears that notice. A network outage or ordinary credential refusal does not authorize this transition. Before forgetting a deleted copy, the CLI commits any pending native move and its durable receipt locally. The notice keeps only the receipt id and intent digests, so interrupted cleanup or an explicit repeat can return the original outcome without applying that move twice; different local work can continue beside it.
A machine publishes an opaque approval with `POST /api/v1/devices/approvals {context,sealed}`. The publishing machine may GET only its own requests. The paired phone reads `/api/v1/devices/:deviceId/approvals`, explicitly POSTs `/:requestId/authorize {}` and completes the encrypted reply through `/:requestId/complete {response}`. The publishing machine executes a native revocation through `/:requestId/execute {grant}`; the two-minute grant binds the entire context and is atomically consumed once. Native reply keys and grants never persist. A refused foreground approval fails immediately with the original refusal code and reason plus its request id. A refused remote approval makes local unlinking or registration exit nonzero while retaining the completed local work: one line names that completion, the refusal code and reason, the request id and the next action. The JSON result preserves the local outcome and includes `remote: {code, reason, requestId}`. New-board linking uses a durable non-person reply key and returns only a board-scoped machine credential. `relay off` immediately unlinks locally even offline or in an agent shell, reports that the relay copy remains, and queues a separate one-tap phone deletion request when possible.
diff --git a/src/cli.js b/src/cli.js
index 3c5fb08f..c7489886 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -579,7 +579,7 @@ function withBoard(ctx, work) {
async function ordered(ctx, board, operation, args) {
const command = ['add', 'edit', 'merged'].includes(ctx.io.relayCommand?.cliOperation) ? ctx.io.relayCommand : undefined;
/** Dispatch while this session holds the checkout, including long-running next/run loops. */
- const execute = () => relayLinked(ctx.info.root)
+ const execute = () => relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)
? relayOperation(ctx.info.root, operation, args, ctx.io, command, () => store[operation](board, ...args)) : store[operation](board, ...args);
const digest = agentSessionDigest();
const boardOnly = CHECKOUT_BOARD_ONLY.get(ctx.io);
diff --git a/src/relay.js b/src/relay.js
index 81035e72..3ad226a4 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -6,7 +6,7 @@ import { basename, dirname, join } from 'node:path';
import { gunzipSync, gzipSync } from 'node:zlib';
import * as store from './board.js';
import { exportBoard, importBoard, restoreRelaySnapshot, semanticBoardDigest } from './exchange.js';
-import { appliedSequence, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, refuseRelayMove, requireSupportedEngine, startRelayEpoch } from './engine.js';
+import { appliedSequence, applyEngineMove, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, refuseRelayMove, 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';
@@ -87,6 +87,12 @@ function deletedLink(root) {
try { value = JSON.parse(readFileSync(file, 'utf8')); } catch { throw new Refused('RELAY_STORAGE', 'restore the private deleted-copy notice before reading relay status'); }
if (value?.version !== 1 || !/^[0-9a-f]{32}$/u.test(value.board ?? '') || typeof value.url !== 'string') throw new Refused('RELAY_STORAGE', 'restore the supported deleted-copy notice before reading relay status');
relayOrigin(value.url);
+ const recovered = value.recovered;
+ if (recovered !== undefined && (!recovered || !/^[A-Za-z0-9_-]{1,80}$/u.test(recovered.id ?? '')
+ || !/^[0-9a-f]{64}$/u.test(recovered.intent ?? '')
+ || (recovered.commandIntent !== undefined && !/^[0-9a-f]{64}$/u.test(recovered.commandIntent)))) {
+ throw new Refused('RELAY_STORAGE', 'restore the private interrupted-move receipt pointer before retrying');
+ }
return value;
}
@@ -96,14 +102,81 @@ function confirmedDeletion(state, error) {
&& error.relayCode === 'RELAY_BOARD_DELETED' && error.relayMessage?.startsWith(`relay copy ${state.board} was deleted;`);
}
-/** Preserve a truthful local notice before removing an inert link; the native board is never replaced. */
-function forgetDeletedCopy(root, file, state, io) {
+/** Atomically persist a private notice and its optional key-free native receipt pointer. */
+function saveDeletedLink(root, value) {
const marker = deletedLinkFile(root);
const temporary = marker + '.' + randomUUID() + '.tmp';
+ const encoded = JSON.stringify(value) + '\n';
+ if (Buffer.byteLength(encoded) > 4096) throw new Refused('RELAY_STORAGE', 'restore a bounded deleted-copy notice before retrying');
try {
- writeFileSync(temporary, JSON.stringify({ version: 1, board: state.board, url: state.url }) + '\n', { flag: 'wx', mode: 0o600 });
+ writeFileSync(temporary, encoded, { flag: 'wx', mode: 0o600 });
renameSync(temporary, marker);
} finally { rmSync(temporary, { force: true }); }
+}
+
+/** Compare an interrupted intent without retaining command arguments or credentials in the notice. */
+function intentDigest(intent) { return createHash('sha256').update(intent).digest('hex'); }
+
+/** Commit the sender's pending native obligation before any link metadata or key can be removed. */
+function retainDeletedMove(root, state) {
+ const recovered = state.pending ?? state.recovered;
+ if (!recovered) return null;
+ const move = recovered.move;
+ if (!move || typeof move.id !== 'string') throw new Refused('RELAY_STORAGE', 'restore the interrupted move before forgetting the deleted copy');
+ const intent = recovered.intent ?? operationIntent(move.operation, move.args);
+ if (typeof intent !== 'string' || recovered.commandIntent !== undefined
+ && recovered.commandIntent !== operationIntent('cli:' + recovered.command?.cliOperation, recovered.command)) {
+ throw new Refused('RELAY_STORAGE', 'restore the interrupted command metadata before retrying');
+ }
+ localRecords(root, board => {
+ const receipt = engineReceipt(board, move.id);
+ if (receipt) {
+ if (receipt.move !== JSON.stringify(move)) throw new Refused('RELAY_MOVE', 'restore the interrupted move that matches its durable receipt before retrying');
+ return; // A crash after the receipt must not advance the native cursor again.
+ }
+ applyEngineMove(board, move, { sequence: appliedSequence(board) + 1, at: board.clock.now().toISOString() });
+ });
+ return { id: move.id, intent: intentDigest(intent),
+ ...(recovered.commandIntent === undefined ? {} : { commandIntent: intentDigest(recovered.commandIntent) }) };
+}
+
+/** Resolve the private pointer only through the exact durable native receipt, never a remote key. */
+function deletedRecovery(root) {
+ const marker = deletedLink(root);
+ if (!marker?.recovered) return null;
+ const receipt = localRecords(root, board => engineReceipt(board, marker.recovered.id));
+ let move;
+ try { move = receipt && JSON.parse(receipt.move); } catch { /* Refuse a corrupt receipt below. */ }
+ if (!move || move.id !== marker.recovered.id || !receipt.outcome) {
+ throw new Refused('RELAY_STORAGE', 'restore the interrupted native receipt before retrying its command');
+ }
+ return { marker, receipt, move };
+}
+
+/** Consume only the reported receipt, preserving the truthful deleted-copy notice. */
+function clearDeletedRecovery(root, marker) {
+ delete marker.recovered;
+ saveDeletedLink(root, marker);
+}
+
+/** Return an exact interrupted result once; a different command can continue beside the saved move. */
+function deletedMoveResult(root, operation, args, command, io, applyLocally) {
+ const recovered = deletedRecovery(root);
+ const pointer = recovered?.marker.recovered;
+ const matches = pointer && (pointer.commandIntent === undefined
+ ? pointer.intent === intentDigest(operationIntent(operation, args))
+ : recovered.move.operation === operation && pointer.commandIntent === intentDigest(operationIntent('cli:' + command?.cliOperation, command)));
+ if (!matches) return applyLocally();
+ clearDeletedRecovery(root, recovered.marker);
+ if (recovered.receipt.outcome.error) throw refusalFromReceipt(recovered.receipt.outcome.error);
+ for (const event of recovered.receipt.outcome.events ?? []) io.onEvent?.(event);
+ return recovered.receipt.outcome.result;
+}
+
+/** Preserve the pending native move and a truthful notice before removing the inert link. */
+function forgetDeletedCopy(root, file, state, io) {
+ const recovered = retainDeletedMove(root, state);
+ saveDeletedLink(root, { version: 1, board: state.board, url: state.url, ...(recovered ? { recovered } : {}) });
updateRelayMachine(machine => { const project = repoInfo(root).root; if (!machine.excluded.includes(project)) machine.excluded.push(project); });
rmSync(file, { force: true });
try { forgetBoardKey(state.board, state.keyStorage); } catch { /* An unavailable key store cannot block completed local opt-out. */ }
@@ -963,6 +1036,11 @@ export async function relayOperation(root, operation, args, io, command, applyLo
const file = linkFile(root);
return locked(file, async () => {
const state = loadLink(file);
+ /** Apply through the CLI's existing board handle so local events and guards remain unchanged. */
+ const applyPausedMoveLocally = () => typeof applyLocally === 'function'
+ ? applyLocally()
+ : localRecords(root, (board) => store[operation](board, ...args));
+ if (!state && deletedRecovery(root)) return deletedMoveResult(root, operation, args, command, io, applyPausedMoveLocally);
if (!state || state.unlinking) throw new Refused('RELAY_UNLINK_PENDING', 'finish unlinking this device with pullboard relay off before sending a move');
if (state.recovery) throw new Refused('RELAY_RECOVERY_PENDING', `finish the saved recovery for sequence ${state.recovery.skip} before sending a linked move`);
if (credentialActor({ operation, args, personRequest: io?.personRequest }) === 'person') {
@@ -972,10 +1050,6 @@ export async function relayOperation(root, operation, args, io, command, applyLo
if (!moves) { moves = new Set(); CHECKPOINT_MOVES.set(io, moves); }
if (moves.has(state.board)) CHECKPOINT_NOTICES.get(io)?.delete(state.board);
moves.add(state.board);
- /** Apply through the CLI's existing board handle so local events and guards remain unchanged. */
- const applyPausedMoveLocally = () => typeof applyLocally === 'function'
- ? applyLocally()
- : localRecords(root, (board) => store[operation](board, ...args));
try {
if (!await ensureOrdered(root, file, state, io)) {
// Preflight's notice covers the first move; long-running commands still name every later move.
@@ -1037,7 +1111,10 @@ export async function relayOperation(root, operation, args, io, command, applyLo
for (const event of receipt.outcome.events ?? []) io.onEvent?.(event);
return receipt.outcome.result;
} catch (error) {
- if (confirmedDeletion(state, error)) { forgetDeletedCopy(root, file, state, io); return applyPausedMoveLocally(); }
+ if (confirmedDeletion(state, error)) {
+ forgetDeletedCopy(root, file, state, io);
+ return deletedMoveResult(root, operation, args, command, io, applyPausedMoveLocally);
+ }
if (error instanceof Refused && error.code === 'AUTH_REQUIRED') throw expiredSignInMoveRefusal(state, error);
throw error;
}
@@ -1143,7 +1220,18 @@ export async function relayCommandReceipt(root, command) {
const file = linkFile(root);
return locked(file, async () => {
const state = loadLink(file);
- if (!state || state.unlinking) return null;
+ if (!state) {
+ const recovered = deletedRecovery(root);
+ if (!recovered || recovered.marker.recovered.commandIntent !== intentDigest(operationIntent('cli:' + command.cliOperation, command))) return null;
+ const expected = { add: 'addItem', edit: 'editItem', merged: 'merged' }[command.cliOperation];
+ if (recovered.move.operation !== expected) throw new Refused('RELAY_STORAGE', 'restore the interrupted command receipt before retrying');
+ if (recovered.receipt.outcome.error) {
+ clearDeletedRecovery(root, recovered.marker);
+ throw refusalFromReceipt(recovered.receipt.outcome.error);
+ }
+ return { result: recovered.receipt.outcome.result, events: recovered.receipt.outcome.events ?? [], move: recovered.move };
+ }
+ if (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)) {
@@ -1170,13 +1258,17 @@ export async function relayCommandReceiptReported(root, moveId) {
if (state?.recovered?.move?.id === moveId) {
delete state.recovered;
saveLink(file, state);
+ } else if (!state) {
+ const recovered = deletedRecovery(root);
+ if (recovered?.move.id === moveId) clearDeletedRecovery(root, recovered.marker);
}
});
}
/** Expose only an unreported operation descriptor so CLI preconditions cannot strand its outcome. */
export function relayRecovered(root) {
- return loadLink(linkFile(root))?.recovered?.move ?? null;
+ const state = loadLink(linkFile(root));
+ return state ? state.recovered?.move ?? null : deletedRecovery(root)?.move ?? null;
}
/** Explicitly refuse one blocked position, replay its valid tail on a private copy, then publish it. */
diff --git a/test/relay-auth-expired.test.js b/test/relay-auth-expired.test.js
index 41c258f5..379c4361 100644
--- a/test/relay-auth-expired.test.js
+++ b/test/relay-auth-expired.test.js
@@ -324,3 +324,130 @@ test('another board deletion never turns this board into local mode [H17,E9]', a
assert.equal((await box.cli('status')).document.relay.board, state.board);
assert.equal((await box.cli('add', box.lane, 'the surviving board still syncs')).code, 0, 'ordinary ordered work remains available with its own credential');
});
+
+test('a move pending acknowledgement when the relay copy is deleted is kept [H17,E9]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const phone = await box.phoneSession();
+ const firstTitle = 'locally originated move before deleted-copy lost acknowledgement';
+ const result = await box.script(`
+ const { main } = await import(${JSON.stringify(box.mainURL)});
+ const realFetch = globalThis.fetch;
+ let intercepted = false;
+ globalThis.fetch = async function(input, init) {
+ const response = await realFetch(input, init);
+ if (!intercepted && init?.method === 'POST' && String(input).endsWith('/moves') && response.ok) {
+ intercepted = true;
+ const removed = await realFetch(${JSON.stringify(box.origin + '/api/v1/boards/' + state.board)}, {
+ method: 'DELETE', headers: { authorization: ${JSON.stringify('Bearer ' + phone.token)}, 'x-pullboard-engine': ${JSON.stringify(String(ENGINE_VERSION))} }
+ });
+ if (removed.status !== 200) throw new Error('review fixture could not delete the remote copy');
+ throw new TypeError('review fixture drops the already accepted move acknowledgement');
+ }
+ return response;
+ };
+ let stdout = '', stderr = '';
+ const code = await main(['add', ${JSON.stringify(box.lane)}, ${JSON.stringify(firstTitle)}, '--json'], {
+ cwd: ${JSON.stringify(box.root)}, stdout: {write(value) {stdout += value;}}, stderr: {write(value) {stderr += value;}}
+ });
+ console.log(JSON.stringify({code, intercepted, output: JSON.parse(stdout), stderr}));
+ `);
+ assert.equal(result.code, 0, 'the private capture process completed');
+ assert.equal(result.document.intercepted, true, 'the real relay accepted the move before its acknowledgement was lost');
+ assert.equal(box.auth.linkedBoards().length, 0, 'a real person-authenticated HTTP deletion completed before the transport refusal');
+ const next = await box.cli('add', box.lane, 'independent local work after deleted-copy lost acknowledgement');
+ assert.equal(next.code, 0, 'subsequent local work succeeds');
+ const exported = await box.cli('export');
+ assert.equal(exported.code, 0);
+ assert.equal(exported.document.tables.item.filter(row => row.item_title === firstTitle).length, 1,
+ 'the local sender retains its earlier accepted obligation across the deletion and lost acknowledgement');
+});
+
+test('a deleted-copy pending move survives interrupted cleanup and is returned only once on retry [H17,E9]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const state = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const phone = await box.phoneSession();
+ const firstTitle = 'pending move retained through an interrupted local deletion cleanup';
+ const captured = await box.script(`
+ const { main } = await import(${JSON.stringify(box.mainURL)});
+ const realFetch = globalThis.fetch;
+ let intercepted = false;
+ globalThis.fetch = async function(input, init) {
+ const response = await realFetch(input, init);
+ if (!intercepted && init?.method === 'POST' && String(input).endsWith('/moves') && response.ok) {
+ intercepted = true;
+ const removed = await realFetch(${JSON.stringify(box.origin + '/api/v1/boards/' + state.board)}, {
+ method: 'DELETE', headers: { authorization: ${JSON.stringify('Bearer ' + phone.token)}, 'x-pullboard-engine': ${JSON.stringify(String(ENGINE_VERSION))} }
+ });
+ if (removed.status !== 200) throw new Error('the private phone could not delete the accepted copy');
+ throw new TypeError('the private fixture loses the accepted move acknowledgement');
+ }
+ return response;
+ };
+ let firstOutput = '';
+ const firstCode = await main(['add', ${JSON.stringify(box.lane)}, ${JSON.stringify(firstTitle)}, '--json'], {
+ cwd: ${JSON.stringify(box.root)}, stdout: {write(value) {firstOutput += value;}}, stderr: {write() {}}
+ });
+ const fs = await import('node:fs');
+ const { syncBuiltinESMExports } = await import('node:module');
+ const rename = fs.default.renameSync;
+ let cleanupInterrupted = false;
+ fs.default.renameSync = function(from, to) {
+ if (!cleanupInterrupted && String(to).endsWith('/relay-deleted.json')) {
+ cleanupInterrupted = true;
+ fs.default.renameSync = rename;
+ syncBuiltinESMExports();
+ throw new Error('the private fixture interrupts deletion-marker persistence');
+ }
+ return rename(from, to);
+ };
+ syncBuiltinESMExports();
+ let cleanupOutput = '';
+ let cleanupCode;
+ let cleanupError;
+ try {
+ cleanupCode = await main(['add', ${JSON.stringify(box.lane)}, 'new work after interrupted deletion cleanup', '--json'], {
+ cwd: ${JSON.stringify(box.root)}, stdout: {write(value) {cleanupOutput += value;}}, stderr: {write() {}}
+ });
+ } catch (error) {
+ if (error.message !== 'the private fixture interrupts deletion-marker persistence') throw error;
+ cleanupError = error.message;
+ } finally { fs.default.renameSync = rename; syncBuiltinESMExports(); }
+ const { localRecords } = await import(${JSON.stringify(new URL('relay.js', box.mainURL).href)});
+ const beforeCleanup = localRecords(${JSON.stringify(box.root)}, board => ({
+ firstCount: board.db.prepare('SELECT COUNT(*) AS count FROM item WHERE item_title=?').get(${JSON.stringify(firstTitle)}).count,
+ cursor: board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='relay_applied_sequence'").get()?.meta_value
+ }));
+ const stillLinked = fs.existsSync(${JSON.stringify(box.linkFile)});
+ console.log(JSON.stringify({ firstCode, intercepted, cleanupInterrupted, cleanupCode, cleanupError, firstOutput, cleanupOutput, beforeCleanup, stillLinked }));
+ `);
+ assert.equal(captured.code, 0, 'the private capture completed both real CLI invocations');
+ assert.equal(captured.document.intercepted, true, 'the relay accepted the original move before its reply was lost');
+ assert.equal(captured.document.cleanupInterrupted, true, 'the next CLI reached the exact deletion-marker write');
+ assert.equal(captured.document.cleanupError, 'the private fixture interrupts deletion-marker persistence',
+ 'the private fault interrupts the command at the marker boundary');
+ assert.equal(box.auth.linkedBoards().length, 0, 'the real person-authenticated deletion remains complete');
+ assert.equal(captured.document.stillLinked, true, 'interruption leaves the original pending link available for recovery');
+ const cursor = document => document.tables.board_meta.find(row => row.meta_key === 'relay_applied_sequence')?.meta_value;
+ const savedCursor = captured.document.beforeCleanup.cursor;
+ assert.equal(captured.document.beforeCleanup.firstCount, 1,
+ 'the pending native move is durable before link cleanup can be interrupted');
+ const next = await box.cli('add', box.lane, 'new work after interrupted deletion cleanup');
+ assert.equal(next.code, 0, 'a fresh invocation completes cleanup and different local work');
+ const repeated = await box.cli('add', box.lane, firstTitle);
+ assert.equal(repeated.code, 0, 'the interrupted original command receives its retained native outcome');
+ const exported = await box.cli('export');
+ assert.equal(exported.code, 0);
+ assert.equal(exported.document.tables.item.filter(row => row.item_title === firstTitle).length, 1,
+ 'neither repeated cleanup nor the original command retry duplicates the native move');
+ assert.equal(cursor(exported.document), savedCursor, 'repeated cleanup does not fabricate another relay position');
+ const marker = JSON.parse(readFileSync(join(box.root, '.git', 'pullboard', 'relay-deleted.json'), 'utf8'));
+ assert.equal(JSON.stringify(marker).includes(state.token), false, 'the deletion notice retains no bearer credential');
+ assert.equal(marker.recovered, undefined, 'reporting the original outcome consumes its recovery pointer');
+ assert.equal((await box.cli('add', box.lane, firstTitle)).code, 0);
+ const later = await box.cli('export');
+ assert.equal(later.document.tables.item.filter(row => row.item_title === firstTitle).length, 2,
+ 'after reporting the retained outcome, the same command can intentionally make new local work');
+});