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(core): route seat person requests through coordinator [B26]

Corey Olsone009a6bf8c16
diff --git a/src/cli.js b/src/cli.js
index 645e34af..0d9a8dd7 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -265,7 +265,6 @@ import { renderSpecView } from './view.js';
import { tour } from './tour.js';
import {
commandOutput,
- refusalDocument,
} from './json.js';
import {
forgetProject,
@@ -838,6 +837,7 @@ function sayBrief(io, brief) {
*/
function context(io) {
const info = repoInfo(io.cwd);
+ if (info.isMain) io.caller?.('coordinator', info.root);
const allowSchemaUpgrade = codeIsFromMain();
const config = configHere(info);
const file = join(info.commonDir, 'pullboard', 'board.sqlite');
@@ -898,7 +898,11 @@ function withBoard(ctx, work) {
store.closeBoard(board);
};
let result;
- try { result = work(board); }
+ try {
+ // Reuse the already-open board to identify a registered seat, without another lock or migration.
+ if (ctx.io.caller && !ctx.info.isMain && !ctx.io.callerKnown?.(ctx.info.root) && store.agentAt(board, ctx.info.root)) ctx.io.caller('seat', ctx.info.root);
+ result = work(board);
+ }
catch (error) { finish(); throw error; }
if (result && typeof result.then === 'function') return result.finally(finish);
finish();
@@ -1030,6 +1034,7 @@ function refuseRemoteCoordinatorModel(ctx, command) {
*/
function whoAmI(ctx, board) {
if (ctx.info.isMain) {
+ ctx.io.caller?.('coordinator', ctx.info.root);
const registered = store.listAgents(board).find((agent) => agent.agent_id === COORDINATOR);
const linked = relayLinked(ctx.info.root);
if (linked && !registered) throw new Refused('NO_AGENT', 'the linked snapshot has no coordinator; restore a consistent relay snapshot before acting');
@@ -1041,6 +1046,7 @@ function whoAmI(ctx, board) {
if (!agent) {
throw new Refused('NOT_JOINED', 'this worktree has not joined a lane: pullboard join <lane> --model "<model name>" (see: pullboard lanes)');
}
+ ctx.io.caller?.('seat', ctx.info.root);
return { id: agent.agent_id, lane: agent.agent_lane, route: agent.agent_route, family: agent.agent_family ?? null, model: agent.agent_model ?? 'unknown', displayName: displayAgentName(agent, ctx.config.agents.names) };
}
@@ -1245,7 +1251,7 @@ function agentRefusalText(message, code, name) {
/** Render the refusal body without its existing final footer; structured errors retain the message. */
function displayedRefusal(io, error) {
- const message = error.message.replace(/\r?\nnext:[ \t]*[^\r\n]*\S[ \t]*(?:\r?\n)*$/u, '');
+ const message = io.guidance(error.message.replace(/\r?\nnext:[ \t]*[^\r\n]*\S[ \t]*(?:\r?\n)*$/u, ''));
if (error.code === 'MODEL_REQUIRED') return message.replace(/; run pullboard .+$/u, '');
if (!['ALREADY_JOINED', 'HELD', 'ITEM_HELD', 'LANE_HELD', 'REVIEW_HELD', 'NOT_YOURS', 'NOT_YOUR_DECISION', 'NO_AGENT', 'NOT_YOUR_CHECKOUT', 'FACT_JUDGEMENT', 'RELAY_PERSON_ONLY', 'RELAY_SENDER_MISMATCH', 'SELF_SHOUT', 'NO_READER'].includes(error.code)) return message;
try {
@@ -1606,7 +1612,7 @@ function boardSetup(ctx, card, identity) {
{ number: 5, done: card.viewOpened,
question: 'Ask the person: shall we open the board so you can follow the work?', command: 'pullboard view',
afterAnswer: 'Run this in the person’s own terminal, or start it in the background as the agent so setup can continue. The view records its successful bind or authenticated reuse for this board.' },
- ];
+ ].map(step => ({ ...step, question: ctx.io.guidance(step.question, { leading: true }) }));
const current = steps.find(step => !step.done);
if (!current && !recordedComplete) recordSetupState(ctx, identity, 'complete');
else if (current && !completed && !started) recordSetupState(ctx, identity, 'started');
@@ -1614,12 +1620,13 @@ function boardSetup(ctx, card, identity) {
const rowIds = drafted.map(row => row.id);
const names = rowIds.join(', ');
const command = `pullboard spec show ${rowIds[0]}`;
+ const seat = ctx.io.callerRole() === 'seat';
return { step: 1, total: 5, ...current, steps, waitingOn: 'person-approval', rowIds,
- question: `Waiting for the person to approve ${names}.`, command,
+ question: seat ? `Waiting for the coordinator to bring approval of ${names} to the person.` : `Waiting for the person to approve ${names}.`, command,
personCommand: `pullboard spec approve ${rowIds.join(',')}`,
afterAnswer: 'The person approves these rows in Pullboard View or their own terminal; then the coordinator runs pullboard spec apply.',
- meanwhile: 'While waiting, the agent may review independent approved work or prepare questions for the person.',
- agentNext: `wait for the person to approve ${names}; meanwhile ${command}` };
+ meanwhile: seat ? 'While waiting, review independent approved work or send questions to the coordinator with pullboard shout coordinator "<what is needed>" --decision.' : 'While waiting, the agent may review independent approved work or prepare questions for the person.',
+ agentNext: seat ? `ask the coordinator to bring approval of ${names} to the person: pullboard shout coordinator "approve ${names}" --decision; meanwhile ${command}` : `wait for the person to approve ${names}; meanwhile ${command}` };
}
return current ? { step: current.number, total: 5, ...current, steps } : null;
}
@@ -4093,7 +4100,7 @@ async function specCommand(io, { first, second, rest, values }) {
const lost = permanenceProblems(parsed === practice ? practice.repo : parsed, { committed: history.ids, cited });
if (name === ctx.config.spec) {
const answered = handAnsweredQuestions(previousSources.get(name) ?? [], parsed.rows, () => hookRead(ctx, (board) => store.rowDecisions(board)) ?? []);
- lost.push(...answered.map((id) => ({ id, message: `pending question answered by hand; ask the person to run pullboard spec answer ${id} "<choice or text>" and restore the pending row` })));
+ lost.push(...answered.map((id) => ({ id, message: io.guidance(`pending question answered by hand; ask the person to run pullboard spec answer ${id} "<choice or text>" and restore the pending row`) })));
}
lost.forEach((problem) => messages.push(`${name}: ${problem.id} error: ${problem.message}`));
const fileErrors = findings.filter((finding) => finding.level === 'error').length + lost.length;
@@ -4258,6 +4265,8 @@ async function hookCommand(io, { first, second }) {
applyFixers(info.root, ctx.config.fix).forEach((note) => io.err(`pullboard pre-commit: ${note}`));
const agent = info.isMain ? null : hookRead(ctx, (board) => store.agentAt(board, info.root));
const landing = hookRead(ctx, (board) => store.landingBatches(board).some((batch) => batch.root === info.root && !['landed', 'blocked'].includes(batch.state)));
+ if (landing) io.caller('coordinator', info.root);
+ else if (agent) io.caller('seat', info.root);
problems = preCommitProblems({ root: info.root, isMain: info.isMain || landing, config: ctx.config, agent, boardFile: ctx.file });
} else if (first === 'commit-msg') {
const message = readFileSync(second ?? '', 'utf8');
@@ -4284,7 +4293,7 @@ async function hookCommand(io, { first, second }) {
throw new Refused('USAGE', 'pullboard hook pre-commit | pre-merge-commit | commit-msg <file> | pre-push');
}
if (!problems.length) return 0;
- io.err(`pullboard ${first}: blocked\n${problems.map((problem) => ` - ${problem}`).join('\n')}\n${FIX_NOTE}`);
+ io.err(`pullboard ${first}: blocked\n${problems.map((problem) => ` - ${io.guidance(problem)}`).join('\n')}\n${FIX_NOTE}`);
return 1;
}
@@ -4302,7 +4311,7 @@ async function runCommand(argv, io) {
} catch (error) {
const refusal = new Refused('USAGE', `${error.message}; run pullboard help`);
io.refusal?.(refusal);
- io.err(`pullboard: ${error.message}\nRun pullboard help --all for the full list.\nnext: ${refusalDocument(refusal).error.next}`);
+ io.err(`pullboard: ${error.message}\nRun pullboard help --all for the full list.\nnext: ${io.refusalDocument(refusal).error.next}`);
return 2;
}
const { values, positionals } = parsed;
@@ -4503,7 +4512,7 @@ async function runCommand(argv, io) {
} catch (error) {
if (error instanceof Refused) {
io.refusal?.(error);
- io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${refusalDocument(error).error.next}`);
+ io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${io.refusalDocument(error).error.next}`);
return 1;
}
throw error;
@@ -4585,16 +4594,21 @@ async function runMain(argv, streams) {
} catch { sync = false; needsRepo = false; }
if (parsed) {
try {
+ // Checkout identity supplies the display role even if a person-channel check refuses first.
+ try { const info = repoInfo(io.cwd); if (info.isMain) io.caller('coordinator', info.root); } catch { /* Unknown checkouts retain existing guidance. */ }
const [command, verb] = parsed.positionals;
const remoteRelayOn = command === 'relay' && verb === 'on' && !parsed.values.all;
if (!parsed.values.help && !parsed.values.version &&
- (parsed.values.as === 'person' && command !== 'decisions' || command === 'relay' && ['on', 'join', 'revoke'].includes(verb) && !remoteRelayOn)) requirePersonChannel(io.personChannel);
+ (parsed.values.as === 'person' && command !== 'decisions' || command === 'relay' && ['on', 'join', 'revoke'].includes(verb) && !remoteRelayOn)) {
+ requirePersonChannel(io.personChannel);
+ io.caller('person');
+ }
checkoutSession = await bindCheckoutSession(io, parsed.positionals, parsed.values);
if (checkoutSession?.lease) CHECKOUT_LEASES.set(io, checkoutSession.lease);
} catch (error) {
if (!(error instanceof Refused)) throw error;
io.refusal(error);
- io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${refusalDocument(error).error.next}`);
+ io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${io.refusalDocument(error).error.next}`);
io.flush(1);
return 1;
}
@@ -4608,7 +4622,7 @@ async function runMain(argv, streams) {
}
catch (error) {
if (!(error instanceof Refused)) throw error;
- if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${refusalDocument(error).error.next}`);
+ if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${io.refusalDocument(error).error.next}`);
}
};
if (needsRepo) rememberTrunk(io);
@@ -4619,7 +4633,7 @@ async function runMain(argv, streams) {
try { await executePersonRequests(io.cwd, io, main); }
catch (error) {
if (!(error instanceof Refused)) throw error;
- if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${refusalDocument(error).error.next}`);
+ if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${io.refusalDocument(error).error.next}`);
}
}
traceServeStartup('cli-command-preamble-ready');
diff --git a/src/json.js b/src/json.js
index 0bc056e0..f8639b52 100644
--- a/src/json.js
+++ b/src/json.js
@@ -1,5 +1,5 @@
/** Versioned command results and refusals for tools that drive the CLI (A1). */
-import { nextStepFor } from './next-steps.js';
+import { nextStepFor, personRequestGuidance } from './next-steps.js';
/** A shape's required top-level fields; optional fields may be added within this version. */
function shape(fields) {
@@ -121,11 +121,11 @@ export const JSON_SHAPES = {
errorFields: { code: 'string', message: 'string', next: 'string' },
};
-/** A refusal shared by the CLI and API, retaining its rule and repair guidance (A1, A2). */
-export function refusalDocument(error) {
+/** A refusal shared by the CLI and API, presenting guidance for a known caller without changing its receipt (A1, A2, B26). */
+export function refusalDocument(error, options = {}) {
const message = String(error.message).replace(/^\[[A-Z][A-Z0-9_]*\] /, '');
const code = error.code ?? 'INTERNAL';
- return { version: JSON_SHAPES.version, error: { code, message, next: nextStepFor({ code, next: error.next }, message) } };
+ return { version: JSON_SHAPES.version, error: { code, message: personRequestGuidance(message, options), next: nextStepFor({ code, next: error.next }, message, options) } };
}
/**
@@ -137,6 +137,8 @@ export function commandOutput(argv, streams) {
let result;
let refusal;
let remote;
+ let caller = 'unknown';
+ let callerRoot;
let written = false;
const messages = [];
const diagnostics = [];
@@ -152,7 +154,7 @@ export function commandOutput(argv, streams) {
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 });
+ 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 {
@@ -175,6 +177,12 @@ export function commandOutput(argv, streams) {
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); },
diff --git a/src/next-steps.js b/src/next-steps.js
index e750dc2c..b9b22b69 100644
--- a/src/next-steps.js
+++ b/src/next-steps.js
@@ -9,6 +9,59 @@
*/
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');
+}
+
/** @type {Readonly<Record<string, string>>} */
export const NEXT_STEPS = Object.freeze({
HEALTH_FINDINGS: 'run pullboard health to read the current findings, then run pullboard resume to capture a fresh observation',
@@ -449,14 +502,16 @@ function stepInMessage(message) {
*
* @param {{ code?: string, next?: string } | null | undefined} error
* @param {string} message
+ * @param {{ caller?: 'seat'|'coordinator'|'person'|'unknown' }} [options]
* @returns {string}
*/
-export function nextStepFor(error, message) {
+export function nextStepFor(error, message, options = {}) {
+ if (personRequestGuidance(String(message), options) !== String(message)) return COORDINATOR_PERSON_REQUEST;
const code = typeof error?.code === 'string' ? error.code : '';
const finalStep = /(?:^|\r?\n)next:[ \t]*([^\r\n]*\S)[ \t]*(?:\r?\n)*$/u.exec(String(message))?.[1];
- if (finalStep) return finalStep.trim();
- if (typeof error?.next === 'string' && error.next.trim() && error.next.trim() !== RECORDED_GENERIC_NEXT) return error.next.trim();
+ if (finalStep) return personRequestStep(finalStep.trim(), options);
+ if (typeof error?.next === 'string' && error.next.trim() && error.next.trim() !== RECORDED_GENERIC_NEXT) return personRequestStep(error.next.trim(), options);
if (code === 'SPEC_BEHIND_MAIN') return NEXT_STEPS.SPEC_BEHIND_MAIN;
- return stepInMessage(message) ?? NEXT_STEPS[code]
- ?? `ask the service owner about refusal code ${code || '(unknown)'}, including the displayed refusal`;
+ return personRequestStep(stepInMessage(message) ?? NEXT_STEPS[code]
+ ?? `ask the service owner about refusal code ${code || '(unknown)'}, including the displayed refusal`, options);
}
diff --git a/src/templates.js b/src/templates.js
index e308e197..25e3ed9b 100644
--- a/src/templates.js
+++ b/src/templates.js
@@ -100,7 +100,7 @@ export function agentsBlock(doctrine = standardDoctrine()) {
return `${AGENTS_START}
## A new board
-On a board that is not set up, run \`pullboard resume\` first. Walk the person through its setup steps before anything else.
+On a board that is not set up, run \`pullboard resume\` first. The coordinator walks the person through its setup steps; every other seat sends the setup decisions to the coordinator as described in Talk.
## Working here: pullboard
@@ -144,7 +144,7 @@ For spare test capacity, use \`pullboard runner add <ssh-host> --slots <n> --bro
If your item needs code another lane owns and it is not there yet, shout that lane and take another item. Never copy their code into your lane, and never build another lane's item, even one that was rejected and blocks you: shout that lane and the coordinator. A claim refused as BLOCKED names the item it waits on.
-**Talk.** \`pullboard shout <lane|agent|all> "<text>"\`. Read \`pullboard inbox\` before you start and after you submit. An MCP client can do the same as your agent: add \`pullboard mcp\`, run from your worktree, as a stdio server; it reads the board, shows an item, shouts and captures ideas for the coordinator, and never makes a person's move.
+**Talk.** \`pullboard shout <lane|agent|all> "<text>"\`. Read \`pullboard inbox\` before you start and after you submit. Only the coordinator (the agent in the main checkout) talks with the person. Every other agent sends anything that needs the person—a decision, an approval, a waiver, a preview or a phone check—to the coordinator with \`pullboard shout coordinator "<what is needed>" --decision\`, and never asks the person in its own session, even when the person is watching. An MCP client can do the same as your agent: add \`pullboard mcp\`, run from your worktree, as a stdio server; it reads the board, shows an item, shouts and captures ideas for the coordinator, and never makes a person's move.
**Listen.** Where your client can run a command in the background, run \`pullboard watch --to <your id>\` there: it prints one line per event as it happens, and Claude Code wakes on each line when it runs under the Monitor tool. \`pullboard watch --work <lane>\` also says when an item in your lane becomes claimable, a review has waited too long, or main moves. Where your client cannot, read \`pullboard inbox\` at session start, after submit and before ending a turn. Coordinator answers and sentinel findings arrive there either way.
@@ -152,6 +152,8 @@ If your item needs code another lane owns and it is not there yet, shout that la
## Helping the person
+Only the coordinator follows this section with the person. Other agents do the technical investigation themselves and send any needed person action to the coordinator with \`pullboard shout coordinator "<what is needed>" --decision\`.
+
When the person asks for help with Pullboard, such as "Help me open my Pullboard board" or "Help me share my boards with my phone", work out the technical side yourself: read \`pullboard status\`, check whether \`pullboard view\` is running, read \`pullboard relay\` for the link, and follow the next step in any refusal. Then say what is going on in plain words and walk the person through each step they must take, one at a time: give one step, wait for them to say what they see, then give the next.
**Opening their board.** Start \`pullboard view\` yourself; it opens the board on this computer and prints its link. On app.pullboard.dev the browser may ask to let the page reach apps on this device: tell the person to click Allow, so the page can read the board running here. If they clicked Block, walk them through turning it back on: click the icon at the left of the address bar, open Site settings for app.pullboard.dev, set the access to apps on this device to Allow, then reload the page.
diff --git a/test/init-ignore.test.js b/test/init-ignore.test.js
index cc9791fe..008fe0a0 100644
--- a/test/init-ignore.test.js
+++ b/test/init-ignore.test.js
@@ -56,7 +56,7 @@ test('a fresh init tells the person and the agent how to start [I9,I1]', t => {
const agents = readFileSync(join(box.root, 'AGENTS.md'), 'utf8');
const section = agents.slice(agents.indexOf('## A new board'), agents.indexOf('## Working here: pullboard'));
- assert.equal(section, '## A new board\n\nOn a board that is not set up, run `pullboard resume` first. Walk the person through its setup steps before anything else.\n\n', 'AGENTS.md includes the new-board setup section');
+ assert.equal(section, '## A new board\n\nOn a board that is not set up, run `pullboard resume` first. The coordinator walks the person through its setup steps; every other seat sends the setup decisions to the coordinator as described in Talk.\n\n', 'AGENTS.md routes new-board setup decisions through the coordinator');
assert.doesNotMatch(section, /\b(?:spec|lanes|gates)\b/iu, 'the first setup guidance uses plain words');
});
diff --git a/test/next-steps.test.js b/test/next-steps.test.js
index 7defb023..bcd82d4f 100644
--- a/test/next-steps.test.js
+++ b/test/next-steps.test.js
@@ -1,9 +1,17 @@
/** Every seat routes person decisions through the coordinator [B26]. */
import assert from 'node:assert/strict';
-import { test } from 'node:test';
-import { refusalDocument } from '../src/json.js';
+import { after, test } from 'node:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { commandOutput, refusalDocument } from '../src/json.js';
import { NEXT_STEPS } from '../src/next-steps.js';
import { agentsBlock } from '../src/templates.js';
+import { Refused } from '../src/refused.js';
+import { recordedRefusal } from '../src/recorded-refusal.js';
+import { createE2eHelpers } from './e2e-helpers.js';
+
+const e2e = createE2eHelpers();
+after(e2e.cleanup);
test('agents are never told to ask the person [B26]', () => {
const route = 'ask the coordinator to bring it to the person: pullboard shout coordinator "<what is needed>" --decision';
@@ -34,3 +42,47 @@ test('agents are never told to ask the person [B26]', () => {
assert.match(talk, /never asks? the person in (?:its|their) own session/iu);
for (const need of ['decision', 'approval', 'waiver', 'preview', 'phone check']) assert.ok(talk.includes(need), `Talk routes a ${need}`);
});
+
+test('person routing preserves reasons, quoted text and canonical refusal receipts [B26]', () => {
+ const error = new Refused('STALE_ROW_DECISION', 'G1 changed; ask the person to approve its current row again');
+ const before = recordedRefusal(error);
+ const original = refusalDocument(error);
+ const builder = refusalDocument(error, { caller: 'seat' });
+ assert.match(builder.error.message, /^G1 changed;/u);
+ assert.match(builder.error.message, /pullboard shout coordinator.*--decision/u);
+ assert.match(builder.error.message, /needed: approve its current row again/u);
+ assert.doesNotMatch(builder.error.next, /ask the person/iu);
+ assert.deepEqual(refusalDocument(error, { caller: 'coordinator' }), original);
+ assert.deepEqual(refusalDocument(error, { caller: 'person' }), original);
+ assert.deepEqual(recordedRefusal(error), before, 'presentation never changes the authoritative receipt');
+ const quoted = new Refused('NO_READER', 'nobody reads "a title; ask the person to approve it": register a reader');
+ assert.equal(refusalDocument(quoted, { caller: 'seat' }).error.message, refusalDocument(quoted).error.message, 'quoted user content stays exact');
+ const diagnostics = new Refused('GATE_RED', 'the gate failed; fix the reported test\nfailing fixture text; ask the person for a waiver\nend of report');
+ assert.equal(refusalDocument(diagnostics, { caller: 'seat' }).error.message, refusalDocument(diagnostics).error.message, 'raw diagnostic lines are not guidance');
+ let output = '';
+ const io = commandOutput(['--json'], { stdout: { write: text => { output += text; } }, stderr: { write() {} } });
+ io.caller('seat', '/private/seat');
+ io.refusal(error);
+ io.flush(1);
+ assert.equal(JSON.parse(output).error.next, builder.error.next, 'JSON flush receives the actual caller');
+ assert.deepEqual(recordedRefusal(error), before);
+});
+
+test('real seat refusals and approved-row hooks send person requests to the coordinator [B26]', () => {
+ const box = e2e.project();
+ const json = box.run(box.web, 'spec', 'answer', 'G1', 'yes', '--json');
+ assert.equal(json.code, 1, json.err);
+ const error = JSON.parse(json.out).error;
+ assert.equal(error.code, 'B26_PERSON_APPROVAL', 'routing never grants the seat person authority');
+ assert.match(error.next, /pullboard shout coordinator.*--decision/u);
+ assert.doesNotMatch(error.next, /ask the person/iu);
+ const text = box.run(box.web, 'spec', 'answer', 'G1', 'yes');
+ assert.equal(text.code, 1);
+ assert.match(text.err, /next: ask the coordinator to bring it to the person/u);
+ const spec = readFileSync(join(box.web, 'SPEC.md'), 'utf8').replace('The page renders.', 'A different promise.');
+ const commit = e2e.commitFile(box, box.web, 'SPEC.md', spec, 'feat: change a private approved promise [G1]');
+ assert.equal(commit.status, 1, 'an approval request is still refused');
+ assert.match(commit.stderr, /G1 changes approved text without the person's exact approval/u);
+ assert.match(commit.stderr, /pullboard shout coordinator.*--decision/u);
+ assert.doesNotMatch(commit.stderr, /ask the person/iu);
+});