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.

perf(cli): a command loads only its own modules [C7]

Corey Olsonf1dd42e3f9b1
diff --git a/bin/pullboard.js b/bin/pullboard.js
index 431435d1..9d9d9f7f 100755
--- a/bin/pullboard.js
+++ b/bin/pullboard.js
@@ -34,7 +34,8 @@ process.stdout.on('error', (error) => {
process.exit(process.exitCode ?? 0);
});
-const { main } = await import('../src/cli.js');
+// The entry loads only the dispatcher; each command's modules load through its own import() [C7].
+const { main } = await import('../src/cli-main.js');
process.exitCode = await main(process.argv.slice(2), {
cwd: process.cwd(),
stdout: process.stdout,
diff --git a/src/board.js b/src/board.js
index 0b6717bc..abd1c011 100644
--- a/src/board.js
+++ b/src/board.js
@@ -276,11 +276,11 @@ export function openBoardReadOnly(file) {
*
* @param {string} file
* @param {{ now: () => Date }} [clock]
- * @param {{ isMain?: boolean }} [options] Only the main checkout may upgrade a shared board.
+ * @param {{ isMain?: boolean | (() => boolean) }} [options] Only the main checkout may upgrade a shared board; a function is asked only of a board behind this code.
* @returns {{ db: DatabaseSync, clock: { now: () => Date } }}
*/
export function openBoard(file, clock = systemClock, { isMain } = {}) {
- if (file !== ':memory:' && isMain === false) {
+ if (file !== ':memory:' && (isMain === false || typeof isMain === 'function')) {
let boardVersion = 0;
let logVersion = 0;
if (existsSync(file)) {
@@ -295,13 +295,13 @@ export function openBoard(file, clock = systemClock, { isMain } = {}) {
} finally {
current?.close();
}
- if (SCHEMA_VERSION > boardVersion) {
+ if (SCHEMA_VERSION > boardVersion && (isMain === false || isMain() === false)) {
throw new Refused(
'UNMERGED_SCHEMA',
`this worktree expects board schema ${SCHEMA_VERSION}, newer than the shared board's version ${boardVersion}; merge this code into the main checkout first, or test it against a throwaway board`,
);
}
- if (EVENT_LOG_VERSION > logVersion) {
+ if (EVENT_LOG_VERSION > logVersion && (isMain === false || isMain() === false)) {
throw new Refused('UNMERGED_SCHEMA', `this worktree expects event log ${EVENT_LOG_VERSION}, newer than the shared board's version ${logVersion}; merge this code into the main checkout first, or test it against a throwaway board`);
}
}
diff --git a/src/check-baseline-worker.js b/src/check-baseline-worker.js
index 72b7f3f3..9c7fe1e5 100644
--- a/src/check-baseline-worker.js
+++ b/src/check-baseline-worker.js
@@ -24,6 +24,10 @@ import {
relayLinked,
relayOperation,
} from './relay.js';
+import {
+ BASELINE_RECEIPT,
+ baselineReceiptDirectory,
+} from './local-state.js';
import { Refused } from './refused.js';
const WORKER = resolve(import.meta.dirname, '../bin/check-baseline.js');
@@ -31,7 +35,7 @@ const WORKER = resolve(import.meta.dirname, '../bin/check-baseline.js');
/** Resolve private completion storage beside this repository's shared board. */
function locations(root) {
const info = repoInfo(root);
- return { board: join(info.commonDir, 'pullboard', 'board.sqlite'), receipts: join(info.commonDir, 'pullboard', 'baseline-results') };
+ return { board: join(info.commonDir, 'pullboard', 'board.sqlite'), receipts: baselineReceiptDirectory(info.commonDir) };
}
/** Close a real board around one short operation; measurements never hold a database connection. */
@@ -62,7 +66,7 @@ function saveReceipt(root, receipt) {
export async function retryCheckBaselines(root, io) {
const directory = locations(root).receipts;
if (!existsSync(directory)) return;
- for (const name of readdirSync(directory).filter((name) => /^[a-f0-9-]{36}\.json$/.test(name))) {
+ for (const name of readdirSync(directory).filter((name) => BASELINE_RECEIPT.test(name))) {
const file = join(directory, name);
try {
const receipt = JSON.parse(readFileSync(file, 'utf8'));
diff --git a/src/check-baseline.js b/src/check-baseline.js
index 6436afd4..ee0b12a1 100644
--- a/src/check-baseline.js
+++ b/src/check-baseline.js
@@ -12,7 +12,7 @@ import {
mainCheckout,
tryGit,
} from './git.js';
-import { runShell } from './gate.js';
+import { runShell } from './shell-run.js';
import { Refused } from './refused.js';
/**
diff --git a/src/cli-context.js b/src/cli-context.js
new file mode 100644
index 00000000..9c3a0e63
--- /dev/null
+++ b/src/cli-context.js
@@ -0,0 +1,277 @@
+/**
+ * What every command shares and a read needs: the checkout's context, the board opened around one piece of work,
+ * argument parsing and the one-line item format. It loads no gate, relay or landing module, so a read command that
+ * imports only this pays for nothing it does not run [C7].
+ */
+import { existsSync } from 'node:fs';
+import {
+ isAbsolute,
+ join,
+ relative,
+ resolve,
+} from 'node:path';
+import { displayAgentName } from './agent-names.js';
+import * as store from './board.js';
+import {
+ CONFIG_FILE,
+ loadConfig,
+} from './config.js';
+import { loadDoctrine } from './doctrine.js';
+import {
+ codeIsFromMain,
+ differFromHead,
+ headCommit,
+ repoInfo,
+ tryGit,
+} from './git.js';
+import { Refused } from './refused.js';
+import { mainPolicy } from './trusted-policy.js';
+import { MAIN_MERGE_LABEL } from './trunk-conflict.js';
+
+/**
+ * A positive whole number from an argument, or a refusal naming what was expected.
+ *
+ * @param {string | undefined} text
+ * @param {string} what
+ * @returns {number}
+ */
+export function idArg(text, what = 'an item id') {
+ const id = Number(String(text ?? '').replace(/^#/, ''));
+ if (!Number.isInteger(id) || id < 1) throw new Refused('USAGE', `expected ${what}, got "${text ?? ''}"`);
+ return id;
+}
+
+/**
+ * A comma list of spec ids from a flag.
+ *
+ * @param {string | undefined} text
+ * @returns {string[]}
+ */
+export const idList = (text) => (text ?? '').split(',').map((id) => id.trim()).filter(Boolean);
+
+/**
+ * The start of a command an agent can paste anywhere: agent shells often start each command in the
+ * main checkout, so every command pullboard suggests names its folder (I5).
+ *
+ * @param {string} root
+ * @returns {string}
+ */
+export const shellWord = (text) => (/^[\w@%+=:,./-]+$/.test(text) ? text : `'${text.replaceAll("'", "'\\''")}'`);
+
+/**
+ * `cd <folder> &&`, the folder quoted for any POSIX shell: single quotes, so a space, a quote or a
+ * dollar sign in the path reaches cd as written (I7).
+ *
+ * @param {string} root
+ * @returns {string}
+ */
+export const cdTo = (root) => `cd ${shellWord(root)} &&`;
+
+/**
+ * Print an item's brief, indented under a heading, when it has one.
+ *
+ * @param {any} io
+ * @param {string} brief
+ */
+export function sayBrief(io, brief) {
+ if (!brief) return;
+ io.say('brief:');
+ brief.split('\n').forEach((line) => io.say(` ${line}`.trimEnd()));
+}
+
+/**
+ * Everything a command needs: the repo, its config, the board's file, and where output goes.
+ *
+ * @param {any} io
+ * @returns {any}
+ */
+export function context(io) {
+ const info = repoInfo(io.cwd);
+ if (info.isMain) io.caller?.('coordinator', info.root);
+ const config = configHere(info);
+ const file = join(info.commonDir, 'pullboard', 'board.sqlite');
+ // Where the running code came from costs Git processes, and only a board behind this code's schema needs it.
+ let allowSchemaUpgrade;
+ return { info, config, file, get allowSchemaUpgrade() { return allowSchemaUpgrade ??= codeIsFromMain(); },
+ doctrine: loadDoctrine(info.root, config), io, clock: io.clock ?? store.systemClock };
+}
+
+/**
+ * This checkout's config. Init is the fix only where pullboard never was (C4): a config deleted
+ * from a checkout whose last commit has it is restored, and a linked worktree made from a commit
+ * that lacks it, beside a main checkout that has one, is made again from there.
+ *
+ * @param {{ root: string, commonDir: string, isMain: boolean }} info
+ * @returns {any}
+ */
+function configHere(info) {
+ try {
+ return loadConfig(info.root);
+ } catch (error) {
+ if (!(error instanceof Refused) || error.code !== 'NO_CONFIG') throw error;
+ if (tryGit(info.root, ['cat-file', '-e', `HEAD:${CONFIG_FILE}`]).status === 0) {
+ throw new Refused('NO_CONFIG', `${CONFIG_FILE} is deleted here, though this checkout's last commit has it: restore it: ${cdTo(info.root)} git checkout HEAD -- ${CONFIG_FILE}`);
+ }
+ const mainRoot = resolve(info.commonDir, '..');
+ if (info.isMain || !existsSync(join(mainRoot, CONFIG_FILE))) throw error;
+ let setup;
+ try {
+ setup = uncommittedSetup(mainRoot, loadConfig(mainRoot));
+ } catch {
+ // Keep the existing recovery for invalid or incomplete main-checkout configuration.
+ }
+ if (setup) {
+ throw new Refused(
+ 'NO_CONFIG',
+ `this worktree has no ${CONFIG_FILE}, and the main checkout has uncommitted Pullboard setup files: ${setup.files.join(', ')}. Commit them in the main checkout first: ${setup.stage}`,
+ );
+ }
+ throw new Refused(
+ 'NO_CONFIG',
+ `this worktree's commit has no ${CONFIG_FILE}, though the main checkout has one: make a new worktree from the main checkout, which says what to commit first: ${cdTo(mainRoot)} pullboard worktree <lane> --model "<model name>"`,
+ );
+ }
+}
+
+/**
+ * Open the board, run `work`, and always close it.
+ *
+ * @template T
+ * @param {any} ctx
+ * @param {(board: any) => T} work
+ * @returns {T}
+ */
+export function withBoard(ctx, work) {
+ const board = store.openBoard(ctx.file, ctx.clock, { isMain: () => ctx.allowSchemaUpgrade });
+ // Whether a proven flake stops blocking a landing is the coordinator's setting, read from accepted main on first use.
+ let quarantine;
+ board.quarantineEnabled = () => quarantine ??= mainPolicy(ctx.info.root).config.flakes?.quarantine === true;
+ const firstEvent = board.emittedEvents?.length ?? 0;
+ /** Forward committed events before releasing either synchronous or asynchronous work. */
+ const finish = () => {
+ for (const event of board.emittedEvents?.slice(firstEvent) ?? []) ctx.io.onEvent?.(event);
+ store.closeBoard(board);
+ };
+ let result;
+ 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();
+ return result;
+}
+
+/** How many characters of an earlier verdict's note show prints (N30). */
+const NOTE_LINE = 120;
+
+/**
+ * A note's first line, cut to NOTE_LINE characters with … marking the cut. A line ends at any break
+ * Unicode makes mandatory (UAX #14): LF, VT, FF, CR, CRLF, NEL, LS and PS. Characters are counted
+ * as a reader sees them, so a cut never splits an emoji or an accented letter.
+ *
+ * @param {string} note
+ * @returns {string}
+ */
+export function firstLineOf(note) {
+ const line = note.split(/[\n\v\f\r\x85\u2028\u2029]/)[0];
+ const characters = [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(line)];
+ return characters.length > NOTE_LINE ? `${characters.slice(0, NOTE_LINE).map((part) => part.segment).join('')}…` : line;
+}
+
+/**
+ * One item on one line: id, status and holder, lane, title, spec ids.
+ *
+ * @param {any} item
+ * @returns {string}
+ */
+export function itemLine(item, name = (id) => id, mainMerge = false) {
+ const holder = item.item_status === 'claimed' ? ` ${name(item.item_owner)}` : '';
+ const verifier = item.item_status === 'verified' ? ` by ${name(item.item_verified_by)}` : '';
+ const specs = item.item_spec_ids ? ` [${item.item_spec_ids}]` : '';
+ const parent = item.item_parent_id ? ` under #${item.item_parent_id}` : '';
+ const after = item.item_after ? ` after ${item.item_after.split(',').map((id) => `#${id}`).join(',')}` : '';
+ const rejected = item.item_status === 'open' && item.item_verdict === 'REJECT' ? ' (rejected)' : mainMerge ? ` (${MAIN_MERGE_LABEL})` : '';
+ const light = item.item_route === 'strong' ? '' : ` ${item.item_route}`;
+ const staleVerdict = item.item_verdict_state ? ` ${item.item_verdict_state.code}` : '';
+ const hold = item.item_hold_reason ? ` held by ${name(item.item_hold_by)}: ${item.item_hold_reason}` : '';
+ return `#${item.item_id} ${item.item_status}${holder}${verifier}${rejected} ${item.item_lane} ${item.item_title}${specs}${parent}${after}${light}${hold}${staleVerdict}`;
+}
+
+/** Format a stable agent id for human-facing CLI output. */
+export function agentDisplayName(agents, config, id) {
+ if (!id) return '';
+ const agent = agents.find((entry) => entry.agent_id === id);
+ if (agent) return displayAgentName(agent, config.agents.names);
+ if (id === 'person' || id === 'all' || Object.hasOwn(config.lanes, id)) return id;
+ return displayAgentName({ agent_id: id }, config.agents.names);
+}
+
+/** Render only declared actor positions in a refusal, preserving user text and stable JSON ids. */
+function agentRefusalText(message, code, name) {
+ const patterns = {
+ ALREADY_JOINED: /^(\[ALREADY_JOINED\] this worktree is )(\S+)( in )/,
+ HELD: /^(\[HELD\] item #\d+ is held by )(\S+)( until )/,
+ ITEM_HELD: /^(\[ITEM_HELD\] item #\d+ is held by )(\S+)(: )/,
+ LANE_HELD: /^(\[LANE_HELD\] )(\S+)( holds the )/,
+ REVIEW_HELD: /^(\[REVIEW_HELD\] )(\S+)( holds the )/,
+ NOT_YOURS: /^(\[NOT_YOURS\] only the coordinator or )(\S+)(, who )/,
+ NO_AGENT: /^(\[NO_AGENT\] no (?:registered )?agent )(\S+)(;|$)/,
+ NOT_YOUR_CHECKOUT: /^(\[NOT_YOUR_CHECKOUT\] this checkout belongs to )(\S+)( in )/,
+ FACT_JUDGEMENT: /^(\[FACT_JUDGEMENT\] only the item's live holder \()(\S+)(\))/,
+ RELAY_PERSON_ONLY: /^(\[RELAY_PERSON_ONLY\] agent )(\S+)( cannot )/,
+ SELF_SHOUT: /^(\[SELF_SHOUT\] a shout cannot be addressed to its sender )(\S+)(;)/,
+ NO_READER: /^(\[NO_READER\] nobody reads ")(.*?)(":)/,
+ };
+ if (code === 'RELAY_SENDER_MISMATCH') {
+ return message.replace(/^(\[RELAY_SENDER_MISMATCH\] agent )(\S+)( cannot act as )(.*?)(; send this operation)/,
+ (_, before, sender, middle, actor, after) => `${before}${name(sender)}${middle}${actor === '(no declared agent)' ? actor : name(actor)}${after}`);
+ }
+ if (code === 'NOT_YOUR_DECISION') {
+ return message.replace(/^(\[NOT_YOUR_DECISION\] shout #\d+ is addressed to )(\S+)(, not your \S+ lane \(agent )(\S+)(\))$/,
+ (_, before, to, middle, caller, after) => `${before}${name(to)}${middle}${name(caller)}${after}`);
+ }
+ return patterns[code] ? message.replace(patterns[code], (_, before, id, after) => `${before}${name(id)}${after}`) : message;
+}
+
+/** Render the refusal body without its existing final footer; structured errors retain the message. */
+export function displayedRefusal(io, error) {
+ 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 {
+ const ctx = context(io);
+ const agents = withBoard(ctx, (board) => store.listAgents(board));
+ return agentRefusalText(message, error.code, (id) => agentDisplayName(agents, ctx.config, id));
+ } catch { return message; }
+}
+
+/**
+ * The files a new worktree takes from the main checkout's last commit and works by: the config, the
+ * spec, the practice file, the rules its opening lines name, and the hooks, when git looks for them
+ * inside each worktree.
+ *
+ * @param {string} mainRoot
+ * @param {any} config
+ * @returns {string[]}
+ */
+export function setupFiles(mainRoot, config) {
+ const hooks = tryGit(mainRoot, ['config', '--get', 'core.hooksPath']).stdout;
+ const inEach = hooks && !isAbsolute(hooks) && !relative(mainRoot, resolve(mainRoot, hooks)).startsWith('..');
+ return [CONFIG_FILE, config.spec, config.practice, 'AGENTS.md', ...(inEach ? [hooks] : [])].filter(Boolean);
+}
+
+/** Find setup files in the main checkout that a new worktree would not receive from HEAD. */
+export function uncommittedSetup(mainRoot, config) {
+ if (headCommit(mainRoot) === null) return null;
+ const differ = differFromHead(mainRoot, setupFiles(mainRoot, config));
+ if (!differ.length) return null;
+ const words = differ.map(({ path }) => shellWord(path)).join(' ');
+ const force = differ.some(({ ignored }) => ignored) ? ' -f' : '';
+ return {
+ files: differ.map(({ path }) => path), differ,
+ stage: `${cdTo(mainRoot)} git add${force} -- ${words}`,
+ };
+}
diff --git a/src/cli-help.js b/src/cli-help.js
new file mode 100644
index 00000000..bb7abb69
--- /dev/null
+++ b/src/cli-help.js
@@ -0,0 +1,96 @@
+/**
+ * The command line's help: the overview, each command's usage and the nearest command to a typo, all built from
+ * the command declarations. A command that is not asking for help never loads it [C7].
+ */
+import {
+ COMMANDS,
+ UNLISTED_COMMANDS,
+} from './commands/index.js';
+import { buildHelp } from './help.js';
+
+/** Find the nearest declared command for a useful typo hint. */
+function closestHelpCommand(input) {
+ const needle = input.toLowerCase();
+ /** Measure edit distance between two command names for a useful typo hint. */
+ const distance = (left, right) => {
+ let row = Array.from({ length: right.length + 1 }, (_, index) => index);
+ for (let i = 1; i <= left.length; i += 1) {
+ const next = [i];
+ for (let j = 1; j <= right.length; j += 1) {
+ next[j] = Math.min(next[j - 1] + 1, row[j] + 1, row[j - 1] + (left[i - 1] === right[j - 1] ? 0 : 1));
+ }
+ row = next;
+ }
+ return row.at(-1);
+ };
+ return Object.keys(HELP.commands).sort((a, b) => distance(needle, a) - distance(needle, b) || a.localeCompare(b))[0];
+}
+
+/** Render one command's usage, one-line flags and a pasteable example from the help declaration. */
+function commandHelp(name) {
+ const entry = HELP.commands[name];
+ if (!entry) return null;
+ return [
+ `Usage: ${entry.usages[0]}`,
+ ...entry.usages.slice(1).map((usage) => ` ${usage}`),
+ 'Flags:',
+ ...(entry.flags.length ? entry.flags.map((flag) => ` ${flag}`) : [' none']),
+ ...(name === 'spec' ? [
+ 'Subcommands:',
+ ' pullboard spec --json — agent or person: print the parsed spec and practice rows',
+ ' pullboard spec check — agent or person: lint the spec and practice files',
+ ' pullboard spec view — agent or person: write the offline spec page',
+ ' pullboard spec show <id> — agent or person: inspect one row and its sign-offs',
+ ' pullboard spec unmet — agent or person: list approved rows without current sign-off',
+ ' pullboard spec draft <text> [--section <letter>] [--aim] [--gate "<gate>"] — any agent: append a draft row; never approve it',
+ ' pullboard spec signoff <ids> — person: sign rows with evidence',
+ ' pullboard spec signers add — person: register an SSH signing key',
+ ' pullboard spec approve <ids> — person: decide from their own terminal or Pullboard View',
+ ' pullboard spec decline <ids> — person: decide from their own terminal or Pullboard View',
+ ' pullboard spec answer <id> "<choice or text>" — person: answer a pending question from their own terminal or Pullboard View',
+ ' pullboard spec apply — coordinator: apply recorded row decisions to the files',
+ ] : []),
+ 'Example:',
+ ...entry.example.split('\n').map((line) => ` ${line}`), ...entry.notes,
+ ].join('\n');
+}
+
+/** Write a selected help view in text and the stable help:string JSON field. */
+export function printHelp(io, text) {
+ io.result?.({ help: text });
+ io.say(text);
+ return 0;
+}
+
+/** Refuse an unknown command with its nearest declared spelling and a route to the full list. */
+export function unknownCommand(io, input) {
+ const closest = closestHelpCommand(input);
+ io.err(`pullboard: no command "${input}"; closest match is "${closest}". Run pullboard help --all for the full list.`);
+ return 2;
+}
+
+/** Resolve overview, command detail or the preserved full list from one invocation. */
+export function selectedHelp(command, first, second, rest, values) {
+ if (command === 'help') {
+ if (values.all) return { text: HELP.all };
+ const requested = [first, second, ...rest].filter(Boolean).join(' ');
+ if (!requested || values.help && !first) return { text: HELP.overview };
+ return { name: requested, text: commandHelp(requested) };
+ }
+ if (values.all && (!command || command === 'help')) return { text: HELP.all };
+ if (!command) return { text: HELP.firstRun };
+ if (values.help) {
+ const words = [command, first, second, ...rest].filter(Boolean);
+ const candidates = words.map((_, index) => words.slice(0, index + 1).join(' ')).filter((name) => HELP.commands[name]);
+ const nested = candidates.at(-1) ?? command;
+ return { name: nested, text: commandHelp(nested) };
+ }
+ return null;
+}
+/** Result-producing command names, including aliases, for API contract coverage (A1). */
+export function resultCommands() {
+ return Object.keys(COMMANDS).filter((name) => !UNLISTED_COMMANDS.includes(name)).sort();
+}
+
+/** Command help follows the same dispatch declarations as execution. */
+export const HELP = buildHelp(resultCommands());
diff --git a/src/cli-main.js b/src/cli-main.js
new file mode 100644
index 00000000..27ef2898
--- /dev/null
+++ b/src/cli-main.js
@@ -0,0 +1,315 @@
+/**
+ * The command line's entry: parse the arguments, bind the checkout, run the relay and baseline work around the
+ * command when there is any, and dispatch through the lazy command table. It loads a module only when the command
+ * in hand needs it, so --version and a read pay for nothing they do not run [C7].
+ */
+import { appendFileSync } from 'node:fs';
+import { loadavg } from 'node:os';
+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 { Refused } from './refused.js';
+
+export const CHECKOUT_LEASES = new WeakMap();
+export const CHECKOUT_BOARD_ONLY = new WeakMap();
+let startupMainTraced = false;
+
+/** Append an opt-in startup phase marker for the real CLI fixture measurement [A2,C7]. */
+export function traceServeStartup(phase) {
+ const path = process.env.PULLBOARD_STARTUP_TRACE_FILE;
+ const entry = process.env.PULLBOARD_STARTUP_TRACE_ENTRY;
+ if (!path || !entry || resolve(process.argv[1] ?? '') !== resolve(entry)) return;
+ try {
+ appendFileSync(path, `${JSON.stringify({ phase, at: Date.now(), elapsedMs: performance.now(),
+ processId: process.pid, cpuUsage: process.cpuUsage(), loadAverage: loadavg(),
+ eventLoopUtilization: performance.eventLoopUtilization() })}\n`);
+ } catch {
+ // Diagnostic tracing must not change normal CLI behavior.
+ }
+}
+
+const OPTIONS = {
+ criterion: { type: 'string' },
+ specs: { type: 'string' },
+ parent: { type: 'string' },
+ reason: { type: 'string' },
+ off: { type: 'boolean' },
+ port: { type: 'string' },
+ slots: { type: 'string' },
+ browser: { type: 'string' },
+ 'new-browser': { type: 'boolean' },
+ node: { type: 'string' },
+ root: { type: 'string' },
+ project: { type: 'boolean' },
+ export: { type: 'string' },
+ 'no-open': { type: 'boolean' },
+ 'no-permissions': { type: 'boolean' },
+ note: { type: 'string' },
+ infra: { type: 'string' },
+ 'note-file': { type: 'string' },
+ by: { type: 'string' },
+ key: { type: 'string' },
+ out: { type: 'string' },
+ watch: { type: 'boolean' },
+ after: { type: 'string' },
+ brief: { type: 'string' },
+ 'brief-file': { type: 'string' },
+ text: { type: 'string' },
+ gate: { type: 'string' },
+ aim: { type: 'boolean' },
+ doctrine: { type: 'boolean' },
+ source: { type: 'string' },
+ section: { type: 'string' },
+ blueprint: { type: 'string', multiple: true },
+ route: { type: 'string' },
+ family: { type: 'string' },
+ model: { type: 'string' },
+ as: { type: 'string' },
+ check: { type: 'string' },
+ // The watch command's options.
+ every: { type: 'string' },
+ owner: { type: 'string' },
+ directory: { type: 'string' },
+ timeout: { type: 'string' },
+ sentinel: { type: 'boolean' },
+ // The rigor quality draft's options.
+ base: { type: 'string' },
+ head: { type: 'string' },
+ rule: { type: 'string' },
+ budget: { type: 'string' },
+ 'draft-quality': { type: 'boolean' },
+ yes: { type: 'boolean' },
+ landing: { type: 'boolean' },
+ adopt: { type: 'boolean' },
+ waive: { type: 'string' },
+ until: { type: 'string' },
+ agent: { type: 'string' },
+ 'agent-light': { type: 'string' },
+ 'agent-mid': { type: 'string' },
+ 'agent-strong': { type: 'string' },
+ attempts: { type: 'string' },
+ minutes: { type: 'string' },
+ items: { type: 'string' },
+ run: { type: 'string' },
+ max: { type: 'string' },
+ 'dry-run': { type: 'boolean' },
+ update: { type: 'boolean' },
+ before: { type: 'string' },
+ target: { type: 'string' },
+ next: { type: 'string' },
+ add: { type: 'string' },
+ remove: { type: 'string' },
+ name: { type: 'string' },
+ title: { type: 'string' },
+ url: { type: 'string' },
+ skip: { type: 'string' },
+ wait: { type: 'string' },
+ verify: { type: 'boolean' },
+ build: { type: 'boolean' },
+ all: { type: 'boolean' },
+ must: { type: 'boolean' },
+ json: { type: 'boolean' },
+ history: { type: 'boolean' },
+ verbose: { type: 'boolean' },
+ since: { type: 'string' },
+ decision: { type: 'boolean' },
+ evidence: { type: 'string' },
+ outcome: { type: 'string' },
+ item: { type: 'string' },
+ kinds: { type: 'string' }, to: { type: 'string' }, work: { type: 'string' }, 'review-wait': { type: 'string' },
+ commit: { type: 'string' },
+ ref: { type: 'string' },
+ supersedes: { type: 'string' },
+ conflict: { type: 'string', multiple: true },
+ cause: { type: 'string' },
+ 'never-again': { type: 'boolean' },
+ 'draft-splits': { type: 'boolean' },
+ implies: { type: 'string' },
+ owns: { type: 'string' },
+ red: { type: 'string' },
+ green: { type: 'string' },
+ help: { type: 'boolean', short: 'h' },
+ version: { type: 'boolean', short: 'v' },
+};
+
+/** Parse --wait as a switch for add/edit and as minutes for next/run, preserving all other options. */
+function parseCommandArgs(argv) {
+ let command;
+ for (const wait of [{ type: 'boolean' }, OPTIONS.wait]) {
+ try {
+ command = parseArgs({ args: argv, options: { ...OPTIONS, wait }, allowPositionals: true }).positionals[0];
+ if (['add', 'edit'].includes(command)) break;
+ } catch { /* The final parser supplies the existing actionable usage error. */ }
+ }
+ const options = ['add', 'edit'].includes(command) ? { ...OPTIONS, wait: { type: 'boolean' } } : OPTIONS;
+ return parseArgs({ args: argv, options, allowPositionals: true });
+}
+
+/**
+ * Run one command. Returns the exit code: 0 done, 1 refused, 2 usage.
+ *
+ * @param {string[]} argv
+ * @param {any} io
+ * @returns {Promise<number>}
+ */
+async function runCommand(argv, io) {
+ let parsed;
+ try {
+ parsed = parseCommandArgs(argv);
+ } 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: ${io.refusalDocument(refusal).error.next}`);
+ return 2;
+ }
+ const { values, positionals } = parsed;
+ io.jsonMode?.(values.json);
+ const [command = '', first, second, ...rest] = positionals;
+ const args = { first, second, rest, values };
+ if ((values.version || command === 'version') && !values.help) return await (await COMMANDS.version()).run(io, args);
+ // Help loads only when asked for: a command name other than help, without --help, never needs it.
+ const help = !command || command === 'help' || values.help
+ ? (await import('./cli-help.js')).selectedHelp(command, first, second, rest, values) : null;
+ if (help) return await (await COMMANDS.help()).run(io, args, help);
+ try {
+ if (values.as === 'person' && !['answer', 'decisions', 'fact'].includes(command)) {
+ throw new Refused('USAGE', '--as person works only with pullboard answer, decisions, or fact --never-again');
+ }
+ const load = COMMANDS[command];
+ if (!load) return (await import('./cli-help.js')).unknownCommand(io, command);
+ return await (await load()).run(io, args);
+ } catch (error) {
+ if (error instanceof Refused) {
+ io.refusal?.(error);
+ io.err(`pullboard: ${await displayedRefusal(io, error)}\nnext: ${io.refusalDocument(error).error.next}`);
+ return 1;
+ }
+ throw error;
+ }
+}
+
+/** Retain the primary branch on every command without creating a board for global help. */
+async function rememberTrunk(io, { repoInfo, mainCheckout }) {
+ let info;
+ try { info = repoInfo(io.cwd); }
+ catch (error) {
+ if (error instanceof Refused && ['NOT_A_REPO', 'NO_REPO', 'CORE_BARE'].includes(error.code)) return;
+ throw error;
+ }
+ if (!info.isMain) return;
+ const primary = mainCheckout(info.root);
+ if (primary?.branch) (await import('./trusted-policy.js')).trunkRef(info.root, primary.branch);
+}
+
+/** Whether a parsed command line only prints version or help, which asks Git nothing. */
+function asksGitNothing(argv) {
+ try {
+ const { values, positionals: [command] } = parseCommandArgs(argv);
+ return Boolean(values.help || values.version || command === 'help' || command === 'version');
+ } catch { return true; }
+}
+
+/**
+ * Bind this checkout to the session behind a write before any sync or side effect. Reads, help and authenticated
+ * person channels keep their identity and load nothing for it.
+ */
+async function bindCheckoutSession(io, positionals, values) {
+ if (values.help || values.version || io.personChannel === 'view' || io.personRequest) return;
+ const [command, first] = positionals;
+ if (command === 'takeover' && (positionals.length !== 1 || Object.keys(values).some((key) => key !== 'json'))) {
+ throw new Refused('USAGE', 'pullboard takeover takes no arguments; run pullboard takeover [--json]');
+ }
+ const writes = ['init', 'join', 'worktree', 'hooks', 'hook', 'skills', 'add', 'edit', 'fact', 'escalate', 'run', 'sweep',
+ 'next', 'claim', 'hold', 'release', 'submit', 'done', 'verify', 'check', 'merged', 'land', 'withdraw', 'refreeze', 'reopen', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget'];
+ if (!writes.includes(command) && !(command === 'lane' && first === 'add') && !(command === 'settings' && first) && !(command === 'spec' && first === 'apply') && !(command === 'relay' && ['on', 'off'].includes(first))) return;
+ if (command === 'answer' && values.as === 'person') return;
+ return (await import('./cli.js')).bindWriteSession(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) {
+ return (await import('./cli-context.js')).displayedRefusal(io, error);
+}
+
+/** Run one command and emit its single versioned JSON result when requested (A1). */
+export async function main(argv, streams) {
+ if (argv[0] === 'serve' && !startupMainTraced) {
+ startupMainTraced = true;
+ traceServeStartup('cli-main-enter');
+ }
+ // Version and help ask Git nothing, so they never load it.
+ if (asksGitNothing(argv)) return runMain(argv, streams);
+ const { withGitFacts } = await import('./git.js');
+ return withGitFacts(() => runMain(argv, streams));
+}
+
+/** Parse and execute one CLI command, binding its checkout session and Git-fact scope. */
+async function runMain(argv, streams) {
+ const io = commandOutput(argv, streams);
+ let sync = true;
+ let needsRepo = true;
+ let parsed;
+ let checkoutSession;
+ try {
+ parsed = parseCommandArgs(argv);
+ const command = parsed.positionals[0];
+ io.relayJson = Boolean(parsed.values.json);
+ io.relayCommand = { cliOperation: command === 'done' ? 'submit' : command, cwd: resolve(io.cwd),
+ positionals: parsed.positionals.slice(1),
+ values: Object.fromEntries(Object.keys(parsed.values).filter(key => key !== 'json').sort().map(key => [key, parsed.values[key]])) };
+ sync = Boolean(command) && !parsed.values.help && !parsed.values.version
+ && !['help', 'version', 'hook', 'init', 'relay', 'tour', 'mcp', 'health', 'watch', 'digest'].includes(command)
+ // A coordinator declaration on a linked clone must refuse before auto-link or relay sync.
+ && !(command === 'join' && parsed.positionals[1] === (await import('./config.js')).COORDINATOR);
+ needsRepo = !(parsed.values.help || parsed.values.version || command === 'help' || command === 'version');
+ } catch { sync = false; needsRepo = false; }
+ const git = needsRepo ? await import('./git.js') : null;
+ if (parsed) {
+ try {
+ // Checkout identity supplies the display role even if a person-channel check refuses first.
+ try { const info = needsRepo ? git.repoInfo(io.cwd) : null; 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)) {
+ (await import('./person.js')).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: ${await displayedRefusal(io, error)}\nnext: ${io.refusalDocument(error).error.next}`);
+ io.flush(1);
+ return 1;
+ }
+ }
+ try {
+ if (needsRepo) await rememberTrunk(io, git);
+ traceServeStartup('cli-command-preamble-start');
+ // The relay and baseline work loads only where a relay token, relay state, a link or a pending result exists.
+ /** Load the work around the command when any of it could act here, or null. */
+ const syncWork = async () => (sync && (await import('./local-state.js')).syncMayAct(io.cwd) ? import('./cli-sync.js') : null);
+ await (await syncWork())?.syncBefore(io, main);
+ traceServeStartup('cli-command-preamble-ready');
+ const code = await runCommand(argv, io);
+ if (code === 0) await checkoutSession?.finish?.();
+ if (code === 0) await (await syncWork())?.retrySync(io);
+ const status = io.exitCode(code);
+ io.flush(status);
+ return status;
+ } finally {
+ CHECKOUT_LEASES.delete(io);
+ CHECKOUT_BOARD_ONLY.delete(io);
+ checkoutSession?.lease?.release();
+ }
+}
+
+// This marker is emitted once when the actual CLI entrypoint finishes evaluating.
+if (process.env.PULLBOARD_STARTUP_TRACE_ENTRY
+ && resolve(process.argv[1] ?? '') === resolve(process.env.PULLBOARD_STARTUP_TRACE_ENTRY)) {
+ traceServeStartup('cli-module-load-complete');
+}
diff --git a/src/cli-support.js b/src/cli-support.js
index 12abac9d..6fb8c37b 100644
--- a/src/cli-support.js
+++ b/src/cli-support.js
@@ -1,30 +1,10 @@
/**
- * Helpers the command line uses to read its caller's input, trace its startup and read the board for a hook. None
+ * Helpers the command line uses to read its caller's input and read the board for a hook. None
* keeps command state, so each is a plain function of its arguments [C9].
*/
-import {
- appendFileSync,
- existsSync,
-} from 'node:fs';
-import { loadavg } from 'node:os';
-import { resolve } from 'node:path';
-import { performance } from 'node:perf_hooks';
+import { existsSync } from 'node:fs';
import * as store from './board.js';
-/** Append an opt-in startup phase marker for the real CLI fixture measurement [A2,C7]. */
-export function traceServeStartup(phase) {
- const path = process.env.PULLBOARD_STARTUP_TRACE_FILE;
- const entry = process.env.PULLBOARD_STARTUP_TRACE_ENTRY;
- if (!path || !entry || resolve(process.argv[1] ?? '') !== resolve(entry)) return;
- try {
- appendFileSync(path, `${JSON.stringify({ phase, at: Date.now(), elapsedMs: performance.now(),
- processId: process.pid, cpuUsage: process.cpuUsage(), loadAverage: loadavg(),
- eventLoopUtilization: performance.eventLoopUtilization() })}\n`);
- } catch {
- // Diagnostic tracing must not change normal CLI behavior.
- }
-}
-
/** Read one consent line without waiting for EOF in an interactive terminal [V2]. */
export async function firstInputLine(stdin) {
if (!stdin) return '';
diff --git a/src/cli-sync.js b/src/cli-sync.js
new file mode 100644
index 00000000..d69213ef
--- /dev/null
+++ b/src/cli-sync.js
@@ -0,0 +1,38 @@
+/**
+ * The relay and baseline work around a command: link a new project, sync the relay, deliver finished baselines and
+ * run the person's waiting requests. The command line loads it only when one of them could act [C7].
+ */
+import { retryCheckBaselines } from './check-baseline-worker.js';
+import { relayOutboxSetting } from './cli.js';
+import { displayedRefusal } from './cli-context.js';
+import { Refused } from './refused.js';
+import { syncRelay } from './relay.js';
+import { executePersonRequests } from './relay-request-execution.js';
+import { autoLinkProject } from './relay-setup.js';
+
+/** Codes a checkout with no board refuses with, which the sync around a command keeps quiet. */
+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) {
+ if (!(error instanceof Refused)) throw error;
+ if (!QUIET.includes(error.code)) io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${io.refusalDocument(error).error.next}`);
+}
+
+/** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */
+export async function retrySync(io) {
+ try {
+ io.relayOutbox ??= () => relayOutboxSetting(io.cwd);
+ await syncRelay(io.cwd, io);
+ await retryCheckBaselines(io.cwd, io);
+ }
+ catch (error) { reportQuietly(io, error); }
+}
+
+/** Before a command: link this project when the machine links new ones, sync, then run the person's waiting requests. */
+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); }
+}
diff --git a/src/cli.js b/src/cli.js
index 7a902224..93271d85 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -19,9 +19,7 @@ import {
renameSync,
writeFileSync,
} from 'node:fs';
-import {
- hostname,
-} from 'node:os';
+import { hostname } from 'node:os';
import {
basename,
dirname,
@@ -31,7 +29,6 @@ import {
resolve,
} from 'node:path';
import { pathToFileURL } from 'node:url';
-import { parseArgs } from 'node:util';
import {
mainLaneWork,
reviewQueueLine,
@@ -46,15 +43,40 @@ import * as seatCheckout from './seat-checkout.js';
import { submitPreflight } from './submit-preflight.js';
import * as store from './board.js';
import * as nativeFlakes from './native-flake-cli.js';
-import {
- COMMANDS,
- UNLISTED_COMMANDS,
-} from './commands/index.js';
import {
hookRead,
readStdin,
- traceServeStartup,
} from './cli-support.js';
+import {
+ agentDisplayName,
+ cdTo,
+ context,
+ firstLineOf,
+ idArg,
+ idList,
+ itemLine,
+ sayBrief,
+ setupFiles,
+ shellWord,
+ uncommittedSetup,
+ withBoard,
+} from './cli-context.js';
+import {
+ CHECKOUT_BOARD_ONLY,
+ CHECKOUT_LEASES,
+ main,
+} from './cli-main.js';
+import {
+ HELP,
+ printHelp,
+ resultCommands,
+ unknownCommand,
+} from './cli-help.js';
+// Commands and tests import these from here; each lives in the module a read can load without the rest.
+export {
+ agentDisplayName, cdTo, CHECKOUT_LEASES, context, firstLineOf, HELP, idArg, idList, itemLine, main, printHelp,
+ resultCommands, sayBrief, shellWord, uncommittedSetup, unknownCommand, withBoard,
+};
import {
CONFIG_FILE,
COORDINATOR,
@@ -83,7 +105,6 @@ import {
AGENT_SESSION_IDS,
agentSessionDigest,
personCommand,
- requirePersonChannel,
} from './person.js';
import {
bindLocalSession,
@@ -127,7 +148,6 @@ import {
explicitCheckFiles,
} from './browser-admission.js';
import {
- codeIsFromMain,
contains,
differFromHead,
git,
@@ -141,7 +161,6 @@ import {
resolveCommit,
tryGit,
untracked,
- withGitFacts,
} from './git.js';
import {
FIX_NOTE,
@@ -162,12 +181,10 @@ import {
starterLaneNotes,
} from './init.js';
import {
- buildHelp,
SETTING_FORMS,
VERSION,
} from './help.js';
import {
- MAIN_MERGE_LABEL,
mainMergeLines,
mainMergesFor,
} from './trunk-conflict.js';
@@ -178,9 +195,7 @@ import {
} from './implies.js';
import { defaultViewPort } from './view-port.js';
export { VERSION };
-import {
- productProblems,
-} from './products.js';
+import { productProblems } from './products.js';
import {
isLane,
laneNames,
@@ -245,17 +260,12 @@ import {
coordinatorInboxLines,
inboxFirst,
} from './resume.js';
-import {
- sayCheckBaseline,
-} from './check-baseline.js';
+import { sayCheckBaseline } from './check-baseline.js';
import {
refuseClaimProvesNothing,
refuseProvesNothing,
} from './check-accept.js';
-import {
- retryCheckBaselines,
- startCheckBaseline,
-} from './check-baseline-worker.js';
+import { startCheckBaseline } from './check-baseline-worker.js';
import {
compareMainFailures,
mainRedMessage,
@@ -266,9 +276,6 @@ import {
sweepItems,
} from './sweep.js';
import { renderSpecView } from './view.js';
-import {
- commandOutput,
-} from './json.js';
import {
listApiProjects,
registerProjectAndLink,
@@ -299,8 +306,6 @@ import { firstRefusalArgs } from './claims.js';
import { serveApi } from './api.js';
import { serveMcp } from './mcp.js';
import { scanHealthSentinel } from './health-sentinel.js';
-import { SENTINEL_OPTIONS } from './sentinel-command.js';
-import { QUALITY_OPTIONS } from './rigor-quality-draft.js';
import { resumeSentinels } from './sentinel-command.js';
import {
staleFrozenItems,
@@ -329,9 +334,7 @@ import {
verdictTrunk,
} from './verdict-freshness.js';
import { proofStats } from './stats.js';
-import {
- flowAlertLine,
-} from './stats-flow.js';
+import { flowAlertLine } from './stats-flow.js';
import { releaseHeadlinesBetween } from './changelog.js';
import {
addSigner,
@@ -355,13 +358,8 @@ import {
relayLinked,
relayOperation,
relayRecovered,
- syncRelay,
} from './relay.js';
-import {
- autoLinkProject,
- unlinkedRelayProjects,
-} from './relay-setup.js';
-import { executePersonRequests } from './relay-request-execution.js';
+import { unlinkedRelayProjects } from './relay-setup.js';
import {
accountedFailures,
landingRemote,
@@ -372,9 +370,6 @@ import {
import { installStep } from './worktree.js';
import * as infraNotes from './infra-note.js';
export { gateWaitReporter };
-export const CHECKOUT_LEASES = new WeakMap();
-const CHECKOUT_BOARD_ONLY = new WeakMap();
-let startupMainTraced = false;
/**
* Read the collision baseline from the primary branch, retained trunk, or detached HEAD default.
*
@@ -412,192 +407,6 @@ export function coordinatorFile(root, path, revision) {
...(detachedHeadDefault ? { baseline: 'collision baseline default: detached HEAD' } : {}),
};
}
-/** Find the nearest declared command for a useful typo hint. */
-function closestHelpCommand(input) {
- const needle = input.toLowerCase();
- /** Measure edit distance between two command names for a useful typo hint. */
- const distance = (left, right) => {
- let row = Array.from({ length: right.length + 1 }, (_, index) => index);
- for (let i = 1; i <= left.length; i += 1) {
- const next = [i];
- for (let j = 1; j <= right.length; j += 1) {
- next[j] = Math.min(next[j - 1] + 1, row[j] + 1, row[j - 1] + (left[i - 1] === right[j - 1] ? 0 : 1));
- }
- row = next;
- }
- return row.at(-1);
- };
- return Object.keys(HELP.commands).sort((a, b) => distance(needle, a) - distance(needle, b) || a.localeCompare(b))[0];
-}
-
-/** Render one command's usage, one-line flags and a pasteable example from the help declaration. */
-function commandHelp(name) {
- const entry = HELP.commands[name];
- if (!entry) return null;
- return [
- `Usage: ${entry.usages[0]}`,
- ...entry.usages.slice(1).map((usage) => ` ${usage}`),
- 'Flags:',
- ...(entry.flags.length ? entry.flags.map((flag) => ` ${flag}`) : [' none']),
- ...(name === 'spec' ? [
- 'Subcommands:',
- ' pullboard spec --json — agent or person: print the parsed spec and practice rows',
- ' pullboard spec check — agent or person: lint the spec and practice files',
- ' pullboard spec view — agent or person: write the offline spec page',
- ' pullboard spec show <id> — agent or person: inspect one row and its sign-offs',
- ' pullboard spec unmet — agent or person: list approved rows without current sign-off',
- ' pullboard spec draft <text> [--section <letter>] [--aim] [--gate "<gate>"] — any agent: append a draft row; never approve it',
- ' pullboard spec signoff <ids> — person: sign rows with evidence',
- ' pullboard spec signers add — person: register an SSH signing key',
- ' pullboard spec approve <ids> — person: decide from their own terminal or Pullboard View',
- ' pullboard spec decline <ids> — person: decide from their own terminal or Pullboard View',
- ' pullboard spec answer <id> "<choice or text>" — person: answer a pending question from their own terminal or Pullboard View',
- ' pullboard spec apply — coordinator: apply recorded row decisions to the files',
- ] : []),
- 'Example:',
- ...entry.example.split('\n').map((line) => ` ${line}`), ...entry.notes,
- ].join('\n');
-}
-
-/** Write a selected help view in text and the stable help:string JSON field. */
-export function printHelp(io, text) {
- io.result?.({ help: text });
- io.say(text);
- return 0;
-}
-
-/** Refuse an unknown command with its nearest declared spelling and a route to the full list. */
-export function unknownCommand(io, input) {
- const closest = closestHelpCommand(input);
- io.err(`pullboard: no command "${input}"; closest match is "${closest}". Run pullboard help --all for the full list.`);
- return 2;
-}
-
-/** Resolve overview, command detail or the preserved full list from one invocation. */
-function selectedHelp(command, first, second, rest, values) {
- if (command === 'help') {
- if (values.all) return { text: HELP.all };
- const requested = [first, second, ...rest].filter(Boolean).join(' ');
- if (!requested || values.help && !first) return { text: HELP.overview };
- return { name: requested, text: commandHelp(requested) };
- }
- if (values.all && (!command || command === 'help')) return { text: HELP.all };
- if (!command) return { text: HELP.firstRun };
- if (values.help) {
- const words = [command, first, second, ...rest].filter(Boolean);
- const candidates = words.map((_, index) => words.slice(0, index + 1).join(' ')).filter((name) => HELP.commands[name]);
- const nested = candidates.at(-1) ?? command;
- return { name: nested, text: commandHelp(nested) };
- }
- return null;
-}
-const OPTIONS = {
- criterion: { type: 'string' },
- specs: { type: 'string' },
- parent: { type: 'string' },
- reason: { type: 'string' },
- off: { type: 'boolean' },
- port: { type: 'string' },
- slots: { type: 'string' },
- browser: { type: 'string' },
- 'new-browser': { type: 'boolean' },
- node: { type: 'string' },
- root: { type: 'string' },
- project: { type: 'boolean' },
- export: { type: 'string' },
- 'no-open': { type: 'boolean' },
- 'no-permissions': { type: 'boolean' },
- note: { type: 'string' },
- infra: { type: 'string' },
- 'note-file': { type: 'string' },
- by: { type: 'string' },
- key: { type: 'string' },
- out: { type: 'string' },
- watch: { type: 'boolean' },
- after: { type: 'string' },
- brief: { type: 'string' },
- 'brief-file': { type: 'string' },
- text: { type: 'string' },
- gate: { type: 'string' },
- aim: { type: 'boolean' },
- doctrine: { type: 'boolean' },
- source: { type: 'string' },
- section: { type: 'string' },
- blueprint: { type: 'string', multiple: true },
- route: { type: 'string' },
- family: { type: 'string' },
- model: { type: 'string' },
- as: { type: 'string' },
- check: { type: 'string' },
- ...SENTINEL_OPTIONS,
- ...QUALITY_OPTIONS,
- yes: { type: 'boolean' },
- landing: { type: 'boolean' },
- adopt: { type: 'boolean' },
- waive: { type: 'string' },
- until: { type: 'string' },
- agent: { type: 'string' },
- 'agent-light': { type: 'string' },
- 'agent-mid': { type: 'string' },
- 'agent-strong': { type: 'string' },
- attempts: { type: 'string' },
- minutes: { type: 'string' },
- items: { type: 'string' },
- run: { type: 'string' },
- max: { type: 'string' },
- 'dry-run': { type: 'boolean' },
- update: { type: 'boolean' },
- before: { type: 'string' },
- target: { type: 'string' },
- next: { type: 'string' },
- add: { type: 'string' },
- remove: { type: 'string' },
- name: { type: 'string' },
- title: { type: 'string' },
- url: { type: 'string' },
- skip: { type: 'string' },
- wait: { type: 'string' },
- verify: { type: 'boolean' },
- build: { type: 'boolean' },
- all: { type: 'boolean' },
- must: { type: 'boolean' },
- json: { type: 'boolean' },
- history: { type: 'boolean' },
- verbose: { type: 'boolean' },
- since: { type: 'string' },
- decision: { type: 'boolean' },
- evidence: { type: 'string' },
- outcome: { type: 'string' },
- item: { type: 'string' },
- kinds: { type: 'string' }, to: { type: 'string' }, work: { type: 'string' }, 'review-wait': { type: 'string' },
- commit: { type: 'string' },
- ref: { type: 'string' },
- supersedes: { type: 'string' },
- conflict: { type: 'string', multiple: true },
- cause: { type: 'string' },
- 'never-again': { type: 'boolean' },
- 'draft-splits': { type: 'boolean' },
- implies: { type: 'string' },
- owns: { type: 'string' },
- red: { type: 'string' },
- green: { type: 'string' },
- help: { type: 'boolean', short: 'h' },
- version: { type: 'boolean', short: 'v' },
-};
-
-/** Parse --wait as a switch for add/edit and as minutes for next/run, preserving all other options. */
-function parseCommandArgs(argv) {
- let command;
- for (const wait of [{ type: 'boolean' }, OPTIONS.wait]) {
- try {
- command = parseArgs({ args: argv, options: { ...OPTIONS, wait }, allowPositionals: true }).positionals[0];
- if (['add', 'edit'].includes(command)) break;
- } catch { /* The final parser supplies the existing actionable usage error. */ }
- }
- const options = ['add', 'edit'].includes(command) ? { ...OPTIONS, wait: { type: 'boolean' } } : OPTIONS;
- return parseArgs({ args: argv, options, allowPositionals: true });
-}
-
/** Start an already-recorded request, recording an unavailable result if its child cannot start. */
export async function launchBaseline(ctx, board, id, baseline) {
try { await startCheckBaseline(ctx.info.root, id, baseline); }
@@ -607,27 +416,6 @@ export async function launchBaseline(ctx, board, id, baseline) {
}
}
-/**
- * A positive whole number from an argument, or a refusal naming what was expected.
- *
- * @param {string | undefined} text
- * @param {string} what
- * @returns {number}
- */
-export function idArg(text, what = 'an item id') {
- const id = Number(String(text ?? '').replace(/^#/, ''));
- if (!Number.isInteger(id) || id < 1) throw new Refused('USAGE', `expected ${what}, got "${text ?? ''}"`);
- return id;
-}
-
-/**
- * A comma list of spec ids from a flag.
- *
- * @param {string | undefined} text
- * @returns {string[]}
- */
-export const idList = (text) => (text ?? '').split(',').map((id) => id.trim()).filter(Boolean);
-
/** Parse an edit's dependency replacement, with the explicit word `none` meaning clear all. */
export function editAfter(text) {
if (text === undefined) return undefined;
@@ -668,24 +456,6 @@ export function textArg(io, values, name) {
*/
export const briefArg = (io, values) => textArg(io, values, 'brief');
-/**
- * The start of a command an agent can paste anywhere: agent shells often start each command in the
- * main checkout, so every command pullboard suggests names its folder (I5).
- *
- * @param {string} root
- * @returns {string}
- */
-export const shellWord = (text) => (/^[\w@%+=:,./-]+$/.test(text) ? text : `'${text.replaceAll("'", "'\\''")}'`);
-
-/**
- * `cd <folder> &&`, the folder quoted for any POSIX shell: single quotes, so a space, a quote or a
- * dollar sign in the path reaches cd as written (I7).
- *
- * @param {string} root
- * @returns {string}
- */
-export const cdTo = (root) => `cd ${shellWord(root)} &&`;
-
/**
* Verifying from the main checkout files the verdict as the coordinator's (V9). An agent whose
* shell started there would be taken for the coordinator, so the coordinator says so explicitly
@@ -764,101 +534,6 @@ export function briefInLane(ctx, lane, brief) {
return brief;
}
-/**
- * Print an item's brief, indented under a heading, when it has one.
- *
- * @param {any} io
- * @param {string} brief
- */
-export function sayBrief(io, brief) {
- if (!brief) return;
- io.say('brief:');
- brief.split('\n').forEach((line) => io.say(` ${line}`.trimEnd()));
-}
-
-/**
- * Everything a command needs: the repo, its config, the board's file, and where output goes.
- *
- * @param {any} io
- * @returns {any}
- */
-export 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');
- return { info, config, file, allowSchemaUpgrade, doctrine: loadDoctrine(info.root, config), io, clock: io.clock ?? store.systemClock };
-}
-
-/**
- * This checkout's config. Init is the fix only where pullboard never was (C4): a config deleted
- * from a checkout whose last commit has it is restored, and a linked worktree made from a commit
- * that lacks it, beside a main checkout that has one, is made again from there.
- *
- * @param {{ root: string, commonDir: string, isMain: boolean }} info
- * @returns {any}
- */
-function configHere(info) {
- try {
- return loadConfig(info.root);
- } catch (error) {
- if (!(error instanceof Refused) || error.code !== 'NO_CONFIG') throw error;
- if (tryGit(info.root, ['cat-file', '-e', `HEAD:${CONFIG_FILE}`]).status === 0) {
- throw new Refused('NO_CONFIG', `${CONFIG_FILE} is deleted here, though this checkout's last commit has it: restore it: ${cdTo(info.root)} git checkout HEAD -- ${CONFIG_FILE}`);
- }
- const mainRoot = resolve(info.commonDir, '..');
- if (info.isMain || !existsSync(join(mainRoot, CONFIG_FILE))) throw error;
- let setup;
- try {
- setup = uncommittedSetup(mainRoot, loadConfig(mainRoot));
- } catch {
- // Keep the existing recovery for invalid or incomplete main-checkout configuration.
- }
- if (setup) {
- throw new Refused(
- 'NO_CONFIG',
- `this worktree has no ${CONFIG_FILE}, and the main checkout has uncommitted Pullboard setup files: ${setup.files.join(', ')}. Commit them in the main checkout first: ${setup.stage}`,
- );
- }
- throw new Refused(
- 'NO_CONFIG',
- `this worktree's commit has no ${CONFIG_FILE}, though the main checkout has one: make a new worktree from the main checkout, which says what to commit first: ${cdTo(mainRoot)} pullboard worktree <lane> --model "<model name>"`,
- );
- }
-}
-
-/**
- * Open the board, run `work`, and always close it.
- *
- * @template T
- * @param {any} ctx
- * @param {(board: any) => T} work
- * @returns {T}
- */
-export function withBoard(ctx, work) {
- const board = store.openBoard(ctx.file, ctx.clock, { isMain: ctx.allowSchemaUpgrade });
- // Whether a proven flake stops blocking a landing is the coordinator's setting, read from accepted main on first use.
- let quarantine;
- board.quarantineEnabled = () => quarantine ??= mainPolicy(ctx.info.root).config.flakes?.quarantine === true;
- const firstEvent = board.emittedEvents?.length ?? 0;
- /** Forward committed events before releasing either synchronous or asynchronous work. */
- const finish = () => {
- for (const event of board.emittedEvents?.slice(firstEvent) ?? []) ctx.io.onEvent?.(event);
- store.closeBoard(board);
- };
- let result;
- 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();
- return result;
-}
-
/**
* Reserve a new row's id on the board in one write transaction before any file names it, so writers
* that plan the same id at the same moment get distinct ids (#878). written: the caller writes the row
@@ -877,7 +552,7 @@ async function withItemSession(info, operation, args, move) { const noted = oper
* Whether the board's committed relay.outbox setting queues moves while the relay is down (#922).
* Why: it is read from the trunk's pullboard.json, so every machine on the board follows the same committed choice.
*/
-function relayOutboxSetting(root) {
+export function relayOutboxSetting(root) {
try { return configFromSource(coordinatorFile(root, CONFIG_FILE).stdout).relay?.outbox === true; } catch { return false; }
}
@@ -930,17 +605,12 @@ export async function claimOrdered(ctx, board, args) {
return await ordered(ctx, board, 'claim', args);
}
-/** Check ownership before sync or command side effects; reads and authenticated person channels keep their identity. A person's takeover in a linked main checkout binds no session (#347). */
-async function bindCheckoutSession(io, positionals, values) {
- if (values.help || values.version || io.personChannel === 'view' || io.personRequest) return;
+/**
+ * Bind this checkout to the session behind a write command, which the command line has already told apart from a
+ * read. A person's takeover in a linked main checkout binds no session (#347).
+ */
+export async function bindWriteSession(io, positionals, values) {
const [command, first] = positionals;
- if (command === 'takeover' && (positionals.length !== 1 || Object.keys(values).some((key) => key !== 'json'))) {
- throw new Refused('USAGE', 'pullboard takeover takes no arguments; run pullboard takeover [--json]');
- }
- const writes = ['init', 'join', 'worktree', 'hooks', 'hook', 'skills', 'add', 'edit', 'fact', 'escalate', 'run', 'sweep',
- 'next', 'claim', 'hold', 'release', 'submit', 'done', 'verify', 'check', 'merged', 'land', 'withdraw', 'refreeze', 'reopen', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget'];
- if (!writes.includes(command) && !(command === 'lane' && first === 'add') && !(command === 'settings' && first) && !(command === 'spec' && first === 'apply') && !(command === 'relay' && ['on', 'off'].includes(first))) return;
- if (command === 'answer' && values.as === 'person') return;
const digest = agentSessionDigest();
if (!digest) {
if (command === 'takeover' && !(repoInfo(io.cwd).isMain && relayLinked(repoInfo(io.cwd).root))) throw new Refused('AGENT_SESSION', 'takeover belongs to an agent session; run pullboard takeover from the agent’s shell');
@@ -1169,90 +839,6 @@ export function evidenceFrom(ctx, values) {
*/
export const evidenceLine = (shout) => `${shout.shout_evidence_kind}: ${shout.shout_evidence_outcome}, #${shout.shout_evidence_item} at ${shout.shout_evidence_commit.slice(0, 12)}`;
-/** How many characters of an earlier verdict's note show prints (N30). */
-const NOTE_LINE = 120;
-
-/**
- * A note's first line, cut to NOTE_LINE characters with … marking the cut. A line ends at any break
- * Unicode makes mandatory (UAX #14): LF, VT, FF, CR, CRLF, NEL, LS and PS. Characters are counted
- * as a reader sees them, so a cut never splits an emoji or an accented letter.
- *
- * @param {string} note
- * @returns {string}
- */
-export function firstLineOf(note) {
- const line = note.split(/[\n\v\f\r\x85\u2028\u2029]/)[0];
- const characters = [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(line)];
- return characters.length > NOTE_LINE ? `${characters.slice(0, NOTE_LINE).map((part) => part.segment).join('')}…` : line;
-}
-
-/**
- * One item on one line: id, status and holder, lane, title, spec ids.
- *
- * @param {any} item
- * @returns {string}
- */
-export function itemLine(item, name = (id) => id, mainMerge = false) {
- const holder = item.item_status === 'claimed' ? ` ${name(item.item_owner)}` : '';
- const verifier = item.item_status === 'verified' ? ` by ${name(item.item_verified_by)}` : '';
- const specs = item.item_spec_ids ? ` [${item.item_spec_ids}]` : '';
- const parent = item.item_parent_id ? ` under #${item.item_parent_id}` : '';
- const after = item.item_after ? ` after ${item.item_after.split(',').map((id) => `#${id}`).join(',')}` : '';
- const rejected = item.item_status === 'open' && item.item_verdict === 'REJECT' ? ' (rejected)' : mainMerge ? ` (${MAIN_MERGE_LABEL})` : '';
- const light = item.item_route === 'strong' ? '' : ` ${item.item_route}`;
- const staleVerdict = item.item_verdict_state ? ` ${item.item_verdict_state.code}` : '';
- const hold = item.item_hold_reason ? ` held by ${name(item.item_hold_by)}: ${item.item_hold_reason}` : '';
- return `#${item.item_id} ${item.item_status}${holder}${verifier}${rejected} ${item.item_lane} ${item.item_title}${specs}${parent}${after}${light}${hold}${staleVerdict}`;
-}
-
-/** Format a stable agent id for human-facing CLI output. */
-export function agentDisplayName(agents, config, id) {
- if (!id) return '';
- const agent = agents.find((entry) => entry.agent_id === id);
- if (agent) return displayAgentName(agent, config.agents.names);
- if (id === 'person' || id === 'all' || Object.hasOwn(config.lanes, id)) return id;
- return displayAgentName({ agent_id: id }, config.agents.names);
-}
-
-/** Render only declared actor positions in a refusal, preserving user text and stable JSON ids. */
-function agentRefusalText(message, code, name) {
- const patterns = {
- ALREADY_JOINED: /^(\[ALREADY_JOINED\] this worktree is )(\S+)( in )/,
- HELD: /^(\[HELD\] item #\d+ is held by )(\S+)( until )/,
- ITEM_HELD: /^(\[ITEM_HELD\] item #\d+ is held by )(\S+)(: )/,
- LANE_HELD: /^(\[LANE_HELD\] )(\S+)( holds the )/,
- REVIEW_HELD: /^(\[REVIEW_HELD\] )(\S+)( holds the )/,
- NOT_YOURS: /^(\[NOT_YOURS\] only the coordinator or )(\S+)(, who )/,
- NO_AGENT: /^(\[NO_AGENT\] no (?:registered )?agent )(\S+)(;|$)/,
- NOT_YOUR_CHECKOUT: /^(\[NOT_YOUR_CHECKOUT\] this checkout belongs to )(\S+)( in )/,
- FACT_JUDGEMENT: /^(\[FACT_JUDGEMENT\] only the item's live holder \()(\S+)(\))/,
- RELAY_PERSON_ONLY: /^(\[RELAY_PERSON_ONLY\] agent )(\S+)( cannot )/,
- SELF_SHOUT: /^(\[SELF_SHOUT\] a shout cannot be addressed to its sender )(\S+)(;)/,
- NO_READER: /^(\[NO_READER\] nobody reads ")(.*?)(":)/,
- };
- if (code === 'RELAY_SENDER_MISMATCH') {
- return message.replace(/^(\[RELAY_SENDER_MISMATCH\] agent )(\S+)( cannot act as )(.*?)(; send this operation)/,
- (_, before, sender, middle, actor, after) => `${before}${name(sender)}${middle}${actor === '(no declared agent)' ? actor : name(actor)}${after}`);
- }
- if (code === 'NOT_YOUR_DECISION') {
- return message.replace(/^(\[NOT_YOUR_DECISION\] shout #\d+ is addressed to )(\S+)(, not your \S+ lane \(agent )(\S+)(\))$/,
- (_, before, to, middle, caller, after) => `${before}${name(to)}${middle}${name(caller)}${after}`);
- }
- return patterns[code] ? message.replace(patterns[code], (_, before, id, after) => `${before}${name(id)}${after}`) : message;
-}
-
-/** Render the refusal body without its existing final footer; structured errors retain the message. */
-function displayedRefusal(io, error) {
- 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 {
- const ctx = context(io);
- const agents = withBoard(ctx, (board) => store.listAgents(board));
- return agentRefusalText(message, error.code, (id) => agentDisplayName(agents, ctx.config, id));
- } catch { return message; }
-}
-
/** Label the holder at the start of a generated wait reason without rewriting its quoted reason. */
export function displayedWait(reason, agents, config) {
return reason.replace(/^(\S+)( holds the )/, (_, id, rest) => `${agentDisplayName(agents, config, id)}${rest}`)
@@ -1636,34 +1222,6 @@ export function unavailableWorktreeLocation() {
return 'unavailable; run pullboard resume from the main checkout to see the configured location';
}
-/**
- * The files a new worktree takes from the main checkout's last commit and works by: the config, the
- * spec, the practice file, the rules its opening lines name, and the hooks, when git looks for them
- * inside each worktree.
- *
- * @param {string} mainRoot
- * @param {any} config
- * @returns {string[]}
- */
-function setupFiles(mainRoot, config) {
- const hooks = tryGit(mainRoot, ['config', '--get', 'core.hooksPath']).stdout;
- const inEach = hooks && !isAbsolute(hooks) && !relative(mainRoot, resolve(mainRoot, hooks)).startsWith('..');
- return [CONFIG_FILE, config.spec, config.practice, 'AGENTS.md', ...(inEach ? [hooks] : [])].filter(Boolean);
-}
-
-/** Find setup files in the main checkout that a new worktree would not receive from HEAD. */
-export function uncommittedSetup(mainRoot, config) {
- if (headCommit(mainRoot) === null) return null;
- const differ = differFromHead(mainRoot, setupFiles(mainRoot, config));
- if (!differ.length) return null;
- const words = differ.map(({ path }) => shellWord(path)).join(' ');
- const force = differ.some(({ ignored }) => ignored) ? ' -f' : '';
- return {
- files: differ.map(({ path }) => path), differ,
- stage: `${cdTo(mainRoot)} git add${force} -- ${words}`,
- };
-}
-
/** Find initialized setup that is on disk but absent from the primary checkout's committed policy. */
export function uncommittedPolicySetup(info) {
const primary = mainCheckout(info.root);
@@ -2200,47 +1758,6 @@ export function specProof(ctx) {
-/**
- * Run one command. Returns the exit code: 0 done, 1 refused, 2 usage.
- *
- * @param {string[]} argv
- * @param {any} io
- * @returns {Promise<number>}
- */
-async function runCommand(argv, io) {
- let parsed;
- try {
- parsed = parseCommandArgs(argv);
- } 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: ${io.refusalDocument(refusal).error.next}`);
- return 2;
- }
- const { values, positionals } = parsed;
- io.jsonMode?.(values.json);
- const [command = '', first, second, ...rest] = positionals;
- const args = { first, second, rest, values };
- if ((values.version || command === 'version') && !values.help) return await (await COMMANDS.version()).run(io, args);
- const help = selectedHelp(command, first, second, rest, values);
- if (help) return await (await COMMANDS.help()).run(io, args, help);
- try {
- if (values.as === 'person' && !['answer', 'decisions', 'fact'].includes(command)) {
- throw new Refused('USAGE', '--as person works only with pullboard answer, decisions, or fact --never-again');
- }
- const load = COMMANDS[command];
- if (!load) return unknownCommand(io, command);
- return await (await load()).run(io, args);
- } catch (error) {
- if (error instanceof Refused) {
- io.refusal?.(error);
- io.err(`pullboard: ${displayedRefusal(io, error)}\nnext: ${io.refusalDocument(error).error.next}`);
- return 1;
- }
- throw error;
- }
-}
-
/**
* Every private name a saved blueprint must never carry: each agent's id, display name, model
* and family, the person's Git name and email, everyone who signed off or signs rows, and this
@@ -2272,117 +1789,3 @@ export function privateNames(root, board, spec) {
return { names: [...names], parts: [...parts] };
}
-/** Retain the primary branch on every command without creating a board for global help. */
-function rememberTrunk(io) {
- let info;
- try { info = repoInfo(io.cwd); }
- catch (error) {
- if (error instanceof Refused && ['NOT_A_REPO', 'NO_REPO', 'CORE_BARE'].includes(error.code)) return;
- throw error;
- }
- if (!info.isMain) return;
- const primary = mainCheckout(info.root);
- if (primary?.branch) trunkRef(info.root, primary.branch);
-}
-
-/** Run one command and emit its single versioned JSON result when requested (A1). */
-export async function main(argv, streams) {
- if (argv[0] === 'serve' && !startupMainTraced) {
- startupMainTraced = true;
- traceServeStartup('cli-main-enter');
- }
- return withGitFacts(() => runMain(argv, streams));
-}
-
-/** Parse and execute one CLI command, binding its checkout session and Git-fact scope. */
-async function runMain(argv, streams) {
- const io = commandOutput(argv, streams);
- let sync = true;
- let needsRepo = true;
- let parsed;
- let checkoutSession;
- try {
- parsed = parseCommandArgs(argv);
- const command = parsed.positionals[0];
- io.relayJson = Boolean(parsed.values.json);
- io.relayCommand = { cliOperation: command === 'done' ? 'submit' : command, cwd: resolve(io.cwd),
- positionals: parsed.positionals.slice(1),
- values: Object.fromEntries(Object.keys(parsed.values).filter(key => key !== 'json').sort().map(key => [key, parsed.values[key]])) };
- sync = Boolean(command) && !parsed.values.help && !parsed.values.version
- && !['help', 'version', 'hook', 'init', 'relay', 'tour', 'mcp', 'health', 'watch', 'digest'].includes(command)
- // A coordinator declaration on a linked clone must refuse before auto-link or relay sync.
- && !(command === 'join' && parsed.positionals[1] === COORDINATOR);
- needsRepo = !(parsed.values.help || parsed.values.version || command === 'help' || command === 'version');
- } 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 = needsRepo ? repoInfo(io.cwd) : null; 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);
- 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: ${io.refusalDocument(error).error.next}`);
- io.flush(1);
- return 1;
- }
- }
- try {
- /** A network refusal preserves offline reads; linked mutation dispatch requires an acknowledgement. */
- const retry = async () => {
- try {
- io.relayOutbox ??= () => relayOutboxSetting(io.cwd);
- await syncRelay(io.cwd, io);
- await retryCheckBaselines(io.cwd, io);
- }
- 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: ${io.refusalDocument(error).error.next}`);
- }
- };
- if (needsRepo) rememberTrunk(io);
- traceServeStartup('cli-command-preamble-start');
- if (sync) {
- try { await autoLinkProject(io.cwd, io); } catch (error) { if (!(error instanceof Refused)) throw error; }
- await retry();
- 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: ${io.refusalDocument(error).error.next}`);
- }
- }
- traceServeStartup('cli-command-preamble-ready');
- const code = await runCommand(argv, io);
- if (code === 0) await checkoutSession?.finish?.();
- if (sync && code === 0) await retry();
- const status = io.exitCode(code);
- io.flush(status);
- return status;
- } finally {
- CHECKOUT_LEASES.delete(io);
- CHECKOUT_BOARD_ONLY.delete(io);
- checkoutSession?.lease?.release();
- }
-}
-
-/** Result-producing command names, including aliases, for API contract coverage (A1). */
-export function resultCommands() {
- return Object.keys(COMMANDS).filter((name) => !UNLISTED_COMMANDS.includes(name)).sort();
-}
-
-/** Command help follows the same dispatch declarations as execution. */
-export const HELP = buildHelp(resultCommands());
-
-// This marker is emitted once when the actual CLI entrypoint finishes evaluating.
-if (process.env.PULLBOARD_STARTUP_TRACE_ENTRY
- && resolve(process.argv[1] ?? '') === resolve(process.env.PULLBOARD_STARTUP_TRACE_ENTRY)) {
- traceServeStartup('cli-module-load-complete');
-}
diff --git a/src/commands/list.js b/src/commands/list.js
index 0271f8bd..ec87bc80 100644
--- a/src/commands/list.js
+++ b/src/commands/list.js
@@ -11,7 +11,7 @@ import {
context,
itemLine,
withBoard,
-} from '../cli.js';
+} from '../cli-context.js';
/** Run `pullboard list` and return its exit code. */
export function run(io, { first, values }) {
diff --git a/src/commands/serve.js b/src/commands/serve.js
index a81f1212..769bbf14 100644
--- a/src/commands/serve.js
+++ b/src/commands/serve.js
@@ -4,7 +4,7 @@ import {
} from '../api.js';
import {
traceServeStartup,
-} from '../cli-support.js';
+} from '../cli-main.js';
import {
loadConfig,
} from '../config.js';
diff --git a/src/commands/show.js b/src/commands/show.js
index ff7a7780..a337e84e 100644
--- a/src/commands/show.js
+++ b/src/commands/show.js
@@ -32,11 +32,11 @@ import {
itemLine,
sayBrief,
withBoard,
-} from '../cli.js';
-import { relayStatus } from '../relay.js';
+} from '../cli-context.js';
+import { relayStateExists } from '../local-state.js';
/** Run `pullboard show` and return its exit code. */
-export function run(io, { first, values }) {
+export async function run(io, { first, values }) {
const ctx = context(io);
const id = idArg(first);
const { item, verdicts, moves, thread, related, reviewer, agents, mainMerge, infra, approval } = withBoard(ctx, (board) => ({
@@ -53,7 +53,9 @@ export function run(io, { first, values }) {
const agentApproved = itemAgentApprovals(item, approval);
const approvalQualification = agentApprovalLine(agentApproved);
// #922: moves on this item made while the relay was down wait in this machine's relay outbox until it answers.
- const relayPending = (relayStatus(ctx.info.root).outbox ?? []).filter((move) => move.item === id);
+ // Without a relay link or deleted-copy notice there is no outbox to read, so the relay client never loads.
+ const outbox = relayStateExists(ctx.info.commonDir) ? (await import('../relay.js')).relayStatus(ctx.info.root).outbox : undefined;
+ const relayPending = (outbox ?? []).filter((move) => move.item === id);
if (values.json) {
io.result({ ...item, verdicts, thread, agentApproved, approvalQualification, ...(relayPending.length ? { relayPending } : {}) });
return 0;
diff --git a/src/commands/version.js b/src/commands/version.js
index c8ee188b..fd1cb06d 100644
--- a/src/commands/version.js
+++ b/src/commands/version.js
@@ -1,9 +1,10 @@
/** The pullboard version command, in its own module so an item adding another command never edits these lines. */
-import { VERSION } from '../cli.js';
+// The release number lives in package.json; reading it here keeps --version to its own module [C7].
+import packageData from '../../package.json' with { type: 'json' };
/** Run `pullboard version` (or any command with --version) and return its exit code. */
export function run(io) {
- io.result?.({ release: VERSION });
- io.say(VERSION);
+ io.result?.({ release: packageData.version });
+ io.say(packageData.version);
return 0;
}
diff --git a/src/gate-output.js b/src/gate-output.js
new file mode 100644
index 00000000..d53eaed9
--- /dev/null
+++ b/src/gate-output.js
@@ -0,0 +1,139 @@
+/**
+ * What a gate run leaves for people and agents: the digest of its output and its sanitized timing profile. Trusted
+ * policy checks write both, so they live apart from the gate's queue and runners, which a board read never needs [C7].
+ */
+import {
+ mkdirSync,
+ writeFileSync,
+} from 'node:fs';
+import { dirname } from 'node:path';
+import { secretsIn } from './hooks.js';
+
+const DIGEST_CHARS = 3000;
+const TAIL_CHARS = 1000;
+const LINE_CHARS = 300;
+const FAILURE_RE = /fail|error|expected|received|assert|not ok|✗|×|cannot|undefined|exception/i;
+// A passing test's own lines, whatever its name says: TAP's `ok N` and the `# Subtest:` before it.
+const PASSING_RE = /^\s*(ok \d+\b|# Subtest:)/;
+// Lines kept under a failure, where test runners say why: the message, expected and actual.
+const CONTEXT_LINES = 20;
+
+/**
+ * The lines of a failure worth an agent's attention: each line that looks like a failure with the
+ * lines under it that say why, then the end of the output, within one cap, so a refusal or a retry
+ * carries the reason and not the whole log. Passing tests are skipped however they are named. The
+ * end has its own share of the cap and every line is cut short, so no single long line can push the
+ * summary out. Unstructured commands keep their first diagnostic, and omitted nonempty lines are
+ * counted so the excerpt never looks like the complete output.
+ *
+ * @param {string} output
+ * @returns {string}
+ */
+export function digestOf(output) {
+ const lines = output
+ .split('\n')
+ .map((line) => line.trimEnd())
+ .filter(Boolean)
+ .map((line) => (line.length > LINE_CHARS ? `${line.slice(0, LINE_CHARS)}…` : line));
+ const tail = [];
+ let room = TAIL_CHARS;
+ for (let at = lines.length - 1; at >= 0 && tail.length < 15 && lines[at].length < room; at -= 1) {
+ tail.unshift(lines[at]);
+ room -= lines[at].length + 1;
+ }
+ room = DIGEST_CHARS - (TAIL_CHARS - room) - 80; // Reserve the omission count inside the same cap.
+ const body = lines.slice(0, lines.length - tail.length);
+ const failing = [];
+ for (let at = 0; at < body.length && failing.length < 40; at += 1) {
+ if (PASSING_RE.test(body[at]) || !FAILURE_RE.test(body[at])) continue;
+ if (/^\s*not ok \d+/u.test(body[at])) {
+ let end = at + 1;
+ while (end < body.length && !/^\s*(?:# Subtest:|(?:not )?ok \d+|\d+\.\.)/u.test(body[end])) end += 1;
+ // Cancelled siblings are fallout; keep the actual assertion's fields inside the digest cap.
+ if (body.slice(at, end).some(line => /failureType:\s*['"]testAborted['"]/u.test(line))) { at = end - 1; continue; }
+ }
+ const block = body.slice(at, at + CONTEXT_LINES + 1);
+ const end = block.findIndex((line, n) => n > 0 && (PASSING_RE.test(line) || /^\s*(not ok \d+|\.\.\.)\s*$|^\s*not ok \d+/.test(line)));
+ for (const line of end === -1 ? block : block.slice(0, end)) {
+ if (line.length >= room) break;
+ failing.push(line);
+ room -= line.length + 1;
+ }
+ at += (end === -1 ? block.length : end) - 1;
+ }
+ if (!failing.length) {
+ for (const line of body.filter(line => !PASSING_RE.test(line)).slice(0, CONTEXT_LINES + 1)) {
+ if (line.length >= room) break;
+ failing.push(line);
+ room -= line.length + 1;
+ }
+ }
+ const omitted = lines.length - failing.length - tail.length;
+ const notice = omitted ? [`… ${omitted} nonempty output lines omitted …`] : [];
+ return [...failing, ...notice, ...tail].join('\n');
+}
+
+/** Persist one sanitized timing profile as a private artifact.
+ * @param {string} path
+ * @param {{ files?: Array<object>, tests?: Array<object>, [key: string]: any }} profile
+ * @returns {object} The sanitized profile written to disk.
+ */
+export function writeTimingProfile(path, profile) {
+ /** Sanitize one reporter-controlled string before persistence or display.
+ * @param {unknown} value
+ * @param {string} label
+ * @returns {unknown}
+ */
+ const sanitize = (value, label) => {
+ if (typeof value !== 'string') return value;
+ if (Buffer.byteLength(value, 'utf8') > 64 * 1024) return '[redacted profile field exceeds 64 KiB safe-scan limit]';
+ const findings = secretsIn([{ path: `timing profile ${label}`, line: 1, text: value }]);
+ return findings.length ? `[redacted ${findings.map(finding => finding.slice(0, finding.lastIndexOf(' at '))).join(', ')}]` : value;
+ };
+ /** Accept only measured, nonnegative durations from reporter events. */
+ const validDuration = value => Number.isFinite(value) && value >= 0;
+ const files = (profile.files ?? []).filter(file => typeof file?.path === 'string' && validDuration(file.durationMs))
+ .map(file => ({ path: sanitize(file.path, 'file path'), durationMs: file.durationMs }));
+ const tests = (profile.tests ?? []).filter(test => (typeof test?.file === 'string' || test?.file === null) && typeof test?.name === 'string' && validDuration(test.durationMs))
+ .map(test => ({ file: sanitize(test.file, 'test file'), name: sanitize(test.name, 'test name'), durationMs: test.durationMs, passed: test.passed === true }));
+ const sanitized = {
+ version: 1,
+ waitMs: validDuration(profile.waitMs) ? profile.waitMs : 0,
+ wallMs: validDuration(profile.wallMs) ? profile.wallMs : null,
+ files,
+ tests,
+ runner: sanitize(profile.runner ?? 'shell', 'runner'),
+ format: sanitize(profile.format ?? 'none', 'format'),
+ unavailable: sanitize(profile.unavailable ?? null, 'availability'),
+ ...(profile.executionRunner ? { executionRunner: sanitize(profile.executionRunner, 'execution runner') } : {}),
+ ...(profile.receipt ? { receipt: { ...profile.receipt, slot: { kind: sanitize(profile.receipt.slot?.kind, 'slot kind'), reason: sanitize(profile.receipt.slot?.reason, 'slot reason') } } } : {}),
+ ...(profile.landingShards ? { landingShards: {
+ balance: sanitize(String(profile.landingShards.balance ?? 'unknown'), 'landing balance'),
+ unverified: (profile.landingShards.unverified ?? []).map(entry => ({ shard: sanitize(String(entry.shard), 'landing unverified shard'),
+ processes: sanitize(String(entry.processes), 'landing unverified processes') })),
+ quarantined: (profile.landingShards.quarantined ?? []).map(entry => ({ host: sanitize(String(entry.host), 'landing quarantine host'),
+ message: sanitize(String(entry.message), 'landing quarantine message') })),
+ floor: profile.landingShards.floor && validDuration(profile.landingShards.floor.ms)
+ ? { path: sanitize(String(profile.landingShards.floor.path), 'landing floor path'), ms: profile.landingShards.floor.ms } : null,
+ // One entry per attempt, so a failed runner attempt stays beside its local rerun.
+ shards: (profile.landingShards.shards ?? []).map(shard => ({ shard: sanitize(String(shard.shard), 'landing shard'),
+ attempt: Number.isSafeInteger(shard.attempt) ? shard.attempt : 1,
+ host: sanitize(String(shard.host), 'landing shard host'), status: sanitize(String(shard.status), 'landing shard status'),
+ reason: shard.reason ? sanitize(String(shard.reason), 'landing shard reason') : null,
+ wallMs: validDuration(shard.wallMs) ? shard.wallMs : null })),
+ files: (profile.landingShards.files ?? []).filter(file => typeof file?.path === 'string').map(file => ({
+ path: sanitize(file.path, 'landing file path'), shard: sanitize(String(file.shard), 'landing file shard'),
+ host: sanitize(String(file.host), 'landing file host'), durationMs: validDuration(file.durationMs) ? file.durationMs : null })),
+ } } : {}),
+ ...(profile.executionSource ? { executionSource: {
+ commit: sanitize(profile.executionSource.commit, 'execution commit'),
+ tree: sanitize(profile.executionSource.tree, 'execution tree'),
+ tooling: Object.fromEntries(Object.entries(profile.executionSource.tooling ?? {})
+ .filter(([key]) => ['kind', 'name', 'version', 'commit', 'tree', 'sha256'].includes(key))
+ .map(([key, value]) => [key, sanitize(value, `execution tooling ${key}`)])),
+ } } : {}),
+ };
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ writeFileSync(path, `${JSON.stringify(sanitized, null, 2)}\n`, { mode: 0o600 });
+ return sanitized;
+}
diff --git a/src/gate.js b/src/gate.js
index ead1127d..c37feb3c 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -15,10 +15,8 @@ import {
import {
existsSync,
mkdirSync,
- mkdtempSync,
readFileSync,
realpathSync,
- rmSync,
statSync,
writeFileSync,
} from 'node:fs';
@@ -34,7 +32,6 @@ import {
availableParallelism,
freemem,
loadavg,
- tmpdir,
} from 'node:os';
import { fileURLToPath } from 'node:url';
import {
@@ -90,13 +87,15 @@ import { receiptOf } from './gate-receipt.js';
import { recordReceipt } from './gate-receipt.js';
import { slotOf } from './gate-receipt.js';
import { startReceipt } from './gate-receipt.js';
-import {
- gateStages,
- stagedScript,
- readPipes,
- readStages,
-} from './gate-stages.js';
export { gateStages } from './gate-stages.js';
+// A read that checks a baseline runs one command without loading the gate's queue and runners.
+import { runShell } from './shell-run.js';
+import {
+ digestOf,
+ writeTimingProfile,
+} from './gate-output.js';
+// A read that checks a baseline or a trusted policy summarizes output without loading the gate's queue and runners.
+export { digestOf, runShell, writeTimingProfile };
import {
RunnerDropped,
runOnRunner,
@@ -116,15 +115,6 @@ const LOG = 'pullboard-gate.log';
const LANDING_RUN_ENV = 'PULLBOARD_LANDING_RUN';
// Live person waivers, as {kind, test}, so a landing run does not stop early on a waived failure.
const LANDING_WAIVERS_ENV = 'PULLBOARD_LANDING_WAIVERS';
-const DIGEST_CHARS = 3000;
-const TAIL_CHARS = 1000;
-const LINE_CHARS = 300;
-const FAILURE_RE = /fail|error|expected|received|assert|not ok|✗|×|cannot|undefined|exception/i;
-// A passing test's own lines, whatever its name says: TAP's `ok N` and the `# Subtest:` before it.
-const PASSING_RE = /^\s*(ok \d+\b|# Subtest:)/;
-// Lines kept under a failure, where test runners say why: the message, expected and actual.
-const CONTEXT_LINES = 20;
-
/** Detect the performance-core budget on Apple Silicon, or the runtime's usable CPU budget elsewhere. */
export function performanceCores() {
if (process.platform === 'darwin') {
@@ -175,61 +165,6 @@ export function landingShardCount(root) {
return count;
}
-/**
- * The lines of a failure worth an agent's attention: each line that looks like a failure with the
- * lines under it that say why, then the end of the output, within one cap, so a refusal or a retry
- * carries the reason and not the whole log. Passing tests are skipped however they are named. The
- * end has its own share of the cap and every line is cut short, so no single long line can push the
- * summary out. Unstructured commands keep their first diagnostic, and omitted nonempty lines are
- * counted so the excerpt never looks like the complete output.
- *
- * @param {string} output
- * @returns {string}
- */
-export function digestOf(output) {
- const lines = output
- .split('\n')
- .map((line) => line.trimEnd())
- .filter(Boolean)
- .map((line) => (line.length > LINE_CHARS ? `${line.slice(0, LINE_CHARS)}…` : line));
- const tail = [];
- let room = TAIL_CHARS;
- for (let at = lines.length - 1; at >= 0 && tail.length < 15 && lines[at].length < room; at -= 1) {
- tail.unshift(lines[at]);
- room -= lines[at].length + 1;
- }
- room = DIGEST_CHARS - (TAIL_CHARS - room) - 80; // Reserve the omission count inside the same cap.
- const body = lines.slice(0, lines.length - tail.length);
- const failing = [];
- for (let at = 0; at < body.length && failing.length < 40; at += 1) {
- if (PASSING_RE.test(body[at]) || !FAILURE_RE.test(body[at])) continue;
- if (/^\s*not ok \d+/u.test(body[at])) {
- let end = at + 1;
- while (end < body.length && !/^\s*(?:# Subtest:|(?:not )?ok \d+|\d+\.\.)/u.test(body[end])) end += 1;
- // Cancelled siblings are fallout; keep the actual assertion's fields inside the digest cap.
- if (body.slice(at, end).some(line => /failureType:\s*['"]testAborted['"]/u.test(line))) { at = end - 1; continue; }
- }
- const block = body.slice(at, at + CONTEXT_LINES + 1);
- const end = block.findIndex((line, n) => n > 0 && (PASSING_RE.test(line) || /^\s*(not ok \d+|\.\.\.)\s*$|^\s*not ok \d+/.test(line)));
- for (const line of end === -1 ? block : block.slice(0, end)) {
- if (line.length >= room) break;
- failing.push(line);
- room -= line.length + 1;
- }
- at += (end === -1 ? block.length : end) - 1;
- }
- if (!failing.length) {
- for (const line of body.filter(line => !PASSING_RE.test(line)).slice(0, CONTEXT_LINES + 1)) {
- if (line.length >= room) break;
- failing.push(line);
- room -= line.length + 1;
- }
- }
- const omitted = lines.length - failing.length - tail.length;
- const notice = omitted ? [`… ${omitted} nonempty output lines omitted …`] : [];
- return [...failing, ...notice, ...tail].join('\n');
-}
-
/**
* The tree a gate run would check, or null when the working copy differs from HEAD or holds
* untracked files, since a pass over it would vouch for something no commit holds.
@@ -254,47 +189,6 @@ export function isStampedGreen(root) {
return tree !== null && existsSync(file) && readFileSync(file, 'utf8').trim() === tree;
}
-/**
- * Run a shell command in a checkout for a digest: both streams in one pipe, in order, read whole
- * however long, stdin closed so nothing waits on a person. With `stages`, each top-level stage's
- * exit status and own output are kept too, or `stages` is null when the command cannot be split.
- *
- * @param {string} root
- * @param {string} command
- * @param {{ pipefail?: boolean, env?: NodeJS.ProcessEnv, stages?: boolean }} [options] - Gate-only pipefail, additional child environment values and per-stage accounting.
- * @returns {{ isGreen: boolean, output: string, seconds: number, sandboxBlocked: string|null, stages?: Array<{ status: number|null, output: string, pipeline?: Array<{ status: number|null, output: string|null }> }> | null }}
- */
-export function runShell(root, command, { pipefail = false, env = {}, stages = false } = {}) {
- const started = Date.now();
- const options = { cwd: root, env: { ...gitChildEnv(root), ...env }, shell: true, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', maxBuffer: 2 ** 30 };
- let prefix = '';
- if (pipefail) {
- // Probe the same shell as the command, with no load-sensitive deadline or alternate shell.
- const probe = spawnSync('set -o pipefail', options);
- if (probe.status === 0) prefix = 'set -o pipefail\n';
- else if (hasPipeline(command)) {
- throw new Refused('PIPEFAIL_UNAVAILABLE', 'the repo gate shell cannot enable pipefail; rewrite the gate without a pipe');
- }
- }
- const split = stages ? gateStages(command) : null;
- const marker = `PULLBOARD_STAGE_${randomUUID().replaceAll('-', '')}`;
- const pipes = split?.some((stage) => stage.pipeline.length > 1) ? mkdtempSync(join(tmpdir(), 'pullboard-pipes-')) : null;
- // Newlines, not spaces, around the command, so a trailing comment in it cannot swallow the `)`.
- const result = spawnSync(`${prefix}(\n${split ? stagedScript(split, marker, pipes) : command}\n) 2>&1`, options);
- invalidateGitFacts();
- const pipeStatuses = pipes ? readPipes(split, pipes) : null;
- if (pipes) rmSync(pipes, { recursive: true, force: true });
- const raw = `${result.stdout ?? ''}${result.stderr ?? ''}`;
- const seconds = Math.round((Date.now() - started) / 1000);
- const blocked = (output) => (result.status === 0 ? null : sandboxBlockedOperation(root, output));
- if (!stages) return { isGreen: result.status === 0, output: raw, seconds, sandboxBlocked: blocked(raw) };
- if (!split) return { isGreen: result.status === 0, output: raw, seconds, stages: null, sandboxBlocked: blocked(raw) };
- const staged = readStages(raw, marker, split.length);
- // Each pipeline component's own status rides on its stage, so no failing producer hides behind a later one.
- const withPipes = staged.stages.map((stage, index) => (pipeStatuses?.[index] ? { ...stage, pipeline: pipeStatuses[index] } : stage));
- return { isGreen: result.status === 0, seconds, ...staged, stages: withPipes, sandboxBlocked: blocked(staged.output) };
-}
-
/** Refuse an environment-blocked proof after its ordinary raw logs and timings are persisted. */
export function refuseSandboxBlocked(run) {
if (run.sandboxBlocked) throw new Refused('SANDBOX_BLOCKED',
@@ -425,79 +319,6 @@ function runTiming(run, command) {
tests: (profile.tests ?? []).map(test => ({ ...test, file: localPath(test.file) })) };
}
-/** Persist one sanitized timing profile as a private artifact.
- * @param {string} path
- * @param {{ files?: Array<object>, tests?: Array<object>, [key: string]: any }} profile
- * @returns {object} The sanitized profile written to disk.
- */
-export function writeTimingProfile(path, profile) {
- /** Sanitize one reporter-controlled string before persistence or display.
- * @param {unknown} value
- * @param {string} label
- * @returns {unknown}
- */
- const sanitize = (value, label) => {
- if (typeof value !== 'string') return value;
- if (Buffer.byteLength(value, 'utf8') > 64 * 1024) return '[redacted profile field exceeds 64 KiB safe-scan limit]';
- const findings = secretsIn([{ path: `timing profile ${label}`, line: 1, text: value }]);
- return findings.length ? `[redacted ${findings.map(finding => finding.slice(0, finding.lastIndexOf(' at '))).join(', ')}]` : value;
- };
- /** Accept only measured, nonnegative durations from reporter events. */
- const validDuration = value => Number.isFinite(value) && value >= 0;
- const files = (profile.files ?? []).filter(file => typeof file?.path === 'string' && validDuration(file.durationMs))
- .map(file => ({ path: sanitize(file.path, 'file path'), durationMs: file.durationMs }));
- const tests = (profile.tests ?? []).filter(test => (typeof test?.file === 'string' || test?.file === null) && typeof test?.name === 'string' && validDuration(test.durationMs))
- .map(test => ({ file: sanitize(test.file, 'test file'), name: sanitize(test.name, 'test name'), durationMs: test.durationMs, passed: test.passed === true }));
- const sanitized = {
- version: 1,
- waitMs: validDuration(profile.waitMs) ? profile.waitMs : 0,
- wallMs: validDuration(profile.wallMs) ? profile.wallMs : null,
- files,
- tests,
- runner: sanitize(profile.runner ?? 'shell', 'runner'),
- format: sanitize(profile.format ?? 'none', 'format'),
- unavailable: sanitize(profile.unavailable ?? null, 'availability'),
- ...(profile.executionRunner ? { executionRunner: sanitize(profile.executionRunner, 'execution runner') } : {}),
- ...(profile.receipt ? { receipt: { ...profile.receipt, slot: { kind: sanitize(profile.receipt.slot?.kind, 'slot kind'), reason: sanitize(profile.receipt.slot?.reason, 'slot reason') } } } : {}),
- ...(profile.landingShards ? { landingShards: {
- balance: sanitize(String(profile.landingShards.balance ?? 'unknown'), 'landing balance'),
- unverified: (profile.landingShards.unverified ?? []).map(entry => ({ shard: sanitize(String(entry.shard), 'landing unverified shard'),
- processes: sanitize(String(entry.processes), 'landing unverified processes') })),
- quarantined: (profile.landingShards.quarantined ?? []).map(entry => ({ host: sanitize(String(entry.host), 'landing quarantine host'),
- message: sanitize(String(entry.message), 'landing quarantine message') })),
- floor: profile.landingShards.floor && validDuration(profile.landingShards.floor.ms)
- ? { path: sanitize(String(profile.landingShards.floor.path), 'landing floor path'), ms: profile.landingShards.floor.ms } : null,
- // One entry per attempt, so a failed runner attempt stays beside its local rerun.
- shards: (profile.landingShards.shards ?? []).map(shard => ({ shard: sanitize(String(shard.shard), 'landing shard'),
- attempt: Number.isSafeInteger(shard.attempt) ? shard.attempt : 1,
- host: sanitize(String(shard.host), 'landing shard host'), status: sanitize(String(shard.status), 'landing shard status'),
- reason: shard.reason ? sanitize(String(shard.reason), 'landing shard reason') : null,
- wallMs: validDuration(shard.wallMs) ? shard.wallMs : null })),
- files: (profile.landingShards.files ?? []).filter(file => typeof file?.path === 'string').map(file => ({
- path: sanitize(file.path, 'landing file path'), shard: sanitize(String(file.shard), 'landing file shard'),
- host: sanitize(String(file.host), 'landing file host'), durationMs: validDuration(file.durationMs) ? file.durationMs : null })),
- } } : {}),
- ...(profile.executionSource ? { executionSource: {
- commit: sanitize(profile.executionSource.commit, 'execution commit'),
- tree: sanitize(profile.executionSource.tree, 'execution tree'),
- tooling: Object.fromEntries(Object.entries(profile.executionSource.tooling ?? {})
- .filter(([key]) => ['kind', 'name', 'version', 'commit', 'tree', 'sha256'].includes(key))
- .map(([key, value]) => [key, sanitize(value, `execution tooling ${key}`)])),
- } } : {}),
- };
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
- writeFileSync(path, `${JSON.stringify(sanitized, null, 2)}\n`, { mode: 0o600 });
- return sanitized;
-}
-
-/** Conservatively detect a pipe when the configured gate shell cannot enforce every stage's status. */
-function hasPipeline(command) {
- for (let index = 0; index < command.length; index += 1) {
- if (command[index] === '|' && command[index + 1] !== '|' && command[index - 1] !== '|') return true;
- }
- return false;
-}
-
/** Run work under the machine queue: landings first, then every other eligible waiter in arrival order.
* The whole queue waits while the machine is out of memory, so a run never starts into swap.
*
diff --git a/src/git.js b/src/git.js
index de73fbb1..65ac2a0e 100644
--- a/src/git.js
+++ b/src/git.js
@@ -30,6 +30,8 @@ const gitFacts = new AsyncLocalStorage();
const gitReadFacts = new AsyncLocalStorage();
const READ_FACT_LIMIT = 512;
const persistentReadFacts = new Map();
+/** Inherited Git variables that select another repository, index, object store or configuration. */
+const INHERITED_SELECTORS = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_PREFIX', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT', 'GIT_IMPLICIT_WORK_TREE', 'GIT_GRAFT_FILE', 'GIT_REPLACE_REF_BASE', 'GIT_SHALLOW_FILE'];
/** Mark API read work so selected facts use the bounded process-lifetime, filesystem-validated cache.
*
@@ -201,6 +203,28 @@ function repositorySignature(cwd, info = null, includeHead = false, { attributio
return JSON.stringify(markers);
}
+/** Whether every GIT_CONFIG_KEY_n override is one that selects no repository or Git object. */
+function safeConfigOverrides(env, count) {
+ // Identity validation and automatic housekeeping do not select repositories or Git objects.
+ const safeOverrides = new Set(['user.useconfigonly', 'gc.auto', 'maintenance.auto']);
+ for (let index = 0; index < count; index += 1) {
+ const key = env[`GIT_CONFIG_KEY_${index}`];
+ const value = env[`GIT_CONFIG_VALUE_${index}`];
+ if (!key || value === undefined || !safeOverrides.has(key.toLowerCase())) return false;
+ }
+ return true;
+}
+
+/**
+ * Whether Git run with this process's environment sees the same repository and refs as with a clean one: nothing
+ * selects another repository, object store or configuration, and config overrides are housekeeping only.
+ */
+function plainRepositoryEnvironment(env = process.env) {
+ if (INHERITED_SELECTORS.some((key) => !['GIT_CONFIG_COUNT', 'GIT_INDEX_FILE', 'GIT_PREFIX'].includes(key) && env[key] !== undefined)) return false;
+ const count = env.GIT_CONFIG_COUNT === undefined ? 0 : Number(env.GIT_CONFIG_COUNT);
+ return Number.isSafeInteger(count) && count >= 0 && count <= 16 && safeConfigOverrides(env, count);
+}
+
/** Describe relevant Git environment/config so harmless process settings can still share read facts. */
function readCacheContext({ attribution = false } = {}) {
const env = process.env;
@@ -217,13 +241,7 @@ function readCacheContext({ attribution = false } = {}) {
if (env.GIT_CONFIG_PARAMETERS) return null;
const count = env.GIT_CONFIG_COUNT === undefined ? 0 : Number(env.GIT_CONFIG_COUNT);
if (!Number.isSafeInteger(count) || count < 0 || count > 16) return null;
- // Identity validation and automatic housekeeping do not select repositories or Git objects.
- const safeOverrides = new Set(['user.useconfigonly', 'gc.auto', 'maintenance.auto']);
- for (let index = 0; index < count; index += 1) {
- const key = env[`GIT_CONFIG_KEY_${index}`];
- const value = env[`GIT_CONFIG_VALUE_${index}`];
- if (!key || value === undefined || !safeOverrides.has(key.toLowerCase())) return null;
- }
+ if (!safeConfigOverrides(env, count)) return null;
const files = new Set();
if (env.GIT_CONFIG) files.add(env.GIT_CONFIG);
if (env.GIT_CONFIG_GLOBAL) files.add(env.GIT_CONFIG_GLOBAL);
@@ -342,7 +360,8 @@ function changesGitFacts(args) {
*/
export function cleanGitEnvironment() {
const env = { ...process.env };
- for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_PREFIX', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT', 'GIT_IMPLICIT_WORK_TREE', 'GIT_GRAFT_FILE', 'GIT_NO_REPLACE_OBJECTS', 'GIT_REPLACE_REF_BASE', 'GIT_SHALLOW_FILE']) delete env[key];
+ for (const key of INHERITED_SELECTORS) delete env[key];
+ delete env.GIT_NO_REPLACE_OBJECTS;
for (const key of Object.keys(env)) if (/^GIT_CONFIG_(?:KEY|VALUE)_/.test(key)) delete env[key];
env.GIT_NO_REPLACE_OBJECTS = '1';
return env;
@@ -512,14 +531,27 @@ export function repoInfo(cwd, { env } = {}) {
return fact(key, () => readRepoInfo(cwd));
}
-/** Read top level, worktree Git dir and shared Git dir in one process.
+/**
+ * Read top level, worktree Git dir and shared Git dir in one process. With no inherited selector, the same process
+ * also reads the primary checkout's branch and commit and keeps them as this command's mainCheckout fact, so a
+ * command learns where it is and what the trunk is from one Git call.
*
* @param {string} cwd
* @returns {{ root: string, commonDir: string, gitDir: string, isMain: boolean }}
*/
function readRepoInfo(cwd, env) {
- const info = tryGit(cwd, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir'], { env });
+ const combined = !env && gitFacts.getStore()?.active && plainRepositoryEnvironment();
+ const primary = combined ? ['main-worktree/HEAD', '--symbolic-full-name', 'main-worktree/HEAD'] : [];
+ const info = tryGit(cwd, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir', ...primary], { env });
+ // An unborn primary branch fails the combined call after the paths; ask for the paths alone, as before.
+ if (combined && info.status !== 0 && info.stdout) return readRepoInfo(cwd, process.env);
const fields = info.stdout.split('\n');
+ if (combined && info.status === 0 && fields.length === 5 && fields.every(Boolean)) {
+ const [root, , , commit, branch] = fields;
+ // A detached primary checkout names no branch, as symbolic-ref reports it.
+ gitFacts.getStore().facts.set(`mainCheckout:${resolve(root)}`, branch.startsWith('refs/') ? { branch, commit } : null);
+ fields.length = 3;
+ }
if (info.status !== 0 || fields.length !== 3 || fields.some((field) => !field)) {
const bare = bareWorktreeFinding(cwd);
if (bare) throw new Refused(bare.code, `${bare.message}; run ${bare.next}`);
diff --git a/src/local-state.js b/src/local-state.js
new file mode 100644
index 00000000..3000a875
--- /dev/null
+++ b/src/local-state.js
@@ -0,0 +1,78 @@
+/**
+ * Where this machine and this repository keep relay links, relay keys and pending baseline results, and whether any
+ * exists. A command around which none exists has no relay or baseline work to do, so it never loads those modules
+ * [C7].
+ */
+import {
+ existsSync,
+ readdirSync,
+} from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { repoInfo } from './git.js';
+import { Refused } from './refused.js';
+
+/** A pending baseline result's file name: one per request id. */
+export const BASELINE_RECEIPT = /^[a-f0-9-]{36}\.json$/;
+
+/** This machine's private pullboard folder, outside every repository. */
+export function pullboardHome() {
+ return process.env.PULLBOARD_HOME || join(homedir(), '.pullboard');
+}
+
+/** The machine's relay settings folder. */
+export function relayMachineDirectory() {
+ return join(pullboardHome(), 'relay-machine');
+}
+
+/** The machine's relay key folder. */
+export function relayKeyDirectory() {
+ return join(pullboardHome(), 'relay-keys');
+}
+
+/** A repository's relay link, beside its board in the shared Git directory. */
+export function relayLinkFile(commonDir) {
+ return join(commonDir, 'pullboard', 'relay.json');
+}
+
+/** A repository's notice that its relay copy was deleted, which relay status still reads. */
+export function relayDeletedFile(commonDir) {
+ return join(commonDir, 'pullboard', 'relay-deleted.json');
+}
+
+/** A repository's relay link and deleted-copy notice, for the relay client that reads and writes them. */
+export function relayFiles(commonDir) {
+ return { link: relayLinkFile(commonDir), deleted: relayDeletedFile(commonDir) };
+}
+
+/** Whether a repository has relay state to read: a link, or the notice of a deleted copy. */
+export function relayStateExists(commonDir) {
+ return existsSync(relayLinkFile(commonDir)) || existsSync(relayDeletedFile(commonDir));
+}
+
+/** A repository's baseline results that finished after their command exited. */
+export function baselineReceiptDirectory(commonDir) {
+ return join(commonDir, 'pullboard', 'baseline-results');
+}
+
+/**
+ * Whether the relay sync, auto-link, person requests or baseline delivery around a command could do anything here:
+ * a relay token in the environment, relay state on this machine, a relay link, or a pending baseline result. False
+ * only when each of them would return without acting, so skipping them changes nothing.
+ *
+ * @param {string} cwd
+ * @returns {boolean}
+ */
+export function syncMayAct(cwd) {
+ if (process.env.PULLBOARD_RELAY_TOKEN !== undefined && process.env.PULLBOARD_RELAY_KEY !== undefined) return true;
+ if (existsSync(relayMachineDirectory()) || existsSync(relayKeyDirectory())) return true;
+ let info;
+ try { info = repoInfo(cwd); }
+ catch (error) {
+ // Outside a repository every step refuses quietly with these codes; any other failure takes the full path.
+ return !(error instanceof Refused && ['NOT_A_REPO', 'CORE_BARE'].includes(error.code));
+ }
+ if (existsSync(relayLinkFile(info.commonDir))) return true;
+ const receipts = baselineReceiptDirectory(info.commonDir);
+ return existsSync(receipts) && readdirSync(receipts).some((name) => BASELINE_RECEIPT.test(name));
+}
diff --git a/src/relay-key.js b/src/relay-key.js
index f2831128..ac309d32 100644
--- a/src/relay-key.js
+++ b/src/relay-key.js
@@ -11,12 +11,12 @@ import {
rmSync,
writeFileSync,
} from 'node:fs';
-import { homedir } from 'node:os';
import { join } from 'node:path';
import {
decodeBoardKey,
encodeBoardKey,
} from './seal.js';
+import { relayKeyDirectory } from './local-state.js';
import { Refused } from './refused.js';
/** Validate a persistent board identity before using it as a file or credential name. */
@@ -27,7 +27,7 @@ function identity(boardId) {
/** Locate the owner-only key under the machine pullboard home, outside repositories. */
function keyFile(boardId) {
- return join(process.env.PULLBOARD_HOME || join(homedir(), '.pullboard'), 'relay-keys', identity(boardId) + '.key');
+ return join(relayKeyDirectory(), identity(boardId) + '.key');
}
/** Probe an available operating-system credential service without requiring a particular shell. */
diff --git a/src/relay-machine.js b/src/relay-machine.js
index d5582659..e8df3d0f 100644
--- a/src/relay-machine.js
+++ b/src/relay-machine.js
@@ -13,7 +13,6 @@ import {
rmSync,
writeFileSync,
} from 'node:fs';
-import { homedir } from 'node:os';
import { join } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import {
@@ -24,13 +23,14 @@ import {
import { scrubLegacyPersonSessions } from './relay-key.js';
import { approvalContext } from './relay-approval.js';
import { createPairingCode } from './pairing.js';
+import { relayMachineDirectory } from './local-state.js';
import { Refused } from './refused.js';
const DEVICE = /^device-[0-9a-f]{32}$/u;
/** Locate only the private machine directory; repositories never carry these credentials. */
function directory() {
- return join(process.env.PULLBOARD_HOME || join(homedir(), '.pullboard'), 'relay-machine');
+ return relayMachineDirectory();
}
/** Refuse symlinks, non-owner files or broader permissions before reading machine secrets. */
diff --git a/src/relay.js b/src/relay.js
index 00128d46..1665faea 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -63,10 +63,7 @@ import {
withSeatName,
} from './relay-seats.js';
import { syncApprovers } from './relay-approvers.js';
-import {
- ENGINE_VERSION,
- VERIFIER_STANDING_ENGINE,
-} from './machine.js';
+import { ENGINE_VERSION } from './machine.js';
import {
presentationDigest,
relayPresentation,
@@ -109,6 +106,7 @@ import {
queueMove,
} from './relay-outbox.js';
import { stampCoordinatorHolder } from './coordinator-hold.js';
+import { relayFiles } from './local-state.js';
import { Refused } from './refused.js';
import { refusalFromReceipt } from './recorded-refusal.js';
import { relayNotices } from './relay-notices.js';
@@ -189,10 +187,10 @@ export function originRepository(root, { optional = false } = {}) {
return repository;
}
/** Find the shared local link metadata without opening a board or connecting for an unlinked repo. */
-function linkFile(root) { return join(repoInfo(root).commonDir, 'pullboard', 'relay.json'); }
+function linkFile(root) { return relayFiles(repoInfo(root).commonDir).link; }
/** Locate the credential-free reason an independently deleted copy no longer syncs. */
-function deletedLinkFile(root) { return join(repoInfo(root).commonDir, 'pullboard', 'relay-deleted.json'); }
+function deletedLinkFile(root) { return relayFiles(repoInfo(root).commonDir).deleted; }
/** Read only a private, bounded deletion marker; it never supplies credentials or an outbound destination. */
function deletedLink(root) {
diff --git a/src/rigor-quality-draft.js b/src/rigor-quality-draft.js
index 582ba1f2..6affda01 100644
--- a/src/rigor-quality-draft.js
+++ b/src/rigor-quality-draft.js
@@ -17,15 +17,6 @@ import {
} from './rigor-quality.js';
import { draftRow } from './spec-draft.js';
-/** The flags these commands add to the CLI's option table. */
-export const QUALITY_OPTIONS = {
- base: { type: 'string' },
- head: { type: 'string' },
- rule: { type: 'string' },
- budget: { type: 'string' },
- 'draft-quality': { type: 'boolean' },
-};
-
/** The source a drafted quality row carries, so a rerun finds it whatever the person decided. */
export function qualitySource(key) {
return `rigor-quality:${key}`;
diff --git a/src/sentinel-command.js b/src/sentinel-command.js
index e376e9f0..51f0d8c2 100644
--- a/src/sentinel-command.js
+++ b/src/sentinel-command.js
@@ -6,16 +6,6 @@ import { sentinels } from './sentinels.js';
import { runDueSentinels } from './sentinel-runner.js';
import { healthSentinelEnabled } from './settings.js';
-/** The watch command's existing string options, shared with the CLI parser. */
-export const SENTINEL_OPTIONS = {
- every: { type: 'string' },
- owner: { type: 'string' },
- directory: { type: 'string' },
- timeout: { type: 'string' },
- next: { type: 'string' },
- sentinel: { type: 'boolean' },
-};
-
/** Run due approved watches from ordinary resume, respecting the health switches. */
export async function resumeSentinels({ ctx, withBoard, whoAmI, ordered }) {
return withBoard(ctx, async board => {
diff --git a/src/shell-run.js b/src/shell-run.js
new file mode 100644
index 00000000..a8d8aaaa
--- /dev/null
+++ b/src/shell-run.js
@@ -0,0 +1,73 @@
+/**
+ * Run one shell command in a checkout and keep its output, apart from the gate's queue, runners and receipts. A
+ * board read that replays a check baseline needs only this, so it never loads the gate [C7].
+ */
+import { spawnSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import {
+ mkdtempSync,
+ rmSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ gitChildEnv,
+ invalidateGitFacts,
+} from './git.js';
+import {
+ gateStages,
+ readPipes,
+ readStages,
+ stagedScript,
+} from './gate-stages.js';
+import { Refused } from './refused.js';
+import { sandboxBlockedOperation } from './sandbox-denial.js';
+
+/**
+ * Run a shell command in a checkout for a digest: both streams in one pipe, in order, read whole
+ * however long, stdin closed so nothing waits on a person. With `stages`, each top-level stage's
+ * exit status and own output are kept too, or `stages` is null when the command cannot be split.
+ *
+ * @param {string} root
+ * @param {string} command
+ * @param {{ pipefail?: boolean, env?: NodeJS.ProcessEnv, stages?: boolean }} [options] - Gate-only pipefail, additional child environment values and per-stage accounting.
+ * @returns {{ isGreen: boolean, output: string, seconds: number, sandboxBlocked: string|null, stages?: Array<{ status: number|null, output: string, pipeline?: Array<{ status: number|null, output: string|null }> }> | null }}
+ */
+export function runShell(root, command, { pipefail = false, env = {}, stages = false } = {}) {
+ const started = Date.now();
+ const options = { cwd: root, env: { ...gitChildEnv(root), ...env }, shell: true, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', maxBuffer: 2 ** 30 };
+ let prefix = '';
+ if (pipefail) {
+ // Probe the same shell as the command, with no load-sensitive deadline or alternate shell.
+ const probe = spawnSync('set -o pipefail', options);
+ if (probe.status === 0) prefix = 'set -o pipefail\n';
+ else if (hasPipeline(command)) {
+ throw new Refused('PIPEFAIL_UNAVAILABLE', 'the repo gate shell cannot enable pipefail; rewrite the gate without a pipe');
+ }
+ }
+ const split = stages ? gateStages(command) : null;
+ const marker = `PULLBOARD_STAGE_${randomUUID().replaceAll('-', '')}`;
+ const pipes = split?.some((stage) => stage.pipeline.length > 1) ? mkdtempSync(join(tmpdir(), 'pullboard-pipes-')) : null;
+ // Newlines, not spaces, around the command, so a trailing comment in it cannot swallow the `)`.
+ const result = spawnSync(`${prefix}(\n${split ? stagedScript(split, marker, pipes) : command}\n) 2>&1`, options);
+ invalidateGitFacts();
+ const pipeStatuses = pipes ? readPipes(split, pipes) : null;
+ if (pipes) rmSync(pipes, { recursive: true, force: true });
+ const raw = `${result.stdout ?? ''}${result.stderr ?? ''}`;
+ const seconds = Math.round((Date.now() - started) / 1000);
+ const blocked = (output) => (result.status === 0 ? null : sandboxBlockedOperation(root, output));
+ if (!stages) return { isGreen: result.status === 0, output: raw, seconds, sandboxBlocked: blocked(raw) };
+ if (!split) return { isGreen: result.status === 0, output: raw, seconds, stages: null, sandboxBlocked: blocked(raw) };
+ const staged = readStages(raw, marker, split.length);
+ // Each pipeline component's own status rides on its stage, so no failing producer hides behind a later one.
+ const withPipes = staged.stages.map((stage, index) => (pipeStatuses?.[index] ? { ...stage, pipeline: pipeStatuses[index] } : stage));
+ return { isGreen: result.status === 0, seconds, ...staged, stages: withPipes, sandboxBlocked: blocked(staged.output) };
+}
+
+/** Conservatively detect a pipe when the configured gate shell cannot enforce every stage's status. */
+function hasPipeline(command) {
+ for (let index = 0; index < command.length; index += 1) {
+ if (command[index] === '|' && command[index + 1] !== '|' && command[index - 1] !== '|') return true;
+ }
+ return false;
+}
diff --git a/src/trusted-policy.js b/src/trusted-policy.js
index 5fc1da6c..e103fcb3 100644
--- a/src/trusted-policy.js
+++ b/src/trusted-policy.js
@@ -3,9 +3,9 @@ import { randomUUID } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import {
digestOf,
- sandboxBlockedScanner,
writeTimingProfile,
-} from './gate.js';
+} from './gate-output.js';
+import { sandboxBlockedScanner } from './sandbox-denial.js';
import {
timingFromOutput,
timingFromLog,
diff --git a/test/api.test.js b/test/api.test.js
index cd422324..28f5ee22 100644
--- a/test/api.test.js
+++ b/test/api.test.js
@@ -551,7 +551,7 @@ test('[A5, A6] a future-schema worktree cannot migrate the shared board; main ca
box.git(repo, 'worktree', 'add', '-q', unguarded, '-b', 'schema/unguarded', 'schema/future');
const guardedSource = join(unguarded, 'src/board.js');
const guardedText = readFileSync(guardedSource, 'utf8');
- const unguardedText = guardedText.replace(/ if \(file !== ':memory:' && isMain === false\) \{[\s\S]*?\n \}\n(?= if \(file !== ':memory:'\) mkdirSync)/, '');
+ const unguardedText = guardedText.replace(/ if \(file !== ':memory:' && \(isMain === false \|\| typeof isMain === 'function'\)\) \{[\s\S]*?\n \}\n(?= if \(file !== ':memory:'\) mkdirSync)/, '');
assert.notEqual(unguardedText, guardedText, 'the mutation removes only the unmerged-schema guard');
writeFileSync(guardedSource, unguardedText);
const mutationProbe = join(unguarded, '.schema-mutation-probe.mjs');
diff --git a/test/cli-help.test.js b/test/cli-help.test.js
index 81d0f6de..9f57450d 100644
--- a/test/cli-help.test.js
+++ b/test/cli-help.test.js
@@ -1,5 +1,5 @@
/** @pullboard-test-input source-tree */
-/** @pullboard-test-loads src/cli.js src/commands/*.js */
+/** @pullboard-test-loads src/cli.js src/cli-help.js src/cli-main.js src/commands/*.js */
/** The layered CLI help stays short, command-specific, and in parity with its declaration [N37,I1]. */
import assert from 'node:assert/strict';
import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
@@ -176,7 +176,8 @@ test('help names come from the command declarations [C7,N37]', async (t) => {
assert.equal(generated.overview, HELP.overview, 'a new declaration preserves the overview bytes');
assert.equal(generated.all, HELP.all, 'a new declaration preserves the full-help bytes');
- const original = readFileSync(join(directory, 'cli.js'), 'utf8');
+ // Help and the result-command list are built in cli-help.js, from the same registry dispatch reads.
+ const original = readFileSync(join(directory, 'cli-help.js'), 'utf8');
const registryUrl = 'data:text/javascript;base64,' + Buffer.from([
`import { COMMANDS as actual, UNLISTED_COMMANDS } from ${JSON.stringify(pathToFileURL(join(directory, 'commands/index.js')).href)};`,
"/** A private new command proves help follows actual dispatch declarations. */",
@@ -282,7 +283,9 @@ test('every command comes from its own module [C7,V4]', async () => {
for (const name of [...resultCommands(), 'mcp']) assert.ok(names.includes(name), `${name} comes from its own module`);
const cli = readFileSync(join(source, 'cli.js'), 'utf8');
assert.doesNotMatch(cli, /function (?:setup|read|work)Commands\(/u, 'src/cli.js holds no command table');
- const dispatch = cli.slice(cli.indexOf('async function runCommand('), cli.indexOf('\n}\n', cli.indexOf('async function runCommand(')));
+ // Dispatch lives in cli-main.js, the entry that loads only the command in hand.
+ const entry = readFileSync(join(source, 'cli-main.js'), 'utf8');
+ const dispatch = entry.slice(entry.indexOf('async function runCommand('), entry.indexOf('\n}\n', entry.indexOf('async function runCommand(')));
assert.ok(dispatch.includes('COMMANDS[command]'), 'runCommand looks the command up in the registry');
assert.doesNotMatch(dispatch, /if \(command === '[a-z-]+'(?: && [^)]*)?\) /u, 'runCommand holds no command of its own');
for (const file of files) {
diff --git a/test/cli-startup.test.js b/test/cli-startup.test.js
new file mode 100644
index 00000000..8b55652c
--- /dev/null
+++ b/test/cli-startup.test.js
@@ -0,0 +1,114 @@
+/** @pullboard-test-input source-tree */
+/**
+ * A command pays only for its own modules and asks Git for repository facts once: the real CLI runs under a
+ * module-load hook and a counting Git shim, so the count is what a person's terminal and the git hooks pay [C7].
+ */
+import assert from 'node:assert/strict';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { delimiter, join, resolve, sep } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { test } from 'node:test';
+import { runFixtureChild } from './fixture-child.js';
+
+const REPO = resolve(import.meta.dirname, '..');
+const BIN = join(REPO, 'bin', 'pullboard.js');
+/** Modules a read must never load: the gate runner, the relay client and the landing machinery. */
+const HEAVY = ['src/gate.js', 'src/relay.js', 'src/land.js', 'src/commands/gate.js', 'src/commands/relay.js', 'src/commands/land.js'];
+
+/** Find the real Git executable before the fixture puts its counting shim first on PATH. */
+function realGitPath() {
+ const found = process.env.PATH.split(delimiter).map((entry) => join(entry || '.', 'git')).find((candidate) => existsSync(candidate));
+ assert.ok(found, 'the test environment has Git on PATH');
+ return found;
+}
+
+/**
+ * A module preloaded with --import that records every file module the process loads. Node 22.15 and newer take
+ * in-thread hooks; 22.13 takes the off-thread loader, which writes the same log.
+ */
+function moduleHook(dir) {
+ const loader = join(dir, 'module-loader.mjs');
+ const record = `if (url.startsWith('file:')) appendFileSync(process.env.PULLBOARD_MODULE_LOG, url + '\\n');`;
+ writeFileSync(loader, [
+ "import { appendFileSync } from 'node:fs';",
+ `export async function load(url, context, next) { ${record} return next(url, context); }`,
+ ].join('\n'));
+ const hook = join(dir, 'module-hook.mjs');
+ writeFileSync(hook, [
+ "import module from 'node:module';",
+ "import { appendFileSync } from 'node:fs';",
+ 'if (module.registerHooks) {',
+ ` module.registerHooks({ load(url, context, next) { ${record} return next(url, context); } });`,
+ `} else module.register(${JSON.stringify(new URL(`file://${loader}`).href)});`,
+ ].join('\n'));
+ return hook;
+}
+
+/** A real coordinator repo with one item on its board, a counting Git shim and a module-load hook. */
+function fixture(t) {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-startup-')));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const repo = join(dir, 'repo');
+ const shims = join(dir, 'shims');
+ const home = join(dir, 'home');
+ mkdirSync(repo);
+ mkdirSync(shims);
+ writeFileSync(join(shims, 'git'), '#!/bin/sh\nprintf "%s\\n" "$*" >> "$PULLBOARD_GIT_CALLS"\nexec "$PULLBOARD_REAL_GIT" "$@"\n');
+ chmodSync(join(shims, 'git'), 0o755);
+ // The repository's git hooks run pullboard from PATH; they must run this checkout, not an installed release.
+ writeFileSync(join(shims, 'pullboard'), `#!/bin/sh\nexec '${process.execPath}' '${BIN}' "$@"\n`);
+ chmodSync(join(shims, 'pullboard'), 0o755);
+ const env = {
+ ...process.env,
+ HOME: home,
+ PULLBOARD_HOME: join(home, '.pullboard'),
+ PULLBOARD_MACHINE_HOME: join(home, '.pullboard-machine'),
+ PULLBOARD_GIT_CALLS: join(dir, 'git-calls.log'),
+ PULLBOARD_MODULE_LOG: join(dir, 'modules.log'),
+ PULLBOARD_REAL_GIT: realGitPath(),
+ PATH: `${shims}${delimiter}${process.env.PATH}`,
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Test Agent',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Test Agent',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ };
+ for (const name of ['PULLBOARD_RELAY_TOKEN', 'PULLBOARD_RELAY_KEY']) delete env[name];
+ const hook = moduleHook(dir);
+ /** Run the real CLI and return its result with the modules it loaded and the Git processes it started. */
+ const run = (...args) => {
+ writeFileSync(env.PULLBOARD_GIT_CALLS, '');
+ writeFileSync(env.PULLBOARD_MODULE_LOG, '');
+ const result = runFixtureChild(process.execPath, ['--import', hook, BIN, ...args], { cwd: repo, env, encoding: 'utf8' });
+ assert.equal(result.status, 0, `${args.join(' ')}: ${result.stdout}${result.stderr}`);
+ const modules = [...new Set(readFileSync(env.PULLBOARD_MODULE_LOG, 'utf8').split('\n').filter(Boolean))]
+ .map((url) => fileURLToPath(url)).filter((path) => path.startsWith(REPO + sep)).map((path) => path.slice(REPO.length + 1).split(sep).join('/'));
+ const gitCalls = readFileSync(env.PULLBOARD_GIT_CALLS, 'utf8').split('\n').filter(Boolean);
+ return { ...result, modules, gitCalls };
+ };
+ const git = (...args) => assert.equal(runFixtureChild(env.PULLBOARD_REAL_GIT, args, { cwd: repo, env, encoding: 'utf8' }).status, 0);
+ git('init', '-q', '-b', 'main');
+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({
+ spec: 'SPEC.md', practice: 'DOCTRINE.md', gate: 'true', lanes: { core: { owns: ['src/'], specs: ['C7'] } },
+ }));
+ writeFileSync(join(repo, 'SPEC.md'), '# Test spec\n\n## C · Core\n- C7 [approved, must] A command loads only its own modules. | gate: test/cli-startup.test.js\n');
+ run('init');
+ git('add', '-A');
+ git('commit', '-q', '-m', 'chore(repo): set up the startup fixture');
+ run('add', 'core', 'Show me', '--specs', 'C7', '--criterion', 'it shows', '--brief', 'Files: src/a.js\nTest: it shows.');
+ return { run };
+}
+
+test('a read command loads only its own modules [C7]', (t) => {
+ const box = fixture(t);
+ const version = box.run('--version');
+ assert.match(version.stdout, /^\d+\.\d+\.\d+/u);
+ assert.ok(version.modules.length <= 10, `--version loaded ${version.modules.length} repository modules: ${version.modules.join(', ')}`);
+ assert.equal(version.gitCalls.length, 0, `--version started Git: ${version.gitCalls.join(' | ')}`);
+ const show = box.run('show', '1');
+ assert.match(show.stdout, /^#1 {2}/u);
+ assert.deepEqual(show.modules.filter((path) => HEAVY.includes(path)), [], 'show loads no gate, relay or land module');
+ assert.ok(show.gitCalls.length <= 2, `show started ${show.gitCalls.length} Git processes: ${show.gitCalls.join(' | ')}`);
+});