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(cli): load move recovery only on refusal [A1,P4,C7]

Corey Olsone1cf1d0f65c3
diff --git a/src/cli-main.js b/src/cli-main.js
index 91a5b5c3..2b1d9845 100644
--- a/src/cli-main.js
+++ b/src/cli-main.js
@@ -9,7 +9,7 @@ import { resolve } from 'node:path';
import { performance } from 'node:perf_hooks';
import { parseArgs } from 'node:util';
import { COMMANDS } from './commands/index.js';
-import { commandOutput } from './json.js';
+import { commandOutput } from './json-output.js';
import { Refused } from './refused.js';
export const CHECKOUT_LEASES = new WeakMap();
@@ -166,6 +166,7 @@ async function runCommand(argv, io) {
parsed = parseCommandArgs(argv);
} catch (error) {
const refusal = new Refused('USAGE', `${error.message}; run pullboard help`);
+ await io.prepareRefusal();
io.refusal?.(refusal);
io.err(`pullboard: ${error.message}\nRun pullboard help --all for the full list.\nnext: ${io.refusalDocument(refusal).error.next}`);
return 2;
@@ -237,6 +238,7 @@ async function bindCheckoutSession(io, positionals, values) {
/** Render a refusal with agents' display names, loading the board only for a refusal that names one. */
async function displayedRefusal(io, error) {
+ await io.prepareRefusal();
return (await import('./cli-context.js')).displayedRefusal(io, error);
}
@@ -308,6 +310,7 @@ async function runMain(argv, streams) {
if (code === 0) await (await syncWork())?.retrySync(io);
const status = io.exitCode(code);
if (status === 0 && needsRepo && !parsed?.values['dry-run']) (await import('./blocks.js')).clearCompletedBlocks(io);
+ if (status !== 0) await io.prepareRefusal();
io.flush(status);
return status;
} finally {
diff --git a/src/cli-sync.js b/src/cli-sync.js
index d69213ef..fa48962a 100644
--- a/src/cli-sync.js
+++ b/src/cli-sync.js
@@ -14,9 +14,12 @@ import { autoLinkProject } from './relay-setup.js';
const QUIET = ['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'];
/** Report a refusal from the work around a command without stopping the command. */
-function reportQuietly(io, error) {
+async function reportQuietly(io, error) {
if (!(error instanceof Refused)) throw error;
- if (!QUIET.includes(error.code)) io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${io.refusalDocument(error).error.next}`);
+ if (!QUIET.includes(error.code)) {
+ await io.prepareRefusal?.();
+ io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${io.refusalDocument(error).error.next}`);
+ }
}
/** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */
@@ -26,7 +29,7 @@ export async function retrySync(io) {
await syncRelay(io.cwd, io);
await retryCheckBaselines(io.cwd, io);
}
- catch (error) { reportQuietly(io, error); }
+ catch (error) { await reportQuietly(io, error); }
}
/** Before a command: link this project when the machine links new ones, sync, then run the person's waiting requests. */
@@ -34,5 +37,5 @@ export async function syncBefore(io, main) {
try { await autoLinkProject(io.cwd, io); } catch (error) { if (!(error instanceof Refused)) throw error; }
await retrySync(io);
try { await executePersonRequests(io.cwd, io, main); }
- catch (error) { reportQuietly(io, error); }
+ catch (error) { await reportQuietly(io, error); }
}
diff --git a/src/json-output.js b/src/json-output.js
new file mode 100644
index 00000000..b8613f45
--- /dev/null
+++ b/src/json-output.js
@@ -0,0 +1,127 @@
+/** Pure person guidance and a lightweight CLI output collector [A1,B26,C7]. */
+/** The coordinator carries every seat's request for a person decision [B26]. */
+export const COORDINATOR_PERSON_REQUEST = 'ask the coordinator to bring it to the person: pullboard shout coordinator "<what is needed>" --decision';
+
+/**
+ * Route presentation-only person requests for a known seat; unknown callers retain existing text.
+ * This does not change a refusal receipt, actor identity or permission to make the person's move.
+ *
+ * @param {string} step
+ * @param {{ caller?: 'seat'|'coordinator'|'person'|'unknown' }} [options]
+ * @returns {string}
+ */
+export function personRequestStep(step, { caller } = {}) {
+ return caller === 'seat' && /\bask the person\b/iu.test(step) ? COORDINATOR_PERSON_REQUEST : step;
+}
+
+/** Keep quoted user text out of generated repair-clause rewriting. */
+function quotedAt(text, at) {
+ let quoted = false;
+ let escaped = false;
+ for (let index = 0; index < at; index += 1) {
+ if (escaped) { escaped = false; continue; }
+ if (text[index] === '\\') { escaped = true; continue; }
+ if (text[index] === '"') quoted = !quoted;
+ }
+ return quoted;
+}
+
+/**
+ * Present a generated person-request clause for a seat, keeping its reason and requested action.
+ * Only the explanatory first line and an explicit final next footer are guidance; raw diagnostic
+ * lines and quoted user text remain intact. Setup questions opt in to a leading imperative.
+ *
+ * @param {string} message
+ * @param {{ caller?: 'seat'|'coordinator'|'person'|'unknown', leading?: boolean }} [options]
+ * @returns {string}
+ */
+export function personRequestGuidance(message, { caller, leading = false } = {}) {
+ if (caller !== 'seat') return message;
+ const lines = String(message).split('\n');
+ /** Route only an unquoted imperative, preserving clauses that explain the refusal. */
+ const route = line => line.replace(/(^|[;.:]\s+|\b(?:or|and)\s+)ask the person(?=$|[\s:;])([^;\n]*)/giu,
+ (whole, before, action, at) => {
+ if ((!before && !leading) || quotedAt(line, at + before.length)) return whole;
+ const request = action.trim().replace(/^:?\s*(?:to\s+|for\s+)?/iu, '');
+ const needed = request.replace(/\bask the person(?:\s+to)?\s*/giu,
+ (words, offset) => quotedAt(request, offset) ? words : '');
+ return `${before}${COORDINATOR_PERSON_REQUEST}${needed ? ` (needed: ${needed})` : ''}`;
+ });
+ lines[0] = route(lines[0]);
+ if (lines.length > 1 && /^next:[ \t]*\S/u.test(lines.at(-1))) lines[lines.length - 1] = route(lines.at(-1));
+ return lines.join('\n');
+}
+
+/**
+ * Collect one command's output; text mode writes immediately and JSON mode writes one document.
+ * Long-running view explicitly flushes its address before waiting for a shutdown signal.
+ */
+export function commandOutput(argv, streams, { version = 1, refusalDocument: suppliedRenderer } = {}) {
+ let renderer = suppliedRenderer;
+ let preparing;
+ /** Load recovery declarations only when this command actually needs a refusal document. */
+ async function prepareRefusal() {
+ if (!renderer) renderer = (await (preparing ??= import('./json.js'))).refusalDocument;
+ }
+ /** Keep rendering synchronous after the explicit asynchronous refusal boundary. */
+ function documentFor(error, options) {
+ if (!renderer) throw new Error('prepare refusal rendering before displaying a command error');
+ return renderer(error, options);
+ }
+ let enabled = argv.slice(0, argv.indexOf('--') < 0 ? argv.length : argv.indexOf('--')).includes('--json');
+ let result;
+ let refusal;
+ let remote;
+ let caller = 'unknown';
+ let callerRoot;
+ let written = false;
+ const messages = [];
+ const diagnostics = [];
+ const emit = (target, lines, line) => {
+ if (enabled) lines.push(String(line));
+ else target.write(`${line}\n`);
+ };
+ const flush = (code) => {
+ if (!enabled || written) return;
+ written = true;
+ let document;
+ if (refusal || (code && result === undefined)) {
+ const text = refusal?.message ?? [...diagnostics, ...messages].join('\n');
+ const match = /\[([A-Z][A-Z0-9_]*)\]\s*([\s\S]*)/.exec(text);
+ const message = refusal ? text.replace(/^\[[A-Z][A-Z0-9_]*\] /, '') : match?.[2] ?? text;
+ document = documentFor({ code: refusal?.code ?? match?.[1] ?? (code === 2 ? 'USAGE' : 'COMMAND_FAILED'), message, next: refusal?.next }, { caller });
+ } else if (result !== undefined) {
+ document = { version: version, ...result, ...(diagnostics.length ? { diagnostics } : {}) };
+ } else {
+ // A native versioned document, such as export, already owns its public shape.
+ let native;
+ if (messages.length === 1) {
+ try { native = JSON.parse(messages[0]); } catch { /* Ordinary command prose is kept as messages. */ }
+ }
+ document = native && !Array.isArray(native) && typeof native.version === 'number'
+ ? { ...native, ...(diagnostics.length ? { diagnostics } : {}) } : { version: version, messages, ...(diagnostics.length ? { diagnostics } : {}) };
+ }
+ if (remote) document.remote = remote;
+ streams.stdout.write(`${JSON.stringify(document, null, 2)}\n`);
+ };
+ return {
+ ...streams,
+ physicalStdoutIsTTY: Boolean(streams.stdout.isTTY),
+ stdout: { get isTTY() { return enabled ? false : streams.stdout.isTTY; }, write: (text) => streams.stdout.write(text) },
+ say: (line) => emit(streams.stdout, messages, line),
+ err: (line) => emit(streams.stderr, diagnostics, line),
+ result: (value) => { result = value; },
+ refusal: (error) => { refusal = error; },
+ // A successfully checked person channel stays the display caller for this command.
+ caller: (value, root) => { if (caller !== 'person') { caller = value; callerRoot = root; } },
+ callerKnown: (root) => caller === 'person' || caller !== 'unknown' && callerRoot === root,
+ callerRole: () => caller,
+ guidance: (message, options = {}) => personRequestGuidance(message, { ...options, caller }),
+ refusalDocument: (error) => documentFor(error, { caller }),
+ prepareRefusal,
+ remote: (value) => { remote = value; },
+ exitCode: (code) => code || (remote ? 1 : 0),
+ jsonMode: (value) => { enabled = Boolean(value); },
+ flush,
+ };
+}
diff --git a/src/json.js b/src/json.js
index 04270de5..a2ca0c7a 100644
--- a/src/json.js
+++ b/src/json.js
@@ -1,8 +1,9 @@
/** Versioned command results and refusals for tools that drive the CLI (A1). */
+import { nextStepFor } from './next-step-words.js';
import {
- nextStepFor,
+ commandOutput as collectCommandOutput,
personRequestGuidance,
-} from './next-step-words.js';
+} from './json-output.js';
/** A shape's required top-level fields; optional fields may be added within this version. */
function shape(fields) {
@@ -144,64 +145,7 @@ export function refusalDocument(error, options = {}) {
return { version: JSON_SHAPES.version, error: { code, message: personRequestGuidance(message, options), next: nextStepFor({ code, next: error.next }, message, options) } };
}
-/**
- * Collect one command's output; text mode writes immediately and JSON mode writes one document.
- * Long-running view explicitly flushes its address before waiting for a shutdown signal.
- */
+/** Collect output with the already-loaded synchronous public refusal renderer [A1]. */
export function commandOutput(argv, streams) {
- let enabled = argv.slice(0, argv.indexOf('--') < 0 ? argv.length : argv.indexOf('--')).includes('--json');
- let result;
- let refusal;
- let remote;
- let caller = 'unknown';
- let callerRoot;
- let written = false;
- const messages = [];
- const diagnostics = [];
- const emit = (target, lines, line) => {
- if (enabled) lines.push(String(line));
- else target.write(`${line}\n`);
- };
- const flush = (code) => {
- if (!enabled || written) return;
- written = true;
- let document;
- if (refusal || (code && result === undefined)) {
- const text = refusal?.message ?? [...diagnostics, ...messages].join('\n');
- const match = /\[([A-Z][A-Z0-9_]*)\]\s*([\s\S]*)/.exec(text);
- const message = refusal ? text.replace(/^\[[A-Z][A-Z0-9_]*\] /, '') : match?.[2] ?? text;
- document = refusalDocument({ code: refusal?.code ?? match?.[1] ?? (code === 2 ? 'USAGE' : 'COMMAND_FAILED'), message, next: refusal?.next }, { caller });
- } else if (result !== undefined) {
- document = { version: JSON_SHAPES.version, ...result, ...(diagnostics.length ? { diagnostics } : {}) };
- } else {
- // A native versioned document, such as export, already owns its public shape.
- let native;
- if (messages.length === 1) {
- try { native = JSON.parse(messages[0]); } catch { /* Ordinary command prose is kept as messages. */ }
- }
- document = native && !Array.isArray(native) && typeof native.version === 'number'
- ? { ...native, ...(diagnostics.length ? { diagnostics } : {}) } : { version: JSON_SHAPES.version, messages, ...(diagnostics.length ? { diagnostics } : {}) };
- }
- if (remote) document.remote = remote;
- streams.stdout.write(`${JSON.stringify(document, null, 2)}\n`);
- };
- return {
- ...streams,
- physicalStdoutIsTTY: Boolean(streams.stdout.isTTY),
- stdout: { get isTTY() { return enabled ? false : streams.stdout.isTTY; }, write: (text) => streams.stdout.write(text) },
- say: (line) => emit(streams.stdout, messages, line),
- err: (line) => emit(streams.stderr, diagnostics, line),
- result: (value) => { result = value; },
- refusal: (error) => { refusal = error; },
- // A successfully checked person channel stays the display caller for this command.
- caller: (value, root) => { if (caller !== 'person') { caller = value; callerRoot = root; } },
- callerKnown: (root) => caller === 'person' || caller !== 'unknown' && callerRoot === root,
- callerRole: () => caller,
- guidance: (message, options = {}) => personRequestGuidance(message, { ...options, caller }),
- refusalDocument: (error) => refusalDocument(error, { caller }),
- remote: (value) => { remote = value; },
- exitCode: (code) => code || (remote ? 1 : 0),
- jsonMode: (value) => { enabled = Boolean(value); },
- flush,
- };
+ return collectCommandOutput(argv, streams, { version: JSON_SHAPES.version, refusalDocument });
}
diff --git a/src/next-step-words.js b/src/next-step-words.js
index 3cb7cb08..37f72b46 100644
--- a/src/next-step-words.js
+++ b/src/next-step-words.js
@@ -3,58 +3,16 @@ import { DEFAULT_NEXT_STEPS } from './next-step-defaults.js';
/** Pure refusal guidance shared by JSON and CLI output without loading ledger or Git [P4,W4,C7]. */
import { RECORDED_GENERIC_NEXT } from './recorded-refusal.js';
-/** The coordinator carries every seat's request for a person decision [B26]. */
-export const COORDINATOR_PERSON_REQUEST = 'ask the coordinator to bring it to the person: pullboard shout coordinator "<what is needed>" --decision';
-
-/**
- * Route presentation-only person requests for a known seat; unknown callers retain existing text.
- * This does not change a refusal receipt, actor identity or permission to make the person's move.
- *
- * @param {string} step
- * @param {{ caller?: 'seat'|'coordinator'|'person'|'unknown' }} [options]
- * @returns {string}
- */
-export function personRequestStep(step, { caller } = {}) {
- return caller === 'seat' && /\bask the person\b/iu.test(step) ? COORDINATOR_PERSON_REQUEST : step;
-}
-
-/** Keep quoted user text out of generated repair-clause rewriting. */
-function quotedAt(text, at) {
- let quoted = false;
- let escaped = false;
- for (let index = 0; index < at; index += 1) {
- if (escaped) { escaped = false; continue; }
- if (text[index] === '\\') { escaped = true; continue; }
- if (text[index] === '"') quoted = !quoted;
- }
- return quoted;
-}
-
-/**
- * Present a generated person-request clause for a seat, keeping its reason and requested action.
- * Only the explanatory first line and an explicit final next footer are guidance; raw diagnostic
- * lines and quoted user text remain intact. Setup questions opt in to a leading imperative.
- *
- * @param {string} message
- * @param {{ caller?: 'seat'|'coordinator'|'person'|'unknown', leading?: boolean }} [options]
- * @returns {string}
- */
-export function personRequestGuidance(message, { caller, leading = false } = {}) {
- if (caller !== 'seat') return message;
- const lines = String(message).split('\n');
- /** Route only an unquoted imperative, preserving clauses that explain the refusal. */
- const route = line => line.replace(/(^|[;.:]\s+|\b(?:or|and)\s+)ask the person(?=$|[\s:;])([^;\n]*)/giu,
- (whole, before, action, at) => {
- if ((!before && !leading) || quotedAt(line, at + before.length)) return whole;
- const request = action.trim().replace(/^:?\s*(?:to\s+|for\s+)?/iu, '');
- const needed = request.replace(/\bask the person(?:\s+to)?\s*/giu,
- (words, offset) => quotedAt(request, offset) ? words : '');
- return `${before}${COORDINATOR_PERSON_REQUEST}${needed ? ` (needed: ${needed})` : ''}`;
- });
- lines[0] = route(lines[0]);
- if (lines.length > 1 && /^next:[ \t]*\S/u.test(lines.at(-1))) lines[lines.length - 1] = route(lines.at(-1));
- return lines.join('\n');
-}
+import {
+ COORDINATOR_PERSON_REQUEST,
+ personRequestStep,
+ personRequestGuidance,
+} from './json-output.js';
+export {
+ COORDINATOR_PERSON_REQUEST,
+ personRequestStep,
+ personRequestGuidance,
+} from './json-output.js';
/** @type {Readonly<Record<string, string>>} */
export const NEXT_STEPS = withMoveNextSteps(DEFAULT_NEXT_STEPS);
diff --git a/src/relay-request-execution.js b/src/relay-request-execution.js
index e46aa404..b49fdad8 100644
--- a/src/relay-request-execution.js
+++ b/src/relay-request-execution.js
@@ -13,7 +13,6 @@ import {
repoInfo,
} from './git.js';
import { laneNames } from './lanes.js';
-import { refusalDocument } from './json.js';
import { Refused } from './refused.js';
import {
relayLinked,
@@ -88,7 +87,10 @@ export async function executePersonRequests(root, io, runCommand) {
if (['PERSON_REQUEST_TAKEN', 'PERSON_REQUEST_CLOSED', 'RELAY_PERSON_ONLY'].includes(error.code)) continue;
if (transportRefusal(error)) { io.err('pullboard: ' + error.message); continue; }
const record = requests(coordinatorRoot).find(entry => entry.id === initial.id);
- if (record?.executor === executor && record.status === 'waiting') await receipt(coordinatorRoot, record, executor, 'refuse', io, refusalDocument(error).error);
+ if (record?.executor === executor && record.status === 'waiting') {
+ const { refusalDocument } = await import('./json.js');
+ await receipt(coordinatorRoot, record, executor, 'refuse', io, refusalDocument(error).error);
+ }
}
}
}
diff --git a/test/refusal-next-steps.test.js b/test/refusal-next-steps.test.js
index ab2543ce..e90cf6ba 100644
--- a/test/refusal-next-steps.test.js
+++ b/test/refusal-next-steps.test.js
@@ -6,6 +6,7 @@ import { after, test } from 'node:test';
import { Refused } from '../src/refused.js';
import { recordedRefusal, refusalFromReceipt, RECORDED_GENERIC_NEXT } from '../src/recorded-refusal.js';
import { refusalDocument } from '../src/json.js';
+import { commandOutput as lightCommandOutput } from '../src/json-output.js';
import { createE2eHelpers } from './e2e-helpers.js';
const e2e = createE2eHelpers();
@@ -136,3 +137,29 @@ test('every refusal names a next step that works [P4,I1,I2]', async () => {
succeeded(box.run(recovery, 'whoami', '--json'));
assert.equal(readFileSync(bindingPath, 'utf8'), binding, 'recovery leaves the main owner binding unchanged');
});
+
+
+test('the light collector preserves prepared JSON refusal documents and a single success output [A1,P4,B26,C7]', async () => {
+ const cases = [
+ { code: 'NO_ITEM', message: 'No item exists.' },
+ { code: 'FUTURE_REMOTE_RULE', message: 'The service refused.', next: 'ask its owner to restore the board' },
+ { code: 'SPEC_NOT_APPROVED', message: 'The rule is pending; ask the person to approve it.' },
+ refusalFromReceipt(recordedRefusal(new Refused('GATE_RED', 'gate red; fix it, commit, submit again'))),
+ ];
+ for (const error of cases) {
+ let text = '';
+ const io = lightCommandOutput(['show', '1', '--json'], { stdout: { write(value) { text += value; } }, stderr: { write() {} } });
+ io.caller('seat', '/fixture');
+ io.refusal(error);
+ await io.prepareRefusal();
+ io.flush(1);
+ io.flush(1);
+ assert.deepEqual(JSON.parse(text), refusalDocument(error, { caller: 'seat' }), 'lazy preparation preserves the synchronous public envelope and caller guidance');
+ }
+ let text = '';
+ const io = lightCommandOutput(['version', '--json'], { stdout: { write(value) { text += value; } }, stderr: { write() {} } });
+ io.result({ release: '0.9.2' });
+ io.flush(0);
+ io.flush(0);
+ assert.deepEqual(JSON.parse(text), { version: 1, release: '0.9.2' }, 'success needs no refusal preparation and flushes once');
+});