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): recover replies before changed inputs [H3,H16]

Corey Olson04dfe6482a2b
diff --git a/src/cli.js b/src/cli.js
index 04475966..90ebe8d1 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -60,7 +60,7 @@ import { mainPolicy, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, de
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, relayRecovered, relayStatus, syncRelay } from './relay.js';
+import { relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecovered, relayStatus, syncRelay } from './relay.js';
const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
export const VERSION = PACKAGE.version;
@@ -640,8 +640,9 @@ function withBoard(ctx, work) {
/** Dispatch a board mutation locally, or seal it before any linked replica applies it. */
async function ordered(ctx, board, operation, args) {
+ const command = ['add', 'edit', 'merged'].includes(ctx.io.relayCommand?.cliOperation) ? ctx.io.relayCommand : undefined;
return relayLinked(ctx.info.root)
- ? relayOperation(ctx.info.root, operation, args, ctx.io)
+ ? relayOperation(ctx.info.root, operation, args, ctx.io, command)
: store[operation](board, ...args);
}
@@ -1787,6 +1788,15 @@ function workCommands(io, args) {
return 0;
}),
add: () => act(async (ctx, board, me) => {
+ const recovered = await relayCommandReceipt(ctx.info.root, io.relayCommand);
+ if (recovered) {
+ const id = recovered.result;
+ io.result?.({ item: store.getItem(board, id) });
+ io.say(`#${id}`);
+ sayCheckBaseline(io, store.getItem(board, id));
+ await relayCommandReceiptReported(ctx.info.root, recovered.move.id);
+ return 0;
+ }
if (!first || !isLane(ctx.config, first)) throw new Refused('NO_LANE', `no lane "${first ?? ''}"; see: pullboard lanes`);
const specIds = idList(values.specs);
const problems = idProblems(loadSpec(ctx.info.root, ctx.config), specIds);
@@ -1816,6 +1826,14 @@ function workCommands(io, args) {
}),
edit: () => act(async (ctx, board, me) => {
const id = idArg(first);
+ const recovered = await relayCommandReceipt(ctx.info.root, io.relayCommand);
+ if (recovered) {
+ io.result?.({ item: store.getItem(board, id) });
+ io.say(`edited #${id}`);
+ sayCheckBaseline(io, store.getItem(board, id));
+ await relayCommandReceiptReported(ctx.info.root, recovered.move.id);
+ return 0;
+ }
const brief = briefArg(io, values);
const change = {
agentId: me.id,
@@ -1905,6 +1923,14 @@ function workCommands(io, args) {
done: async () => submitHere(context(io), idArg(first)),
verify: () => verifyHere(context(io), idArg(first), args),
merged: () => act(async (ctx, board, me) => {
+ const recovered = await relayCommandReceipt(ctx.info.root, io.relayCommand);
+ if (recovered) {
+ const commit = recovered.move.args[1].commit;
+ io.result?.({ id: idArg(first), commit });
+ io.say(`#${first} merged as ${commit.slice(0, 12)}`);
+ await relayCommandReceiptReported(ctx.info.root, recovered.move.id);
+ return 0;
+ }
const commit = resolveCommit(ctx.info.root, second ?? '');
if (!commit) throw new Refused('NO_COMMIT', `no commit "${second ?? ''}" in this repo`);
await ordered(ctx, board, 'merged', [idArg(first), { agentId: me.id, commit }]);
@@ -2362,6 +2388,9 @@ export async function main(argv, streams) {
try {
const parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
const command = parsed.positionals[0];
+ io.relayCommand = { cliOperation: command === 'done' ? 'submit' : command, cwd: resolve(io.cwd),
+ positionals: parsed.positionals.slice(1),
+ values: Object.fromEntries(Object.keys(parsed.values).filter(key => key !== 'json').sort().map(key => [key, parsed.values[key]])) };
sync = Boolean(command) && !parsed.values.help && !parsed.values.version && !['help', 'version', 'hook', 'init', 'relay', 'tour'].includes(command);
} catch { sync = false; }
/** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */
diff --git a/src/relay.js b/src/relay.js
index 1aadca77..3f4e22c7 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -377,23 +377,26 @@ async function sendPending(root, file, state, io) {
/** Compare caller intent without executing frozen callbacks or allocating another operation id. */
function operationIntent(operation, args) {
- const values = args.map((value, index) => {
+ 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) {
+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);
- if (intent !== operationIntent(operation, 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));
@@ -405,7 +408,7 @@ function recoveredMove(root, state, operation, args) {
}
/** 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);
@@ -416,11 +419,12 @@ export async function relayOperation(root, operation, args, io) {
delete state.pending;
saveLink(file, state);
}
- let move = recoveredMove(root, state, operation, args);
+ let move = recoveredMove(root, state, operation, args, command);
if (!move) {
move = localRecords(root, (board) => prepareEngineMove(board, operation, args));
const sequence = state.sequence + 1;
- state.pending = { move, intent: operationIntent(operation, args), sequence,
+ 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); }
@@ -477,6 +481,43 @@ export async function syncRelay(root, 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 () => {
+ 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, 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;
diff --git a/test/machine.test.js b/test/machine.test.js
index 95b02fbf..294ecfd5 100644
--- a/test/machine.test.js
+++ b/test/machine.test.js
@@ -60,7 +60,7 @@ const CAUGHT = { 'cli.js#submitHere': ['cli.js#freezer'], 'cli.js#verifyHere': [
* Encrypted transport authenticates/orders a move; its board operation is walked separately above.
* Keep walking the CLI dispatcher itself so a new item rule there cannot hide behind this boundary.
*/
-const TRANSPORT_BOUNDARIES = new Set(['relay.js#relayLinked', 'relay.js#relayOperation', 'relay.js#relayRecovered']);
+const TRANSPORT_BOUNDARIES = new Set(['relay.js#relayLinked', 'relay.js#relayOperation', 'relay.js#relayRecovered', 'relay.js#relayCommandReceipt', 'relay.js#relayCommandReceiptReported']);
/** A top-level function, or a top-level arrow function bound to a const. */
const START = /^(?:export )?(?:(?:async )?function (\w+)\(|const (\w+) = (?:async )?(?:\([^)]*\)|\w+) =>)/;
diff --git a/test/relay-client.test.js b/test/relay-client.test.js
index 439a6e2e..e32b2653 100644
--- a/test/relay-client.test.js
+++ b/test/relay-client.test.js
@@ -55,7 +55,7 @@ function cliResult(root, env, ...args) {
/** Run a successful actual CLI command and retain refusal diagnostics on failure. */
async function cli(root, env, ...args) {
const result = await cliResult(root, env, ...args);
- if (result.status !== 0) throw new Error(`pullboard ${args.join(' ')} exited ${result.status}: ${result.stderr}\n${JSON.stringify(result.document)}`);
+ assert.equal(result.status, 0, `pullboard ${args.join(' ')} exited ${result.status}: ${result.stderr}\n${JSON.stringify(result.document)}`);
return result.document;
}
@@ -131,6 +131,7 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offli
assert.ok(gitBinary, 'the fixture PATH contains git');
symlinkSync(realpathSync(gitBinary), join(privateBin, 'git'));
symlinkSync(realpathSync(process.execPath), join(privateBin, 'node'));
+ symlinkSync(realpathSync('/bin/sh'), join(privateBin, 'sh'));
const env = {
...process.env,
HOME: home,
@@ -162,6 +163,7 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offli
const git = spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: root, env, encoding: 'utf8' });
assert.equal(git.status, 0, git.stderr);
await cli(root, env, 'init');
+ writeFileSync(join(root, 'SPEC.md'), '# Spec\n\n## G · Goals\n- G1 [approved, must] A lost reply has one original outcome. | gate: review\n');
const config = JSON.parse(readFileSync(join(root, 'pullboard.json'), 'utf8'));
const originRemote = spawnSync('git', ['remote', 'add', 'origin', '[email protected]:fixture/repository.git'], { cwd: root, env, encoding: 'utf8' });
assert.equal(originRemote.status, 0, originRemote.stderr);
@@ -258,8 +260,10 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offli
assert.equal(caughtUp.relay.behind, 0, 'the next reachable command recovers the durable send');
const recoveredRows = localEvents(boardFile).slice(beforeOffline.length);
assert.deepEqual(recoveredRows, [], 'offline refusal cannot become a later unsolicited move');
+ const lostBrief = join(root, 'lost-brief.md');
+ writeFileSync(lostBrief, 'The original lost-reply brief.\n');
relay.dropNextReply({ offline: true });
- await assert.rejects(cli(root, relayEnv, 'add', lane, 'committed reply lost'), /RELAY_UNAVAILABLE/);
+ await assert.rejects(cli(root, relayEnv, 'add', lane, 'committed reply lost', '--specs', 'G1', '--brief-file', lostBrief), /RELAY_UNAVAILABLE/);
const durableId = JSON.parse(readFileSync(linkFile, 'utf8')).pending.move.id;
await cli(root, relayEnv, 'status');
assert.equal(JSON.parse(readFileSync(linkFile, 'utf8')).pending.move.id, durableId,
@@ -272,7 +276,11 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offli
assert.equal(different.status, 1);
assert.equal(different.document.error.code, 'RELAY_RETRY_PENDING');
const sentBeforeRetry = relay.uploads.length;
- const repeated = await cli(root, relayEnv, 'add', lane, 'committed reply lost');
+ writeFileSync(join(root, 'SPEC.md'), '# Spec\n\n## G · Goals\n');
+ rmSync(lostBrief);
+ const repeated = await cli(root, relayEnv, 'add', lane, 'committed reply lost', '--specs', 'G1', '--brief-file', lostBrief);
+ assert.equal(repeated.item.item_brief, 'The original lost-reply brief.', 'an acknowledged retry does not re-read removed spec or brief files');
+ writeFileSync(join(root, 'SPEC.md'), '# Spec\n\n## G · Goals\n- G1 [approved, must] A lost reply has one original outcome. | gate: review\n');
assert.equal(repeated.item.item_title, 'committed reply lost');
assert.equal(repeated.item.item_id, 3, 'retry reports the original allocated item id');
assert.equal(relay.uploads.length, sentBeforeRetry, 'retry never creates another relay position');
@@ -333,6 +341,7 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover l
assert.ok(gitBinary, 'the fixture PATH contains git');
symlinkSync(realpathSync(gitBinary), join(privateBin, 'git'));
symlinkSync(realpathSync(process.execPath), join(privateBin, 'node'));
+ symlinkSync(realpathSync('/bin/sh'), join(privateBin, 'sh'));
const envs = homes.map((home) => {
const env = { ...process.env, HOME: home, USERPROFILE: home, PULLBOARD_HOME: join(home, '.pullboard'), PATH: privateBin };
for (const key of Object.keys(env)) if (key.startsWith('GIT_')) delete env[key];
@@ -623,6 +632,32 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover l
assert.equal(retriedVerify.decision, 'ACCEPT');
assert.equal(relay.uploads.length, beforeVerifyRetry, 'verified-state preconditions also preserve the original outcome');
+ const lostEditBrief = join(clones[0], 'lost-edit-brief.md');
+ writeFileSync(lostEditBrief, 'Files: web/README.md\nTest: the original edit is recovered once.\n');
+ const beforeEdit = relay.uploads.length;
+ relay.dropNextReply({ offline: true });
+ const lostEdit = await cliResult(clones[0], envs[0], 'edit', '1', '--brief-file', lostEditBrief);
+ assert.equal(lostEdit.document.error.code, 'RELAY_UNAVAILABLE');
+ relay.failReads(false);
+ await cli(clones[0], envs[0], 'status');
+ rmSync(lostEditBrief);
+ const editRetry = await cli(clones[0], envs[0], 'edit', '1', '--brief-file', lostEditBrief);
+ assert.equal(editRetry.item.item_brief, 'Files: web/README.md\nTest: the original edit is recovered once.');
+ assert.equal(relay.uploads.length, beforeEdit + 1, 'edit retries recover the original receipt after its brief disappears');
+
+ const lostRef = 'lost-merge-reference';
+ gitAt(clones[0], envs[0], 'tag', lostRef, originalCommit);
+ const beforeMerge = relay.uploads.length;
+ relay.dropNextReply({ offline: true });
+ const lostMerge = await cliResult(clones[0], envs[0], 'merged', '2', lostRef);
+ assert.equal(lostMerge.document.error.code, 'RELAY_UNAVAILABLE');
+ relay.failReads(false);
+ await cli(clones[0], envs[0], 'status');
+ gitAt(clones[0], envs[0], 'tag', '-d', lostRef);
+ const mergeRetry = await cli(clones[0], envs[0], 'merged', '2', lostRef);
+ assert.equal(mergeRetry.commit, originalCommit);
+ assert.equal(relay.uploads.length, beforeMerge + 1, 'merge retries report the original full commit after its ref disappears');
+
const beforeAutomatic = relay.uploads.length;
relay.dropNextReply();
const automatic = await cli(clones[2], envs[2], 'add', 'web', 'Automatically recovered reply');