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 remote-tracking branch 'origin/main' into core/695-merge
Corey Olson9f85e7cde418
diff --cc src/approved-rows.jsindex e80fa663,56c16104..b98209b4--- a/src/approved-rows.js+++ b/src/approved-rows.js@@@ -9,24 -3,12 +9,25 @@@ importimport { tmpdir } from 'node:os';import { join } from 'node:path';import { spawnSync } from 'node:child_process';-import { parseSpec, SIGNOFFS_FILE } from './spec.js';-import { boardBusyError, openBoardReadOnly, rowDecisions } from './board.js';-import { hasSignerFile, verifySignedRecords } from './signature.js';+import {+ parseSpec,+ SIGNOFFS_FILE,+} from './spec.js';+import {+ boardBusyError,+ openBoardReadOnly,+ rowDecisions,+} from './board.js';+import {+ hasSignerFile,+ verifySignedRecords,+} from './signature.js';import { Refused } from './refused.js';-import { CONFIG_FILE, configFromSource } from './config.js';+import {+ CONFIG_FILE,+ configFromSource,+} from './config.js';+ import { checkLoosening } from './doctrine-checks.js';const TRUST_FILES = ['.pullboard/signers', '.pullboard/first-commit', '.pullboard/signers.initial', SIGNOFFS_FILE];diff --cc src/blueprints.jsindex 7f3a86d0,98f80bff..4716a6f4--- a/src/blueprints.js+++ b/src/blueprints.js@@@ -28,21 -30,11 +30,22 @@@* Rule and question keys ("W1", "Q1") are unique within the file; an item cites them by key and* waits on other items by their keys. On a board they get real ids from the section's prefix.*/-import { existsSync, readdirSync, readFileSync } from 'node:fs';-import { basename, join, resolve } from 'node:path';+import {+ existsSync,+ readdirSync,+ readFileSync,+} from 'node:fs';+import {+ basename,++ join,+ resolve,+} from 'node:path';import { fileURLToPath } from 'node:url';import { Refused } from './refused.js';-import { insertSectionRows, nextRowId } from './spec.js';+import {+ insertSectionRows,+ nextRowId,+} from './spec.js';/** The blueprint file format this Pullboard reads and writes. */export const BLUEPRINT_FORMAT = 1;diff --cc src/board.jsindex 4ba127fc,004f398a..6cb7b45c--- a/src/board.js+++ b/src/board.js@@@ -6,32 -6,17 +6,41 @@@* every move lands in an append-only event log (R2). The caller supplies what only git and the* spec know: the commit, the verifier's checkout, the frozen criterion.*/-import { randomBytes, randomUUID } from 'node:crypto';-import { existsSync, mkdirSync } from 'node:fs';+import {+ randomBytes,+ randomUUID,+} from 'node:crypto';+import {+ existsSync,+ mkdirSync,+} from 'node:fs';import { dirname } from 'node:path';import { DatabaseSync } from 'node:sqlite';+ import { boardNotWritable } from './board-access.js';-import { briefFiles, briefSections } from './brief.js';+import {+ briefFiles,- briefSections,++ checkRouted,+} from './brief.js';import { COORDINATOR } from './config.js';-import { ENGINE_VERSION, GUARDS, IN_STATE, MOVES, STATES, UNKNOWN_MOVE, effectiveGuards, storeTriggers } from './machine.js';+import {+ ENGINE_VERSION,+ GUARDS,+ IN_STATE,+ MOVES,+ STATES,+ UNKNOWN_MOVE,+ effectiveGuards,+ storeTriggers,+} from './machine.js';import { Refused } from './refused.js';+ import { barCorrectionFields } from './bar-corrections.js';-import { factFromEvent, requestAnswerRefusal, tellAnswerImplications, tellFactImplications, tellVerdictImplications } from './implies.js';++import {++ factFromEvent,++ requestAnswerRefusal,++ tellAnswerImplications,++ tellFactImplications,++ tellVerdictImplications,++} from './implies.js';import { parseSpec } from './spec.js';export const ACCEPT_REASON = 'CRITERION_MET';@@@ -64,7 -49,7 +73,6 @@@ export function boardBusyError(file, st* at its tier and below.*/export const ROUTES = ['light', 'mid', 'strong'];--const BRIEF_LIMIT = 8000;const REVIEW_RELEASE_COOLDOWN_MS = 60 * 60 * 1000;/**@@@ -639,30 -624,30 +647,6 @@@ function checkRoute(route)}}--/**-- * Refuse an item a lighter model could not build cold (B10, B14). Any brief stays short enough to-- * read. Below the strong route the item needs all of it: a criterion, a check command that proves-- * it, and a brief naming the files and the test.-- *-- * @param {{ brief: string, route: string, criterion: string, check: string }} item-- */--function checkRouted({ brief, route, criterion, check }) {-- if (brief.length > BRIEF_LIMIT) {-- throw new Refused('BRIEF_TOO_LONG', `the brief is ${brief.length} characters; keep it under ${BRIEF_LIMIT} and point to longer docs by path`);-- }-- if (route === 'strong') return;-- const sections = briefSections(brief);-- const missing = [-- ...(briefFiles(brief).length ? [] : ['a brief with a Files: section naming the paths to touch']),-- ...(sections.test?.length ? [] : ['a Test: section saying what the test asserts']),-- ...(criterion.trim() ? [] : ['--criterion, saying when it is done']),-- ...(check.trim() ? [] : ['--check, the command that proves it']),-- ];-- if (missing.length) {-- throw new Refused('NO_BRIEF', `an item routed ${route} must be buildable cold; it needs ${missing.join(', ')}`);-- }--}--/*** The route an agent joined on; strong for the coordinator and for ids the board does not know.*diff --cc src/brief.jsindex b07f24cb,b07f24cb..237dba45--- a/src/brief.js+++ b/src/brief.js@@@ -3,7 -3,7 +3,9 @@@* followed by text on the same line or by lines below it, until the next label. Below the strong* route a brief must name its files and its test, because a lighter model works from the brief alone.*/++import { Refused } from './refused.js';++const BRIEF_LIMIT = 8000;const LABEL_RE = /^(files|change|test|out of scope)\s*:\s*(.*)$/i;/** Remove closed parenthetical notes while leaving an unmatched note visible to path checks.@@@ -72,3 -72,3 +74,27 @@@ export function briefFiles(brief)&& !/^[a-z]+:\/\//i.test(token)&& (token.includes('/') || /\.[a-z0-9]+(?:\.[a-z0-9]+)*$/i.test(token)));}++++/**++ * Refuse an item a lighter model could not build cold (B10, B14). Any brief stays short enough to++ * read. Below the strong route the item needs all of it: a criterion, a check command that proves++ * it, and a brief naming the files and the test.++ *++ * @param {{ brief: string, route: string, criterion: string, check: string }} item++ */++export function checkRouted({ brief, route, criterion, check }) {++ if (brief.length > BRIEF_LIMIT) {++ throw new Refused('BRIEF_TOO_LONG', `the brief is ${brief.length} characters; keep it under ${BRIEF_LIMIT} and point to longer docs by path`);++ }++ if (route === 'strong') return;++ const sections = briefSections(brief);++ const missing = [++ ...(briefFiles(brief).length ? [] : ['a brief with a Files: section naming the paths to touch']),++ ...(sections.test?.length ? [] : ['a Test: section saying what the test asserts']),++ ...(criterion.trim() ? [] : ['--criterion, saying when it is done']),++ ...(check.trim() ? [] : ['--check, the command that proves it']),++ ];++ if (missing.length) {++ throw new Refused('NO_BRIEF', `an item routed ${route} must be buildable cold; it needs ${missing.join(', ')}`);++ }++}diff --cc src/check-baseline.jsindex ccd80b85,5a2e89dc..4a556932--- a/src/check-baseline.js+++ b/src/check-baseline.js@@@ -1,19 -1,13 +1,20 @@@/** Observe a proposed check on an isolated copy of main before recording its move [V2,H16]. */import { spawnSync } from 'node:child_process';import { randomUUID } from 'node:crypto';-import { mkdtempSync, rmSync } from 'node:fs';+import {+ mkdtempSync,+ rmSync,+} from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { gitChildEnv, mainCheckout, tryGit } from './git.js';+import {+ gitChildEnv,+ mainCheckout,+ tryGit,+} from './git.js';import { runShell } from './gate.js';import { CONFIG_FILE } from './config.js';+ import { Refused } from './refused.js';/*** Capture the command and coordinator commit once on the sender; replay only receives this observation.diff --cc src/cli.jsindex e2992f60,ccf54309..f272a725--- a/src/cli.js+++ b/src/cli.js@@@ -2,99 -2,25 +2,108 @@@* The pullboard command line: every command, bound to who is asking (B3, R3). The main checkout is the* coordinator; every other worktree is the agent that joined from it.*/-import { createHash, randomUUID } from 'node:crypto';-import { spawn, spawnSync } from 'node:child_process';-import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';-import { hostname, loadavg } from 'node:os';-import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';+import {+ createHash,+ randomUUID,+} from 'node:crypto';+import {+ spawn,+ spawnSync,+} from 'node:child_process';+import {+ appendFileSync,+ existsSync,+ mkdirSync,- readdirSync,+ readFileSync,- renameSync,++ realpathSync,+ writeFileSync,+} from 'node:fs';+import {+ hostname,+ loadavg,+} from 'node:os';+import {+ basename,+ dirname,+ isAbsolute,+ join,+ relative,+ resolve,+} from 'node:path';import { performance } from 'node:perf_hooks';-import { fileURLToPath, pathToFileURL } from 'node:url';+import {+ fileURLToPath,+ pathToFileURL,+} from 'node:url';import { parseArgs } from 'node:util';import * as store from './board.js';-import { CONFIG_FILE, COORDINATOR, DOCTRINE_FILE, LEGACY_DOCTRINE_FILE, loadConfig } from './config.js';+import {+ CONFIG_FILE,+ COORDINATOR,+ DOCTRINE_FILE,+ LEGACY_DOCTRINE_FILE,+ loadConfig,+} from './config.js';import { displayAgentName } from './agent-names.js';-import { doctrineHistory, loadDoctrine } from './doctrine.js';-import { checkRulesAt, doctrineReport, hasSubmitRules, holdDoctrine, ruleLine } from './doctrine-checks.js';-import { agentSessionDigest, requirePersonChannel } from './person.js';-import { bindLocalSession, localSessionMatches } from './agent-session.js';-import { decisionAnswer, decisionProjection, handAnsweredQuestions, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';-import { digestOf, gateReport, refuseSandboxBlocked, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';+import {+ doctrineHistory,+ loadDoctrine,+} from './doctrine.js';++import {++ checkRulesAt,++ doctrineReport,++ hasSubmitRules,++ holdDoctrine,++ ruleLine,++} from './doctrine-checks.js';+import {+ agentSessionDigest,+ requirePersonChannel,+} from './person.js';+import {+ bindLocalSession,+ localSessionMatches,+} from './agent-session.js';+import {++ decisionAnswer,+ decisionProjection,++ handAnsweredQuestions,+ planRowApply,+ prepareRowDecisions,+ restoreRowApply,+ writeRowApply,+} from './row-decisions.js';+import {+ digestOf,+ gateReport,++ refuseSandboxBlocked,+ runGate,+ runProfiledShell,+ runSubmitGate,+ submitGateReport,+ timingDigest,+ withGateSlot,+} from './gate.js';import { checkNeedsBrowser } from './browser-admission.js';-import { bareWorktreeFinding, codeIsFromMain, contains, differFromHead, git, gitChildEnv, headCommit, headTree, invalidateGitFacts, isClean, mainCheckout, patchId, repoInfo, resolveCommit, tryGit, untracked, withGitFacts } from './git.js';+import {+ bareWorktreeFinding,+ codeIsFromMain,+ contains,+ differFromHead,+ git,+ gitChildEnv,+ headCommit,+ headTree,+ invalidateGitFacts,+ isClean,+ mainCheckout,+ patchId,+ repoInfo,+ resolveCommit,+ tryGit,+ untracked,+ withGitFacts,+} from './git.js';import {FIX_NOTE,applyFixers,@@@ -106,28 -32,15 +115,44 @@@pushesTrunk,unwiredHookProblems,} from './hooks.js';-import { askedLaneNotes, detectGate, initRepo, proposeLanes, starterLane, starterLaneNotes } from './init.js';+import {- detectGate,++ askedLaneNotes,+ initRepo,++ proposeLanes,++ starterLane,++ starterLaneNotes,+} from './init.js';import { lifecycleMarkdown } from './machine.js';-import { HELP, VERSION } from './help.js';-import { barCorrectionLine, barCorrections, barStatsLines } from './bar-corrections.js';-import { checkImplies, decisionsImplying, parseImplies, takeDecisionNotices, whyLine } from './implies.js';+import {+ buildHelp,+ VERSION,+} from './help.js';++import {++ barCorrectionLine,++ barCorrections,++ barStatsLines,++} from './bar-corrections.js';++import {++ checkImplies,++ decisionsImplying,++ parseImplies,++ takeDecisionNotices,++ whyLine,++} from './implies.js';import { defaultViewPort } from './view-port.js';-export { HELP, VERSION };-import { productLine, productProblems, productSummaries } from './products.js';-import { addLane, isLane, laneNames, laneOf, outOfLane } from './lanes.js';+export { VERSION };+import {+ productLine,+ productProblems,+ productSummaries,+} from './products.js';+import {++ addLane,+ isLane,+ laneNames,+ laneOf,+ outOfLane,+} from './lanes.js';import { Refused } from './refused.js';import { personNeeds } from './needs.js';import { personNeedsState } from './needs-state.js';@@@ -155,137 -61,42 +180,174 @@@ importstandings,unmetRows,} from './spec.js';-import { answerQuestion, bundledBlueprints, landBlueprint, planBlueprint, readBlueprint, repoAnswers, saveBlueprint } from './blueprints.js';+import {++ answerQuestion,+ bundledBlueprints,++ landBlueprint,+ planBlueprint,+ readBlueprint,++ repoAnswers,+ saveBlueprint,+} from './blueprints.js';import { briefFiles } from './brief.js';-import { commitFirst, commitOwnerLines, commitOwners, coordinatorInbox, coordinatorInboxLines, inboxFirst } from './resume.js';-import { checkBaseline, prepareCheckBaseline, sayCheckBaseline, refuseCheckSyntax } from './check-baseline.js';-import { retryCheckBaselines, startCheckBaseline } from './check-baseline-worker.js';-import { compareMainFailures, mainRedMessage, mainRedReworkItems } from './main-red.js';++import {++ commitFirst,++ commitOwnerLines,++ commitOwners,++ coordinatorInbox,++ coordinatorInboxLines,++ inboxFirst,++} from './resume.js';+import {+ checkBaseline,+ prepareCheckBaseline,+ sayCheckBaseline,++ refuseCheckSyntax,+} from './check-baseline.js';+import {+ retryCheckBaselines,+ startCheckBaseline,+} from './check-baseline-worker.js';+import {+ compareMainFailures,+ mainRedMessage,+ mainRedReworkItems,+} from './main-red.js';import { runItems } from './run.js';-import { parseProblems, sweepItems } from './sweep.js';+import {+ parseProblems,+ sweepItems,+} from './sweep.js';import { renderSpecView } from './view.js';import { tour } from './tour.js';-import { commandOutput, refusalDocument } from './json.js';-import { forgetProject, listApiProjects, registerProjectAndLink, registeredProjectRootsSnapshot } from './projects.js';+import {+ commandOutput,+ refusalDocument,+} from './json.js';+import {+ forgetProject,+ listApiProjects,+ registerProjectAndLink,++ registeredProjectRootsSnapshot,+} from './projects.js';import { milestoneRoadmap } from './roadmap.js';-import { listResources, memoryVerdict, readMachineMemory, runnerResourceStatus } from './resources.js';-import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';-import { exportView, serveView } from './serve.js';-import { forgetView, portHolder, rememberView, runningView } from './view-session.js';+import {+ listResources,++ memoryVerdict,++ readMachineMemory,+ runnerResourceStatus,+} from './resources.js';+import {+ citedTestFiles,+ rowEvidence,+ rowStage,+} from './evidence.js';+import {+ exportView,+ serveView,+} from './serve.js';+import {+ forgetView,++ portHolder,+ rememberView,+ runningView,+} from './view-session.js';import { serveApi } from './api.js';import { serveMcp } from './mcp.js';-import { doctorProblems, doctrineProblems } from './doctor.js';-import { staleFrozenItems, staleItemFinding } from './approved-rows.js';-import { mainPolicy, policyAt, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots, requireTrunkMerge, trunkRef } from './trusted-policy.js';+import {+ doctorProblems,+ doctrineProblems,+} from './doctor.js';+import {+ staleFrozenItems,+ staleItemFinding,+} from './approved-rows.js';+import {+ mainPolicy,+ policyAt,+ itemPolicy,+ submissionPaths,+ frozenCheck,+ checkAtCommit,+ dependencySnapshots,+ requireTrunkMerge,+ trunkRef,+} from './trusted-policy.js';import { proofStats } from './stats.js';-import { flowLines, flowAlertLine } from './stats-flow.js';+import {+ flowLines,+ flowAlertLine,+} from './stats-flow.js';import { releaseHeadlinesBetween } from './changelog.js';-import { exportBoard, importBoard } from './exchange.js';-import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';-import { addRunner, browserFreeChecksEnabled, gateQueueSettings, loadMachineSettings, memoryFloorMB, setBrowserSlots, setGateSlots } from './settings.js';-import { formatSnapshotLimit, pendingSnapshotSize, pendingCheckpointProblem, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecover, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';-import { autoLinkProject, relayOnAll, revokeRelayDevice, unlinkedRelayProjects } from './relay-setup.js';+import {+ exportBoard,+ importBoard,+} from './exchange.js';+import {+ addSigner,+ assertRequiredSigners,+ defaultPrincipal,+ hasSignerFile,+} from './signature.js';+import {- addRunner,+ browserFreeChecksEnabled,++ gateQueueSettings,+ loadMachineSettings,- setBrowserSlots,- setGateSlots,++ memoryFloorMB,+} from './settings.js';+import {- formatSnapshotLimit,+ pendingSnapshotSize,+ pendingCheckpointProblem,+ relayCommandReceipt,+ relayCommandReceiptReported,+ relayLinked,+ relayOff,+ relayOn,+ relayOperation,+ relayRecover,+ relayRecovered,+ relayRevoke,+ relayStatus,+ relayTokens,+ syncRelay,+} from './relay.js';+import {+ autoLinkProject,+ relayOnAll,+ revokeRelayDevice,+ unlinkedRelayProjects,+} from './relay-setup.js';import { readRelayMachine } from './relay-machine.js';-import { relayJoin, relayPair } from './relay-pairing-client.js';+import {+ relayJoin,+ relayPair,+} from './relay-pairing-client.js';import { executePersonRequests } from './relay-request-execution.js';--import { engineReceipt } from './engine.js';- import { land } from './land.js';-import { land, landingRemote, landingSubject } from './land.js';++import {++ boardSetup,++ recordSetupState,++ recordViewBind,++ recordViewReuse,++ setupIdentity,++ viewSetupComplete,++} from './setup-card.js';++import { formatSnapshotLimit } from './relay-messages.js';++import {++ runnerCommand,++ settingsCommand,++} from './machine-commands.js';++import {++ filesSince,++ recordedRecovery,++ refuseUnverifiedStack,++ reportSubmission,++} from './submission.js';++import {++ land,++ landingRemote,++ landingSubject,++} from './land.js';+ import { installStep } from './worktree.js';const CHECKOUT_LEASES = new WeakMap();const CHECKOUT_BOARD_ONLY = new WeakMap();@@@ -1126,60 -940,60 +1191,6 @@@ function dirtyFiles(root)return tryGit(root, ['status', '--porcelain', '--untracked-files=all']).stdout.split('\n').filter(Boolean).map((line) => line.slice(3));}--/**-- * The files an item's own commits changed since its claim (N21). First parents only, so main merged-- * into a lane branch is not counted as the item's work; and nothing another item submitted, such as-- * a verified dependency fast-forwarded in, which merges no commit to skip.-- *-- * @param {string} root-- * @param {number} id-- * @param {string | null} from-- * @param {string} to-- * @returns {string[]}-- */--function filesSince(root, id, from, to) {-- if (!from) return [];-- const others = [`--exclude=refs/pullboard/items/${id}/*`, '--glob=refs/pullboard/items/*'];-- const result = tryGit(root, ['log', '--first-parent', '--no-merges', '--no-renames', '--format=', '--name-only', to, '--not', from, ...others]);-- return result.status === 0 ? [...new Set(result.stdout.split('\n').filter(Boolean))].sort() : [];--}----/** Refuse a candidate containing another item's unverified submitted commit [V1].-- *-- * Trunk-reachable commits are already landed, including when the candidate is trunk itself.-- * Inspect all remaining reachable commits, including merged topic parents.-- *-- * @param {string} root-- * @param {any} board-- * @param {any} item-- * @param {string} commit-- * @param {{ ref: string, commit: string } | null} trunk-- * @returns {void}-- */--function refuseUnverifiedStack(root, board, item, commit, trunk) {-- const trunkRange = trunk?.commit-- ? tryGit(root, ['rev-list', `${trunk.commit}..${commit}`])-- : { status: 1, stdout: '' };-- if (trunkRange.status !== 0) {-- throw new Refused('NO_POLICY', 'the current trunk range cannot be read; restore Git history and retry the submit or verification');-- }-- const commits = new Set(trunkRange.stdout.split('\n').filter(Boolean));-- const stacked = store.unverifiedSubmissions(board)-- .find((other) => other.item_id !== item.item_id && commits.has(other.item_commit));-- if (stacked) {-- throw new Refused(-- 'STACKED_ON_UNVERIFIED',-- `#${item.item_id} includes unverified item #${stacked.item_id} at ${stacked.item_commit}; wait for #${stacked.item_id} to be accepted or rebuild without its commits before continuing`,-- );-- }--}----/** Return the durable outcome only when a recovered move exactly matches its original receipt. */--function recordedRecovery(board, move) {-- const receipt = engineReceipt(board, move.id);-- return receipt?.move === JSON.stringify(move) ? receipt : null;--}--/*** How long ago an ISO time was, or how long until it, in the board's clock: 45m, 3h, 2d.*@@@ -1327,133 -1141,135 +1338,6 @@@ function resumeReleaseNotes(info)return releases.length ? { releases: releases.slice(0, 3), omitted: Math.max(0, releases.length - 3), notes: 'CHANGELOG.md' } : null;}--/** Identify setup from this board's coordinator enrollment, independently of agent flags. */--function setupIdentity(board) {-- return { boardId: store.boardId(board),-- setupStartedAt: store.listAgents(board).find(agent => agent.agent_id === COORDINATOR)?.agent_created_at };--}----/** Read only the view's typed successful-bind receipt for this board and setup. */--function viewBindComplete(ctx, board) {-- let receipt;-- try { receipt = JSON.parse(readFileSync(join(ctx.info.commonDir, 'pullboard', 'view-bind.json'), 'utf8')); }-- catch (error) { if (error.code === 'ENOENT' || error instanceof SyntaxError) return false; throw error; }-- const identity = setupIdentity(board);-- return receipt?.type === 'pullboard.view.bound' && receipt.version === 1-- && receipt.boardId === identity.boardId && receipt.setupStartedAt === identity.setupStartedAt-- && Number.isFinite(Date.parse(receipt.boundAt))-- && Date.parse(receipt.boundAt) >= Date.parse(identity.setupStartedAt);--}----/** A separately typed, authenticated reuse also proves that this board's view was opened. */--function viewSetupComplete(ctx, board) {-- if (viewBindComplete(ctx, board)) return true;-- let receipt;-- try { receipt = JSON.parse(readFileSync(join(ctx.info.commonDir, 'pullboard', 'view-reuse.json'), 'utf8')); }-- catch (error) { if (error.code === 'ENOENT' || error instanceof SyntaxError) return false; throw error; }-- const identity = setupIdentity(board);-- return receipt?.type === 'pullboard.view.reused' && receipt.version === 1-- && receipt.boardId === identity.boardId && receipt.setupStartedAt === identity.setupStartedAt-- && Number.isFinite(Date.parse(receipt.openedAt))-- && Date.parse(receipt.openedAt) >= Date.parse(identity.setupStartedAt);--}----/** Atomically record a successful real view bind, scoped to this board's current setup. */--function recordViewBind(ctx, board, boundAt) {-- const file = join(ctx.info.commonDir, 'pullboard', 'view-bind.json');-- const temporary = file + '.' + randomUUID() + '.tmp';-- const receipt = { type: 'pullboard.view.bound', version: 1, ...setupIdentity(board), boundAt };-- mkdirSync(dirname(file), { recursive: true });-- writeFileSync(temporary, JSON.stringify(receipt) + '\n', { mode: 0o600 });-- renameSync(temporary, file);--}----/** Record this board's authenticated reuse without claiming that its existing listener bound again. */--function recordViewReuse(ctx, board, view) {-- const file = join(ctx.info.commonDir, 'pullboard', 'view-reuse.json');-- const temporary = file + '.' + randomUUID() + '.tmp';-- const receipt = { type: 'pullboard.view.reused', version: 1, ...setupIdentity(board),-- openedAt: new Date().toISOString(), boundAt: view.boundAt, port: view.port, pid: view.pid };-- mkdirSync(dirname(file), { recursive: true });-- writeFileSync(temporary, JSON.stringify(receipt) + '\n', { mode: 0o600 });-- renameSync(temporary, file);--}----/** Read a typed setup receipt only for this board's current coordinator enrollment. */--function setupReceiptMatches(ctx, identity, state) {-- let receipt;-- try { receipt = JSON.parse(readFileSync(join(ctx.info.commonDir, 'pullboard', `setup-${state}.json`), 'utf8')); }-- catch (error) { if (error.code === 'ENOENT' || error instanceof SyntaxError) return false; throw error; }-- return receipt?.type === `pullboard.setup.${state === 'complete' ? 'completed' : state}` && receipt.version === 1-- && receipt.boardId === identity.boardId && receipt.setupStartedAt === identity.setupStartedAt;--}----/** Atomically record a setup transition, scoped to this board enrollment. */--function recordSetupState(ctx, identity, state) {-- const file = join(ctx.info.commonDir, 'pullboard', `setup-${state}.json`);-- const temporary = file + '.' + randomUUID() + '.tmp';-- mkdirSync(dirname(file), { recursive: true });-- writeFileSync(temporary, JSON.stringify({ type: `pullboard.setup.${state === 'complete' ? 'completed' : state}`, version: 1, ...identity }) + '\n', { mode: 0o600 });-- renameSync(temporary, file);--}----/** Derive the next setup question from the real requirements, config, items and view receipt. */--function boardSetup(ctx, card, identity) {-- const rows = loadSpec(ctx.info.root, ctx.config).rows;-- const approved = rows.filter(row => row.status === 'approved');-- const drafted = rows.filter(row => row.status === 'draft' || row.status === 'pending');-- const recordedComplete = setupReceiptMatches(ctx, identity, 'complete');-- const started = setupReceiptMatches(ctx, identity, 'started');-- const lanes = laneNames(ctx.config).filter(lane => !['review', COORDINATOR].includes(lane));-- const folders = readdirSync(ctx.info.root, { withFileTypes: true })-- .filter(entry => entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules')-- .map(entry => entry.name).sort();-- const lane = lanes[0] ?? folders[0] ?? 'app';-- // Older installations had no setup marker. Preserve their completed five-step state on upgrade.-- const legacyUnmarked = !existsSync(join(ctx.info.commonDir, 'pullboard', 'setup-started.json'))-- && !existsSync(join(ctx.info.commonDir, 'pullboard', 'setup-complete.json'));-- const legacyComplete = legacyUnmarked && approved.length > 0 && lanes.length > 0-- && Boolean(ctx.config.gate?.trim()) && card.all.length > 0 && card.viewOpened;-- const completed = recordedComplete || legacyComplete;-- const detectedGate = detectGate(ctx.info.root);-- /** Quote the exact suggested command safely for a shell. */-- const quote = value => "'" + String(value).replaceAll("'", "'\\''") + "'";- /** Quote one shell word only when it needs it, so a plain lane command reads as typed. */- const word = value => /^[A-Za-z0-9._/-]+$/u.test(String(value)) ? String(value) : quote(value);-- /** Preserve all existing configuration when recording one setup answer. */-- const configure = patch => `node -e ${quote(`const fs=require('node:fs');const p='pullboard.json';const c=JSON.parse(fs.readFileSync(p,'utf8'));${patch};fs.writeFileSync(p,JSON.stringify(c,null,2)+${JSON.stringify('\n')})`)}`;-- const steps = [-- { number: 1, done: approved.length > 0 && (!drafted.length || completed), question: 'Ask the person: what are we building, and who will use it? Draft a few requirements, then ask the person to approve them.',-- command: 'pullboard spec draft "<text>"',-- afterAnswer: 'Record each answer with pullboard spec draft "<text>"; the person approves the returned ids in Pullboard View or runs pullboard spec approve <ids> in their own terminal; then the coordinator runs pullboard spec apply.' },-- { number: 2, done: lanes.length > 0, question: `Ask the person: how should we divide the work? Suggested folders: ${folders.join(', ') || 'app/ (create it for the app)'}.`,- command: configure(`c.lanes[${JSON.stringify(lane)}]={owns:[${JSON.stringify(lane + '/')}]}`) },- command: `pullboard lane add ${word(lane)} --owns ${word(lane + '/')}` },-- { number: 3, done: Boolean(ctx.config.gate?.trim()),-- question: detectedGate-- ? `Ask the person: which command proves the build works? Suggested: ${detectedGate}.`-- : 'Ask the person: if this board has no build, use `pullboard spec check` to check its spec and practice files; a second agent review checks the actual work. Or choose a custom gate command.',-- command: configure(`c.gate=${JSON.stringify(detectedGate || 'pullboard spec check')}`) },-- { number: 4, done: card.all.length > 0, question: 'Ask the person: what is the first small piece we should build?',-- command: `pullboard add ${quote(lane)} 'First small piece' --specs ${quote(approved[0]?.id ?? 'G1')} --criterion 'Describe what the person will be able to do'` },-- { number: 5, done: card.viewOpened,-- question: 'Ask the person: shall we open the board so you can follow the work?', command: 'pullboard view',-- afterAnswer: 'Run this in the person’s own terminal, or start it in the background as the agent so setup can continue. The view records its successful bind or authenticated reuse for this board.' },-- ];-- const current = steps.find(step => !step.done);-- if (!current && !recordedComplete) recordSetupState(ctx, identity, 'complete');-- else if (current && !completed && !started) recordSetupState(ctx, identity, 'started');-- if (current?.number === 1 && drafted.length) {-- const rowIds = drafted.map(row => row.id);-- const names = rowIds.join(', ');-- const command = `pullboard spec show ${rowIds[0]}`;-- return { step: 1, total: 5, ...current, steps, waitingOn: 'person-approval', rowIds,-- question: `Waiting for the person to approve ${names}.`, command,-- personCommand: `pullboard spec approve ${rowIds.join(',')}`,-- afterAnswer: 'The person approves these rows in Pullboard View or their own terminal; then the coordinator runs pullboard spec apply.',-- meanwhile: 'While waiting, the agent may review independent approved work or prepare questions for the person.',-- agentNext: `wait for the person to approve ${names}; meanwhile ${command}` };-- }-- return current ? { step: current.number, total: 5, ...current, steps } : null;--}--/*** `pullboard resume` (N19): one short card that puts an agent back to work after a fresh start,* a restart or a compaction, from the board rather than from a summary.@@@ -2444,21 -2348,21 +2416,9 @@@ async function submitHere(ctx, id)...(gate.deferred ? { note: 'full suite deferred to the landing gate' } : {}) }]);});return reportSubmission(ctx, id, commit, { green: gate.isGreen, report: submitGateReport(gate), files: gate.files, full: gate.full, deferred: gate.deferred, deferFullFallback: gate.deferFullFallback, reason: gate.reason, check: gate.check,- log: gate.log, profile: gate.profile, profilePath: gate.profilePath, proofLog: gate.proofLog, proofProfilePath: gate.proofProfilePath });- }-- /** Report and pin the original submitted commit, including a recovered acknowledged outcome. */- function reportSubmission(ctx, id, commit, gate) {- const { root } = ctx.info;- const pin = `refs/pullboard/items/${id}/${commit.slice(0, 12)}`;- git(root, ['update-ref', pin, commit]);- ctx.io.result?.({ id, commit, pin, gate });- ctx.io.say(`submitted #${id} at ${commit.slice(0, 12)}; ${gate.report}`);- ctx.io.say(`pinned as ${pin}, so this work can't be lost; keep your worktree until it is merged`);- ctx.io.say(`next: another agent checks out ${commit.slice(0, 12)} and runs: pullboard verify ${id} accept|reject`);- return 0;+ log: gate.log, profile: gate.profile, profilePath: gate.profilePath, proofLog: gate.proofLog, proofProfilePath: gate.proofProfilePath }, doctrine);}-/** Report and pin the original submitted commit, including a recovered acknowledged outcome. */-function reportSubmission(ctx, id, commit, gate, doctrine = []) {- const { root } = ctx.info;- const pin = `refs/pullboard/items/${id}/${commit.slice(0, 12)}`;- git(root, ['update-ref', pin, commit]);- ctx.io.result?.({ id, commit, pin, gate, ...(doctrine.length ? { doctrine } : {}) });- ctx.io.say(`submitted #${id} at ${commit.slice(0, 12)}; ${gate.report}`);- ctx.io.say(`pinned as ${pin}, so this work can't be lost; keep your worktree until it is merged`);- ctx.io.say(`next: another agent checks out ${commit.slice(0, 12)} and runs: pullboard verify ${id} accept|reject`);- return 0;-}-/*** Add a blueprint to the board of the checkout io.cwd names, exactly as pullboard blueprint add* does; init --blueprint calls it after setting up the repo. With report false it prints nothing@@@ -3254,41 -3274,47 +3330,6 @@@ export function gateWaitReporter(io)};}--/** Read or update machine-wide gate capacity. */--function settingsCommand(io, { first, second, rest }) {-- if (!first && !second && !rest.length) {-- const settings = loadMachineSettings();- io.result?.({ settings });- const queue = gateQueueSettings();- // The result names the queue order in effect, defaults included; the file keeps only what was set.- io.result?.({ settings: { ...settings, gate: { ...settings.gate, queue: { ...settings.gate?.queue, ...queue } } }, memoryFloorMB: memoryFloorMB() });-- io.say(`gateSlots: ${settings.gateSlots}`);-- io.say(`browserSlots: ${settings.browserSlots}`);- io.say(`gate.queue.reviewsFirst: ${queue.reviewsFirst}${queue.reviewsFirst ? '' : ' (landings first, then arrival order)'}`);- io.say(`gate.queue.currentReleaseFirst: ${queue.currentReleaseFirst}${queue.currentReleaseFirst ? '' : ' (release priority is off)'}`);- io.say(`gate.queue.agingMinutes: ${queue.agingMinutes}${queue.reviewsFirst || queue.currentReleaseFirst ? '' : ' (used only while reviewsFirst or currentReleaseFirst is true)'}`);- io.say(`gate.memoryFloorMB: ${memoryFloorMB() ?? 'off (the gate queue does not wait for memory)'}`);-- return 0;-- }-- if (!['gateSlots', 'browserSlots'].includes(first) || !second || rest.length) {-- throw new Refused('USAGE', 'pullboard settings gateSlots <n> | browserSlots <n>');-- }-- if (!/^[1-9]\d*$/u.test(second) || !Number.isSafeInteger(Number(second))) {-- if (first === 'gateSlots') throw new Refused('USAGE', 'pullboard settings gateSlots <positive integer>');-- throw new Refused(first === 'browserSlots' ? 'BAD_BROWSER_SLOTS' : 'BAD_GATE_SLOTS', `${first} must be a positive integer; run pullboard settings ${first} <n>`);-- }-- const settings = first === 'browserSlots' ? setBrowserSlots(Number(second)) : setGateSlots(Number(second));-- io.result?.({ settings });-- io.say(`${first} set to ${settings[first]}`);-- return 0;--}----/** Register machine-level SSH capacity without requiring a board identity or a runner account. */--function runnerCommand(io, { first, second, rest, values }) {-- if (first !== 'add' || !second || rest.length || !/^[1-9]\d*$/u.test(values.slots ?? '')-- || !/^(?:0|[1-9]\d*)$/u.test(values.browser ?? '')) {-- throw new Refused('USAGE', 'pullboard runner add <ssh-host> --slots <positive integer> --browser <integer from zero through slots>');-- }-- const runner = addRunner({ host: second, slots: Number(values.slots), browser: Number(values.browser),-- ...(values.node !== undefined ? { node: values.node } : {}), ...(values.root !== undefined ? { root: values.root } : {}) });-- io.result?.({ runner });-- io.say(`registered runner ${runner.host}: ${runner.slots} slots, ${runner.browser} browser`);-- return 0;--}--/*** Every spec id something cites (S8): commit headers since the spec's first commit, and every item* on the board, open or closed. The connection is read-only: spec lint never migrates a shared board. Each must still be in the spec. The board is shared by everydiff --cc src/doctrine-checks.jsindex 00000000,d442d5cc..b3021801mode 000000,100644..100644--- a/src/doctrine-checks.js+++ b/src/doctrine-checks.js@@@ -1,0 -1,269 +1,282 @@@+ /**+ * Doctrine checks with a count that only falls (D1, D3). A rule row may carry+ * `| gate: check <command> | count: N`, and `| files: <paths>` to narrow it; the command prints one+ * line per problem and exits 0 or 1. Submit holds every touched rule's count at or below its+ * committed count and refuses a changed file that gains a problem. Rules come only from committed+ * doctrine: accepted main's at submit, HEAD's for `pullboard doctrine check`, never a working-tree+ * edit.+ */+ import { spawnSync } from 'node:child_process';-import { mkdtempSync, rmSync } from 'node:fs';++import {++ mkdtempSync,++ rmSync,++} from 'node:fs';+ import { tmpdir } from 'node:os';+ import { join } from 'node:path';-import { DOCTRINE_FILE, LEGACY_DOCTRINE_FILE } from './config.js';-import { cleanGitEnvironment, gitChildEnv, invalidateGitFacts } from './git.js';++import {++ DOCTRINE_FILE,++ LEGACY_DOCTRINE_FILE,++} from './config.js';++import {++ cleanGitEnvironment,++ gitChildEnv,++ invalidateGitFacts,++} from './git.js';+ import { Refused } from './refused.js';-import { checkFieldFindings, parseSpec } from './spec.js';++import {++ checkFieldFindings,++ parseSpec,++} from './spec.js';++ const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;++ /**+ * A row's check rule, or null when the row carries no well-formed check. Malformed check fields+ * are lint errors in `pullboard spec check`; here they simply carry no rule.+ *+ * @param {any} row+ * @returns {{ id: string, text: string, status: string, command: string, count: number, runs: string, mode: string, files: string[] } | null}+ */+ export function checkRule(row) {+ if (!/^check\s/u.test(row?.gate ?? '') || checkFieldFindings(row).length) return null;+ return { id: row.id, text: row.text, status: row.status, command: row.gate.slice('check'.length).trim(),+ count: Number(row.count), runs: row.runs ?? 'submit', mode: row.mode ?? 'hold', files: ruleFiles(row.files) };+ }++ /** A row's `files:` paths, comma or space separated, without `./` or a trailing slash; none is the whole repo. */+ export function ruleFiles(value) {+ return [...new Set(String(value ?? '').split(/[\s,]+/u).map((path) => path.replace(/^\.\//u, '').replace(/\/+$/u, '')).filter(Boolean))];+ }++ /**+ * How an approved row's new version loosens its check, or '' when it does not. Lowering count:+ * is free; anything that lets more problems through needs the person's signature.+ *+ * @param {any} before - The committed row.+ * @param {any} after - The staged row with the same id.+ * @returns {string}+ */+ export function checkLoosening(before, after) {+ const old = checkRule(before);+ if (!old) return '';+ // Only approved rows are enforced, so any other status takes the check out of force.+ if (before.status === 'approved' && after.status !== 'approved') return `takes its check out of force (${after.status})`;+ const next = checkRule(after);+ if (!next) return 'drops its check';+ if (next.command !== old.command) return 'changes its check command';+ if (next.count > old.count) return `raises count: from ${old.count} to ${next.count}`;+ if (old.mode === 'hold' && next.mode === 'watch') return 'sets mode: watch';+ if (old.runs === 'submit' && next.runs === 'nightly') return 'moves its check to runs: nightly';+ // files: narrows a rule: adding it to a whole-repo rule, or dropping a path, covers less.+ if ((!old.files.length && next.files.length) || old.files.some((path) => !next.files.includes(path))) return 'narrows its files:';+ return '';+ }++ /** Read one file's committed bytes at a revision, or null when the revision lacks it. */+ function gitShow(root, revision, file) {+ const result = spawnSync('git', ['--no-replace-objects', 'show', `${revision}:${file}`], { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });+ return result.status === 0 ? result.stdout : null;+ }++ /** Run git for a list of names or a commit id, or null when git refuses. */+ function gitOut(root, args) {+ const result = spawnSync('git', ['--no-replace-objects', '-c', 'core.quotepath=false', ...args], { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });+ return result.status === 0 ? result.stdout : null;+ }++ /**+ * The approved check rules in the doctrine committed at a revision, following the conventional+ * DOCTRINE.md / PRACTICE.md rename so a renamed file keeps its rules.+ *+ * @param {string} root+ * @param {string} revision+ * @param {string} [name] - The configured doctrine file.+ * @returns {ReturnType<typeof checkRule>[]}+ */+ export function checkRulesAt(root, revision, name = DOCTRINE_FILE) {+ let source = gitShow(root, revision, name);+ if (source === null && [DOCTRINE_FILE, LEGACY_DOCTRINE_FILE].includes(name)) {+ source = gitShow(root, revision, name === DOCTRINE_FILE ? LEGACY_DOCTRINE_FILE : DOCTRINE_FILE);+ }+ if (source === null) return [];+ let parsed;+ try { parsed = parseSpec(source, { strictGrammarVersion: false }); } catch { return []; }+ return parsed.rows.filter((row) => row.status === 'approved').map(checkRule).filter(Boolean);+ }++ /**+ * Run one check where it stands and keep each non-empty output line as a problem. Exit 0 or 1 is+ * counted (`grep` exits 1 when it finds nothing); any other exit, a signal or a timeout cannot+ * count, so its error lines never pass for problems.+ *+ * @param {string} cwd+ * @param {string} command+ * @param {number} timeoutMs+ * @returns {{ problems: string[], broken: string, seconds: number }}+ */+ export function runRuleCheck(cwd, command, timeoutMs = DEFAULT_TIMEOUT_MS) {+ const started = Date.now();+ const result = spawnSync(`(\n${command}\n) 2>&1`, {+ cwd, env: gitChildEnv(cwd), shell: true, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8',+ timeout: timeoutMs, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 * 1024,+ });+ invalidateGitFacts();+ const seconds = Math.round((Date.now() - started) / 1000);+ if (result.error) {+ const broken = result.error.code === 'ETIMEDOUT' ? `timed out after ${Math.round(timeoutMs / 1000)}s` : `could not run (${result.error.code ?? 'error'})`;+ return { problems: [], broken, seconds };+ }+ if (result.signal) return { problems: [], broken: `was killed by ${result.signal}`, seconds };+ if (result.status !== 0 && result.status !== 1) return { problems: [], broken: `exited ${result.status}`, seconds };+ const output = `${result.stdout ?? ''}${result.stderr ?? ''}`;+ return { problems: output.split(/\r?\n/u).map((line) => line.trimEnd()).filter((line) => line.trim()), broken: '', seconds };+ }++ /** True when a changed path is one of a rule's watched paths or lies under one. */+ function inScope(scope, path) {+ return !scope.length || scope.some((watched) => path === watched || path.startsWith(`${watched}/`));+ }++ /** True when a problem line starts with the file's repo path, as `path:...` or `./path:...`. */+ function namesFile(line, file) {+ return line.startsWith(`${file}:`) || line.startsWith(`./${file}:`);+ }++ /** A problem line without its line number, so a moved problem is not counted as new. */+ function problemKey(line) {+ return line.replace(/:\d+:/u, '::').trim();+ }++ /** The lines in `after` beyond those in `before`, compared without line numbers. */+ function newLines(before, after) {+ const left = new Map();+ for (const line of before) left.set(problemKey(line), (left.get(problemKey(line)) ?? 0) + 1);+ return after.filter((line) => {+ const key = problemKey(line);+ const remaining = left.get(key) ?? 0;+ if (remaining > 0) { left.set(key, remaining - 1); return false; }+ return true;+ });+ }++ /**+ * One rule's line, as `pullboard doctrine check` and submit print it:+ * `D9 No silent catch · 9, was 12 · holding`.+ *+ * @param {{ id: string, text: string, count: number, committed: number, state: string, broken?: string }} result+ * @returns {string}+ */+ export function ruleLine(result) {+ const counts = result.broken ? `cannot count: its check ${result.broken}, was ${result.committed}` : `${result.count}, was ${result.committed}`;+ return `${result.id} ${result.text} · ${counts} · ${result.state}`;+ }++ /** Name how a rule stands: a check that cannot count never holds; watching never refuses a count. */+ function ruleState(rule, count, committed, broken) {+ if (broken) return 'uncounted';+ if (rule.mode === 'watch') return 'watching';+ return count <= committed ? 'holding' : 'rose';+ }++ /**+ * Count every committed rule's problems in this checkout (`pullboard doctrine check`). Rules come+ * from HEAD's committed doctrine; the command runs over the working tree, so a builder sees the+ * count its next commit would carry.+ *+ * @param {string} root+ * @param {{ practice?: string, check?: { timeoutMs?: number } }} config+ * @returns {{ id: string, text: string, command: string, count: number, committed: number, holds: boolean, state: string, mode: string, runs: string, problems: string[], broken: string }[]}+ */+ export function doctrineReport(root, config) {+ return checkRulesAt(root, 'HEAD', config.practice).map((rule) => {+ const run = runRuleCheck(root, rule.command, config.check?.timeoutMs);+ const count = run.problems.length;+ const state = ruleState(rule, count, rule.count, run.broken);+ return { id: rule.id, text: rule.text, command: rule.command, count, committed: rule.count,+ holds: state === 'holding' || state === 'watching', state, mode: rule.mode, runs: rule.runs, problems: run.problems, broken: run.broken };+ });+ }++ /** True when the accepted main doctrine has a rule submit must run; a repo without one skips it all. */+ export function hasSubmitRules(root, mainCommit, practice) {+ return checkRulesAt(root, mainCommit, practice).some((rule) => rule.runs === 'submit');+ }++ /** Run a check at an exact commit in a private shared clone, leaving every live worktree alone. */+ function runAtCommit(root, commit, command, timeoutMs) {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-doctrine-base-'));+ const checkout = join(directory, 'checkout');+ const env = gitChildEnv(root);+ try {+ const clone = spawnSync('git', ['clone', '--quiet', '--shared', '--no-checkout', '--', root, checkout], { env, stdio: 'ignore' });+ const selected = clone.status === 0 && spawnSync('git', ['-c', 'core.hooksPath=/dev/null', 'checkout', '--quiet', '--detach', commit], { cwd: checkout, env, stdio: 'ignore' });+ if (!selected || selected.status !== 0) return { problems: [], broken: 'could not check out the base commit', seconds: 0 };+ return runRuleCheck(checkout, command, timeoutMs);+ } finally {+ rmSync(directory, { recursive: true, force: true });+ }+ }++ /**+ * Hold the doctrine's counts for a submission. Rules, commands and modes come from accepted main;+ * the submitted commit may only lower a count. Each touched rule runs at the clean submitted+ * checkout; a changed file's problems are compared with the merge base only when it has any.+ * Refuses RATCHET_ROSE with the rule, its counts and the new problem lines.+ *+ * @param {string} root - The clean submitting checkout, at `commit`.+ * @param {{ mainCommit: string, commit: string, practice?: string, timeoutMs?: number }} options+ * @returns {ReturnType<typeof doctrineReport>}+ */+ export function holdDoctrine(root, { mainCommit, commit, practice = DOCTRINE_FILE, timeoutMs = DEFAULT_TIMEOUT_MS }) {+ const rules = checkRulesAt(root, mainCommit, practice).filter((rule) => rule.runs === 'submit');+ if (!rules.length) return [];+ const lowered = new Map(checkRulesAt(root, commit, practice).map((rule) => [rule.id, rule.count]));+ const base = (gitOut(root, ['merge-base', mainCommit, commit]) ?? '').trim() || mainCommit;+ const changed = (gitOut(root, ['diff', '-z', '--no-renames', '--name-only', base, commit, '--']) ?? '').split('\0').filter(Boolean);+ const results = [];+ const refusals = [];+ const uncounted = [];+ for (const rule of rules) {+ if (!changed.some((path) => inScope(rule.files, path))) continue;+ const committed = Math.min(rule.count, lowered.get(rule.id) ?? rule.count);+ const run = runRuleCheck(root, rule.command, timeoutMs);+ const count = run.problems.length;+ const state = ruleState(rule, count, committed, run.broken);+ const result = { id: rule.id, text: rule.text, command: rule.command, count, committed,+ holds: state === 'holding' || state === 'watching', state, mode: rule.mode, runs: rule.runs, problems: run.problems, broken: run.broken };+ results.push(result);+ const name = `${rule.id} ${rule.text}`;+ // A broken check never passes, whatever its mode.+ if (run.broken) {+ uncounted.push(`${name} cannot count: its check ${run.broken}`);+ continue;+ }+ if (rule.mode === 'watch') continue;+ const touched = changed.filter((path) => run.problems.some((line) => namesFile(line, path)));+ const before = touched.length ? runAtCommit(root, base, rule.command, timeoutMs) : { problems: [], broken: '' };+ if (count > committed) {+ const fresh = newLines(before.broken ? [] : before.problems, run.problems);+ refusals.push(`${name} rose to ${count}, was ${committed}; new problems:\n${(fresh.length ? fresh : run.problems).map((line) => ` ${line}`).join('\n')}`);+ continue;+ }+ if (before.broken) {+ uncounted.push(`${name} cannot count at the base ${base.slice(0, 12)}: its check ${before.broken}`);+ continue;+ }+ for (const path of touched) {+ const now = run.problems.filter((line) => namesFile(line, path));+ const then = before.problems.filter((line) => namesFile(line, path));+ if (now.length <= then.length) continue;+ const gained = now.length - then.length;+ const fresh = newLines(then, now);+ refusals.push(`${name}: ${path} gains ${gained} problem${gained === 1 ? '' : 's'}, had ${then.length}:\n${(fresh.length ? fresh : now).map((line) => ` ${line}`).join('\n')}`);+ }+ }+ if (uncounted.length) {+ throw new Refused('RATCHET_UNCOUNTED', `${uncounted.join('\n')}\na check exits 0 or 1 within its timeout; fix the check, or ask the coordinator to, then submit again`);+ }+ if (refusals.length) {+ throw new Refused('RATCHET_ROSE', `${refusals.join('\n')}\nthe doctrine holds these counts; fix the new problems, commit, and submit again; only the person's signature raises count:`);+ }+ return results;+ }diff --cc src/engine.jsindex 5d619ef4,8be6dc97..52f5ecb4--- a/src/engine.js+++ b/src/engine.js@@@ -1,21 -1,13 +1,29 @@@/** Versioned, deterministic replay through the CLI's existing board engine [H3,H16]. */-import { createHash, randomUUID } from 'node:crypto';+import {+ createHash,+ randomUUID,+} from 'node:crypto';import * as store from './board.js';import { recordedRefusal } from './recorded-refusal.js';-import { BAR_ENGINE, carriesBarReason } from './bar-corrections.js';-import { carriesImplies, IMPLIES_ENGINE } from './implies.js';++import {++ BAR_ENGINE,++ carriesBarReason,++} from './bar-corrections.js';++import {++ carriesImplies,++ IMPLIES_ENGINE,++} from './implies.js';import { ENGINE_VERSION } from './machine.js';import { Refused } from './refused.js';-import { requestMoveProblem, recordRequestMove } from './relay-requests.js';-import { relayMoveActor, relaySenderProblem, validRelaySender } from './relay-sender.js';+import {+ requestMoveProblem,+ recordRequestMove,+} from './relay-requests.js';+import {+ relayMoveActor,+ relaySenderProblem,+ validRelaySender,+} from './relay-sender.js';const ITEM_ID_FIRST_ARGUMENT = new Set(['editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze', 'reopen', 'appendFact']);diff --cc src/gate.jsindex 26ecb764,bb2e99c5..b0e7c2c3--- a/src/gate.js+++ b/src/gate.js@@@ -4,62 -4,22 +4,69 @@@* tree's id in the git dir, so the same tree is never checked twice. An agent sees a digest of the* run, not the run (V10): a passing suite's output costs tokens and says nothing.*/-import { spawn, spawnSync } from 'node:child_process';+import {+ spawn,+ spawnSync,+} from 'node:child_process';import { randomUUID } from 'node:crypto';-import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';-import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';+import {+ existsSync,+ mkdirSync,+ readFileSync,++ realpathSync,+ statSync,+ writeFileSync,+} from 'node:fs';+import {+ dirname,+ isAbsolute,+ join,+ relative,++ resolve,+ sep,+} from 'node:path';import { availableParallelism } from 'node:os';import { fileURLToPath } from 'node:url';-import { gitChildEnv, gitPath, headTree, invalidateGitFacts, isClean, untracked } from './git.js';+import {+ gitChildEnv,+ gitPath,+ headTree,+ invalidateGitFacts,+ isClean,+ untracked,+} from './git.js';import { secretsIn } from './hooks.js';import { Refused } from './refused.js';-import { GATE_SLOT_HELD_ENV, gateSlotEnvironment, inheritedGateSlot, memoryAdmission, readMachineMemory, takeResource } from './resources.js';-import { browserFreeChecksEnabled, gateQueueSettings, loadMachineSettings, memoryFloorMB } from './settings.js';+import {+ GATE_SLOT_HELD_ENV,+ gateSlotEnvironment,+ inheritedGateSlot,++ memoryAdmission,++ readMachineMemory,+ takeResource,+} from './resources.js';+import {+ browserFreeChecksEnabled,++ gateQueueSettings,+ loadMachineSettings,++ memoryFloorMB,+} from './settings.js';import { selectAffectedTests } from './affected-tests.js';-import { checkNeedsBrowser, testsNeedBrowser } from './browser-admission.js';-import { timingFromOutput, timingRunner } from './timing.js';+import {+ checkNeedsBrowser,+ testsNeedBrowser,+} from './browser-admission.js';+import {+ timingFromOutput,+ timingRunner,+} from './timing.js';+ import { landingShardProfile } from './landing-shards.js';-import { RunnerDropped, runOnRunner, runOnRunnerAsync, runnerSource } from './runners.js';+import {+ RunnerDropped,+ runOnRunner,+ runOnRunnerAsync,+ runnerSource,+} from './runners.js';const STAMP = 'pullboard-gate-green';const LOG = 'pullboard-gate.log';diff --cc src/implies.jsindex 00000000,760443b9..9071545fmode 000000,100644..100644--- a/src/implies.js+++ b/src/implies.js@@@ -1,0 -1,337 +1,348 @@@+ /**+ * A decision names the items it changes, and each named item carries it [B29,B30,B31,N29,P6].+ *+ * An answer, a verdict or a fact can carry `implies`: the ids of other items the decision changes.+ * Each named item gets a fact citing the decision, and when the decision is superseded each gets a+ * second fact naming the new one. Both are ordinary item facts in the event log; no other store.+ *+ * Who decided always comes from the board's own record of the decision (the answer's sender, the+ * verdict's reviewer, the fact's author), never from the caller's arguments, so no relay or API+ * caller can mint a person-origin citation (P6). The only route to `by: "person"` is a real+ * person answer, which keeps its own person-channel rules.+ */-import { createHash, randomUUID } from 'node:crypto';-import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';-import { dirname, join } from 'node:path';++import {++ createHash,++ randomUUID,++} from 'node:crypto';++import {++ mkdirSync,++ readFileSync,++ renameSync,++ writeFileSync,++} from 'node:fs';++import {++ dirname,++ join,++} from 'node:path';+ import { COORDINATOR } from './config.js';+ import { ENGINE_VERSION } from './machine.js';+ import { Refused } from './refused.js';++ /** The engine whose moves may carry `implies`, or supersede an answer; older replays never do. */+ export const IMPLIES_ENGINE = 20;++ /** The operations whose sealed options may carry `implies`. */+ export const IMPLYING_OPERATIONS = Object.freeze(['appendFact', 'answerDecision', 'verify']);++ /**+ * Parse an `--implies` value into item ids, accepting `12,13` or `#12, #13`.+ *+ * @param {string | undefined} text+ * @returns {number[] | undefined}+ */+ export function parseImplies(text) {+ if (text === undefined) return undefined;+ const parts = String(text).split(',').map((part) => part.trim()).filter(Boolean);+ if (!parts.length || parts.some((part) => !/^#?[1-9]\d*$/u.test(part))) {+ throw new Refused('USAGE', `--implies takes item ids separated by commas, as in --implies 12,13 (saw "${text}")`);+ }+ return [...new Set(parts.map((part) => Number(part.replace('#', ''))))];+ }++ /**+ * True when a sealed move carries this engine's meaning: items it implies, or an answer it supersedes.+ * The relay refuses such a move from an older engine before it changes any board.+ *+ * @param {string} operation+ * @param {any[]} args+ * @returns {boolean}+ */+ export function carriesImplies(operation, args) {+ const options = args?.[1];+ if (!IMPLYING_OPERATIONS.includes(operation) || !options || typeof options !== 'object') return false;+ return (Array.isArray(options.implies) && options.implies.length > 0)+ || (operation === 'answerDecision' && options.supersedes !== undefined && options.supersedes !== null);+ }++ /**+ * Validate the implied ids before any part of the decision is written, naming the first unknown one.+ * Refuses on a board replaying an older engine, so a forged older move cannot change state.+ *+ * @param {any} board+ * @param {unknown} implies+ * @returns {number[]}+ */+ export function checkImplies(board, implies) {+ if (implies === undefined || implies === null) return [];+ if (!Array.isArray(implies) || implies.some((id) => !Number.isSafeInteger(id) || id < 1)) {+ throw new Refused('USAGE', '--implies takes item ids separated by commas, as in --implies 12,13');+ }+ const engine = board.executionEngineVersion ?? ENGINE_VERSION;+ if (implies.length && engine < IMPLIES_ENGINE) {+ throw new Refused('ENGINE_VERSION', `a decision that implies items requires engine ${IMPLIES_ENGINE}; this board uses engine ${engine}; upgrade Pullboard before using --implies`);+ }+ for (const id of implies) {+ if (!board.db.prepare('SELECT 1 FROM item WHERE item_id = ?').get(id)) {+ throw new Refused('NO_ITEM', `no item #${id} to imply; name items from pullboard list --all`);+ }+ }+ return [...new Set(implies)];+ }++ /** The first nonempty line of a decision's text, trimmed, as its citation reads it. */+ export function firstLine(text) {+ return String(text ?? '').split('\n').map((line) => line.trim()).find(Boolean) ?? '';+ }++ /** A short name for a decision, as the facts and `pullboard why` print it. */+ export function decisionLabel(decision) {+ if (decision.source === 'answer') return `answer #${decision.id}`;+ if (decision.source === 'verdict') return `verdict on #${decision.item}`;+ return `fact ${decision.id} on #${decision.item}`;+ }++ /** The citation of an answer, read from its shout row. */+ export function answerDecisionRef(shout) {+ return { source: 'answer', id: shout.shout_id, item: null, by: shout.shout_from, line: firstLine(shout.shout_text) };+ }++ /** The citation of a verdict, read from its verdict row. */+ export function verdictDecisionRef(verdict) {+ const verb = verdict.verdict_decision === 'ACCEPT' ? 'accept' : 'reject';+ const note = firstLine(verdict.verdict_note);+ return { source: 'verdict', id: verdict.verdict_id, item: verdict.item_id, by: verdict.verdict_by,+ line: `${verb} ${verdict.verdict_reason}${note ? `: ${note}` : ''}` };+ }++ /** The citation of a fact, read from its stamped event. */+ export function factDecisionRef(fact, itemId) {+ return { source: 'fact', id: fact.id, item: itemId, by: fact.by, line: firstLine(fact.text) };+ }++ /**+ * The seed for implied-fact ids: the sealed move id on replay, or a fresh one when no move supplies it.+ * A move id may be 80 characters, but an implied id adds a suffix and must still fit a fact id, so a+ * move id longer than 72 is replaced by a digest of itself: every replica derives the same ids.+ */+ export function impliesSeed(seed) {+ if (typeof seed === 'string' && /^[A-Za-z0-9_-]{1,72}$/u.test(seed)) return seed;+ if (typeof seed === 'string' && /^[A-Za-z0-9_-]{73,80}$/u.test(seed)) return `h${createHash('sha256').update(seed).digest('base64url').slice(0, 43)}`;+ return randomUUID();+ }++ /**+ * Write one fact on each implied item citing the decision, stamped with the decider.+ *+ * @param {(by: string, itemId: number, detail: object) => void} log appends one fact event+ * @param {{ seed: string, decision: object, implies: number[] }} options+ */+ export function writeImplied(log, { seed, decision, implies }) {+ for (const itemId of implies) {+ log(decision.by, itemId, { id: `${seed}-i${itemId}`, kind: 'note', text: `implied by ${decisionLabel(decision)} by ${decision.by}: ${decision.line}`,+ ref: null, supersedes: null, decision });+ }+ }++ /**+ * Tell each item the old decision implied that a new decision supersedes it, stamped with the new decider.+ *+ * @param {(by: string, itemId: number, detail: object) => void} log appends one fact event+ * @param {{ seed: string, old: object, next: object, implies: number[] }} options+ */+ export function writeSuperseded(log, { seed, old, next, implies }) {+ for (const itemId of implies) {+ log(next.by, itemId, { id: `${seed}-s${itemId}`, kind: 'note',+ text: `${decisionLabel(old)} by ${old.by} is superseded by ${decisionLabel(next)} by ${next.by}: ${next.line}`,+ ref: null, supersedes: null, decision: old, supersededBy: next });+ }+ }++ /** True when two citations name the same decision. */+ function sameDecision(left, right) {+ return Boolean(left && right) && left.source === right.source && left.id === right.id && (left.item ?? null) === (right.item ?? null);+ }++ /**+ * The items an earlier decision implied, read from the facts it wrote.+ *+ * @param {any} board+ * @param {object} decision+ * @returns {number[]}+ */+ export function impliedItems(board, decision) {+ const rows = board.db.prepare("SELECT item_id, event_detail FROM event WHERE event_kind = 'fact' AND json_extract(event_detail, '$.decision') IS NOT NULL AND json_extract(event_detail, '$.supersededBy') IS NULL ORDER BY event_id").all();+ return [...new Set(rows.filter((row) => sameDecision(JSON.parse(row.event_detail).decision, decision)).map((row) => row.item_id))];+ }++ /**+ * The decisions that imply an item, newest first, each with the decision that superseded it (N29).+ *+ * @param {any[]} thread the item's facts and moves, oldest first+ * @returns {{ source: string, id: any, item: number | null, by: string, line: string, at: string, fact: string, supersededBy: object | null }[]}+ */+ export function decisionsImplying(thread) {+ const facts = thread.filter((entry) => entry.type === 'fact' && entry.decision);+ return facts.filter((fact) => !fact.supersededBy)+ .map((fact) => ({ ...fact.decision, at: fact.at, fact: fact.id,+ supersededBy: facts.filter((notice) => notice.supersededBy && sameDecision(notice.decision, fact.decision)).at(-1)?.supersededBy ?? null }))+ .reverse();+ }++ /** One line for a decision as `pullboard why` prints it. */+ export function whyLine(entry) {+ return `${entry.at} ${decisionLabel(entry)} by ${entry.by}: ${entry.line}${entry.supersededBy ? ` (superseded by ${decisionLabel(entry.supersededBy)} by ${entry.supersededBy.by})` : ''}`;+ }++ /** True when this replay's engine tells implied items about supersession; older replays never did. */+ export function tellsSupersession(board) {+ return (board.executionEngineVersion ?? ENGINE_VERSION) >= IMPLIES_ENGINE;+ }++ /** One shout row, or a refusal naming its id. */+ function shoutRow(board, id) {+ const found = board.db.prepare('SELECT * FROM shout WHERE shout_id = ?').get(id);+ if (!found) throw new Refused('NO_SHOUT', `no shout #${id}`);+ return found;+ }++ /**+ * The earlier answer a new answer supersedes, or null; refuses anything that is not an answered+ * decision, and an agent overruling the person (P6) or another agent's answer (B30).+ *+ * @param {any} board+ * @param {number | null} supersedes+ * @param {{ from: string, person: string }} answerer who answers now, and the person's id+ * @returns {any | null}+ */+ export function supersededAnswer(board, supersedes, { from, person }) {+ if (supersedes === null || supersedes === undefined) return null;+ const engine = board.executionEngineVersion ?? ENGINE_VERSION;+ if (engine < IMPLIES_ENGINE) throw new Refused('ENGINE_VERSION', `superseding an answer requires engine ${IMPLIES_ENGINE}; this board uses engine ${engine}; upgrade Pullboard before using --supersedes`);+ if (!Number.isSafeInteger(supersedes) || supersedes < 1) throw new Refused('USAGE', 'name the answer this one supersedes by its shout id: --supersedes 12');+ const old = shoutRow(board, supersedes);+ const ask = old.shout_answers === null ? null : shoutRow(board, old.shout_answers);+ if (old.shout_decision || !ask?.shout_decision || ask.shout_request) {+ throw new Refused('NOT_A_DECISION', `shout #${supersedes} is not an answer to a decision; supersede an answer id from pullboard decisions`);+ }+ if (old.shout_from === person && from !== person) {+ throw new Refused('B26_PERSON_ANSWER', `answer #${supersedes} is the person's; only the person supersedes it: ask your coordinator to pass a new decision to the person`);+ }+ if (from !== person && from !== COORDINATOR && old.shout_from !== from) {+ throw new Refused('NOT_YOUR_DECISION', `answer #${supersedes} is ${old.shout_from}'s; only its author, the coordinator or the person supersedes it`);+ }+ return old;+ }++ /**+ * Cite the newest verdict on each item it implies, and tell the items the verdict before it+ * implied that this one supersedes it. Engines before IMPLIES_ENGINE replay unchanged.+ * Runs inside the verdict's transaction, so a refused id leaves no verdict behind.+ *+ * @param {any} board+ * @param {(by: string, itemId: number, detail: object) => void} log appends one fact event+ * @param {number} id the verdict's item+ * @param {{ seed?: string, implies?: number[] }} options+ */+ export function tellVerdictImplications(board, log, id, { seed, implies }) {+ const named = checkImplies(board, implies);+ const [latest, previous] = board.db.prepare('SELECT * FROM verdict WHERE item_id = ? ORDER BY verdict_id DESC LIMIT 2').all(id);+ const decision = verdictDecisionRef(latest);+ const ids = impliesSeed(seed);+ writeImplied(log, { seed: ids, decision, implies: named });+ if (!previous || !tellsSupersession(board)) return;+ const old = verdictDecisionRef(previous);+ writeSuperseded(log, { seed: ids, old, next: decision, implies: impliedItems(board, old) });+ }++ /**+ * Cite a new answer on each item it implies, and tell the items an earlier answer implied that this+ * one supersedes it. Runs inside the answer's transaction, so a refusal leaves no answer behind.+ *+ * @param {any} board+ * @param {(by: string, itemId: number, detail: object) => void} log appends one fact event+ * @param {number} answerId the new answer's shout id+ * @param {{ seed?: string, implies?: number[], supersedes?: number | null, from: string, person: string }} options+ * @returns {number} the answer's id, so the caller records and tells in one step+ */+ export function tellAnswerImplications(board, log, answerId, { seed, implies, supersedes, from, person }) {+ const named = checkImplies(board, implies);+ const replaced = supersededAnswer(board, supersedes, { from, person });+ const decision = answerDecisionRef(shoutRow(board, answerId));+ const ids = impliesSeed(seed);+ writeImplied(log, { seed: ids, decision, implies: named });+ if (replaced) writeSuperseded(log, { seed: ids, old: answerDecisionRef(replaced), next: decision, implies: impliedItems(board, answerDecisionRef(replaced)) });+ return answerId;+ }++ /**+ * Cite a new fact on each item it implies, and tell the items the fact it supersedes implied.+ * Runs inside the fact's transaction, so a refused id leaves no fact behind.+ *+ * @param {any} board+ * @param {(by: string, itemId: number, detail: object) => void} log appends one fact event+ * @param {any} fact the new fact as the thread reads it+ * @param {{ id: number, implies?: number[], supersedes: string | null }} options its item, implied ids and the fact it corrects+ * @returns {any} the new fact+ */+ export function tellFactImplications(board, log, fact, { id, implies, supersedes }) {+ const named = checkImplies(board, implies);+ const decision = factDecisionRef(fact, id);+ const seed = impliesSeed(fact.id);+ writeImplied(log, { seed, decision, implies: named });+ if (supersedes !== null && tellsSupersession(board)) {+ const row = board.db.prepare("SELECT event_by, event_detail FROM event WHERE event_kind = 'fact' AND item_id = ? AND json_extract(event_detail, '$.id') = ?").get(id, supersedes);+ const old = factDecisionRef({ id: supersedes, by: row.event_by, text: JSON.parse(row.event_detail).text }, id);+ writeSuperseded(log, { seed, old, next: decision, implies: impliedItems(board, old) });+ }+ return fact;+ }++ /** The refusal for an answer to a request: a person answer, or one that names items or supersedes. */+ export function requestAnswerRefusal(id, { asPerson }) {+ return asPerson+ ? new Refused('B26_PERSON_ANSWER', `requests are answered by the coordinator; run pullboard answer ${id} done or declined <reason>`)+ : new Refused('NOT_A_DECISION', `request #${id} is not a decision, so it implies and supersedes nothing; answer it with pullboard answer ${id} done or declined <reason>`);+ }++ /** The optional engine-20 fields of a fact, present only when its event set them. */+ export function decisionFields(detail) {+ return { ...(detail.implies ? { implies: detail.implies } : {}), ...(detail.decision ? { decision: detail.decision } : {}),+ ...(detail.supersededBy ? { supersededBy: detail.supersededBy } : {}) };+ }++ /** The most fact ids one checkout remembers as shown; older ones age out first. */+ const SEEN_LIMIT = 2000;++ /**+ * The decision facts on the items this agent holds that its resume has not shown yet, marking them+ * shown. The record is per checkout, like resume's release notes, so each shows once (B29).+ *+ * @param {string} gitDir this checkout's own git directory+ * @param {{ item: number, facts: any[] }[]} held each held item and its thread+ * @returns {{ item: number, fact: string, text: string }[]}+ */+ export function takeDecisionNotices(gitDir, held) {+ const record = join(gitDir, 'pullboard-checkout', 'decisions-seen.json');+ let seen = [];+ try { seen = JSON.parse(readFileSync(record, 'utf8')).seen ?? []; }+ catch (error) { if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error; }+ if (!Array.isArray(seen)) seen = [];+ const known = new Set(seen);+ const notices = held.flatMap(({ item, facts }) => facts+ .filter((fact) => fact.type === 'fact' && fact.decision && !known.has(fact.id))+ .map((fact) => ({ item, fact: fact.id, text: fact.text })));+ if (!notices.length) return notices;+ const next = [...seen, ...notices.map((notice) => notice.fact)].slice(-SEEN_LIMIT);+ mkdirSync(dirname(record), { recursive: true });+ const temporary = `${record}.${randomUUID()}.tmp`;+ writeFileSync(temporary, `${JSON.stringify({ version: 1, seen: next })}\n`);+ renameSync(temporary, record);+ return notices;+ }++ /** Give facts the same stamped identity on CLI, API, export and replica reads [B29,B31]. */+ export function factFromEvent(event) {+ const detail = JSON.parse(event.event_detail);+ return { id: detail.id, eventId: event.event_id, kind: detail.kind, text: detail.text,+ by: event.event_by, at: event.event_at, ref: detail.ref ?? null, supersedes: detail.supersedes ?? null, ...decisionFields(detail) };+ }diff --cc src/init.jsindex a1991598,01242641..0f510bc3--- a/src/init.js+++ b/src/init.js@@@ -5,27 -5,11 +5,28 @@@* write.*/import {- accessSync, appendFileSync, constants as fsConstants, existsSync, mkdirSync,- readdirSync, readFileSync, statSync, writeFileSync,+ accessSync,+ appendFileSync,+ constants as fsConstants,+ existsSync,+ mkdirSync,++ readdirSync,+ readFileSync,+ statSync,+ writeFileSync,} from 'node:fs';-import { delimiter, basename, join, resolve } from 'node:path';-import { CONFIG_FILE, COORDINATOR, doctrineFile, loadConfig } from './config.js';+import {+ delimiter,+ basename,+ join,+ resolve,+} from 'node:path';+import {+ CONFIG_FILE,+ COORDINATOR,+ doctrineFile,+ loadConfig,+} from './config.js';import { loadDoctrine } from './doctrine.js';import { installHooks } from './hooks.js';import { Refused } from './refused.js';diff --cc src/land.jsindex a92066bb,e5e12876..5e01af74--- a/src/land.js+++ b/src/land.js@@@ -1,36 -1,10 +1,39 @@@/** Coordinator landing batches retain exact Git and gate receipts across interruptions [B3,R3]. */-import { createHash, randomUUID } from 'node:crypto';-import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync } from 'node:fs';-import { dirname, isAbsolute, join, relative } from 'node:path';+import {+ createHash,+ randomUUID,+} from 'node:crypto';+import {++ closeSync,+ copyFileSync,+ existsSync,+ mkdirSync,++ openSync,+ readFileSync,++ readSync,+} from 'node:fs';+import {+ dirname,+ isAbsolute,+ join,+ relative,+} from 'node:path';import * as store from './board.js';-import { git, headCommit, headTree, isClean, mainCheckout, repoInfo, tryGit, untracked } from './git.js';-import { runGate, runProfiledShell, withGateSlot } from './gate.js';+import {+ git,+ headCommit,+ headTree,+ isClean,+ mainCheckout,+ repoInfo,+ tryGit,+ untracked,+} from './git.js';+import {+ runGate,+ runProfiledShell,+ withGateSlot,+} from './gate.js';import { laneOf } from './lanes.js';import { Refused } from './refused.js';diff --cc src/landing-shards.jsindex 00000000,2b167432..e5075377mode 000000,100644..100644--- a/src/landing-shards.js+++ b/src/landing-shards.js@@@ -1,0 -1,528 +1,548 @@@+ /**+ * The landing gate in shards [C7,V4]: split the tracked test files into balanced shards, run each on+ * a free local gate slot or a registered runner, and report one result. One red shard stops the rest,+ * and a shard whose runner fails mid-run reruns locally.+ */-import { spawn, spawnSync } from 'node:child_process';-import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, renameSync, writeFileSync } from 'node:fs';-import { dirname, join } from 'node:path';-import { createHash, randomUUID } from 'node:crypto';-import { gitChildEnv, repoInfo } from './git.js';++import {++ spawn,++ spawnSync,++} from 'node:child_process';++import {++ existsSync,++ lstatSync,++ mkdirSync,++ readFileSync,++ readlinkSync,++ renameSync,++ writeFileSync,++} from 'node:fs';++import {++ dirname,++ join,++} from 'node:path';++import {++ createHash,++ randomUUID,++} from 'node:crypto';++import {++ gitChildEnv,++ repoInfo,++} from './git.js';+ import { parseProcessCensus } from './process-census.js';+ import {+ BROWSER_SLOT_HELD_ENV,+ GATE_SLOT_HELD_ENV,+ GATE_SLOT_POOL_ENV,+ GATE_SLOT_TOKEN_ENV,+ gateSlotEnvironment,+ } from './resources.js';++ /** Environment variable naming the shard a nested run-tests process runs, as `<i>/<n>`. */+ export const LANDING_SHARD_ENV = 'PULLBOARD_LANDING_SHARD';+ /** Environment variable naming the file where each test file process appends its wall time. */+ export const LANDING_FILE_TIMES_ENV = 'PULLBOARD_LANDING_FILE_TIMES';+ /** Prefix of the per-file wall-time lines a shard prints for its orchestrator. */+ export const FILE_TIME_LINE = '# landing-file-ms ';++ const GATE_MARKERS = [GATE_SLOT_HELD_ENV, GATE_SLOT_POOL_ENV, GATE_SLOT_TOKEN_ENV, BROWSER_SLOT_HELD_ENV];+ // Budget: a stopped shard's run-tests drains its owned processes within its 12 s custody limit; past+ // this its group is killed.+ const STOP_GRACE_MS = 20_000;+ // Budget: each signal round of the final sweep waits this long for a process to go.+ const SWEEP_WAIT_MS = 1_000;++ /** Where the last landing's per-file wall times live, shared by every worktree of the repository. */+ export function fileTimesPath(root) {+ return join(repoInfo(root).commonDir, 'pullboard', 'landing-file-times.json');+ }++ /** Read the last per-file wall times; a missing or unreadable record means none are known. */+ export function readFileTimes(root) {+ try {+ const value = JSON.parse(readFileSync(fileTimesPath(root), 'utf8'));+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {};+ return Object.fromEntries(Object.entries(value.files ?? {}).filter(([, ms]) => Number.isFinite(ms) && ms >= 0));+ } catch { return {}; }+ }++ /** Keep the newest wall time for every file this landing measured, beside the older ones. */+ function writeFileTimes(root, measured) {+ const path = fileTimesPath(root);+ const files = { ...readFileTimes(root), ...measured };+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;+ writeFileSync(temporary, `${JSON.stringify({ version: 1, files }, null, 2)}\n`, { mode: 0o600 });+ renameSync(temporary, path);+ }++ /** Normalize a test file path to its repository-relative form, without a leading `./`. */+ export function fileKey(file) {+ return String(file).replace(/^\.\//u, '');+ }++ /**+ * Split files into at most `count` shards by weight, heaviest first onto the lightest shard.+ * A file with a known wall time weighs that time; with no times at all every file weighs one, so the+ * split falls back to file count. A new file weighs the average known time. Empty shards are dropped.+ *+ * @param {string[]} files+ * @param {number} count+ * @param {Record<string, number>} [times] - Last wall time in ms by repository-relative path.+ * @returns {{ files: string[], weight: number }[]}+ */+ export function planLandingShards(files, count, times = {}) {+ const known = files.map(file => times[fileKey(file)]).filter(ms => Number.isFinite(ms));+ const average = known.length ? known.reduce((sum, ms) => sum + ms, 0) / known.length : 1;+ const weight = file => known.length ? (Number.isFinite(times[fileKey(file)]) ? times[fileKey(file)] : average) : 1;+ const ordered = [...files].sort((a, b) => weight(b) - weight(a) || a.localeCompare(b));+ const shards = Array.from({ length: Math.max(1, count) }, () => ({ files: [], weight: 0 }));+ for (const file of ordered) {+ const lightest = shards.reduce((best, shard) => shard.weight < best.weight+ || (shard.weight === best.weight && shard.files.length < best.files.length) ? shard : best);+ lightest.files.push(file);+ lightest.weight += weight(file);+ }+ for (const shard of shards) shard.files.sort((a, b) => a.localeCompare(b));+ return shards.filter(shard => shard.files.length);+ }++ /**+ * Name how a plan was balanced: by the last measured per-file wall times when every file has one,+ * by those times with new files at their average when some do, and by file count when none do.+ *+ * @param {string[]} files+ * @param {Record<string, number>} [times]+ * @returns {'history'|'history and average'|'file count'}+ */+ export function landingBalance(files, times = {}) {+ const known = files.filter(file => Number.isFinite(times[fileKey(file)])).length;+ return known === files.length && known ? 'history' : known ? 'history and average' : 'file count';+ }++ /** The slowest file with a recorded wall time, which no shard count can beat; null with no history. */+ export function landingFloor(files, times = {}) {+ let floor = null;+ for (const file of files) {+ const ms = times[fileKey(file)];+ if (Number.isFinite(ms) && (!floor || ms > floor.ms)) floor = { path: fileKey(file), ms: Math.round(ms) };+ }+ return floor;+ }++ /** Read the per-file wall-time lines a shard printed, keeping the longest report for each file. */+ export function shardFileTimes(output) {+ const times = {};+ for (const line of String(output).split(/\r?\n/u)) {+ if (!line.startsWith(FILE_TIME_LINE)) continue;+ const rest = line.slice(FILE_TIME_LINE.length);+ const space = rest.indexOf(' ');+ const ms = Number(rest.slice(0, space));+ const file = fileKey(rest.slice(space + 1));+ if (space > 0 && Number.isFinite(ms) && ms >= 0 && file) times[file] = Math.max(times[file] ?? 0, ms);+ }+ return times;+ }++ /** The process environment without this process's own gate markers, so a shard never reuses them. */+ function withoutGateMarkers(env) {+ const copy = { ...env };+ for (const key of GATE_MARKERS) delete copy[key];+ return copy;+ }++ /** Quote one word for the runner's POSIX shell. */+ function word(value) {+ return `'${String(value).replaceAll("'", "'\\''")}'`;+ }++ /** One process census, or null when it cannot be taken; a missing census is never an empty machine. */+ function census() {+ const result = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], {+ encoding: 'utf8', timeout: 5_000, maxBuffer: 16 * 1024 * 1024, env: { PATH: '/bin:/usr/bin', LANG: 'C', LC_ALL: 'C', TZ: 'UTC' } }); // budget: one bounded ps call.+ if (result.error || result.status !== 0 || typeof result.stdout !== 'string') return null;+ return parseProcessCensus(result.stdout);+ }++ /**+ * Every process a shard owns: its parent-tree descendants, including detached ones that started+ * their own group or session, plus every member of their groups. Taken before any signal, while the+ * tree still links them, since an orphaned process loses its parent link.+ */+ export function shardProcesses(rootPid, rows = census()) {+ if (!rows) return null;+ const owned = new Map();+ const children = new Map();+ for (const row of rows.values()) {+ if (!children.has(row.ppid)) children.set(row.ppid, []);+ children.get(row.ppid).push(row);+ }+ const queue = rows.has(rootPid) ? [rows.get(rootPid)] : [];+ while (queue.length) {+ const row = queue.shift();+ if (owned.has(row.pid)) continue;+ owned.set(row.pid, row);+ queue.push(...(children.get(row.pid) ?? []));+ }+ const ownGroup = rows.get(process.pid)?.pgid;+ const groups = new Set([...owned.values()].map(row => row.pgid).filter(pgid => pgid !== ownGroup));+ for (const row of rows.values()) if (groups.has(row.pgid) && row.pid !== process.pid) owned.set(row.pid, row);+ return owned;+ }++ /** The owned processes still alive with the same identity, or null when no census can tell. */+ function survivors(owned) {+ const rows = census();+ if (!rows) return null;+ return [...owned.values()].filter(row => rows.get(row.pid)?.started === row.started);+ }++ /** Signal one process only while it is still the one the shard owned. */+ function signalOwned(row, name) {+ try { process.kill(row.pid, name); } catch (error) { if (error.code !== 'ESRCH') throw error; }+ }++ /**+ * Stop a shard and prove its processes are gone. TERM asks its run-tests to stop through its own+ * custody, which drains every descendant it tracked; whatever the census still finds is signalled+ * here. Returns the processes that could not be shown gone, named by pid and command hash.+ */+ async function stopShard(child, closed) {+ const owned = shardProcesses(child.pid);+ signalOwned({ pid: child.pid }, 'SIGTERM');+ let timer;+ const drained = await Promise.race([closed.then(() => true), new Promise(resolveWait => { timer = setTimeout(() => resolveWait(false), STOP_GRACE_MS); })]);+ clearTimeout(timer);+ if (!drained) {+ try { process.kill(-child.pid, 'SIGKILL'); } catch (error) { if (error.code !== 'ESRCH') throw error; }+ await closed;+ }+ if (!owned) return ['process census unavailable'];+ for (const name of ['SIGTERM', 'SIGKILL']) {+ const left = survivors(owned);+ if (!left) return ['process census unavailable'];+ if (!left.length) return [];+ for (const row of left) signalOwned(row, name);+ await new Promise(resolveWait => setTimeout(resolveWait, SWEEP_WAIT_MS));+ }+ const left = survivors(owned);+ if (!left) return ['process census unavailable'];+ return left.map(row => `pid ${row.pid} (${row.processSha256.slice(0, 12)})`);+ }++ /** Run one shard's files in a local child run-tests that inherits the shard's own gate lease. */+ async function runLocalShard({ root, runner, files, label, lease, stop }) {+ const env = { ...withoutGateMarkers(process.env), ...gateSlotEnvironment(lease),+ PULLBOARD_LANDING_RUN: '1', [LANDING_SHARD_ENV]: label };+ // Its own process group, so a stop reaches the shard's test files and their children together.+ const child = spawn(process.execPath, [runner, ...files], { cwd: root, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+ const chunks = [];+ child.stdout.setEncoding('utf8').on('data', part => chunks.push(part));+ child.stderr.setEncoding('utf8').on('data', part => chunks.push(part));+ const closed = new Promise(resolveClose => {+ child.once('error', error => { chunks.push(`\n${error.message}\n`); resolveClose({ status: 1, signal: null }); });+ child.once('close', (status, signal) => resolveClose({ status, signal }));+ });+ let stopping = null;+ const onStop = () => { stopping = stopShard(child, closed).catch(error => [`stop failed: ${error.message}`]); };+ if (stop.aborted) onStop();+ else stop.addEventListener('abort', onStop, { once: true });+ const { status, signal } = await closed;+ stop.removeEventListener('abort', onStop);+ const unverified = stopping ? await stopping : [];+ return { isGreen: status === 0 && !signal && !stopping, output: chunks.join(''), unverified };+ }++ /**+ * A fingerprint of exactly what a local shard would run: HEAD, every tracked change against it and+ * the names and contents of the untracked files Git does not ignore. A landing pins it before its+ * first shard; a same-name replacement of an untracked file changes it too.+ *+ * @param {string} root+ * @returns {{ commit: string, fingerprint: string }}+ */+ export function landingSource(root) {+ const git = args => {+ const result = spawnSync('git', args, { cwd: root, env: gitChildEnv(root), encoding: 'buffer', maxBuffer: 1024 ** 3 });+ if (result.status !== 0) throw new Error(`git ${args[0]} failed while pinning the landing source`);+ return result.stdout;+ };+ const commit = git(['rev-parse', 'HEAD']).toString('utf8').trim();+ const hash = createHash('sha256').update(commit).update('\0')+ .update(git(['diff', 'HEAD', '--binary', '--no-ext-diff'])).update('\0');+ for (const path of git(['ls-files', '--others', '--exclude-standard', '-z']).toString('utf8').split('\0').filter(Boolean)) {+ const full = join(root, path);+ let content;+ try {+ const stat = lstatSync(full);+ content = stat.isSymbolicLink() ? `link:${readlinkSync(full)}` : stat.isFile() ? readFileSync(full) : `kind:${stat.mode}`;+ } catch { content = 'missing'; }+ hash.update(path).update('\0').update(content).update('\0');+ }+ return { commit, fingerprint: hash.digest('hex') };+ }++ /** Runner refusals that mean the host could not run the shard right now, so a local rerun is sound. */+ const RERUN_REFUSALS = new Set(['RUNNER_SETUP_REFUSED', 'RESOURCE_LEASE_LOST']);++ /**+ * How a sharded landing answers a runner that gave no test result. A lost host or transport, or a+ * setup the runner's own pool refused (#690), reruns the shard locally. An unverified cleanup also+ * reruns locally, but takes that host out of this landing. Changed source means the code under test+ * drifted, so the landing fails; so does any refusal this does not know, with no silent retry.+ *+ * @param {unknown} error+ * @param {{ RunnerDropped: Function, Refused: Function }} kinds+ * @returns {{ action: 'rerun'|'quarantine'|'fail', reason: string, code: string|null }|null} null when it is not a runner answer at all.+ */+ export function runnerFailureClass(error, { RunnerDropped, Refused }) {+ if (error instanceof RunnerDropped) return { action: 'rerun', reason: 'runner transport lost', code: null };+ if (!(error instanceof Refused)) return null;+ if (RERUN_REFUSALS.has(error.code)) return { action: 'rerun', reason: `runner refused: ${error.code}`, code: error.code };+ if (error.code === 'RUNNER_CLEANUP_TIMEOUT') return { action: 'quarantine', reason: `runner refused: ${error.code}`, code: error.code };+ return { action: 'fail', reason: `runner refused: ${error.code}`, code: error.code };+ }++ /** A shard's acquisition stopped waiting because the shard ran elsewhere or the landing stopped. */+ class NotNeeded extends Error {}++ /**+ * Run the landing gate's test files as `count` shards and return one result.+ *+ * The slot this process already holds is a lane of its own: it runs the first shard, then any shard+ * no other slot has taken yet. Every other shard also queues for a slot of its own, locally or on a+ * runner, and whichever slot reaches it first runs it. So a landing always finishes on its own slot,+ * and two landings that hold the only two slots cannot wait on each other.+ *+ * A red shard is a test failure: it stops the others and the landing is red, with no retry. Only an+ * infrastructure failure of a runner (a dropped transport or a runner refusal) reruns that shard,+ * locally, after a named line; both attempts stay in the merged log and profile.+ *+ * @param {{ root: string, runner: string, files: string[], count: number, inherited?: object|null,+ * needsBrowser?: (files: string[]) => Promise<boolean>, write?: (text: string) => void }} options+ * `runner` is this repository's bin/run-tests.js; `inherited` is the gate lease this process already+ * holds; `write` receives the merged log.+ * @returns {Promise<{ isGreen: boolean, balance: string, shards: object[], files: object[] }>}+ */+ export async function runLandingShards({ root, runner, files, count, inherited = null, needsBrowser = async () => true, write = text => process.stdout.write(text), remoteRun }) {+ const { withGateSlot } = await import('./gate.js');+ const runners = await import('./runners.js');+ const { RunnerDropped } = runners;+ // A test may stand in for the SSH round trip to make a runner answer with a given refusal.+ const runOnRunnerAsync = remoteRun ?? runners.runOnRunnerAsync;+ const quarantined = new Map();+ // Every local shard, first run or rerun, must run exactly this source or refuse by name.+ const pinned = landingSource(root);+ const { Refused } = await import('./refused.js');+ const history = readFileTimes(root);+ const plan = planLandingShards(files, count, history);+ const balance = landingBalance(files, history);+ const total = plan.length;+ const stopper = new AbortController();+ const stop = stopper.signal;+ let firstFailure = null;+ // The parent's own markers would make every shard reuse its one lease; each lane passes its own.+ const saved = Object.fromEntries(GATE_MARKERS.map(key => [key, process.env[key]]));+ for (const key of GATE_MARKERS) delete process.env[key];+ write(`# landing shards: ${total} balanced by ${balance} (${plan.map((shard, index) => `${index + 1}/${total} ${shard.files.length} files`).join(', ')})\n`);+ const floor = landingFloor(files, history);+ // The slowest single file bounds the gate however many shards there are.+ if (floor) write(`# landing floor: ${floor.ms} ms ${floor.path}\n`);++ let wake = () => {};+ let changed = new Promise(resolveChange => { wake = resolveChange; });+ /** Tell the parent's lane that a shard became free to take or finished. */+ const signalChange = () => { const resolveChange = wake; changed = new Promise(next => { wake = next; }); resolveChange(); };+ const entries = await Promise.all(plan.map(async (shard, index) => ({ shard, label: `${index + 1}/${total}`,+ browser: await needsBrowser(shard.files), claimed: false, localOnly: false, done: false, attempts: [], status: null })));++ /** Run one attempt of a shard on a lease: a local child, or the runner it names. */+ const attempt = async (entry, lease) => {+ const started = Date.now();+ const number = entry.attempts.length + 1;+ if (!lease.runner) {+ const drifted = () => landingSource(root).fingerprint !== pinned.fingerprint;+ /** A local result on other source than the landing pinned is never a result for this landing. */+ const sourceChanged = when => {+ write(`landing shard ${entry.label}: [LANDING_SOURCE_CHANGED] the checkout changed from the landing's pinned source ${pinned.commit.slice(0, 12)} ${when} this shard ran; restore that commit with no other changes and run the landing again\n`);+ return { attempt: number, host: 'local', outcome: 'refused', reason: 'landing refused: LANDING_SOURCE_CHANGED', output: '', wallMs: Date.now() - started };+ };+ if (drifted()) return sourceChanged('before');+ const run = await runLocalShard({ root, runner, files: entry.shard.files, label: entry.label, lease, stop });+ if (run.unverified.length) {+ // Fail closed: name what may still run, as a runner's unverified cleanup does.+ write(`landing shard ${entry.label}: [LANDING_SHARD_CLEANUP_UNVERIFIED] the stopped shard's processes could not be shown gone: ${run.unverified.join(', ')}; inspect and stop them before another run\n`);+ }+ if (!stop.aborted && drifted()) return sourceChanged('while');+ return { attempt: number, host: 'local', outcome: run.isGreen ? 'green' : 'red', output: run.output, wallMs: Date.now() - started };+ }+ const command = `${LANDING_SHARD_ENV}=${word(entry.label)} ${['node', './bin/run-tests.js', ...entry.shard.files].map(word).join(' ')}`;+ try {+ const run = await runOnRunnerAsync(root, command, { runner: lease.runner, source: lease.source, browser: lease.browser,+ metadata: { ...(lease.runMetadata ?? {}), landing: true }, signal: stop });+ return { attempt: number, host: lease.runner.host, outcome: run.isGreen ? 'green' : 'red', output: run.output, wallMs: Date.now() - started };+ } catch (error) {+ // A stop ends the runner's transport on purpose; that shard was stopped, not dropped.+ if (stop.aborted) return { attempt: number, host: lease.runner.host, outcome: 'stopped', output: '', wallMs: Date.now() - started };+ const failure = runnerFailureClass(error, { RunnerDropped, Refused });+ if (!failure) throw error;+ const host = lease.runner.host;+ const message = error instanceof Refused ? error.message : '';+ if (message) write(`landing shard ${entry.label}: runner ${host} refused it: ${message}\n`);+ if (failure.action === 'quarantine' && !quarantined.has(host)) {+ quarantined.set(host, message);+ write(`landing runner ${host} quarantined for the rest of this landing: ${message}\n`);+ }+ // Infrastructure, not a test result: the runner could not give this shard a complete answer.+ return { attempt: number, host, outcome: failure.action === 'fail' ? 'refused' : 'infrastructure', reason: failure.reason,+ output: '', wallMs: Date.now() - started };+ }+ };++ /** Record an attempt's outcome, stopping the landing at the first test failure. */+ const settle = (entry, record) => {+ const stopped = record.outcome !== 'green' && (stop.aborted || firstFailure !== null);+ const status = record.outcome === 'infrastructure' && !stopped ? 'infrastructure' : stopped ? 'stopped' : record.outcome;+ entry.attempts.push({ ...record, status });+ write(`# landing shard ${entry.label} attempt ${record.attempt} on ${record.host}: ${status}${record.reason ? ` (${record.reason})` : ''} in ${record.wallMs} ms\n`);+ if (record.output) write(record.output.endsWith('\n') ? record.output : `${record.output}\n`);+ if (status === 'infrastructure') {+ write(`landing shard ${entry.label}: runner ${record.host} failed mid-shard; rerunning shard ${entry.label} locally\n`);+ entry.claimed = false;+ entry.localOnly = true;+ acquire(entry);+ } else {+ entry.done = true;+ entry.status = status;+ if (status === 'red' || status === 'refused') {+ firstFailure = entry.label;+ stopper.abort();+ }+ }+ signalChange();+ };++ /** Run a claimed shard on a lease, unless the landing already stopped. */+ const runOnLease = async (entry, lease) => {+ if (entry.done) return;+ if (stop.aborted) {+ entry.done = true;+ entry.status = 'stopped';+ entry.attempts.push({ attempt: entry.attempts.length + 1, host: 'none', outcome: 'stopped', status: 'stopped', wallMs: 0, output: '' });+ write(`# landing shard ${entry.label} attempt ${entry.attempts.length} on none: stopped in 0 ms\n`);+ signalChange();+ return;+ }+ entry.running = true;+ try { settle(entry, await attempt(entry, lease)); }+ finally { entry.running = false; }+ };++ const failures = [];+ /** Queue this shard for a slot of its own; the parent's lane may take it first. */+ const acquire = (entry) => {+ const localOnly = entry.localOnly;+ const running = withGateSlot(root, async lease => {+ if (entry.claimed || entry.done) return;+ // A host quarantined in this landing gets no more shards; queue again for a local slot.+ if (lease.runner && quarantined.has(lease.runner.host)) return 'divert';+ entry.claimed = true;+ await runOnLease(entry, lease);+ }, { landing: true, browser: entry.browser, remote: !localOnly, kind: 'landing', item: `shard ${entry.label}`,+ onWait: () => { if (entry.claimed || entry.done || stop.aborted) throw new NotNeeded(); } });+ running.then(result => {+ if (result !== 'divert' || entry.claimed || entry.done) return;+ entry.localOnly = true;+ acquire(entry);+ }, () => {});+ running.catch(error => {+ if (error instanceof NotNeeded) {+ // A stopped shard that was only waiting for a slot is recorded as stopped here.+ if (stop.aborted && !entry.done && !entry.running) runOnLease(entry, {}).catch(() => {});+ return;+ }+ failures.push(error);+ stopper.abort();+ signalChange();+ });+ };++ /** The parent's own slot: run free shards one after another until every shard is done. */+ const lane = async () => {+ while (!entries.every(entry => entry.done) && !failures.length) {+ const next = entries.find(entry => !entry.claimed && !entry.done);+ if (!next) { await changed; continue; }+ next.claimed = true;+ await runOnLease(next, inherited);+ }+ };++ let shards;+ try {+ for (const entry of entries) if (!inherited || entry !== entries[0]) acquire(entry);+ if (inherited) await lane();+ while (!entries.every(entry => entry.done) && !failures.length) await changed;+ if (failures.length) throw failures[0];+ shards = entries;+ } finally {+ for (const [key, value] of Object.entries(saved)) if (value !== undefined) process.env[key] = value;+ }+ const merged = [];+ const measured = {};+ for (const entry of shards) {+ const last = entry.attempts.at(-1);+ const times = shardFileTimes(last?.output ?? '');+ for (const file of entry.shard.files.map(fileKey)) {+ const ms = times[file];+ if (Number.isFinite(ms)) measured[file] = ms;+ merged.push({ path: file, shard: entry.label, host: last?.host ?? 'none', durationMs: Number.isFinite(ms) ? ms : null });+ }+ }+ for (const file of merged.sort((a, b) => a.path.localeCompare(b.path))) {+ write(`# landing file ${file.shard} ${file.host} ${file.durationMs ?? '-'} ${file.path}\n`);+ }+ const isGreen = shards.every(entry => entry.status === 'green');+ write(`# landing result: ${isGreen ? 'green' : `red, first failure in shard ${firstFailure ?? shards.find(entry => entry.status !== 'green')?.label}`}\n`);+ if (Object.keys(measured).length) writeFileTimes(root, measured);+ return { isGreen, balance,+ shards: shards.map(entry => ({ shard: entry.label, status: entry.status,+ attempts: entry.attempts.map(({ output, ...record }) => record) })),+ files: merged };+ }++ /** Read the merged shard lines from a gate log into profile fields, or null for an unsharded run. */+ export function landingShardProfile(output) {+ const shards = [];+ const files = [];+ let balance = null;+ let floor = null;+ const quarantined = [];+ const unverified = [];+ for (const line of String(output).split(/\r?\n/u)) {+ const plan = /^# landing shards: \d+ balanced by (history|history and average|file count) \(/u.exec(line);+ if (plan) balance = plan[1];+ const leftover = /^landing shard (\d+\/\d+): \[LANDING_SHARD_CLEANUP_UNVERIFIED\] the stopped shard's processes could not be shown gone: (.*); inspect/u.exec(line);+ if (leftover) unverified.push({ shard: leftover[1], processes: leftover[2] });+ const held = /^landing runner (\S+) quarantined for the rest of this landing: (.*)$/u.exec(line);+ if (held) quarantined.push({ host: held[1], message: held[2] });+ const slowest = /^# landing floor: (\d+) ms (.+)$/u.exec(line);+ if (slowest) floor = { path: slowest[2], ms: Number(slowest[1]) };+ const shard = /^# landing shard (\d+\/\d+) attempt (\d+) on (\S+): (green|red|stopped|infrastructure|refused)(?: \(([^)]*)\))? in (\d+) ms$/u.exec(line);+ if (shard) shards.push({ shard: shard[1], attempt: Number(shard[2]), host: shard[3], status: shard[4], reason: shard[5] ?? null, wallMs: Number(shard[6]) });+ const file = /^# landing file (\d+\/\d+) (\S+) (\d+|-) (.+)$/u.exec(line);+ if (file) files.push({ path: file[4], shard: file[1], host: file[2], durationMs: file[3] === '-' ? null : Number(file[3]) });+ }+ return shards.length ? { balance, floor, quarantined, unverified, shards, files } : null;+ }++ /** Print this shard's per-file wall times for its orchestrator; a missing record prints nothing. */+ export function printShardFileTimes(path, write = text => process.stdout.write(text)) {+ if (!path || !existsSync(path)) return;+ const times = {};+ for (const line of readFileSync(path, 'utf8').split('\n')) {+ try {+ const { file, ms } = JSON.parse(line);+ if (typeof file === 'string' && Number.isFinite(ms)) times[fileKey(file)] = Math.max(times[fileKey(file)] ?? 0, ms);+ } catch { /* A torn last line from a killed file process carries no time. */ }+ }+ for (const [file, ms] of Object.entries(times)) write(`${FILE_TIME_LINE}${Math.round(ms)} ${file}\n`);+ }diff --cc src/lanes.jsindex a88599a3,2d100f4d..34bfffaa--- a/src/lanes.js+++ b/src/lanes.js@@@ -1,8 -1,11 +1,21 @@@/*** Lanes (L1, L2): which folders each lane owns. The board, `pullboard lanes` and the pre-commit- * lane check all read the same declaration in pullboard.json.+ * lane check all read the same declaration in pullboard.json, and `pullboard lane add` writes it.*/- import { COORDINATOR } from './config.js';-import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';++import {++ existsSync,++ readFileSync,++ statSync,++ writeFileSync,++} from 'node:fs';+ import { join } from 'node:path';-import { CONFIG_FILE, COORDINATOR, configFromSource, loadConfig } from './config.js';++import {++ CONFIG_FILE,++ COORDINATOR,++ configFromSource,++ loadConfig,++} from './config.js';+ import { Refused } from './refused.js';/*** Every lane name, the coordinator first.diff --cc src/machine-commands.jsindex 00000000,00000000..4d8fc0a9new file mode 100644--- /dev/null+++ b/src/machine-commands.js@@@ -1,0 -1,0 +1,54 @@@++/**++ * Machine-wide commands that need no board (Q1): pullboard settings reads or sets this machine's++ * gate and browser capacity, and pullboard runner add registers SSH test capacity.++ */++import { Refused } from './refused.js';++import {++ addRunner,++ gateQueueSettings,++ loadMachineSettings,++ memoryFloorMB,++ setBrowserSlots,++ setGateSlots,++} from './settings.js';++++/** Read or update machine-wide gate capacity. */++export function settingsCommand(io, { first, second, rest }) {++ if (!first && !second && !rest.length) {++ const settings = loadMachineSettings();++ const queue = gateQueueSettings();++ // The result names the queue order in effect, defaults included; the file keeps only what was set.++ io.result?.({ settings: { ...settings, gate: { ...settings.gate, queue: { ...settings.gate?.queue, ...queue } } }, memoryFloorMB: memoryFloorMB() });++ io.say(`gateSlots: ${settings.gateSlots}`);++ io.say(`browserSlots: ${settings.browserSlots}`);++ io.say(`gate.queue.reviewsFirst: ${queue.reviewsFirst}${queue.reviewsFirst ? '' : ' (landings first, then arrival order)'}`);++ io.say(`gate.queue.currentReleaseFirst: ${queue.currentReleaseFirst}${queue.currentReleaseFirst ? '' : ' (release priority is off)'}`);++ io.say(`gate.queue.agingMinutes: ${queue.agingMinutes}${queue.reviewsFirst || queue.currentReleaseFirst ? '' : ' (used only while reviewsFirst or currentReleaseFirst is true)'}`);++ io.say(`gate.memoryFloorMB: ${memoryFloorMB() ?? 'off (the gate queue does not wait for memory)'}`);++ return 0;++ }++ if (!['gateSlots', 'browserSlots'].includes(first) || !second || rest.length) {++ throw new Refused('USAGE', 'pullboard settings gateSlots <n> | browserSlots <n>');++ }++ if (!/^[1-9]\d*$/u.test(second) || !Number.isSafeInteger(Number(second))) {++ if (first === 'gateSlots') throw new Refused('USAGE', 'pullboard settings gateSlots <positive integer>');++ throw new Refused(first === 'browserSlots' ? 'BAD_BROWSER_SLOTS' : 'BAD_GATE_SLOTS', `${first} must be a positive integer; run pullboard settings ${first} <n>`);++ }++ const settings = first === 'browserSlots' ? setBrowserSlots(Number(second)) : setGateSlots(Number(second));++ io.result?.({ settings });++ io.say(`${first} set to ${settings[first]}`);++ return 0;++}++++/** Register machine-level SSH capacity without requiring a board identity or a runner account. */++export function runnerCommand(io, { first, second, rest, values }) {++ if (first !== 'add' || !second || rest.length || !/^[1-9]\d*$/u.test(values.slots ?? '')++ || !/^(?:0|[1-9]\d*)$/u.test(values.browser ?? '')) {++ throw new Refused('USAGE', 'pullboard runner add <ssh-host> --slots <positive integer> --browser <integer from zero through slots>');++ }++ const runner = addRunner({ host: second, slots: Number(values.slots), browser: Number(values.browser),++ ...(values.node !== undefined ? { node: values.node } : {}), ...(values.root !== undefined ? { root: values.root } : {}) });++ io.result?.({ runner });++ io.say(`registered runner ${runner.host}: ${runner.slots} slots, ${runner.browser} browser`);++ return 0;++}diff --cc src/queue-settings.jsindex 00000000,2e803c00..5891b522mode 000000,100644..100644--- a/src/queue-settings.js+++ b/src/queue-settings.js@@@ -1,0 -1,72 +1,75 @@@+ /** The gate queue's machine settings, read with node: built-ins only so a runner's trusted runtime can ship them [O5]. */-import { existsSync, readFileSync } from 'node:fs';++import {++ existsSync,++ readFileSync,++} from 'node:fs';+ import { join } from 'node:path';+ import { machineHome } from './machine-home.js';+ import { Refused } from './refused.js';++ /** A waiting run moves up one class after this many minutes, unless the machine sets agingMinutes. */+ export const DEFAULT_QUEUE_AGING_MINUTES = 30;++ /** Resolve the separate machine settings file. */+ export function machineSettingsFile() {+ return join(machineHome(), 'settings.json');+ }++ /**+ * Read the machine settings file as a plain object, or null when there is none. Why here and not+ * in settings.js: resources.js runs on remote runners, whose trusted runtime ships only a few+ * files, and settings.js imports runners.js and resources.js.+ *+ * @param {string} [file]+ * @returns {object|null}+ */+ export function readMachineSettingsFile(file = machineSettingsFile()) {+ if (!existsSync(file)) return null;+ let value;+ try { value = JSON.parse(readFileSync(file, 'utf8')); }+ catch { throw new Refused('BAD_MACHINE_SETTINGS', `cannot read ${file}; fix its JSON before running Pullboard`); }+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ throw new Refused('BAD_MACHINE_SETTINGS', `settings in ${file} must be a JSON object; fix it before running Pullboard`);+ }+ if (value.gate !== undefined && (!value.gate || typeof value.gate !== 'object' || Array.isArray(value.gate))) {+ throw new Refused('BAD_MACHINE_SETTINGS', `gate in ${file} must be an object; fix it before running Pullboard`);+ }+ return value;+ }++ /**+ * Refuse an unusable gate.queue setting by name, with the fix.+ *+ * @param {object} value - The parsed machine settings.+ * @param {string} file - The settings file, for the message.+ */+ export function validateGateQueue(value, file) {+ const queue = value.gate?.queue;+ if (queue !== undefined && (!queue || typeof queue !== 'object' || Array.isArray(queue))) {+ throw new Refused('BAD_MACHINE_SETTINGS', `gate.queue in ${file} must be an object; fix it before running Pullboard`);+ }+ if (queue?.reviewsFirst !== undefined && typeof queue.reviewsFirst !== 'boolean') {+ throw new Refused('BAD_MACHINE_SETTINGS', `gate.queue.reviewsFirst in ${file} must be true or false`);+ }+ if (queue?.currentReleaseFirst !== undefined && typeof queue.currentReleaseFirst !== 'boolean') {+ throw new Refused('BAD_MACHINE_SETTINGS', `gate.queue.currentReleaseFirst in ${file} must be true or false`);+ }+ if (queue?.agingMinutes !== undefined && (!Number.isSafeInteger(queue.agingMinutes) || queue.agingMinutes < 1)) {+ throw new Refused('BAD_MACHINE_SETTINGS', `gate.queue.agingMinutes in ${file} must be a positive whole number of minutes; fix it or remove it for the default ${DEFAULT_QUEUE_AGING_MINUTES}`);+ }+ }++ /**+ * The gate pool's admission order. Reviews-first class order is opt-in per machine because it+ * changes who waits for whom on every board sharing the pool; absent or false keeps landings+ * first, then arrival. agingMinutes only matters while class order is on.+ *+ * @returns {{ reviewsFirst: boolean, currentReleaseFirst: boolean, agingMinutes: number }}+ */+ export function gateQueueSettings() {+ const file = machineSettingsFile();+ const value = readMachineSettingsFile(file) ?? {};+ validateGateQueue(value, file);+ const queue = value.gate?.queue;+ return { reviewsFirst: queue?.reviewsFirst === true, currentReleaseFirst: queue?.currentReleaseFirst === true, agingMinutes: queue?.agingMinutes ?? DEFAULT_QUEUE_AGING_MINUTES };+ }diff --cc src/relay-messages.jsindex 00000000,00000000..b50baa81new file mode 100644--- /dev/null+++ b/src/relay-messages.js@@@ -1,0 -1,0 +1,75 @@@++/**++ * The relay's bounded, credential-free wording (H1, H10): how a request failed before any answer, why a++ * baseline upload or checkpoint paused, and the safe next step. Pure text, so the relay client and++ * the CLI print the same lines without either holding a link or a credential.++ */++import { Refused } from './refused.js';++++/**++ * Name how a relay request failed before any response, from the error's own fields only.++ * Why: a bare "did not answer" hid whether a request timed out, was refused or lost its socket,++ * so load-dependent relay failures could not be attributed (#512).++ */++export function transportFailure(error) {++ if (error?.name === 'TimeoutError' || error?.name === 'AbortError') return 'timed out';++ const code = error?.cause?.code ?? error?.code;++ return typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,40}$/u.test(code) ? code : 'no connection';++}++++/** Format a shared status line for an oversized sealed snapshot. */++export function formatSnapshotLimit(problem, { paused = false } = {}) {++ const size = `${(problem.sealedBytes / 1_000_000).toFixed(1)} MB`;++ const limit = `${(problem.limit / 1_000_000).toFixed(1)} MB`;++ if (paused) return `relay paused for ${problem.board}: snapshot ${size} over the relay limit ${limit}; it resumes on its own once a snapshot fits`;++ return `relay snapshot for ${problem.board}: sealed snapshot ${size} over the relay limit ${limit}`;++}++++/** Keep a permanent refusal only as a bounded, credential-free diagnostic. */++export function safePauseMessage(error) {++ const message = String(error.relayMessage ?? error.message ?? 'the relay refused the baseline upload')++ .replace(/https?:\/\/[^\s]+/gu, '[relay]')++ .replace(/\b(?:Bearer\s+)?(?:ps|pa|pm|pg)_[A-Za-z0-9_-]{20,}\b/gu, '[credential]')++ .replace(/[\r\n\t\x00-\x1f\x7f]+/gu, ' ')++ .replace(/\s+/gu, ' ').trim();++ return message.slice(0, 240) || 'the relay refused the baseline upload';++}++++/** Preserve the ordered-move refusal while naming this board and both recovery choices. */++export function expiredSignInMoveRefusal(state, error) {++ const reason = safePauseMessage(error);++ if (process.env.PULLBOARD_RELAY_TOKEN !== undefined) {++ return new Refused('AUTH_REQUIRED', `the supplied PULLBOARD_RELAY_TOKEN was refused for board ${state.board}: ${reason}; unset PULLBOARD_RELAY_TOKEN to use this machine credential or supply a current PULLBOARD_RELAY_TOKEN`);++ }++ return new Refused('AUTH_REQUIRED', `relay sign-in expired or was revoked for board ${state.board}: ${reason}; run pullboard relay on to give this machine a credential or pullboard relay off to stop syncing`);++}++++/** Pause only definitive baseline 4xx refusals; throttling and transient errors retain retries. */++export function permanentBaselineRefusal(error) {++ return Number.isInteger(error?.httpStatus) && error.httpStatus >= 400 && error.httpStatus < 500 &&++ ![408, 425, 429].includes(error.httpStatus);++}++++/** Name the safe next step for the saved permanent refusal. */++function pauseFix(state) {++ const pause = state.baselinePause;++ if (pause.size || /(?:exceeds?|over|larger than|too large).{0,40}(?:bytes|snapshot|limit)|(?:snapshot|limit).{0,40}(?:exceeds?|over|too large)/iu.test(pause.message)) {++ return 'it resumes automatically once a snapshot fits';++ }++ if ([401, 403].includes(pause.status) || pause.code === 'AUTH_REQUIRED') return 'run pullboard relay on to sign in again';++ return 'upgrade Pullboard or run pullboard relay on again, then report the refusal if it persists';++}++++/** Render one bounded line with board, safe refusal reason and recovery step. */++export function baselinePauseLine(state) {++ const pause = state.baselinePause;++ const code = /^[A-Z][A-Z0-9_]{0,63}$/.test(pause.code) ? pause.code : 'RELAY_REFUSED';++ const size = pause.size && Number.isSafeInteger(pause.size.sealedBytes) && Number.isSafeInteger(pause.size.limit)++ ? formatSnapshotLimit({ board: state.board, ...pause.size }, { paused: true }) : `relay paused for ${state.board} before its baseline upload`;++ return `pullboard: [${code}] ${size}: ${pause.message}; ${pauseFix(state)}`;++}++++/** Persist only a stable refusal code, never arbitrary relay text masquerading as a code. */++export function safePauseCode(error) {++ const code = error.relayCode ?? error.code;++ return typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : 'RELAY_REFUSED';++}diff --cc src/relay.jsindex a08490a5,6767a6df..1fb59672--- a/src/relay.js+++ b/src/relay.js@@@ -1,92 -1,26 +1,102 @@@/** Opt-in, sealed relay ordering, with crash-safe migration from the older mirror [H1,H3,H5,H16,H17,P5]. */-import { createHash, randomUUID } from 'node:crypto';-import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import {+ createHash,+ randomUUID,+} from 'node:crypto';+import {+ existsSync,+ lstatSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ renameSync,+ rmSync,+ writeFileSync,+} from 'node:fs';import { hostname } from 'node:os';-import { basename, dirname, join } from 'node:path';-import { gunzipSync, gzipSync } from 'node:zlib';+import {+ basename,+ dirname,+ join,+} from 'node:path';+import {+ gunzipSync,+ gzipSync,+} from 'node:zlib';import * as store from './board.js';-import { exportBoard, importBoard, restoreRelaySnapshot, semanticBoardDigest } from './exchange.js';-import { appliedSequence, applyRelayMove, checkpointSequence, engineReceipt, prepareEngineMove, refuseRelayMove, requireSupportedEngine, startRelayEpoch } from './engine.js';+import {+ exportBoard,+ importBoard,+ restoreRelaySnapshot,+ semanticBoardDigest,+} from './exchange.js';+import {+ appliedSequence,+ applyRelayMove,+ checkpointSequence,+ engineReceipt,+ prepareEngineMove,+ refuseRelayMove,+ requireSupportedEngine,+ startRelayEpoch,+} from './engine.js';import { relayMoveActor } from './relay-sender.js';import { ENGINE_VERSION } from './machine.js';-import { presentationDigest, relayPresentation, relaySnapshot } from './relay-presentation.js';-import { codeIsFromMain, repoInfo, tryGit } from './git.js';-import { forgetBoardKey, readBoardKey, storeBoardKey } from './relay-key.js';-import { encodeBoardKey, generateBoardKey, seal, unseal } from './seal.js';+import {+ presentationDigest,+ relayPresentation,+ relaySnapshot,+} from './relay-presentation.js';+import {+ codeIsFromMain,+ repoInfo,+ tryGit,+} from './git.js';+import {+ forgetBoardKey,+ readBoardKey,+ storeBoardKey,+} from './relay-key.js';+import {+ encodeBoardKey,+ generateBoardKey,+ seal,+ unseal,+} from './seal.js';import { terminalQr } from './qr.js';import { Refused } from './refused.js';++import {++ baselinePauseLine,++ expiredSignInMoveRefusal,++ formatSnapshotLimit,++ permanentBaselineRefusal,++ safePauseCode,++ safePauseMessage,++ transportFailure,++} from './relay-messages.js';import { refusalFromReceipt } from './recorded-refusal.js';import { relaySenderProblem } from './relay-sender.js';-import { readRelayMachine, removeRecordedDevice, updateRelayMachine, wrapForRecordedDevice } from './relay-machine.js';-import { receivePersonRequest, requestMoveProblem } from './relay-requests.js';-import { nativePhoneAction, phoneProposal, publishPhoneApproval, warnPhoneApproval } from './relay-phone.js';-import { remoteShell as isRemoteShell, requirePersonChannel, requireRelayOnChannel } from './person.js';+import {+ readRelayMachine,+ removeRecordedDevice,+ updateRelayMachine,+ wrapForRecordedDevice,+} from './relay-machine.js';+import {+ receivePersonRequest,+ requestMoveProblem,+} from './relay-requests.js';+import {+ nativePhoneAction,+ phoneProposal,+ publishPhoneApproval,+ warnPhoneApproval,+} from './relay-phone.js';+import {++ remoteShell as isRemoteShell,+ requirePersonChannel,+ requireRelayOnChannel,+} from './person.js';import { listApiProjects } from './projects.js';export const DEFAULT_RELAY = 'https://app.pullboard.dev';@@@ -210,17 -144,17 +220,6 @@@ function notices(document, io)}}--/**-- * Name how a relay request failed before any response, from the error's own fields only.-- * Why: a bare "did not answer" hid whether a request timed out, was refused or lost its socket,-- * so load-dependent relay failures could not be attributed (#512).-- */--function transportFailure(error) {-- if (error?.name === 'TimeoutError' || error?.name === 'AbortError') return 'timed out';-- const code = error?.cause?.code ?? error?.code;-- return typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,40}$/u.test(code) ? code : 'no connection';--}--/** The sole outbound transport in the CLI: explicit sign-in or a saved, opted-in board link. */async function request(state, path, { method = 'GET', body, allowMissing = false, initialBaseline = false, signal } = {}, io) {const supplied = io?.ignoreRelayEnvironmentToken ? undefined : process.env.PULLBOARD_RELAY_TOKEN;@@@ -338,24 -272,24 +337,6 @@@ export function pendingSnapshotSize(rooreturn snapshotSize(loadLink(linkFile(root)));}--/** Format a shared status line for an oversized sealed snapshot. */--export function formatSnapshotLimit(problem, { paused = false } = {}) {-- const size = `${(problem.sealedBytes / 1_000_000).toFixed(1)} MB`;-- const limit = `${(problem.limit / 1_000_000).toFixed(1)} MB`;-- if (paused) return `relay paused for ${problem.board}: snapshot ${size} over the relay limit ${limit}; it resumes on its own once a snapshot fits`;-- return `relay snapshot for ${problem.board}: sealed snapshot ${size} over the relay limit ${limit}`;--}----/** Keep a permanent refusal only as a bounded, credential-free diagnostic. */--function safePauseMessage(error) {-- const message = String(error.relayMessage ?? error.message ?? 'the relay refused the baseline upload')-- .replace(/https?:\/\/[^\s]+/gu, '[relay]')-- .replace(/\b(?:Bearer\s+)?(?:ps|pa|pm|pg)_[A-Za-z0-9_-]{20,}\b/gu, '[credential]')-- .replace(/[\r\n\t\x00-\x1f\x7f]+/gu, ' ')-- .replace(/\s+/gu, ' ').trim();-- return message.slice(0, 240) || 'the relay refused the baseline upload';--}--/** Whether the CLI command will make an ordered move whose refusal should be reported at dispatch. */function orderedMoveCommand(io) {const command = io.relayCommand;@@@ -373,21 -307,21 +354,6 @@@ function reportExpiredSignIn(state, ioio.err(`pullboard: [AUTH_REQUIRED] relay sign-in expired or was revoked for board ${state.board}; ${fix}`);}--/** Preserve the ordered-move refusal while naming this board and both recovery choices. */--function expiredSignInMoveRefusal(state, error) {-- const reason = safePauseMessage(error);-- if (process.env.PULLBOARD_RELAY_TOKEN !== undefined) {-- return new Refused('AUTH_REQUIRED', `the supplied PULLBOARD_RELAY_TOKEN was refused for board ${state.board}: ${reason}; unset PULLBOARD_RELAY_TOKEN to use this machine credential or supply a current PULLBOARD_RELAY_TOKEN`);-- }-- return new Refused('AUTH_REQUIRED', `relay sign-in expired or was revoked for board ${state.board}: ${reason}; run pullboard relay on to give this machine a credential or pullboard relay off to stop syncing`);--}----/** Pause only definitive baseline 4xx refusals; throttling and transient errors retain retries. */--function permanentBaselineRefusal(error) {-- return Number.isInteger(error?.httpStatus) && error.httpStatus >= 400 && error.httpStatus < 500 &&-- ![408, 425, 429].includes(error.httpStatus);--}--/** Explain a refused later checkpoint without changing the ordered-move recovery policy. */function checkpointProblem(state) {const refusal = state.checkpointRefusal;@@@ -418,25 -352,25 +384,6 @@@ function reportCheckpointRefusal(stateelse io.err(line);}--/** Name the safe next step for the saved permanent refusal. */--function pauseFix(state) {-- const pause = state.baselinePause;-- if (pause.size || /(?:exceeds?|over|larger than|too large).{0,40}(?:bytes|snapshot|limit)|(?:snapshot|limit).{0,40}(?:exceeds?|over|too large)/iu.test(pause.message)) {-- return 'it resumes automatically once a snapshot fits';-- }-- if ([401, 403].includes(pause.status) || pause.code === 'AUTH_REQUIRED') return 'run pullboard relay on to sign in again';-- return 'upgrade Pullboard or run pullboard relay on again, then report the refusal if it persists';--}----/** Render one bounded line with board, safe refusal reason and recovery step. */--function baselinePauseLine(state) {-- const pause = state.baselinePause;-- const code = /^[A-Z][A-Z0-9_]{0,63}$/.test(pause.code) ? pause.code : 'RELAY_REFUSED';-- const size = pause.size && Number.isSafeInteger(pause.size.sealedBytes) && Number.isSafeInteger(pause.size.limit)-- ? formatSnapshotLimit({ board: state.board, ...pause.size }, { paused: true }) : `relay paused for ${state.board} before its baseline upload`;-- return `pullboard: [${code}] ${size}: ${pause.message}; ${pauseFix(state)}`;--}--/** Report the durable pause once across preflight, move and postflight in one command. */function reportBaselinePause(state, io) {if (!BASELINE_NOTICES.has(io)) {@@@ -471,12 -405,12 +418,6 @@@ async function remoteBaselineAbsent(stareturn false;}--/** Persist only a stable refusal code, never arbitrary relay text masquerading as a code. */--function safePauseCode(error) {-- const code = error.relayCode ?? error.code;-- return typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : 'RELAY_REFUSED';--}--/** Keep a conflicting remote baseline fenced across process restarts without discarding local work. */function requireUnconflictedBaseline(state) {if (state.baselineConflict) throw new Refused('RELAY_BASELINE_EXISTS', 'the relay already holds this board; save the local board with pullboard export, then run pullboard relay off to keep working locally; local moves stay off to protect its ordered history');diff --cc src/release-queue.jsindex 00000000,1afc9cf5..39726049mode 000000,100644..100644--- a/src/release-queue.js+++ b/src/release-queue.js@@@ -1,0 -1,45 +1,49 @@@+ /** Capture one board's release priority before joining the machine resource transaction [C7,V4]. */+ import { existsSync } from 'node:fs';+ import { join } from 'node:path';-import { boardId, openBoardReadOnly, roadmap } from './board.js';++import {++ boardId,++ openBoardReadOnly,++ roadmap,++} from './board.js';+ import { repoInfo } from './git.js';++ /**+ * Capture the item's roadmap rank once, without opening or migrating a board for writing.+ * The first unfinished local milestone is current; later milestones follow, then completed earlier+ * milestones, then unplanned work. External references are neither counted nor opened. Board identity joins worktrees and local relay replicas of+ * the same board. A checkout with no board has no release identity and keeps its queue position.+ * Why outside resources.js: remote workers ship only its small trusted runtime, not the board.+ *+ * @param {string} root - The gate caller's checkout.+ * @param {string|number} item - The local item id, or empty for an unplanned run.+ * @returns {{ board: string, rank: number }|undefined}+ */+ export function captureReleaseQueue(root, item) {+ let info;+ try { info = repoInfo(root); } catch { return undefined; }+ const file = join(info.commonDir, 'pullboard', 'board.sqlite');+ if (!existsSync(file)) return undefined;+ const db = openBoardReadOnly(file);+ try {+ const board = { db, clock: { now: () => new Date() } };+ return { board: boardId(board), rank: localReleaseRank(roadmap(board), item) };+ } finally { db.close(); }+ }++ /**+ * Rank local work using the board's own verified-item completion. A repo-qualified reference+ * cannot pin this board to an old milestone: its state belongs to another board and is not read.+ *+ * @param {{ items: { id: number|string, status: string }[] }[]} releases - Public roadmap projection.+ * @param {string|number} item - The local item id.+ * @returns {number} Current, later, completed earlier, then unplanned.+ */+ export function localReleaseRank(releases, item) {+ const local = releases.map(release => release.items.filter(entry => typeof entry.id === 'number'));+ const first = local.findIndex(items => items.some(entry => entry.status !== 'verified'));+ const current = first < 0 ? 0 : first;+ const ranks = local.flatMap((items, index) => items.some(entry => String(entry.id) === String(item))+ ? [index >= current ? index - current : releases.length + index] : []);+ return ranks.length ? Math.min(...ranks) : Number.MAX_SAFE_INTEGER;+ }diff --cc src/resources.jsindex 212afdb6,af90f406..0b32cb48--- a/src/resources.js+++ b/src/resources.js@@@ -1,23 -1,16 +1,40 @@@- /** Machine and repository queues persist leases; landings go first, then eligible waiters in arrival order [Q1,Q2,Q3]. */+ /** Machine and repository queues persist leases; landings first, then arrival order, or by class (landing, review, submit, other) aging up over time where the machine opts in [Q1,Q2,Q3]. */-import { mkdirSync, realpathSync } from 'node:fs';-import { execFile, execFileSync } from 'node:child_process';-import { readFile, readlink } from 'node:fs/promises';-import { basename, dirname, join, resolve } from 'node:path';+import {+ mkdirSync,+ realpathSync,+} from 'node:fs';- import { execFileSync } from 'node:child_process';++import {++ execFile,++ execFileSync,++} from 'node:child_process';++import {++ readFile,++ readlink,++} from 'node:fs/promises';+import {+ basename,+ dirname,+ join,+ resolve,+} from 'node:path';import { randomUUID } from 'node:crypto';import { DatabaseSync } from 'node:sqlite';import { repoInfo } from './git.js';-import { machineHome, withMachineHomeWrite } from './machine-home.js';+import {+ machineHome,+ withMachineHomeWrite,+} from './machine-home.js';import { Refused } from './refused.js';+ import { gateQueueSettings } from './queue-settings.js';-import { ARRIVAL_ORDER, classedMarker, classOrderInEffect, orderedWaiters, queueClass, releaseOrderInEffect } from './queue-order.js';++import {++ ARRIVAL_ORDER,++ classedMarker,++ classOrderInEffect,++ orderedWaiters,++ queueClass,++ releaseOrderInEffect,++} from './queue-order.js';+ export { QUEUE_CLASSES, QUEUE_AGE_MS, queueClass } from './queue-order.js';const LEASE_MS = 20_000;const HEARTBEAT_MS = 3_000;diff --cc src/row-decisions.jsindex d89d2a66,3357325c..4f38f2c8--- a/src/row-decisions.js+++ b/src/row-decisions.js@@@ -1,27 -1,10 +1,29 @@@/** Exact person row decisions and coordinator file application [B26,S18,S19]. */-import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { dirname, join } from 'node:path';+import {+ appendFileSync,+ existsSync,+ mkdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import {+ dirname,+ join,+} from 'node:path';import { loadDoctrine } from './doctrine.js';+ import { answerFromText } from './blueprints.js';-import { loadSpec, parseSpec, SIGNOFFS_FILE } from './spec.js';-import { defaultPrincipal, hasSignerFile, signRowDecision, verifyRowDecision } from './signature.js';+import {+ loadSpec,++ parseSpec,+ SIGNOFFS_FILE,+} from './spec.js';+import {+ defaultPrincipal,+ hasSignerFile,+ signRowDecision,+ verifyRowDecision,+} from './signature.js';import { Refused } from './refused.js';/** Resolve qualified doctrine ids while bare ids continue to name the spec. */diff --cc src/run.jsindex 4031fcfe,cf450722..bccbd39f--- a/src/run.js+++ b/src/run.js@@@ -25,32 -14,11 +25,34 @@@ importimport { join } from 'node:path';import * as store from './board.js';import { briefFiles } from './brief.js';-import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';-import { doctrineText, loadDoctrine } from './doctrine.js';-import { digestOf, refuseSandboxBlocked, sandboxBlockedOperation, runGate } from './gate.js';-import { contains, git, headCommit, invalidateGitFacts, isClean, tryGit, untracked } from './git.js';-import { laneNames, outOfLane } from './lanes.js';+import {+ CONFIG_FILE,+ COORDINATOR,+ loadConfig,+} from './config.js';+import {+ doctrineText,+ loadDoctrine,+} from './doctrine.js';+import {+ digestOf,++ refuseSandboxBlocked,++ sandboxBlockedOperation,+ runGate,+} from './gate.js';+import {+ contains,+ git,+ headCommit,+ invalidateGitFacts,+ isClean,+ tryGit,+ untracked,+} from './git.js';+import {+ laneNames,+ outOfLane,+} from './lanes.js';import { Refused } from './refused.js';/** Report changing machine queue state while an unattended item waits for a gate slot. */diff --cc src/runner-worker.jsindex d06e2ed9,925143a6..ad901fcb--- a/src/runner-worker.js+++ b/src/runner-worker.js@@@ -267,9 -240,9 +267,18 @@@ function writeChildJournalPreload(direcconst overflowPath = join(journalDirectory, 'overflow');const source = `import diagnostics from 'node:diagnostics_channel';--import { closeSync, openSync, statSync, writeSync, writeFileSync } from 'node:fs';++import {++ closeSync,++ openSync,++ statSync,++ writeSync,++ writeFileSync,++} from 'node:fs';import { join } from 'node:path';--import { createHash, randomUUID } from 'node:crypto';++import {++ createHash,++ randomUUID,++} from 'node:crypto';const directory = ${JSON.stringify(journalDirectory)};const overflowPath = ${JSON.stringify(overflowPath)};const instance = randomUUID();diff --cc src/runners.jsindex e2eaca3b,19e539d6..9ff81ac5--- a/src/runners.js+++ b/src/runners.js@@@ -389,7 -349,7 +389,11 @@@ function remoteWorkerCommand(runner, woconst files = { ...runtime.files, 'runner-worker.js': worker };const payload = gzipSync(Buffer.from(JSON.stringify(files))).toString('base64');const installer = `import { chmodSync, mkdirSync, mkdtempSync, writeFileSync, readFileSync, renameSync, rmSync } from 'node:fs';--import { dirname, isAbsolute, join } from 'node:path';++import {++ dirname,++ isAbsolute,++ join,++} from 'node:path';import { createHash } from 'node:crypto';import { gunzipSync } from 'node:zlib';${installRuntime.toString()}diff --cc src/settings.jsindex 9227aeeb,b7e67c6e..7560ea96--- a/src/settings.js+++ b/src/settings.js@@@ -1,24 -1,14 +1,27 @@@/** Machine-wide settings shared by every Pullboard checkout on this machine. */-import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import {- existsSync,+ mkdirSync,- readFileSync,+ renameSync,+ rmSync,+ writeFileSync,+} from 'node:fs';- import {- dirname,- join,- } from 'node:path';+ import { dirname } from 'node:path';import { randomUUID } from 'node:crypto';- import { machineHome } from './machine-home.js';-import { setResourceCapacity, updateRunnerSettings } from './resources.js';+import {+ setResourceCapacity,+ updateRunnerSettings,+} from './resources.js';import { validateRunner } from './runners.js';import { Refused } from './refused.js';-import { gateQueueSettings, machineSettingsFile, readMachineSettingsFile, validateGateQueue } from './queue-settings.js';++import {++ gateQueueSettings,++ machineSettingsFile,++ readMachineSettingsFile,++ validateGateQueue,++} from './queue-settings.js';++ // The gate queue's settings live in queue-settings.js so the runner runtime can read them too.+ export { gateQueueSettings, machineSettingsFile };const DEFAULT_GATE_SLOTS = 2;const DEFAULT_BROWSER_SLOTS = 1;diff --cc src/setup-card.jsindex 00000000,00000000..28760d30new file mode 100644--- /dev/null+++ b/src/setup-card.js@@@ -1,0 -1,0 +1,152 @@@++/**++ * The first-run setup card and its receipts (N19, I1): which of the five setup steps comes next for++ * this board, and the typed setup and view-bind receipts that prove a step happened. Each receipt is++ * scoped to the board's current coordinator enrollment, so a re-initialised board starts over.++ */++import { randomUUID } from 'node:crypto';++import {++ existsSync,++ mkdirSync,++ readdirSync,++ readFileSync,++ renameSync,++ writeFileSync,++} from 'node:fs';++import {++ dirname,++ join,++} from 'node:path';++import * as store from './board.js';++import { COORDINATOR } from './config.js';++import { detectGate } from './init.js';++import { laneNames } from './lanes.js';++import { loadSpec } from './spec.js';++++/** Identify setup from this board's coordinator enrollment, independently of agent flags. */++export function setupIdentity(board) {++ return { boardId: store.boardId(board),++ setupStartedAt: store.listAgents(board).find(agent => agent.agent_id === COORDINATOR)?.agent_created_at };++}++++/** Read only the view's typed successful-bind receipt for this board and setup. */++function viewBindComplete(ctx, board) {++ let receipt;++ try { receipt = JSON.parse(readFileSync(join(ctx.info.commonDir, 'pullboard', 'view-bind.json'), 'utf8')); }++ catch (error) { if (error.code === 'ENOENT' || error instanceof SyntaxError) return false; throw error; }++ const identity = setupIdentity(board);++ return receipt?.type === 'pullboard.view.bound' && receipt.version === 1++ && receipt.boardId === identity.boardId && receipt.setupStartedAt === identity.setupStartedAt++ && Number.isFinite(Date.parse(receipt.boundAt))++ && Date.parse(receipt.boundAt) >= Date.parse(identity.setupStartedAt);++}++++/** A separately typed, authenticated reuse also proves that this board's view was opened. */++export function viewSetupComplete(ctx, board) {++ if (viewBindComplete(ctx, board)) return true;++ let receipt;++ try { receipt = JSON.parse(readFileSync(join(ctx.info.commonDir, 'pullboard', 'view-reuse.json'), 'utf8')); }++ catch (error) { if (error.code === 'ENOENT' || error instanceof SyntaxError) return false; throw error; }++ const identity = setupIdentity(board);++ return receipt?.type === 'pullboard.view.reused' && receipt.version === 1++ && receipt.boardId === identity.boardId && receipt.setupStartedAt === identity.setupStartedAt++ && Number.isFinite(Date.parse(receipt.openedAt))++ && Date.parse(receipt.openedAt) >= Date.parse(identity.setupStartedAt);++}++++/** Atomically record a successful real view bind, scoped to this board's current setup. */++export function recordViewBind(ctx, board, boundAt) {++ const file = join(ctx.info.commonDir, 'pullboard', 'view-bind.json');++ const temporary = file + '.' + randomUUID() + '.tmp';++ const receipt = { type: 'pullboard.view.bound', version: 1, ...setupIdentity(board), boundAt };++ mkdirSync(dirname(file), { recursive: true });++ writeFileSync(temporary, JSON.stringify(receipt) + '\n', { mode: 0o600 });++ renameSync(temporary, file);++}++++/** Record this board's authenticated reuse without claiming that its existing listener bound again. */++export function recordViewReuse(ctx, board, view) {++ const file = join(ctx.info.commonDir, 'pullboard', 'view-reuse.json');++ const temporary = file + '.' + randomUUID() + '.tmp';++ const receipt = { type: 'pullboard.view.reused', version: 1, ...setupIdentity(board),++ openedAt: new Date().toISOString(), boundAt: view.boundAt, port: view.port, pid: view.pid };++ mkdirSync(dirname(file), { recursive: true });++ writeFileSync(temporary, JSON.stringify(receipt) + '\n', { mode: 0o600 });++ renameSync(temporary, file);++}++++/** Read a typed setup receipt only for this board's current coordinator enrollment. */++function setupReceiptMatches(ctx, identity, state) {++ let receipt;++ try { receipt = JSON.parse(readFileSync(join(ctx.info.commonDir, 'pullboard', `setup-${state}.json`), 'utf8')); }++ catch (error) { if (error.code === 'ENOENT' || error instanceof SyntaxError) return false; throw error; }++ return receipt?.type === `pullboard.setup.${state === 'complete' ? 'completed' : state}` && receipt.version === 1++ && receipt.boardId === identity.boardId && receipt.setupStartedAt === identity.setupStartedAt;++}++++/** Atomically record a setup transition, scoped to this board enrollment. */++export function recordSetupState(ctx, identity, state) {++ const file = join(ctx.info.commonDir, 'pullboard', `setup-${state}.json`);++ const temporary = file + '.' + randomUUID() + '.tmp';++ mkdirSync(dirname(file), { recursive: true });++ writeFileSync(temporary, JSON.stringify({ type: `pullboard.setup.${state === 'complete' ? 'completed' : state}`, version: 1, ...identity }) + '\n', { mode: 0o600 });++ renameSync(temporary, file);++}++++/** Derive the next setup question from the real requirements, config, items and view receipt. */++export function boardSetup(ctx, card, identity) {++ const rows = loadSpec(ctx.info.root, ctx.config).rows;++ const approved = rows.filter(row => row.status === 'approved');++ const drafted = rows.filter(row => row.status === 'draft' || row.status === 'pending');++ const recordedComplete = setupReceiptMatches(ctx, identity, 'complete');++ const started = setupReceiptMatches(ctx, identity, 'started');++ const lanes = laneNames(ctx.config).filter(lane => !['review', COORDINATOR].includes(lane));++ const folders = readdirSync(ctx.info.root, { withFileTypes: true })++ .filter(entry => entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules')++ .map(entry => entry.name).sort();++ const lane = lanes[0] ?? folders[0] ?? 'app';++ // Older installations had no setup marker. Preserve their completed five-step state on upgrade.++ const legacyUnmarked = !existsSync(join(ctx.info.commonDir, 'pullboard', 'setup-started.json'))++ && !existsSync(join(ctx.info.commonDir, 'pullboard', 'setup-complete.json'));++ const legacyComplete = legacyUnmarked && approved.length > 0 && lanes.length > 0++ && Boolean(ctx.config.gate?.trim()) && card.all.length > 0 && card.viewOpened;++ const completed = recordedComplete || legacyComplete;++ const detectedGate = detectGate(ctx.info.root);++ /** Quote the exact suggested command safely for a shell. */++ const quote = value => "'" + String(value).replaceAll("'", "'\\''") + "'";++ /** Quote one shell word only when it needs it, so a plain lane command reads as typed. */++ const word = value => /^[A-Za-z0-9._/-]+$/u.test(String(value)) ? String(value) : quote(value);++ /** Preserve all existing configuration when recording one setup answer. */++ const configure = patch => `node -e ${quote(`const fs=require('node:fs');const p='pullboard.json';const c=JSON.parse(fs.readFileSync(p,'utf8'));${patch};fs.writeFileSync(p,JSON.stringify(c,null,2)+${JSON.stringify('\n')})`)}`;++ const steps = [++ { number: 1, done: approved.length > 0 && (!drafted.length || completed), question: 'Ask the person: what are we building, and who will use it? Draft a few requirements, then ask the person to approve them.',++ command: 'pullboard spec draft "<text>"',++ afterAnswer: 'Record each answer with pullboard spec draft "<text>"; the person approves the returned ids in Pullboard View or runs pullboard spec approve <ids> in their own terminal; then the coordinator runs pullboard spec apply.' },++ { number: 2, done: lanes.length > 0, question: `Ask the person: how should we divide the work? Suggested folders: ${folders.join(', ') || 'app/ (create it for the app)'}.`,++ command: `pullboard lane add ${word(lane)} --owns ${word(lane + '/')}` },++ { number: 3, done: Boolean(ctx.config.gate?.trim()),++ question: detectedGate++ ? `Ask the person: which command proves the build works? Suggested: ${detectedGate}.`++ : 'Ask the person: if this board has no build, use `pullboard spec check` to check its spec and practice files; a second agent review checks the actual work. Or choose a custom gate command.',++ command: configure(`c.gate=${JSON.stringify(detectedGate || 'pullboard spec check')}`) },++ { number: 4, done: card.all.length > 0, question: 'Ask the person: what is the first small piece we should build?',++ command: `pullboard add ${quote(lane)} 'First small piece' --specs ${quote(approved[0]?.id ?? 'G1')} --criterion 'Describe what the person will be able to do'` },++ { number: 5, done: card.viewOpened,++ question: 'Ask the person: shall we open the board so you can follow the work?', command: 'pullboard view',++ afterAnswer: 'Run this in the person’s own terminal, or start it in the background as the agent so setup can continue. The view records its successful bind or authenticated reuse for this board.' },++ ];++ const current = steps.find(step => !step.done);++ if (!current && !recordedComplete) recordSetupState(ctx, identity, 'complete');++ else if (current && !completed && !started) recordSetupState(ctx, identity, 'started');++ if (current?.number === 1 && drafted.length) {++ const rowIds = drafted.map(row => row.id);++ const names = rowIds.join(', ');++ const command = `pullboard spec show ${rowIds[0]}`;++ return { step: 1, total: 5, ...current, steps, waitingOn: 'person-approval', rowIds,++ question: `Waiting for the person to approve ${names}.`, command,++ personCommand: `pullboard spec approve ${rowIds.join(',')}`,++ afterAnswer: 'The person approves these rows in Pullboard View or their own terminal; then the coordinator runs pullboard spec apply.',++ meanwhile: 'While waiting, the agent may review independent approved work or prepare questions for the person.',++ agentNext: `wait for the person to approve ${names}; meanwhile ${command}` };++ }++ return current ? { step: current.number, total: 5, ...current, steps } : null;++}diff --cc src/submission.jsindex 00000000,00000000..94a16b35new file mode 100644--- /dev/null+++ b/src/submission.js@@@ -1,0 -1,0 +1,78 @@@++/**++ * What submit and verify read about a submitted commit (N21, V1): the files the item's own commits++ * changed, a refusal when the candidate stacks on another item's unverified commit, a recovered++ * move's durable receipt, and the pinned report a submit prints.++ */++import * as store from './board.js';++import { engineReceipt } from './engine.js';++import {++ git,++ tryGit,++} from './git.js';++import { Refused } from './refused.js';++++/**++ * The files an item's own commits changed since its claim (N21). First parents only, so main merged++ * into a lane branch is not counted as the item's work; and nothing another item submitted, such as++ * a verified dependency fast-forwarded in, which merges no commit to skip.++ *++ * @param {string} root++ * @param {number} id++ * @param {string | null} from++ * @param {string} to++ * @returns {string[]}++ */++export function filesSince(root, id, from, to) {++ if (!from) return [];++ const others = [`--exclude=refs/pullboard/items/${id}/*`, '--glob=refs/pullboard/items/*'];++ const result = tryGit(root, ['log', '--first-parent', '--no-merges', '--no-renames', '--format=', '--name-only', to, '--not', from, ...others]);++ return result.status === 0 ? [...new Set(result.stdout.split('\n').filter(Boolean))].sort() : [];++}++++/** Refuse a candidate containing another item's unverified submitted commit [V1].++ *++ * Trunk-reachable commits are already landed, including when the candidate is trunk itself.++ * Inspect all remaining reachable commits, including merged topic parents.++ *++ * @param {string} root++ * @param {any} board++ * @param {any} item++ * @param {string} commit++ * @param {{ ref: string, commit: string } | null} trunk++ * @returns {void}++ */++export function refuseUnverifiedStack(root, board, item, commit, trunk) {++ const trunkRange = trunk?.commit++ ? tryGit(root, ['rev-list', `${trunk.commit}..${commit}`])++ : { status: 1, stdout: '' };++ if (trunkRange.status !== 0) {++ throw new Refused('NO_POLICY', 'the current trunk range cannot be read; restore Git history and retry the submit or verification');++ }++ const commits = new Set(trunkRange.stdout.split('\n').filter(Boolean));++ const stacked = store.unverifiedSubmissions(board)++ .find((other) => other.item_id !== item.item_id && commits.has(other.item_commit));++ if (stacked) {++ throw new Refused(++ 'STACKED_ON_UNVERIFIED',++ `#${item.item_id} includes unverified item #${stacked.item_id} at ${stacked.item_commit}; wait for #${stacked.item_id} to be accepted or rebuild without its commits before continuing`,++ );++ }++}++++/** Return the durable outcome only when a recovered move exactly matches its original receipt. */++export function recordedRecovery(board, move) {++ const receipt = engineReceipt(board, move.id);++ return receipt?.move === JSON.stringify(move) ? receipt : null;++}++++/** Report and pin the original submitted commit, including a recovered acknowledged outcome. */++export function reportSubmission(ctx, id, commit, gate, doctrine = []) {++ const { root } = ctx.info;++ const pin = `refs/pullboard/items/${id}/${commit.slice(0, 12)}`;++ git(root, ['update-ref', pin, commit]);++ ctx.io.result?.({ id, commit, pin, gate, ...(doctrine.length ? { doctrine } : {}) });++ ctx.io.say(`submitted #${id} at ${commit.slice(0, 12)}; ${gate.report}`);++ ctx.io.say(`pinned as ${pin}, so this work can't be lost; keep your worktree until it is merged`);++ ctx.io.say(`next: another agent checks out ${commit.slice(0, 12)} and runs: pullboard verify ${id} accept|reject`);++ return 0;++}diff --cc src/trusted-policy.jsindex b7d82e1f,26ac9d9b..c95d7c1a--- a/src/trusted-policy.js+++ b/src/trusted-policy.js@@@ -1,26 -1,9 +1,27 @@@/** Coordinator policy and immutable submission checks cannot come from a builder's candidate [V4,V16,L3,M3]. */import { randomUUID } from 'node:crypto';import { spawnSync } from 'node:child_process';-import { digestOf, sandboxBlockedScanner, writeTimingProfile } from './gate.js';-import { timingFromOutput, timingFromLog, timingRunner } from './timing.js';-import { closeSync, existsSync, mkdtempSync, mkdirSync, openSync, readFileSync, readSync, rmSync, writeSync } from 'node:fs';+import {+ digestOf,++ sandboxBlockedScanner,+ writeTimingProfile,+} from './gate.js';+import {+ timingFromOutput,+ timingFromLog,+ timingRunner,+} from './timing.js';+import {+ closeSync,+ existsSync,+ mkdtempSync,+ mkdirSync,+ openSync,+ readFileSync,+ readSync,+ rmSync,+ writeSync,+} from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { StringDecoder } from 'node:string_decoder';diff --cc src/view-session.jsindex 2f09dc01,409c47fa..f44321af--- a/src/view-session.js+++ b/src/view-session.js@@@ -1,20 -1,8 +1,22 @@@/** Private runtime records that let an unattended CLI hand off its live view link. */+ import { spawnSync } from 'node:child_process';-import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';-import { dirname, join } from 'node:path';-import { LOOPBACK, lastPort } from './serve.js';+import {+ chmodSync,++ existsSync,+ mkdirSync,+ readFileSync,+ renameSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import {+ dirname,+ join,+} from 'node:path';+import {+ LOOPBACK,+ lastPort,+} from './serve.js';import { registryFile } from './projects.js';import { fetchLocal } from './local-fetch.js';diff --cc src/worktree.jsindex 00000000,f91d351e..d0b35ffbmode 000000,100644..100644--- a/src/worktree.js+++ b/src/worktree.js@@@ -1,0 -1,59 +1,65 @@@-import { existsSync, readFileSync } from 'node:fs';++import {++ existsSync,++ readFileSync,++} from 'node:fs';+ import { join } from 'node:path';-import { cleanGitEnvironment, tryGit } from './git.js';++import {++ cleanGitEnvironment,++ tryGit,++} from './git.js';++ /** The npm lockfiles `npm ci` installs from, in the order npm itself prefers them. */+ const NPM_LOCKFILES = ['npm-shrinkwrap.json', 'package-lock.json'];++ /**+ * Count the packages a package.json declares under dependencies and devDependencies.+ *+ * An unreadable or malformed package.json counts as none: an install would fail on it anyway.+ *+ * @param {string} root+ * @returns {number}+ */+ function declaredDependencies(root) {+ const file = join(root, 'package.json');+ if (!existsSync(file)) return 0;+ let manifest;+ try { manifest = JSON.parse(readFileSync(file, 'utf8')); } catch { return 0; }+ if (!manifest || typeof manifest !== 'object') return 0;+ const count = (field) => (field && typeof field === 'object' && !Array.isArray(field) ? Object.keys(field).length : 0);+ return count(manifest.dependencies) + count(manifest.devDependencies);+ }++ /**+ * Name the npm lockfile the checkout's HEAD commit holds, or null when none is committed.+ *+ * A lockfile counts only when HEAD has it: one that sits on disk or is only staged (a hook can+ * stage one in a new worktree) is not in the commit, and `npm ci` from it would install+ * something the commit does not record.+ *+ * @param {string} root+ * @returns {string | null}+ */+ function committedLockfile(root) {+ const listed = tryGit(root, ['ls-tree', '-z', '--name-only', 'HEAD', '--', ...NPM_LOCKFILES], { env: cleanGitEnvironment() });+ if (listed.status !== 0) return null;+ const tracked = new Set(listed.stdout.split('\0').filter(Boolean));+ return NPM_LOCKFILES.find((name) => tracked.has(name)) ?? null;+ }++ /**+ * The install step a new worktree's next steps suggest, or null when the project needs none.+ *+ * A zero-dependency project gets no step, because `npm install` there only writes a+ * package-lock.json the first submit then refuses as UNTRACKED (I1, L3). A committed lockfile+ * gets `npm ci`, which installs exactly what it records and writes nothing. Without one,+ * `npm install` is still the step, with a note that the lockfile it writes must be committed.+ *+ * @param {string} root - The new worktree's top level.+ * @returns {{ command: string, note: string } | null}+ */+ export function installStep(root) {+ if (declaredDependencies(root) === 0) return null;+ const lockfile = committedLockfile(root);+ if (lockfile) return { command: 'npm ci', note: `its own install from the committed ${lockfile}, so its tests run its own code` };+ return { command: 'npm install', note: 'its own install; it writes package-lock.json, so commit that file or the first submit is refused UNTRACKED' };+ }diff --cc test/cli-help.test.jsindex 8f58748e,a4a15494..a93bfc6d--- a/test/cli-help.test.js+++ b/test/cli-help.test.js@@@ -1,6 -1,6 +1,7 @@@++/** @pullboard-test-input source-tree *//** The layered CLI help stays short, command-specific, and in parity with its declaration [N37,I1]. */import assert from 'node:assert/strict';-import { mkdtempSync, rmSync } from 'node:fs';+import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { runFixtureChild } from './fixture-child.js';