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): catch-up names the cause of a recovered lost reply [H16,C7]

Corey Olson7e5b6ff5306d
diff --git a/src/cli.js b/src/cli.js
index aae4e243..9ccc8f9c 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -2526,7 +2526,7 @@ function workCommands(io, args) {
return 0;
}),
add: () => act(async (ctx, board, me) => {
- const recovered = await relayCommandReceipt(ctx.info.root, io.relayCommand, io);
+ const recovered = await relayCommandReceipt(ctx.info.root, io.relayCommand);
if (recovered) {
for (const event of recovered.events) io.onEvent?.(event);
const id = recovered.result;
@@ -2566,7 +2566,7 @@ function workCommands(io, args) {
}),
edit: () => act(async (ctx, board, me) => {
const id = idArg(first);
- const recovered = await relayCommandReceipt(ctx.info.root, io.relayCommand, io);
+ const recovered = await relayCommandReceipt(ctx.info.root, io.relayCommand);
if (recovered) {
for (const event of recovered.events) io.onEvent?.(event);
io.result?.({ item: store.getItem(board, id) });
@@ -2722,7 +2722,7 @@ function workCommands(io, args) {
return 0;
}),
merged: () => act(async (ctx, board, me) => {
- const recovered = await relayCommandReceipt(ctx.info.root, io.relayCommand, io);
+ const recovered = await relayCommandReceipt(ctx.info.root, io.relayCommand);
if (recovered) {
for (const event of recovered.events) io.onEvent?.(event);
const commit = recovered.move.args[1].commit;
diff --git a/src/relay.js b/src/relay.js
index f57309bf..1157a99f 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -161,9 +161,11 @@ async function request(state, path, { method = 'GET', body, allowMissing = false
if (readToken !== undefined && !/^pa_[A-Za-z0-9_-]{43}$/.test(readToken)) throw new Refused('AUTH_REQUIRED', 'supply a current scoped board token without including it in command arguments');
const token = readToken ?? state.token;
let response;
+ // Validate first: a refusal below repeats this address, so it must already be credential-free.
+ const origin = relayOrigin(state.url);
const startedAt = Date.now();
try {
- response = await fetch(relayOrigin(state.url) + path, {
+ response = await fetch(origin + path, {
method, redirect: 'error', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(10000)]) : AbortSignal.timeout(10000),
headers: { 'x-pullboard-engine': String(ENGINE_VERSION), ...(token ? { authorization: 'Bearer ' + token } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...(initialBaseline ? { 'if-none-match': '*' } : {}) },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
@@ -728,6 +730,31 @@ async function restoreCheckpoint(root, state, io, key) {
localRecords(root, (board) => restoreRelaySnapshot(board, native, snapshot.sequence));
}
+/**
+ * Keep why a move's reply was lost on its durable send record, then return the original refusal.
+ * Why: the command that gave up exits here, so only the saved cause lets whichever later command
+ * recovers the move say what the earlier request failed with (#642). It holds the cause name only.
+ */
+function rememberLostReply(file, state, id, error) {
+ const held = [state.pending, state.recovered].find((record) => record?.move?.id === id);
+ if (held) {
+ held.lostReply = error.transportFailure ?? error.code;
+ saveLink(file, state);
+ }
+ return error;
+}
+
+/**
+ * Say once that catch-up recovered a move whose earlier reply was lost, with that request's cause.
+ * Why: any later command, a read included, may be the one that recovers it; the saved cause is
+ * cleared here so the repeated command does not say it again (#642).
+ */
+function reportRecoveredReply(record, io) {
+ if (!record?.lostReply) return;
+ io?.err?.(`pullboard: recovered move ${record.sequence} (${record.move.operation}) whose earlier reply was lost: ${record.lostReply}`);
+ delete record.lostReply;
+}
+
/** Apply a validated relay prefix with durable, transaction-bound receipts on this replica. */
async function catchUp(root, file, state, io) {
const key = readBoardKey(state.board);
@@ -753,12 +780,14 @@ async function catchUp(root, file, state, io) {
&& record.sealed === state.pending.sealed && outcome?.error
&& !localRecords(root, board => engineReceipt(board, state.pending.move.id))) {
pendingRefusal = outcome.error;
+ reportRecoveredReply(state.pending, io);
delete state.pending;
delete state.recovered;
}
}
state.sequence = localRecords(root, appliedSequence);
if (state.pending?.move && localRecords(root, (board) => engineReceipt(board, state.pending.move.id))) {
+ reportRecoveredReply(state.pending, io);
state.recovered = state.pending;
delete state.pending;
}
@@ -865,7 +894,7 @@ function operationIntent(operation, args) {
}
/** Keep a recovered outcome until its caller repeats the interrupted operation to receive it. */
-function recoveredMove(root, state, operation, args, command, io) {
+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);
@@ -880,8 +909,6 @@ function recoveredMove(root, state, operation, args, command, io) {
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');
}
- // The earlier command gave up on this move's reply; say so once, with the cause it saw (#642).
- if (recovered.lostReply) io?.err?.(`pullboard: recovered move ${recovered.sequence} (${recovered.move.operation}) whose earlier reply was lost: ${recovered.lostReply}`);
return recovered.move;
}
@@ -926,7 +953,7 @@ export async function relayOperation(root, operation, args, io, command, applyLo
for (const event of previousReceipt.outcome.events ?? []) io.onEvent?.(event);
return previousReceipt.outcome.result;
}
- let move = recoveredMove(root, state, operation, args, command, io);
+ 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);
@@ -942,14 +969,9 @@ export async function relayOperation(root, operation, args, io, command, applyLo
try { await sendPending(root, file, state, io); }
catch (error) {
if (!['RELAY_UNAVAILABLE', 'RELAY_RESPONSE'].includes(error.code)) throw error;
- // Keep why the reply was lost, so whichever later command recovers this move can say so.
- if (state.pending?.move?.id === move.id) {
- state.pending.lostReply = error.transportFailure ?? error.code;
- saveLink(file, state);
- }
// 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;
+ try { await catchUp(root, file, state, io); } catch { throw rememberLostReply(file, state, move.id, error); }
+ if (!localRecords(root, (board) => engineReceipt(board, move.id))) throw rememberLostReply(file, state, move.id, error);
}
}
const receipt = localRecords(root, (board) => engineReceipt(board, move.id));
@@ -1066,11 +1088,8 @@ export async function relayRevoke(root, id, io) {
});
}
-/**
- * Read an acknowledged exact CLI result before changed spec, brief or Git refs can block it.
- * Why io: a recovered move whose earlier reply was lost says so once on this command (#642).
- */
-export async function relayCommandReceipt(root, command, io) {
+/** 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 () => {
@@ -1083,7 +1102,7 @@ export async function relayCommandReceipt(root, command, io) {
}
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, io);
+ 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;
diff --git a/test/relay-client.test.js b/test/relay-client.test.js
index 07cd6bad..4ee0de8a 100644
--- a/test/relay-client.test.js
+++ b/test/relay-client.test.js
@@ -502,9 +502,8 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offli
'person deletion removes the relay journal and SQLite sidecars');
});
-/** Inject a lost reply at the transport, then recover its move on the repeated command [H16,C7]. */
-
-test('[H16,C7] a relay transport failure names its cause', async (t) => {
+/** Link one real repository to a local relay whose next move reply can be lost at the transport. */
+async function lostReplyFixture(t) {
const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-relay-cause-')));
const root = join(scratch, 'repo');
const home = join(scratch, 'home');
@@ -524,6 +523,7 @@ test('[H16,C7] a relay transport failure names its cause', async (t) => {
GIT_COMMITTER_NAME: 'Relay Test', GIT_COMMITTER_EMAIL: '[email protected]',
};
for (const name of [...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete env[name];
+ for (const name of Object.keys(env)) if (name.startsWith('GIT_') && !name.startsWith('GIT_CONFIG') && !name.startsWith('GIT_AUTHOR') && !name.startsWith('GIT_COMMITTER')) delete env[name];
for (const name of ['PULLBOARD_RELAY_KEY', 'PULLBOARD_RELAY_TOKEN']) delete env[name];
const provider = await githubFixture(t);
SIGN_INS.set(root, async () => {
@@ -541,29 +541,97 @@ test('[H16,C7] a relay transport failure names its cause', async (t) => {
const lane = Object.keys(JSON.parse(readFileSync(join(root, 'pullboard.json'), 'utf8')).lanes)[0];
mkdirSync(join(pullboardHome, 'relay-keys'), { recursive: true, mode: 0o700 });
await cli(root, env, 'relay', 'on', '--url', relay.origin);
+ return { root, env, lane, relay, pullboardHome };
+}
- // The relay applies the move but the client loses its reply at the transport.
+/** Every credential string the linked replica holds: its relay tokens and its board key files. */
+function heldSecrets(root, pullboardHome) {
+ const secrets = [];
+ /** Collect every string under a key that names a token, a key or a secret. */
+ const walk = (value, name = '') => {
+ if (typeof value === 'string') { if (/token|key|secret|cookie/iu.test(name) && value.length >= 16) secrets.push(value); return; }
+ if (value && typeof value === 'object') for (const [key, inner] of Object.entries(value)) walk(inner, Array.isArray(value) ? name : key);
+ };
+ walk(JSON.parse(readFileSync(join(root, '.git', 'pullboard', 'relay.json'), 'utf8')));
+ const keys = join(pullboardHome, 'relay-keys');
+ for (const entry of readdirSync(keys, { recursive: true })) {
+ if (!statSync(join(keys, entry)).isFile()) continue;
+ const text = readFileSync(join(keys, entry), 'utf8').trim();
+ secrets.push(text);
+ try { walk(JSON.parse(text), 'key'); } catch { /* a raw key file is already held whole */ }
+ }
+ assert.ok(secrets.some((secret) => /^p[ma]_/u.test(secret)), 'the fixture holds a relay token to keep out of diagnostics');
+ return secrets;
+}
+
+/** Lose a move's reply at the transport and assert the refusal names its cause and keeps its contract. */
+async function loseReplyAtTransport({ root, env, lane, relay, pullboardHome }) {
relay.dropNextReply({ offline: true });
const lost = await cliResult(root, env, 'add', lane, 'reply lost at the transport');
- assert.equal(lost.status, 1);
+ assert.equal(lost.status, 1, lost.stderr);
const refusal = lost.document.error;
assert.equal(refusal.code, 'RELAY_UNAVAILABLE', 'the refusal code is unchanged');
- assert.match(refusal.next, /\S/, 'the refusal keeps its next step');
- assert.ok(refusal.message.includes(relay.origin), 'the refusal names the relay address');
+ assert.ok(refusal.message.endsWith('; read the local board offline, then retry this move when the relay is reachable'), 'the refusal keeps its next step');
+ assert.match(refusal.next, /\S/u, 'the refusal document keeps a next step');
+ assert.ok(refusal.message.includes(`the relay ${relay.origin} did not answer`), 'the refusal names the relay address');
assert.match(refusal.message, /did not answer \((?:timed out|no connection|[A-Z][A-Z0-9_]+) after \d+ ms on POST \/api\/v1\/boards\/[0-9a-f]{32}\/moves\)/u,
'the refusal names the underlying transport failure and the request');
const cause = /did not answer \(([^)]+?) after \d+ ms/u.exec(refusal.message)[1];
+ assert.notEqual(cause, 'no connection', `the injected socket loss is named by its error code: ${refusal.message}`);
+ const secrets = heldSecrets(root, pullboardHome);
+ for (const text of [JSON.stringify(lost.document), lost.stderr]) {
+ assert.ok(!secrets.some((secret) => text.includes(secret)), 'the refusal never prints a held token or key');
+ assert.doesNotMatch(text, /authorization|bearer|cookie|\bp[ma]_[A-Za-z0-9_-]{8,}|\?after=/iu, 'the refusal carries no credential, header or query string');
+ }
+ return { cause, secrets };
+}
+
+/** Find the recovery lines a command printed, in --json diagnostics or on stderr. */
+function recoveryLines(result) {
+ return [...(result.document.diagnostics ?? []), result.stderr].join('\n').split('\n')
+ .filter((line) => line.includes('whose earlier reply was lost'));
+}
+
+/** Escape text for a literal match inside a regular expression. */
+function literal(text) { return text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&'); }
+
+test('[H16,C7] a relay transport failure names its cause', async (t) => {
+ const fixture = await lostReplyFixture(t);
+ const { root, env, lane, relay } = fixture;
+ const { cause, secrets } = await loseReplyAtTransport(fixture);
+
+ // The repeated command recovers the move and says so once, with the earlier cause.
+ relay.failReads(false);
+ const repeated = await cliResult(root, env, 'add', lane, 'reply lost at the transport');
+ assert.equal(repeated.status, 0, repeated.stderr);
+ const lines = recoveryLines(repeated);
+ assert.equal(lines.length, 1, repeated.stderr);
+ assert.match(lines[0], new RegExp(`^pullboard: recovered move \\d+ \\(addItem\\) whose earlier reply was lost: ${literal(cause)}$`, 'u'));
+ assert.ok(!secrets.some((secret) => repeated.stderr.includes(secret) || JSON.stringify(repeated.document).includes(secret)), 'the recovery line never prints a held token or key');
+ assert.equal(repeated.document.item.item_title, 'reply lost at the transport', 'the recovered command reports its original outcome');
+});
+
+test('[H16,C7] a relay transport failure names its cause when a read recovers the move', async (t) => {
+ const fixture = await lostReplyFixture(t);
+ const { root, env, lane, relay } = fixture;
+ const { cause, secrets } = await loseReplyAtTransport(fixture);
- // A later command that recovers the move says so once, with the earlier cause.
+ // A read-only command is the later command whose catch-up recovers the move: it prints the line.
relay.failReads(false);
+ const read = await cliResult(root, env, 'list', lane);
+ assert.equal(read.status, 0, read.stderr);
+ const lines = recoveryLines(read);
+ assert.equal(lines.length, 1, read.stderr);
+ assert.match(lines[0], new RegExp(`^pullboard: recovered move \\d+ \\(addItem\\) whose earlier reply was lost: ${literal(cause)}$`, 'u'));
+ assert.ok(!secrets.some((secret) => read.stderr.includes(secret) || JSON.stringify(read.document).includes(secret)), 'the recovery line never prints a held token or key');
+
+ // The line is said once: the repeated command receives the original outcome without repeating it.
const repeated = await cliResult(root, env, 'add', lane, 'reply lost at the transport');
assert.equal(repeated.status, 0, repeated.stderr);
- // --json carries diagnostic lines in the document; plain output writes the same lines to stderr.
- const printed = [...(repeated.document.diagnostics ?? []), repeated.stderr].join('\n').split('\n');
- const recoveredLines = printed.filter((line) => line.includes('whose earlier reply was lost'));
- assert.equal(recoveredLines.length, 1, printed.join('\n'));
- assert.match(recoveredLines[0], new RegExp(`^pullboard: recovered move \\d+ \\(addItem\\) whose earlier reply was lost: ${cause.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')}$`, 'u'));
+ assert.deepEqual(recoveryLines(repeated), [], 'the recovery line is printed once');
assert.equal(repeated.document.item.item_title, 'reply lost at the transport', 'the recovered command reports its original outcome');
+ const titles = (await cli(root, env, 'list', lane)).items.map((item) => item.item_title);
+ assert.equal(titles.filter((title) => title === 'reply lost at the transport').length, 1, 'the recovered move is never duplicated');
});
/** Create the same three real linked replicas for each independently budgeted scenario. */