Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
Merge accepted main while retaining lazy read dispatch
Corey Olsonc520f79052fd
diff --cc src/board-read.jsindex 00000000,f68bb918..144e5d1dmode 000000,100644..100644--- a/src/board-read.js+++ b/src/board-read.js@@@ -1,0 -1,28 +1,28 @@@+ /** The read-only board open for commands that only read, kept beside cli.js's withBoard [C7]. */+ import * as store from './board.js';-import { withBoard } from './cli.js';++import { withBoard } from './cli-context.js';+ import { Refused } from './refused.js';++ /**+ * withBoard for a command that only reads: the board opens read-only, without the write lock, and a+ * read never migrates it (#1047). A board this code has not migrated is read as it is; only the next+ * command that writes upgrades it. Branch code keeps withBoard's schema guard, which never migrates+ * a shared board either. Work that writes after all (a first coordinator registration) runs again+ * through withBoard on a current board; SQLite refused the write, so nothing ran twice.+ *+ * @template T+ * @param {any} ctx+ * @param {(board: any) => T} work+ * @returns {T}+ */+ export function withBoardRead(ctx, work) {+ const board = store.openBoardForRead(ctx.file, ctx.clock);+ if (board && !board.current && !ctx.allowSchemaUpgrade) store.closeBoard(board);+ if (!board || (!board.current && !ctx.allowSchemaUpgrade)) return withBoard(ctx, work);+ try { return withBoard(ctx, work, board); }+ catch (error) {+ if (board.current && store.writeRefused(error)) return withBoard(ctx, work);+ if (!store.writeRefused(error) && !store.schemaMissing(error)) throw error;+ throw new Refused('BOARD_SCHEMA_BEHIND', 'this board was made by an older pullboard and a read never upgrades it');+ }+ }diff --cc src/cli-context.jsindex 9c810476,00000000..e38fe906mode 100644,000000..100644--- a/src/cli-context.js+++ b/src/cli-context.js@@@ -1,300 -1,0 +1,301 @@@+/**+ * 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++ * @param {any} [opened] an already-open board, as withBoardRead passes+ * @returns {T}+ */- export function withBoard(ctx, work) {- const board = store.openBoard(ctx.file, ctx.clock, { isMain: ctx.allowSchemaUpgrade,++export function withBoard(ctx, work, opened) {++ const board = opened ?? store.openBoard(ctx.file, ctx.clock, { isMain: ctx.allowSchemaUpgrade,+ /** Report each source mismatch once through this invocation's text or JSON diagnostics. */+ onDiagnostic(message) {+ ctx.io.schemaDiagnostics ??= new Set();+ const key = ctx.file + '\n' + message;+ if (ctx.io.schemaDiagnostics.has(key)) return;+ ctx.io.schemaDiagnostics.add(key);+ ctx.io.err(message);+ },+ });+ // 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}`,+ };+}++/**+ * How long ago an ISO time was, or how long until it, in the board's clock: 45m, 3h, 2d.+ *+ * @param {any} ctx+ * @param {string} iso+ * @returns {string}+ */+export function span(ctx, iso) {+ const minutes = Math.round(Math.abs(ctx.clock.now().getTime() - Date.parse(iso)) / 60_000);+ if (minutes < 60) return `${minutes}m`;+ if (minutes < 48 * 60) return `${Math.round(minutes / 60)}h`;+ return `${Math.round(minutes / 1440)}d`;+}diff --cc src/cli.jsindex 2896038a,b624b67a..0afb2a0f--- a/src/cli.js+++ b/src/cli.js@@@ -30,10 -31,11 +30,9 @@@ importresolve,} from 'node:path';import { pathToFileURL } from 'node:url';-import { parseArgs } from 'node:util';import {mainLaneWork,- reviewQueueLine,refuseNextIdle,- reportBlock,} from './next-steps.js';import { reviewerStartup } from './next-steps.js';import { environmentAgent } from './relay-environment.js';@@@ -43,7 -45,13 +42,9 @@@ import * as itemSessions from './item-simport * as seatCheckout from './seat-checkout.js';import { submitPreflight } from './submit-preflight.js';import * as store from './board.js';+ import { withBoardRead } from './board-read.js';+ export { withBoardRead };import * as nativeFlakes from './native-flake-cli.js';-import {- COMMANDS,- UNLISTED_COMMANDS,-} from './commands/index.js';import {hookRead,readStdin,diff --cc src/commands/list.jsindex ec87bc80,f1cf9d51..5b3e7795--- a/src/commands/list.js+++ b/src/commands/list.js@@@ -1,3 -1,3 +1,4 @@@++import { withBoardRead } from '../board-read.js';/** The pullboard list command, in its own module so an item adding another command never edits these lines. */import * as store from '../board.js';import {@@@ -10,8 -10,8 +11,7 @@@ importagentDisplayName,context,itemLine,- withBoard,- withBoardRead,-} from '../cli.js';+} from '../cli-context.js';/** Run `pullboard list` and return its exit code. */export function run(io, { first, values }) {diff --cc src/commands/show.jsindex a337e84e,1bded843..30055ff9--- a/src/commands/show.js+++ b/src/commands/show.js@@@ -1,3 -1,3 +1,4 @@@++import { withBoardRead } from '../board-read.js';/** The pullboard show command, in its own module so an item adding another command never edits these lines. */import {displayAgentName,@@@ -31,15 -31,15 +32,14 @@@ importidArg,itemLine,sayBrief,- withBoard,- withBoardRead,-} 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) => ({+ const { item, verdicts, moves, thread, related, reviewer, agents, mainMerge, infra, approval } = withBoardRead(ctx, (board) => ({item: verdictProjector(ctx.info.root, board).project(store.getItem(board, id)),verdicts: store.verdictsFor(board, id),moves: store.events(board, { itemId: id }).filter((event) => ['attempt', 'escalate'].includes(event.event_kind)),diff --cc src/commands/status.jsindex a8e2e491,fc3c0bf0..9c60219f--- a/src/commands/status.js+++ b/src/commands/status.js@@@ -1,9 -1,6 +1,10 @@@++import { withBoardRead } from '../board-read.js';/** The pullboard status command, in its own module so an item adding another command never edits these lines. */import * as store from '../board.js';-import { personNeedsSummary } from '../needs-state.js';+import { personNeedsSummary } from '../needs-summary.js';+import { identifyCaller } from '../cli-identity.js';+import { relayStateExists } from '../local-state.js';+import { unlinkedRelayStatus } from '../relay-status-fields.js';import {reviewQueueLine,} from '../next-steps.js';@@@ -22,22 -23,18 +23,21 @@@ importimport {context,span,- withBoard,- whoAmI,- withBoardRead,-} from '../cli.js';+} from '../cli-context.js';/** Run `pullboard status` and return its exit code. */-export function run(io, { values }) {+export async function run(io, { values }) {const ctx = context(io);+ const hasRelayState = relayStateExists(ctx.info.commonDir);+ const relay = hasRelayState ? await import('../relay.js') : null;+ const environment = hasRelayState && process.env.PULLBOARD_RELAY_TOKEN !== undefined+ ? await import('../relay-environment.js') : null;- const summary = withBoard(ctx, (board) => {+ const summary = withBoardRead(ctx, (board) => {- const me = whoAmI(ctx, board);+ const me = identifyCaller(ctx, board, { environmentAgent: environment?.environmentAgent ?? (() => null),+ relayLinked: relay?.relayLinked ?? (() => false) });const mine = store.listItems(board).filter((item) => item.item_status === 'claimed' && item.item_owner === me.id);const approvalState = personNeedsSummary(ctx.info.root, { board, config: ctx.config });- return { me, mine, needs: approvalState.needs, specApprovalBaseline: approvalState.specApprovalBaseline, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relayStatus(ctx.info.root),+ return { me, mine, needs: approvalState.needs, specApprovalBaseline: approvalState.specApprovalBaseline, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relay ? relay.relayStatus(ctx.info.root) : unlinkedRelayStatus(),submitInvariantProposals: submitInvariantProposals(store.eventsOfKinds(board, ['submit', 'landing_batch']), ctx.config) };});if (values.json) {diff --cc src/relay.jsindex c225fbad,4bb74bfd..440d1d2a--- a/src/relay.js+++ b/src/relay.js@@@ -112,8 -109,10 +112,11 @@@ importqueueMove,} from './relay-outbox.js';import { stampCoordinatorHolder } from './coordinator-hold.js';+import { relayFiles } from './local-state.js';import { Refused } from './refused.js';+ import { landingRelayCallbacks } from './landing-relay.js';+ import { relayOrigin } from './relay-origin.js';+ export { relayOrigin };import { refusalFromReceipt } from './recorded-refusal.js';import { relayNotices } from './relay-notices.js';import {@@@ -160,21 -159,33 +163,11 @@@ const DELETION_NOTICES = new WeakSet()const ORDERED_MOVE_COMMANDS = new Set(['add', 'edit', 'fact', 'escalate', 'run', 'sweep', 'next', 'claim', 'hold', 'release','submit', 'done', 'verify', 'merged', 'land', 'withdraw', 'refreeze', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget', 'join', 'worktree']);- /** Require a trusted origin; HTTP exists only for loopback development and test relays. */- export function relayOrigin(address) {- let url;- try { url = new URL(address); } catch { throw new Refused('RELAY_URL', 'use an HTTPS relay address, such as https://app.pullboard.dev'); }- if (url.username || url.password || url.search || url.hash || url.pathname !== '/' ||- (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))) {- throw new Refused('RELAY_URL', 'use an HTTPS origin without credentials, a path, query or fragment; loopback HTTP is allowed for a local relay');-/** Resolve the actual GitHub origin; optional discovery leaves ineligible local projects alone. */-export function originRepository(root, { optional = false } = {}) {- const remote = tryGit(root, ['remote', 'get-url', 'origin']);- if (remote.status !== 0 && optional) return null;- if (remote.status !== 0) throw new Refused('RELAY_ORIGIN', 'add a GitHub origin remote before running pullboard relay on');- let repository;- const ssh = /^git@github\.com:([^\s?#]+)$/.exec(remote.stdout);- if (ssh) repository = ssh[1];- else {- try {- const url = new URL(remote.stdout);- if (url.hostname === 'github.com' && !url.password && !url.search && !url.hash &&- ((url.protocol === 'https:' && !url.username) || (url.protocol === 'ssh:' && url.username === 'git')) && !url.port) repository = url.pathname.slice(1);- } catch { /* A local path or another host is not a GitHub repository. */ }-- }- return url.origin;- repository = repository?.replace(/\.git$/, '');- if (!repository || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || repository.split('/').some((part) => ['.', '..'].includes(part))) {- if (optional) return null;- throw new Refused('RELAY_ORIGIN', 'origin must name a GitHub owner/repository using HTTPS or git SSH; fix origin and run pullboard relay on');- }- 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 --cc test/cli-startup.test.jsindex f440f596,00000000..1fffb46cmode 100644,000000..100644--- a/test/cli-startup.test.js+++ b/test/cli-startup.test.js@@@ -1,130 -1,0 +1,136 @@@+/** @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';+import { assertStartupBudgets } from './cli-startup-budget-fixture.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);+ // Each line names the folder Git ran in, then its arguments, so a count can tell this repository from the code's own.+ writeFileSync(join(shims, 'git'), '#!/bin/sh\nprintf "%s\\t%s\\n" "$(pwd -P)" "$*" >> "$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 runIn = (cwd, ...args) => {+ writeFileSync(env.PULLBOARD_GIT_CALLS, '');+ writeFileSync(env.PULLBOARD_MODULE_LOG, '');+ const result = runFixtureChild(process.execPath, ['--import', hook, BIN, ...args], { cwd, 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 run = (...args) => runIn(repo, ...args);+ 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.');+ const worktree = join(dir, 'core-1');+ git('worktree', 'add', '-q', '-b', 'core/one', worktree);+ runIn(worktree, 'join', 'core', '--model', 'test-model');+ return { run, runIn, worktree };+}++test('a read command loads only its own modules [C7]', async (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(' | ')}`);++ const status = box.run('status', '--json');++ assert.equal(JSON.parse(status.stdout).stats.items.open, 1);++ assert.deepEqual(status.modules.filter((path) => HEAVY.includes(path)), [], 'offline status loads no gate, relay or land module');++ const list = box.run('list', '--json');++ assert.equal(JSON.parse(list.stdout).items.length, 1);++ assert.deepEqual(list.modules.filter((path) => HEAVY.includes(path)), [], 'list loads no gate, relay or land module');+ // One rev-parse in the worktree answers top level, Git dirs, HEAD and the primary checkout for the whole process;+ // the only other is the code's own checkout, asked once where the running code came from.+ const claim = box.runIn(box.worktree, 'claim', '1');+ assert.match(claim.stdout, /claimed #1/u);+ const revParses = claim.gitCalls.filter((call) => /\brev-parse\b/u.test(call));+ const here = revParses.filter((call) => call.startsWith(`${box.worktree}\t`));+ assert.equal(here.length, 1, `claim asked the worktree for repo facts ${here.length} times: ${here.join(' | ')}`);+ assert.ok(revParses.length <= 2, `claim started ${revParses.length} rev-parse processes: ${revParses.join(' | ')}`);+ assert.ok(claim.gitCalls.length <= 10, `claim started ${claim.gitCalls.length} Git processes: ${claim.gitCalls.join(' | ')}`);+ await assertStartupBudgets(t);+});