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.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(cli): give refusals concrete recovery actions [P4,I1,I2]
Corey Olson00d13d09ed42
diff --git a/src/agent-session.js b/src/agent-session.jsindex c32f010d..3ef0e2bb 100644--- a/src/agent-session.js+++ b/src/agent-session.js@@ -44,7 +44,8 @@ export async function bindLocalSession(info, { agent, digest, takeover = false,try {const previous = readBinding(file, takeover);if (!takeover && previous && previous.digest !== digest) {- throw new Refused('NOT_YOUR_CHECKOUT', `this checkout belongs to ${previous.agent} in another agent session; run pullboard worktree <lane> and work there, or, if you are the same agent in a new session, run pullboard takeover`);+ throw new Refused('NOT_YOUR_CHECKOUT', `this checkout belongs to ${previous.agent} in another agent session`,+ 'create a separate checkout with git worktree add --detach .claude/worktrees/<new-name> HEAD, using an unused folder; then cd there and run pullboard join <lane> --model "<model name>". If you are the same agent in a new session, run pullboard takeover instead');}if (takeover) await recordTakeover();if (!previous || takeover || previous.agent !== agent) persist(agent);diff --git a/src/api-http.js b/src/api-http.jsindex 1caee339..1ba76da8 100644--- a/src/api-http.js+++ b/src/api-http.js@@ -88,7 +88,7 @@ function boardCursors(value) {/** Name the board a many-board stream refused, unless the refusal already does (A2). */function namedRefusal(id, error) {if (!(error instanceof Refused) || error.message.includes(id)) return error;- return new Refused(error.code, `board ${id}: ${error.message.replace(/^\[[A-Z0-9_]+\] /u, '')}`);+ return new Refused(error.code, `board ${id}: ${error.message.replace(/^\[[A-Z0-9_]+\] /u, '')}`, error.next);}/** Whether a request asks for a live text/event-stream response rather than JSON. */diff --git a/src/cli.js b/src/cli.jsindex 9ccc8f9c..3bddb06f 100644--- a/src/cli.js+++ b/src/cli.js@@ -412,7 +412,8 @@ function checkMainVerifier(ctx, board, values) {const detached = tryGit(ctx.info.root, ['symbolic-ref', '-q', 'HEAD']).status !== 0 ? ' The main checkout is not on its branch; whoever switched it puts it back.' : '';throw new Refused('MAIN_IS_COORDINATOR',- `this is the main checkout, so this verdict would be the coordinator's. An agent verifies from its own worktree, starting every command with cd <worktree> &&.${listed}${detached} The coordinator adds --as coordinator`,+ `this is the main checkout, so this verdict would be the coordinator's.${listed}${detached}`,+ 'create a new reviewer worktree with git worktree add --detach .claude/worktrees/<reviewer-name> HEAD, using an unused folder; then cd there and run pullboard join <lane> --model "<model name>" and pullboard next --verify <id>. The reviewer must not be the builder. The coordinator instead adds --as coordinator',);}@@ -2146,7 +2147,7 @@ async function submitHere(ctx, id) {let comparison = { main: null, files: [], unavailable: 'main comparison could not be completed' };try { comparison = await compareMainFailures(root, gate.profile, gateWaitReporter(ctx.io), gate.output); } catch { /* Keep the original gate refusal if main evidence is unavailable. */ }const mainNote = withBoard(ctx, board => mainRedMessage(root, board, gate.profile, comparison));- throw new Refused('GATE_RED', `${message}${mainNote ? `\n${mainNote}` : ''}`);+ throw new Refused('GATE_RED', `${message}${mainNote ? `\n${mainNote}` : ''}`, 'fix the reported test or gate, commit the change, and run pullboard submit <id> again');}if (headCommit(root) !== commit || !isClean(root)) {throw new Refused(diff --git a/src/json.js b/src/json.jsindex cb556f2c..f8446299 100644--- a/src/json.js+++ b/src/json.js@@ -1,4 +1,5 @@/** Versioned command results and refusals for tools that drive the CLI (A1). */+import { nextStepFor } from './next-steps.js';/** A shape's required top-level fields; optional fields may be added within this version. */function shape(fields) {@@ -102,16 +103,11 @@ export const JSON_SHAPES = {errorFields: { code: 'string', message: 'string', next: 'string' },};-/** Extract a concrete repair from existing refusals, retaining their original guidance. */-function nextStep(message) {- const match = /(?:; |\. |: )((?:run|install|upgrade|fix|restore|commit|merge|test|check out|set|give|use|reject|ask your coordinator|answer from the main checkout|the coordinator|to keep looking|never work around)\b[\s\S]*)/i.exec(message);- return match?.[1] ?? 'Run pullboard help, correct the reported problem, and retry the command.';-}-/** A refusal shared by the CLI and API, retaining its rule and repair guidance (A1, A2). */export function refusalDocument(error) {const message = String(error.message).replace(/^\[[A-Z][A-Z0-9_]*\] /, '');- return { version: JSON_SHAPES.version, error: { code: error.code ?? 'INTERNAL', message, next: error.code === 'SPEC_BEHIND_MAIN' ? 'git merge main' : nextStep(message) } };+ const code = error.code ?? 'INTERNAL';+ return { version: JSON_SHAPES.version, error: { code, message, next: nextStepFor({ code, next: error.next }, message) } };}/**@@ -138,7 +134,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 });+ document = refusalDocument({ code: refusal?.code ?? match?.[1] ?? (code === 2 ? 'USAGE' : 'COMMAND_FAILED'), message, next: refusal?.next });} else if (result !== undefined) {document = { version: JSON_SHAPES.version, ...result, ...(diagnostics.length ? { diagnostics } : {}) };} else {diff --git a/src/next-steps.js b/src/next-steps.jsnew file mode 100644index 00000000..ffa34e60--- /dev/null+++ b/src/next-steps.js@@ -0,0 +1,375 @@+/**+ * The next step for every refusal code the CLI and API can raise (P4, W4).+ *+ * A raise site that knows more (an item id, a commit, a path) says so in its message or passes its+ * own step to Refused; this table is the step a refusal falls back to when it does neither, so no+ * refusal ends without one. Each step is a command or an action that gets past the rule, never a+ * step that leads straight back to the same refusal. test/refusal-next-steps.test.js checks that+ * every code raised in src/ has a row here.+ */++/** @type {Readonly<Record<string, string>>} */+export const NEXT_STEPS = Object.freeze({+ A5_GRAMMAR_VERSION: 'upgrade Pullboard: npm install -g pullboard@latest',+ AGENT_SESSION: 'run pullboard takeover from the agent session that should own this checkout',+ ALREADY_ANSWERED: 'read the answer with pullboard inbox; ask again with a new pullboard shout <to> "<text>" --decision',+ ALREADY_JOINED: 'create a worktree for the other lane: pullboard worktree <lane> --model "<model name>", then work from the path it prints',+ ALREADY_MERGED: 'file the follow-up as a new item: pullboard add <lane> "<title>"',+ AMBIGUOUS: 'name the code with an explicit line range: path:line-line@commit',+ API_ORIGIN: 'call the API from the address pullboard serve printed',+ API_LISTEN: 'choose a free port with --port 0, then retry pullboard serve',+ API_POLL: 'pass a poll interval from 10 to 60000 milliseconds',+ APPROVED_ROW_CHANGE: 'restore the committed file: git checkout HEAD -- <file>',+ AUTH_REQUIRED: 'run pullboard relay on to sign in again, or use the address and secret pullboard serve printed',+ B26_PERSON_ANSWER: 'ask your coordinator to answer or pass the decision: pullboard shout coordinator "<question>" --decision',+ B26_PERSON_APPROVAL: 'ask the person to decide in pullboard view',+ B26_PERSON_CHANNEL: 'record it as the person through pullboard view or the person\'s own terminal',+ B26_PERSON_DECISION: 'ask your coordinator: pullboard shout coordinator "<question>" --decision',+ BAD_BOARD: 'run the command from the board\'s own repo, where pullboard status names its board id',+ BAD_BROWSER_RESOURCE: 'request the "gate" resource with browser: true',+ BAD_CHECK: 'ask your coordinator to set the check: pullboard edit <id> --check "<command>"',+ BAD_CHECK_BASELINE: 'the coordinator sets the check again: pullboard edit <id> --check "<command>"',+ BAD_CONFIG: 'fix pullboard.json as the message says, then commit it: git commit -m "chore: fix pullboard config" pullboard.json',+ BAD_CURSOR: 'pass a nonnegative integer from the last response you received',+ BAD_DECISION: 'choose accept or reject with a supported reason: pullboard verify <id> reject --reason TEST_FAILURE --note "<what failed>"',+ BAD_DEPENDENCIES: 'use --after with item ids, such as --after 1,2, or --after none',+ BAD_EVIDENCE: 'pass the evidence fields the message names, then retry',+ BAD_FACT_ID: 'upgrade to the current Pullboard engine, then retry the original fact operation',+ BAD_FACT_KIND: 'use a supported kind, such as note: pullboard fact <id> note "<what you observed>"',+ BAD_FACT_REF: 'cite code as path:line[-line]@<full 40-character commit>, from git rev-parse HEAD',+ BAD_FIRST_COMMIT: 'commit the repository first, then run pullboard spec signers add',+ BAD_LANE: 'choose a lane name made of lowercase letters, digits and dashes, then retry pullboard lane add',+ BAD_LANE_PATH: 'give pullboard lane add a folder path inside the repository, relative to its root',+ BAD_GATE_SLOTS: 'choose a positive gateSlots value no lower than browserSlots shown by pullboard settings: pullboard settings gateSlots <n>',+ BAD_BROWSER_SLOTS: 'choose browserSlots from 1 through gateSlots shown by pullboard settings: pullboard settings browserSlots <n>',+ BAD_MACHINE_SETTINGS: 'fix or remove the machine settings file the message names, then run pullboard settings',+ MACHINE_HOME_NOT_WRITABLE: 'give the agent write access to the named machine-home directory, or run the command outside the sandbox',+ BAD_REASON: 'accept with --note "how you proved it", or reject with --reason TEST_FAILURE, BEHAVIOR_MISMATCH, INSUFFICIENT_EVIDENCE, STALE_HEAD or OTHER',+ BAD_REF: 'name the code as path:line-line@commit using a full 40-character commit SHA, such as src/serve.js:12-30@<full-sha>',+ BAD_REQUEST: 'send the request body the message names as an application/json object',+ BAD_RESOURCE_CAPACITY: 'pass a positive integer capacity',+ BAD_RESOURCE_METADATA: 'pass the resource item and kind as text',+ BAD_RESOURCE_NAME: 'pass a nonempty resource name',+ BAD_RESOURCE_PRIORITY: 'request the slot as one kind: a landing, an item check or a diagnostic',+ BAD_RESOURCE_SCOPE: 'use the machine or repo scope',+ BAD_ROUTE: 'use --route light, mid or strong',+ BAD_SIGNATURE: 'make sure the signer is listed, then record a fresh sign-off: pullboard spec signoff <ids>',+ BAD_SIGNER: 'set git config user.email, or pass --by <principal>',+ BAD_SIGNERS_BASE: 'restore .pullboard/signers.initial and its hash from git: git checkout HEAD -- .pullboard',+ BAD_SIGNOFF: 'sign the current approved rows from this repository: pullboard spec signoff <ids>',+ BAD_SIGNOFFS: 'restore the sign-off file from git: git checkout HEAD -- .pullboard/signoffs.jsonl',+ BAD_SINCE: 'pass a date: --since 2026-10-08',+ BLOCKED: 'take another item with pullboard next, or shout the lane it waits on: pullboard shout <lane> "<text>"',+ BOARD_BUSY: 'wait for the other pullboard process to finish, then retry',+ BOARD_SCOPE_UNAVAILABLE: 'link the board: pullboard relay on',+ BOARD_UNAVAILABLE: 'restore the repo, or drop it: pullboard forget <path>',+ BRIEF_LANE: 'split the item by lane, or add the other lane\'s part as its own item and wait on it with --after',+ BRIEF_TOO_LONG: 'shorten the brief and point to a longer doc by path, or pass --brief-file <file>',+ BROWSER_SLOT_REQUIRED: 'release the gate lease and take it again with browser: true',+ CANNOT_SIGN: 'sign only approved rows: pullboard spec signoff <approved ids>',+ CHECKOUT_SESSION: 'run pullboard takeover from the agent session that owns this checkout',+ CHECK_CANNOT_FAIL: 'write a check that exits nonzero on the problem, then add the item again',+ CHECK_CONFIRM: 'read the check command, then run pullboard check <id> --yes',+ CHECK_RED: 'reject with what failed: pullboard verify <id> reject --reason TEST_FAILURE --note "<what failed>"',+ CHECK_UNVERIFIED: 'restore the install or check environment, then run pullboard verify <id> again',+ CHILDREN_OPEN: 'finish the child items (pullboard list --all), or ask the coordinator to withdraw them',+ CLOSED: 'read its state with pullboard show <id>, then take open work: pullboard next',+ CODE_NOT_AVAILABLE: 'read code through pullboard view or a local pullboard serve',+ COMMAND_FAILED: 'read the reported output above, fix what it names, and run the command again',+ CORE_BARE: 'turn off core.bare: git config core.bare false',+ COORDINATOR_CHECK: 'ask your coordinator to set the check: pullboard shout coordinator "please set a check on #<id>"',+ COORDINATOR_ONLY: 'ask the coordinator to do it: pullboard shout coordinator "<what you need>"',+ COORDINATOR_VERIFIES: 'leave the review to the coordinator; shout it when the item is ready: pullboard shout coordinator "#<id> is ready to verify"',+ CRITERIA_CHANGED: 'ask the coordinator to refreeze it: pullboard shout coordinator "please refreeze #<id>"',+ DELTA_NOT_AVAILABLE: 'read the full board state from this API instead of since=N',+ DEPENDENCY_CYCLE: 'change --after so no item waits on itself',+ DEVICE_CRYPTO: 'use Node 22 or newer, or a browser on a secure (https) page',+ DEVICE_ENDPOINT: 'upgrade Pullboard on this machine and the phone, then retry',+ DEVICE_ENROLLMENT: 'make a fresh pairing link: pullboard relay on --all',+ DEVICE_ENROLL_AUTH: 'make a fresh pairing link: pullboard relay on --all',+ DEVICE_EXISTS: 'make a fresh pairing link: pullboard relay on --all',+ DEVICE_FORMAT: 'make a fresh pairing link: pullboard relay on --all',+ DEVICE_ID: 'list paired devices with pullboard relay devices and name one of them',+ DEVICE_KEY: 'pair the device again: pullboard relay on --all',+ DEVICE_NOT_ENROLLED: 'list paired devices with pullboard relay devices, or pair one: pullboard relay on --all',+ DEVICE_PAIR_EXPIRED: 'make a fresh pairing link: pullboard relay on --all',+ DEVICE_PAIR_SECRET: 'open the pairing link exactly as printed, or make a fresh one: pullboard relay on --all',+ DEVICE_PAIR_USED: 'make a fresh pairing link: pullboard relay on --all',+ DEVICE_REVOKED: 'pair the device again: pullboard relay on --all',+ DEVICE_WRAP_AUTH: 'pair the device again: pullboard relay on --all',+ DEVICE_WRAP_BINDING: 'upgrade Pullboard, then pair the device again: pullboard relay on --all',+ DEVICE_WRAP_KEY: 'pair the device again: pullboard relay on --all',+ DIFF_TOO_LARGE: 'split the change into smaller commits',+ DIRTY: 'commit your changes, then run the command again',+ EMPTY_FACT: 'give nonempty fact text: pullboard fact <id> note "<what you saw>"',+ EMPTY_NOTE: 'say why: pullboard pass <id> --note "<reason>"',+ EMPTY_SHOUT: 'give the shout text: pullboard shout <to> "<text>"',+ EMPTY_SIGNERS: 'restore the signer list from Git: git restore --source=HEAD -- .pullboard/signers',+ ENGINE_VERSION: 'upgrade Pullboard: npm install -g pullboard@latest',+ EVENT_LOG_VERSION: 'upgrade Pullboard: npm install -g pullboard@latest',+ EXPORT_EXISTS: 'name an empty folder for the export',+ FACT_JUDGEMENT: 'use a nonjudgement fact kind such as note, or ask the coordinator to record a judgement: pullboard fact <id> note "<what you observed>"',+ FLAG_NOT_ALLOWED: 'drop the flag; pullboard help spec lists what each spec command takes',+ GATE_RED: 'fix what the gate report names, commit, and submit again',+ GATE_SLOT_LEASE_LOST: 'let the parent process take the gate slot again, then restart the child',+ GATE_SLOT_LEASE_REQUIRED: 'start the child test process with the live gate lease',+ GATE_SLOT_MARKER_INVALID: 'restart the child with gateSlotEnvironment(lease)',+ GATE_SLOT_TOKEN_REQUIRED: 'restart the child with gateSlotEnvironment(lease)',+ GIT_GRAFTS: 'ask the coordinator to remove the git graft file: pullboard shout coordinator "please remove .git/info/grafts"',+ HEAD_NOT_NEW: 'commit the rework, then pullboard submit <id>',+ HELD: 'take another item: pullboard next',+ HUMAN_REQUIRED: 'send it from the paired phone, or run pullboard relay on --all from the person\'s terminal',+ IMPORT_FORMAT: 'make an export with pullboard export > board.json, then import that file',+ IMPORT_NOT_EMPTY: 'import into a fresh repo whose board is empty: git init <dir> && cd <dir> && pullboard init',+ IMPORT_SCHEMA: 'export and import with the same Pullboard version',+ IMPORT_VERSION: 'export the board again with this Pullboard version: pullboard export > board.json',+ INTERNAL: 'run the command again; if it repeats, report it with pullboard shout coordinator "<command and output>"',+ ITEM_HELD: 'take another item with pullboard next while the coordinator holds this one',+ ITEM_NOT_AVAILABLE: 'read the item from this API\'s board state',+ ITEM_NOT_OPEN: 'hold only open or claimed items; see pullboard list',+ LANDING_FAILURE_REQUIRED: 'reopen with --note "<test file>: <test name>; merge commit <sha>"',+ LANE_TAKEN: 'choose a different lane name with pullboard lane add',+ LAND_ADOPT: 'read pullboard resume, then run pullboard land --adopt, or pullboard land when nothing is unfinished',+ LAND_BATCH: 'adopt the recorded batch: pullboard land --adopt',+ LAND_DIAGNOSTIC: 'read the landing log the message names, and make the test reporter print file names',+ LAND_DIRTY: 'inspect the landing worktree, commit or remove its edits, then pullboard land --adopt',+ LAND_FLAKE: 'fix the flaky test, or ask the person for a waiver: pullboard land --waive <test> --until <date> --reason "why"',+ LAND_HEADER: 'shorten the item\'s cited rows (pullboard edit <id>), then pullboard land',+ LAND_INTERACTION: 'read the batch\'s failing tests, then land the items in separate batches',+ LAND_ITEM_MOVED: 'rebuild the batch from current verified work: pullboard land',+ LAND_MERGE: 'inspect the landing worktree and its hooks, then pullboard land --adopt',+ LAND_MOVED: 'read pullboard resume, then adopt the current batch: pullboard land --adopt',+ LAND_NOT_PUSHED: 'push the batch, then pullboard land --adopt',+ LAND_PERSON_ONLY: 'ask the person to waive it from their terminal or pullboard view',+ LAND_PUSH: 'inspect the remote and hooks, then pullboard land --adopt',+ LAND_REMOTE_MOVED: 'inspect the remote branch, then pullboard land --adopt',+ LAND_TRUNK: 'check the recorded trunk branch with pullboard resume, then switch the main checkout to that branch: git switch <trunk-branch>',+ LAND_TRUNK_MOVED: 'rebuild the batch from the new main: pullboard land',+ LAND_WAIVER: 'pullboard land --waive <test> --until <date> --reason "why"',+ LAND_WORKTREE: 'restore the landing worktree the message names, then pullboard land --adopt',+ LANE_HELD: 'wait for the lane: pullboard next --wait 9 (minutes)',+ MAIN_IS_COORDINATOR: 'use an independent agent checkout for agent work, or run person-only actions from the main checkout as the coordinator',+ MERGE_CHECK_FAILED: 'use Git 2.38 or newer (git --version), then retry',+ MERGE_CONFLICT: 'merge main into your branch, resolve the conflicts, commit, and run the command again',+ MILESTONES_CORRUPT: 'restore the board from a known-good export: pullboard import <file>',+ MILESTONE_EDIT: 'pass --name or --note: pullboard milestone edit <name> --note "<text>"',+ MILESTONE_EXISTS: 'pick another name, or edit the existing one: pullboard milestone edit <name>',+ MILESTONE_ITEMS: 'list item ids once each: pullboard milestone add <name> --items 1,2',+ MILESTONE_NAME: 'pullboard milestone add <name>',+ MILESTONE_NOTE: 'pass the note text: --note "<text>"',+ MILESTONE_ORDER: 'move it before a different milestone; see pullboard roadmap',+ MISSING_SIGNATURE: 'have the person repeat approval for the named row: pullboard spec approve <id>',+ MISSING_SIGNERS: 'restore the signer list from git: git checkout HEAD -- .pullboard/signers',+ MODEL_REQUIRED: 'pass --model "<model name>", or set PULLBOARD_MODEL in this shell',+ MOVED_DURING_GATE: 'leave the worktree alone until the gate finishes, then submit again',+ NOTE_REQUIRED: 'add --note "<what happened>"',+ NOTHING_FREE: 'wait for work: pullboard next --wait 9 (minutes)',+ NOT_AT_COMMIT: 'check out the submitted commit shown by pullboard show <id>: git switch --detach <commit>',+ NOT_A_DECISION: 'reply with a shout: pullboard shout <to> "<text>"',+ NOT_A_REPO: 'cd into a git repo, or make one: git init',+ NOT_CLAIMABLE: 'take open work: pullboard next',+ NOT_COMMITTED: 'commit the files the message names, then run the command again',+ NOT_COORDINATOR_DECISION: 'list open decisions with pullboard decisions and answer one of those',+ NOT_HELD: 'see what is held with pullboard status',+ NOT_HOLDING: 'name an item: pullboard check <id>, or run the project gate: pullboard gate',+ NOT_JOINED: 'join a lane from this worktree: pullboard join <lane> --model "<model name>" (see: pullboard lanes)',+ NOT_MAIN: 'run this coordinator-owned operation from the main checkout, or ask the coordinator to do it',+ NOT_MERGED: 'merge the item\'s commit onto the trunk, then pullboard merged <id>',+ NOT_SSH_KEY: 'add a valid OpenSSH public key: pullboard spec signers add --key ~/.ssh/id_ed25519.pub',+ NOT_SSH_KEY_PATH: 'set user.signingkey to an SSH key file: git config user.signingkey ~/.ssh/id_ed25519.pub',+ NOT_SUBMITTED: 'see its state with pullboard show <id>; verify only submitted items: pullboard next --verify',+ NOT_VERIFIED: 'merge only verified items; see pullboard list --all',+ NOT_YOURS: 'shout its holder or the coordinator: pullboard shout coordinator "<what you need>"',+ NOT_YOUR_CHECKOUT: 'make an independent checkout with git worktree add -b <lane>/<n> ../<repo>-<lane>-<n>, then run pullboard join <lane> --model "<model name>" there; the same agent in a new session should run pullboard takeover from its own shell',+ SANDBOX_BLOCKED: 'ask the person to allow the named operation, or run the gate outside the sandbox; keep the tests unchanged',+ NOT_YOUR_DECISION: 'answer only decisions addressed to you; see pullboard inbox',+ NO_AGENT: 'create and join a lane worktree: pullboard worktree <lane> --model "<model name>"',+ NO_BOARD: 'initialize the board in this repository: pullboard init',+ NO_BRIEF: 'add the missing fields with pullboard edit <id> --brief "..." --criterion "..."',+ NO_CHECK: 'run the project gate: pullboard gate',+ NO_COMMIT: 'commit your work, or name a commit that exists: git log --oneline',+ NO_CONFIG: 'run pullboard init in the main checkout and commit pullboard.json',+ NO_ENDPOINT: 'use a path under /api/v1/boards',+ NO_EVIDENCE: 'cite the row id in a test name, or build it first',+ NO_FACT: 'name a fact id from pullboard show <id> --json',+ NO_FILE: 'check the path and pass a file that exists',+ NO_FIRST_COMMIT: 'commit the repo, then pullboard spec signers add',+ NO_GATE: 'set "gate" in pullboard.json, such as "npm test", and commit it',+ NO_ITEM: 'find the item id: pullboard list --all',+ NO_LANE: 'pick a lane from pullboard lanes',+ NO_LINES: 'name a line range inside the file',+ NO_MILESTONE: 'name a milestone from pullboard roadmap',+ NO_POLICY: 'restore and commit pullboard.json, then run the command again',+ NO_READER: 'name a lane, an agent or all: pullboard shout all "<text>"',+ NO_REPO: 'run pullboard init in the repo, or pick a project in pullboard view',+ NO_ROLE: 'choose one of the roles listed by pullboard skills',+ NO_ROW: 'list the rows with pullboard spec --json, then name one of them',+ NO_SECTION: 'add a section heading such as "## G · Goals" to the spec, then draft the row',+ NO_SHOUT: 'name a shout id from pullboard inbox',+ NO_SIGNERS: 'add an SSH signer: pullboard spec signers add',+ NO_SIGNING_COMMIT: 'commit the repo, then sign again',+ NO_SPEC: 'run pullboard init',+ NO_TITLE: 'give a title: pullboard add <lane> "<title>"',+ NO_TRUNK: 'in the main checkout, switch to the repository’s trunk branch and run pullboard inbox',+ O2_FAMILY_MATCH: 'ask the coordinator for a verifier from another family: pullboard shout coordinator "#<id> needs a verifier from another family"',+ OAUTH_CANCELLED: 'start sign-in again: pullboard relay on',+ OAUTH_CLEANUP: 'run pullboard relay on again once the relay answers',+ OAUTH_EXPIRED: 'start sign-in again: pullboard relay on',+ ONE_CLAIM: 'submit or release the item you hold: pullboard release <id> --note "why"',+ ONE_COORDINATOR: 'make a lane worktree and join it as an agent: pullboard worktree <lane> --model "<model name>"',+ OUTSIDE_LANE: 'move those changes out of this commit, and shout the lane that owns them: pullboard shout <lane> "<text>"',+ PAIR_BUSY: 'let sync finish, then pair again: pullboard relay pair',+ PAIR_CODE_INVALID: 'ask the linked device for a new code: pullboard relay pair',+ PAIR_LINK_LONG: 'open the printed link instead of scanning the code',+ PAIR_PACKAGE: 'make a fresh code on the linked device: pullboard relay pair',+ PAIR_PACKAGE_SIZE: 'ask the linked device for a smaller package, or join from a fresh clone',+ PAIR_PENDING: 'finish sync first (pullboard status), then pair again',+ PAIR_RELAY: 'run pullboard relay join with the relay address the code came from',+ PAIR_REPOSITORY: 'ask the linked device for a fresh code, then join inside the matching clone',+ PAIR_STATE: 'sync this device (pullboard status), then pair again',+ PATH_OWNED: 'choose a folder no existing lane owns, or edit the lane ownership in pullboard.json from the main checkout',+ PARENT_CLOSED: 'add the item without --parent, or under an open parent',+ PARENT_LANE: 'add the child in its parent\'s lane',+ PENDING_REFREEZE: 'the coordinator runs pullboard refreeze <id>',+ PERSON_REQUEST_CLOSED: 'read the request\'s original result in pullboard view',+ PERSON_REQUEST_ID: 'reload the paired view and send a new request',+ PERSON_REQUEST_RECEIPT: 'upgrade Pullboard on the linked machine, then retry from the paired view',+ PERSON_REQUEST_TAKEN: 'wait for the other machine\'s receipt in pullboard view',+ PERSON_REQUEST_VERSION: 'upgrade Pullboard on the linked machine and reload the view',+ PHONE_APPROVAL_AUTH: 'request a fresh approval on the phone and retry',+ PHONE_APPROVAL_CONTEXT: 'request approval for this exact board, action and command',+ PHONE_APPROVAL_EXPIRED: 'run the command again and approve it on the phone',+ PHONE_APPROVAL_UNAVAILABLE: 'retry the phone approval when the relay answers; if it repeats, pair again with pullboard relay on --all',+ PHONE_APPROVAL_PENDING: 'approve the named action on the paired phone before it expires',+ PHONE_NOT_PAIRED: 'pair the phone: pullboard relay on --all',+ PIN_FAILED: 'fix what git reported, then run pullboard run again',+ PIPEFAIL_UNAVAILABLE: 'rewrite the gate in pullboard.json without a pipe',+ PORT_BUSY: 'pick a free port with --port 0',+ PROJECT_NOT_REGISTERED: 'run pullboard view --project inside a registered repo, or plain pullboard view',+ PROJECT_SCOPE: 'scope the API to one registered project repo',+ PROOF_REQUIRED: 'say how you proved it: --note "what you broke or which edge you tried, and what happened"',+ RELAY_ACTOR: 'send the move with the token of the agent that makes it',+ RELAY_ANSWER: 'use pullboard answer <id> "<answer>" or pullboard pass <id> --note "<reason>"',+ RELAY_BASELINE_EXISTS: 'save the board with pullboard export > board.json, then pullboard relay off',+ RELAY_BUSY: 'run the command again after the other worktree finishes sending',+ RELAY_CURSOR: 'fetch a consistent snapshot: pullboard relay',+ RELAY_DIVERGED: 'run pullboard relay off, then pullboard relay on to link again from this machine',+ RELAY_KEYCHAIN: 'unlock the system keychain, then run the command again',+ RELAY_KEY_EXISTS: 'keep this clone\'s key, and join from a fresh device home',+ RELAY_KEY_FILE_ENV_MISMATCH: 'unset PULLBOARD_RELAY_KEY, or set it to this device\'s key',+ RELAY_KEY_MISSING: 'pair this device again: pullboard relay on --all',+ RELAY_KEY_STORAGE: 'restore owner-only permissions: chmod 700 on the relay-keys folder, 600 on its files',+ RELAY_LINKED: 'run pullboard relay off before linking it elsewhere, or use a fresh clone',+ RELAY_LOCAL_CHANGED: 'save the board with pullboard export > board.json, then retry the recovery',+ RELAY_MACHINE_STORAGE: 'restore owner-only permissions on the relay-machine folder (700) and its files (600)',+ RELAY_MOVE: 'upgrade Pullboard: npm install -g pullboard@latest',+ RELAY_NOT_LINKED: 'link the board: pullboard relay on --all',+ RELAY_OFF: 'link the board: pullboard relay on',+ RELAY_ORDER: 'fetch and apply the missing moves: pullboard relay',+ RELAY_ORIGIN: 'set a GitHub origin: git remote add origin https://github.com/<owner>/<repo>.git, then pullboard relay on',+ RELAY_PERSON_ONLY: 'do it as the person from the paired phone or the person\'s own session',+ RELAY_PRESENTATION_PENDING: 'run pullboard status again',+ RELAY_RECOVERY_HEALTHY: 'replay it normally: pullboard relay',+ RELAY_RECOVERY_PENDING: 'finish the saved recovery: pullboard relay recover --skip <sequence>',+ RELAY_REPLAY_REQUIRED: 'upgrade Pullboard: npm install -g pullboard@latest',+ RELAY_RESPONSE: 'retry once the relay answers; if it repeats, pair again: pullboard relay on --all',+ RELAY_REFUSED: 'retry after fixing the displayed relay refusal; if it repeats, upgrade Pullboard and report the refusal to the service owner',+ RELAY_CHECKPOINT_REFUSED: 'upgrade Pullboard or run pullboard relay off then pullboard relay on --all; if it repeats, report the displayed checkpoint refusal',+ RELAY_SNAPSHOT_LIMIT: 'reduce the board snapshot until it fits the relay limit, then retry the command',+ RELAY_RECORD: 'retry the relay action after the displayed blocker is resolved',+ RELAY_RETRY_PENDING: 'repeat the interrupted command exactly to get its original outcome',+ RELAY_SEAL: 'continue with the next record: pullboard relay',+ RELAY_SENDER: 'restore the record\'s sender before replaying it',+ RELAY_SENDER_MISMATCH: 'send the move as the agent that makes it, from that agent\'s worktree',+ RELAY_SEQUENCE: 'inspect pullboard relay and skip only the blocked next sequence',+ RELAY_SESSION: 'link this project and pair the phone: pullboard relay on --all',+ RELAY_SNAPSHOT: 'fetch a consistent snapshot (pullboard relay), or join by pairing',+ RELAY_SNAPSHOT_BUSY: 'run the command again',+ RELAY_STORAGE: 'restore relay.json as an owner-only file (chmod 600), or pullboard relay off and on again',+ RELAY_UNAVAILABLE: 'keep working offline, and run the command again when the relay answers',+ RELAY_UNLINK_PENDING: 'finish unlinking: pullboard relay off',+ RELAY_URL: 'use an HTTPS relay address, such as https://app.pullboard.dev',+ RELAY_VERSION: 'upgrade Pullboard: npm install -g pullboard@latest',+ REMOTE_COORDINATOR_MODEL: 'run the command in the coordinator\'s own checkout',+ REQUEST_CLOSED: 'read pullboard inbox before answering another request',+ REQUEST_OUTCOME: 'pullboard answer <id> done "<reason>", or pullboard answer <id> declined "<reason>"',+ RESOURCE_BUSY: 'check the holder and queue with pullboard resources, wait for the resource to become free, then retry',+ RESOURCE_CAPACITY_MISMATCH: 'check the configured capacity with pullboard settings, then retry using that capacity',+ RESOURCE_LEASE_LOST: 'take the resource again, then retry',+ REVIEW_COOLDOWN: 'take another review: pullboard next --verify',+ REVIEW_HELD: 'take another review: pullboard next --verify',+ ROUTE: 'take an item your route covers: pullboard next',+ ROW_DECISION: 'pullboard spec approve <ids>, or pullboard spec decline <ids>',+ SEAL_AUTH_FAILED: 'fetch the board again, or pair this device again: pullboard relay on --all',+ SEAL_BINDING: 'upgrade Pullboard on this device, then retry',+ SEAL_CRYPTO: 'use Node 22 or newer, or a browser on a secure (https) page',+ SEAL_FORMAT: 'fetch the board again: pullboard relay',+ SEAL_KEY: 'pair this device again: pullboard relay on --all',+ SEAL_VERSION: 'upgrade Pullboard on this device: npm install -g pullboard@latest',+ SELF_SHOUT: 'name another agent, a lane or all: pullboard shout all "<text>"',+ SELF_VERIFY: 'ask a different agent to verify it; from main create its worktree with pullboard worktree <lane> --model "<model name>"',+ SERVICE_ERROR: 'retry the call; if it repeats, restart pullboard serve',+ SHALLOW_BEFORE_OPT_IN: 'git fetch --unshallow, then pullboard spec signers add',+ SHOUT_NOT_AVAILABLE: 'read shouts with pullboard inbox, or refresh the snapshot with a current CLI',+ SNAPSHOT_FORMAT: 'refresh the snapshot from a linked machine: pullboard relay',+ SPEC_BEHIND_MAIN: 'git merge main',+ SPEC_INVALID: 'fix the unparsed row the message names, then pullboard spec check',+ SPEC_SECTION: 'name a section the spec has; see pullboard spec',+ SSH_KEY_FAILED: 'check the SSH key and that ssh-keygen is installed: ssh-keygen -l -f <key>',+ SSH_KEY_NOT_FOUND: 'pass the key path: --key ~/.ssh/id_ed25519.pub',+ STACKED_ON_UNVERIFIED: 'wait for the earlier item to be accepted, or rebuild on main without its commits',+ STALE_ROW_DECISION: 'ask the person to approve the current row again in pullboard view',+ TOKENS_NOT_AVAILABLE: 'manage agent tokens in pullboard view or the signed-in relay account',+ TOKEN_NOT_OWNED: 'name a token id from pullboard relay tokens',+ TOO_LARGE: 'open the file in your editor instead',+ UNAUTHORIZED_SIGNERS_CHANGE: 'restore the previous signer list (git checkout HEAD -- .pullboard/signers), or sign the change with a listed key',+ UNKNOWN_SPEC: 'ask the coordinator to restore the named spec rows or withdraw the item: pullboard shout coordinator "please fix the rows cited by #<id>"',+ UNLISTED_SIGNER: 'add the signer: pullboard spec signers add --by <principal> --key <path>',+ UNMERGED_SCHEMA: 'merge this code into the main checkout first, or test it against its own board',+ UNTRACKED: 'commit or ignore the untracked files, then run the command again',+ USAGE: 'run pullboard help',+ VIEW_START: 'run pullboard view in the foreground to see why it stopped',+ VIEW_PAIRING_CLEANUP: 'run pullboard relay off, then pullboard relay on --all to finish pairing cleanup',+ VIEW_STATE: 'check that the Pullboard home folder is writable, then run pullboard view again',+ VIEW_UNAVAILABLE: 'start the view with pullboard view, then export again',+ VIEW_PAIRING_NOT_READY: 'read this sign-in’s status again: pullboard view',+ VIEW_SIGN_IN_BUSY: 'finish or cancel the sign-in already in progress, then start it again',+ VIEW_SIGN_IN_LINKING: 'let the current board-linking batch finish before starting another sign-in',+ VIEW_SIGN_IN_RESPONSE: 'check the configured relay address, then start sign-in again',+ VIEW_SIGN_IN_STOPPED: 'start sign-in again with pullboard view',+ VIEW_SIGN_IN_UNKNOWN: 'start sign-in again with pullboard view',+ WITHDRAWN: 'wait on an item that is not withdrawn; see pullboard list --all',+ WRONG_BOARD: 'open the repository registered to this board and confirm its identity with pullboard status',+ WRONG_LANE: 'create a worktree in the required lane with pullboard worktree <lane> --model "<model name>", or take an item in your lane with pullboard next',+});++/**+ * Take the step a message already spells out: the clause from its first repair word to the end of+ * that line. One line only, so a multi-line report (a gate digest) is never repeated as the step.+ *+ * @param {string} message+ * @returns {string | undefined}+ */+function stepInMessage(message) {+ const line = String(message).split('\n')[0];+ const match = /(?:^|; |\. |: )((?:run|install|upgrade|fix|restore|commit|merge|test|check out|set|give|use|reject|ask your coordinator|answer from the main checkout|the coordinator(?= (?:runs?|sets?|restores?|either|must)\b)|to keep looking|never work around)\b.*)/i.exec(line);+ const step = match?.[1];+ // UNKNOWN_MOVE contains a documentation placeholder, not a supported reason value.+ return step && !/--reason\s+CODE\b/u.test(step) ? step : undefined;+}++/**+ * The next step for one refusal: the step its raise site passed, else the one its message spells+ * out, else this code's row. Unknown remote codes ask the service owner about the displayed refusal.+ *+ * @param {{ code?: string, next?: string } | null | undefined} error+ * @param {string} message+ * @returns {string}+ */+export function nextStepFor(error, message) {+ const code = typeof error?.code === 'string' ? error.code : '';+ if (typeof error?.next === 'string' && error.next.trim()) return error.next.trim();+ 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`;+}diff --git a/src/refused.js b/src/refused.jsindex 9c2df86e..388d28eb 100644--- a/src/refused.js+++ b/src/refused.js@@ -5,10 +5,12 @@ export class Refused extends Error {/*** @param {string} code - The rule that refused, in UPPER_SNAKE, e.g. SELF_VERIFY.* @param {string} message - Why, and the next step.+ * @param {string} [next] - A contextual recovery action, when the raise site knows it.*/- constructor(code, message) {+ constructor(code, message, next) {super(`[${code}] ${message}`);this.name = 'Refused';this.code = code;+ if (typeof next === 'string' && next.trim()) this.next = next.trim();}}diff --git a/src/relay-pairing-client.js b/src/relay-pairing-client.jsindex a90d5395..6d2b885d 100644--- a/src/relay-pairing-client.js+++ b/src/relay-pairing-client.js@@ -73,7 +73,7 @@ async function relayRequest(url, token, path, body) {} catch { throw new Refused('RELAY_UNAVAILABLE', 'the relay did not answer; retry pairing with the same code before it expires'); }let document;try { document = await response.json(); } catch { throw new Refused('RELAY_RESPONSE', 'the relay returned an invalid pairing response; ask for a fresh code'); }- if (!response.ok) throw new Refused(document.error?.code || 'RELAY_UNAVAILABLE', document.error?.message || 'the relay refused pairing; ask the linked device for a fresh code');+ if (!response.ok) throw new Refused(document.error?.code || 'RELAY_UNAVAILABLE', document.error?.message || 'the relay refused pairing; ask the linked device for a fresh code', document.error?.next);if (document.version !== 1) throw new Refused('RELAY_VERSION', 'the relay pairing API version is unsupported; upgrade Pullboard before pairing');return document;}diff --git a/src/relay.js b/src/relay.jsindex bbb42d66..9268cb33 100644--- a/src/relay.js+++ b/src/relay.js@@ -172,7 +172,8 @@ async function request(state, path, { method = 'GET', body, allowMissing = false// Only off can forget a link after a supported API reports that the board is gone.if (allowMissing && method === 'DELETE' && response.status === 404 && document.version === 1) return { alreadyDeleted: true };if (!response.ok) {- const error = new Refused(document.error?.code || 'RELAY_UNAVAILABLE', (document.error?.code === 'AUTH_REQUIRED' ? ((state.agent || token?.startsWith('pa_')) ? 'this agent token is expired or revoked; use a new token issued by the person for this agent, then retry with PULLBOARD_RELAY_TOKEN' : 'the relay sign-in expired or was revoked; run pullboard relay on to sign in again without changing the board key') : (document.error?.message ? `the relay ${state.url}: ${document.error.message}` : null)) || 'the relay refused this send; retry this command explicitly when reachable');+ const error = new Refused(document.error?.code || 'RELAY_UNAVAILABLE', (document.error?.code === 'AUTH_REQUIRED' ? ((state.agent || token?.startsWith('pa_')) ? 'this agent token is expired or revoked; use a new token issued by the person for this agent, then retry with PULLBOARD_RELAY_TOKEN' : 'the relay sign-in expired or was revoked; run pullboard relay on to sign in again without changing the board key') : (document.error?.message ? `the relay ${state.url}: ${document.error.message}` : null)) || 'the relay refused this send; retry this command explicitly when reachable',+ document.error?.code === 'AUTH_REQUIRED' ? undefined : document.error?.next);error.httpStatus = response.status;error.relayVersion = document.version;error.relayCode = document.error?.code;@@ -749,7 +750,7 @@ async function catchUp(root, file, state, io) {delete state.pending;}saveLink(file, state);- if (pendingRefusal) throw new Refused(pendingRefusal.code, pendingRefusal.message);+ if (pendingRefusal) throw new Refused(pendingRefusal.code, pendingRefusal.message, pendingRefusal.next);}/** Finish a durable executable send; a collision reseals its unchanged id after applying the winner. */@@ -906,7 +907,7 @@ export async function relayOperation(root, operation, args, io, command, applyLodelete state.recovered;saveLink(file, state);}- if (previousReceipt.outcome.error) throw new Refused(previousReceipt.outcome.error.code, previousReceipt.outcome.error.message);+ if (previousReceipt.outcome.error) throw new Refused(previousReceipt.outcome.error.code, previousReceipt.outcome.error.message, previousReceipt.outcome.error.next);for (const event of previousReceipt.outcome.events ?? []) io.onEvent?.(event);return previousReceipt.outcome.result;}@@ -942,7 +943,7 @@ export async function relayOperation(root, operation, args, io, command, applyLoif (error.code === 'AUTH_REQUIRED') reportExpiredSignIn(state, io);else io.err(`pullboard: ${error.message}`);}- if (receipt.outcome.error) throw new Refused(receipt.outcome.error.code, receipt.outcome.error.message);+ if (receipt.outcome.error) throw new Refused(receipt.outcome.error.code, receipt.outcome.error.message, receipt.outcome.error.next);if (['register', 'ensureCoordinator'].includes(operation)) await actorTransport(root, file, state, receipt.outcome.result, io);for (const event of receipt.outcome.events ?? []) io.onEvent?.(event);return receipt.outcome.result;@@ -1064,7 +1065,7 @@ export async function relayCommandReceipt(root, command) {if (receipt.outcome.error) {delete state.recovered;saveLink(file, state);- throw new Refused(receipt.outcome.error.code, receipt.outcome.error.message);+ throw new Refused(receipt.outcome.error.code, receipt.outcome.error.message, receipt.outcome.error.next);}return { result: receipt.outcome.result, events: receipt.outcome.events ?? [], move };});diff --git a/test/agent-session.test.js b/test/agent-session.test.jsindex 01343424..71ada77c 100644--- a/test/agent-session.test.js+++ b/test/agent-session.test.js@@ -122,8 +122,8 @@ test('a second session cannot write in the main checkout until takeover [B3,B7]'const error = JSON.parse(refused.stdout).error;assert.equal(error.code, 'NOT_YOUR_CHECKOUT');assert.match(error.message, /coordinator/u);- assert.match(error.next, /pullboard worktree/u);- assert.match(error.message, /pullboard takeover/u);+ assert.match(error.next, /git worktree add --detach/u);+ assert.match(error.next, /pullboard takeover/u);assert.deepEqual(boardSnapshot(box.boardFile), before, 'refusal leaves all board counts unchanged');const worktrees = box.git(box.repo, 'worktree', 'list', '--porcelain');for (const args of [['init'], ['worktree', 'web'], ['hooks'], ['spec', 'apply'], ['hook', 'pre-commit'], ['submit', '1']]) {@@ -163,7 +163,7 @@ test('lane ownership is session-scoped and takeover preserves the joined agent [assert.notEqual(refused.status, 0);assert.equal(JSON.parse(refused.stdout).error.code, 'NOT_YOUR_CHECKOUT');assert.match(JSON.parse(refused.stdout).error.message, /web-1/u);- assert.match(JSON.parse(refused.stdout).error.next, /pullboard worktree/u);+ assert.match(JSON.parse(refused.stdout).error.next, /git worktree add --detach/u);assert.deepEqual(boardSnapshot(box.boardFile), before, 'refused lane write leaves event and item counts unchanged');const takeover = box.run(box.web, ['takeover', '--json'], { session: second, sessionKey: 'CODEX_THREAD_ID' });diff --git a/test/api.test.js b/test/api.test.jsindex 965afe14..e4adc9bc 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -779,7 +779,7 @@ test('[A1,B21,B27] decisions shows an agent its direct and lane asks only', () =status: 1,code: 'NOT_YOUR_DECISION',message: `shout #${app2Ask} is addressed to app-2, not your app lane (agent app-1)`,- next: 'Run pullboard help, correct the reported problem, and retry the command.',+ next: 'answer only decisions addressed to you; see pullboard inbox',});const coordinatorText = box.run(box.repo, 'decisions');assert.equal(coordinatorText.status, 0, coordinatorText.stderr);@@ -801,7 +801,7 @@ test('[A1] refusals are one JSON document with exact public error fields', () =>status: 1,code: 'NO_ROW',message: 'no row G99 in SPEC.md',- next: 'Run pullboard help, correct the reported problem, and retry the command.',+ next: 'list the rows with pullboard spec --json, then name one of them',}, 'show');assert.equal(noRow.error.code, 'NO_ROW');@@ -856,7 +856,7 @@ test('[A1] refusals are one JSON document with exact public error fields', () =>shapeFor('spec', 'check');assert.equal(invalidDocument.error.code, 'COMMAND_FAILED');assert.equal(invalidDocument.error.message, textCheck.stdout.trim());- assert.equal(invalidDocument.error.next, 'Run pullboard help, correct the reported problem, and retry the command.');+ assert.equal(invalidDocument.error.next, 'read the reported output above, fix what it names, and run the command again');rmSync(box.dir, { recursive: true, force: true });});diff --git a/test/refusal-next-steps.test.js b/test/refusal-next-steps.test.jsnew file mode 100644index 00000000..31ec205e--- /dev/null+++ b/test/refusal-next-steps.test.js@@ -0,0 +1,108 @@+/** Refusals give concrete recovery steps that work in real checkouts [P4,I1,I2]. */+import assert from 'node:assert/strict';+import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { after, test } from 'node:test';+import { Refused } from '../src/refused.js';+import { refusalDocument } from '../src/json.js';+import { createE2eHelpers } from './e2e-helpers.js';++const e2e = createE2eHelpers();+after(e2e.cleanup);++/** Keep both command streams in an assertion so a refusal is never hidden by fixture diagnostics. */+function succeeded(result) {+ assert.equal(result.code, 0, `${result.out}\n${result.err}`);+ return result;+}++/** File a real build with a frozen check that fails only when the fixture arms its gate. */+function addBuild(box, repo, title, check) {+ const result = succeeded(box.run(repo, 'add', 'web', title, '--specs', 'G1',+ '--criterion', 'the real fixture gate passes', '--check', check, '--json'));+ return JSON.parse(result.out).item.item_id;+}++test('every refusal names a next step that works [P4,I1,I2]', async () => {+ const sourceRoot = resolve(import.meta.dirname, '../src');+ const codes = new Set(['API_LISTEN', 'CORE_BARE', 'VIEW_SIGN_IN_STOPPED']);+ for (const file of readdirSync(sourceRoot).filter(name => name.endsWith('.js'))) {+ const source = readFileSync(join(sourceRoot, file), 'utf8');+ for (const match of source.matchAll(/new Refused\(\s*['"]([A-Z][A-Z0-9_]*)['"]/gu)) codes.add(match[1]);+ }+ for (const code of codes) {+ const { next } = refusalDocument(new Refused(code, 'This operation was refused.')).error;+ assert.ok(next.trim(), `${code} supplies a recovery action`);+ assert.doesNotMatch(next, /Run pullboard help, correct the reported problem/u, `${code} has its own recovery`);+ }+ const { NEXT_STEPS } = await import('../src/next-steps.js');+ for (const code of codes) assert.ok(Object.hasOwn(NEXT_STEPS, code), `${code} has an explicit recovery entry`);+ assert.equal(refusalDocument({ code: 'FUTURE_REMOTE_RULE', message: 'The service refused.', next: 'ask the service owner to restore this board' }).error.next,+ 'ask the service owner to restore this board', 'remote recovery guidance survives serialization');+ assert.match(refusalDocument(new Refused('FUTURE_REMOTE_RULE', 'The service refused.')).error.next, /service owner.*FUTURE_REMOTE_RULE/u,+ 'an unknown remote rule names its owner and code rather than inventing a command');+ assert.equal(refusalDocument(new Refused('REMOTE_COORDINATOR_MODEL',+ "the coordinator's model is declared on its own checkout; run pullboard join coordinator there")).error.next,+ 'run pullboard join coordinator there', 'a coordinator description does not hide the later recovery action');++ const box = e2e.sandbox();+ box.env.PULLBOARD_MODEL = 'Refusal Fixture Model';+ const gateFile = join(box.dir, 'fixture-gate.cjs');+ writeFileSync(gateFile, "if (require('node:fs').existsSync('web/RED')) { console.log('GATE_FAILURE_MARKER'); process.exit(1); }\n");+ const gate = `'${process.execPath.replaceAll("'", "'\\''")}' '${gateFile.replaceAll("'", "'\\''")}'`;+ const { repo, web } = e2e.project(gate, box);+ const id = addBuild(box, repo, 'Independent review recovery', gate);+ succeeded(box.run(web, 'claim', String(id)));+ mkdirSync(join(web, 'web'), { recursive: true });+ writeFileSync(join(web, 'web', 'receipt.txt'), 'a real build\n');+ box.git(web, 'add', '-A');+ box.git(web, 'commit', '-q', '-m', 'test: build review fixture [G1]');+ succeeded(box.run(web, 'submit', String(id)));++ const mainRefusal = box.run(repo, 'next', '--verify', String(id), '--json');+ assert.equal(mainRefusal.code, 1, `${mainRefusal.out}\n${mainRefusal.err}`);+ const mainError = JSON.parse(mainRefusal.out).error;+ assert.equal(mainError.code, 'MAIN_IS_COORDINATOR');+ assert.match(mainError.next, /git worktree add --detach/u);+ assert.match(mainError.next, /reviewer.*(?:did not|not).*build/iu, 'the step requires an independent reviewer');+ const reviewer = join(repo, '.claude', 'worktrees', 'reviewer');+ box.git(repo, 'worktree', 'add', '-q', '--detach', reviewer, 'HEAD');+ succeeded(box.run(reviewer, 'join', 'web', '--model', 'Independent Reviewer Model'));+ const selected = succeeded(box.run(reviewer, 'next', '--verify', String(id), '--json'));+ assert.equal(JSON.parse(selected.out).item.item_id, id, 'the recovery reaches review without SELF_VERIFY');++ const gateBox = e2e.sandbox();+ gateBox.env.PULLBOARD_MODEL = 'Gate Fixture Model';+ const { repo: gateRepo, web: gateWeb } = e2e.project(gate, gateBox);+ const redId = addBuild(gateBox, gateRepo, 'Gate failure recovery', gate);+ succeeded(gateBox.run(gateWeb, 'claim', String(redId)));+ mkdirSync(join(gateWeb, 'web'), { recursive: true });+ writeFileSync(join(gateWeb, 'web', 'RED'), 'armed\n');+ gateBox.git(gateWeb, 'add', '-A');+ gateBox.git(gateWeb, 'commit', '-q', '-m', 'test: arm gate fixture [G1]');+ const red = gateBox.run(gateWeb, 'submit', String(redId));+ assert.equal(red.code, 1, `${red.out}\n${red.err}`);+ assert.equal((red.err.match(/\[GATE_RED\]/gu) ?? []).length, 1, `${red.out}\n${red.err}`);+ assert.equal((red.err.match(/GATE_FAILURE_MARKER/gu) ?? []).length, 1, `the failure report appears once\n${red.out}\n${red.err}`);+ assert.match(red.err, /next: .*fix.*commit.*submit/iu);+ rmSync(join(gateWeb, 'web', 'RED'));+ gateBox.git(gateWeb, 'add', '-u');+ gateBox.git(gateWeb, 'commit', '-q', '-m', 'test: fix gate fixture [G1]');+ succeeded(gateBox.run(gateWeb, 'submit', String(redId)));++ box.env.CODEX_THREAD_ID = 'main-owner-session';+ succeeded(box.run(repo, 'join', 'coordinator', '--model', 'Coordinator Fixture Model'));+ const bindingPath = join(repo, '.git', 'pullboard-checkout-session.json');+ const binding = readFileSync(bindingPath, 'utf8');+ box.env.CODEX_THREAD_ID = 'new-agent-session';+ const foreign = box.run(repo, 'claim', String(id), '--json');+ assert.equal(foreign.code, 1, `${foreign.out}\n${foreign.err}`);+ const foreignError = JSON.parse(foreign.out).error;+ assert.equal(foreignError.code, 'NOT_YOUR_CHECKOUT');+ assert.match(foreignError.next, /git worktree add --detach/u, 'recovery does not call Pullboard from the blocked checkout');+ const recovery = join(repo, '.claude', 'worktrees', 'new-agent');+ box.git(repo, 'worktree', 'add', '-q', '--detach', recovery, 'HEAD');+ succeeded(box.run(recovery, 'join', 'web', '--model', 'New Agent Fixture Model'));+ succeeded(box.run(recovery, 'whoami', '--json'));+ assert.equal(readFileSync(bindingPath, 'utf8'), binding, 'recovery leaves the main owner binding unchanged');+});