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 branch 'main' into core/695-merge
Corey Olsonfc7961f886e0
diff --cc src/board.jsindex 6cb7b45c,b471ca02..23d7c2dc--- a/src/board.js+++ b/src/board.js@@@ -17,31 -11,14 +17,32 @@@ importimport { dirname } from 'node:path';import { DatabaseSync } from 'node:sqlite';import { boardNotWritable } from './board-access.js';-import { briefFiles, briefSections } from './brief.js';+import {+ briefFiles,+ 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 { acceptCheck } from './check-accept.js';export const ACCEPT_REASON = 'CRITERION_MET';export const PERSON = 'person';diff --cc src/browser-slot-guard.jsindex 00000000,b5cde9a4..f8d33b40mode 000000,100644..100644--- a/src/browser-slot-guard.js+++ b/src/browser-slot-guard.js@@@ -1,0 -1,175 +1,184 @@@+ /**+ * The runtime half of gate.browserByLaunch [C7]: a test file the runner admitted without a browser slot+ * (PULLBOARD_TEST_BROWSER_SLOT=none) fails by name when it launches Chrome through the repository's+ * launch helper (test/chrome-fixture.js), which checks the slot itself; cockpit files always hold one.+ *+ * This module is a best-effort second guard for direct launches. The runner imports it in each+ * browser-free test file's process before the test body, and puts it in NODE_OPTIONS so Node children+ * that inherit that environment install it too. A child that strips its environment, a non-Node child,+ * or a shell running a script file is out of scope and not caught (docs/api.md). Installed, it wraps+ * node:child_process's spawn, spawnSync, exec, execSync, execFile, execFileSync and fork: a call whose+ * executable is a browser (Chrome's known install paths, PULLBOARD_CHROME's value, or a browser basename,+ * directly, through PATH or inside a shell command string) throws BROWSER_SLOT_REQUIRED naming the file,+ * before anything starts. test/chrome-fixture.js keeps its own check at the launch point as a second layer.+ * Without the marker, importing this module changes nothing.+ */+ import childProcess from 'node:child_process';-import { statSync, realpathSync } from 'node:fs';++import {++ statSync,++ realpathSync,++} from 'node:fs';+ import { syncBuiltinESMExports } from 'node:module';-import { basename, delimiter, isAbsolute, relative, resolve } from 'node:path';++import {++ basename,++ delimiter,++ isAbsolute,++ relative,++ resolve,++} from 'node:path';+ import { promisify } from 'node:util';+ import { Refused } from './refused.js';++ /** The marker the runner sets in a test file's process: held, none, or unset when the setting is off. */+ export const BROWSER_SLOT_ENV = 'PULLBOARD_TEST_BROWSER_SLOT';+ /** Install paths test/chrome-fixture.js's findChromeExecutable looks in, besides PULLBOARD_CHROME. */+ const KNOWN_BROWSERS = ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome',+ '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser'];+ /** Executable names that are a browser wherever they live. */+ const BROWSER_NAME = /^(?:chrome|chromium|chromium-browser|google-chrome(?:-stable|-beta|-unstable)?|headless_shell|chrome-headless-shell|google chrome(?: for testing| canary)?)(?:\.exe)?$/iu;+ /** Shells whose -c argument is a command string this guard reads word by word. */+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'ash']);+ const INSTALLED = Symbol.for('pullboard.browserSlotGuard');++ /**+ * The refusal for a browser launch without a slot, naming the test file the runner recorded.+ *+ * @param {string} what - what was started, for the message+ * @returns {Refused}+ */+ export function browserSlotRefusal(what) {+ const absolute = process.env.PULLBOARD_TEST_FILE ? resolve(process.env.PULLBOARD_TEST_FILE) : '';+ const local = absolute ? relative(process.cwd(), absolute) : '';+ const file = !absolute ? 'this test file' : (local && !local.startsWith('..') && !isAbsolute(local) ? local : absolute).split('\\').join('/');+ return new Refused('BROWSER_SLOT_REQUIRED', `${file} launched Chrome (${what}), but the gate classified it browser-free, so it holds no browser slot; import startChrome or launchChromeProcess from test/chrome-fixture.js in that file's own import graph so the gate admits it with a browser slot`,+ `import startChrome or launchChromeProcess from test/chrome-fixture.js in ${file}'s import graph, then run it again`);+ }++ /** A path with symlinks resolved when it exists, so a link to Chrome still reads as Chrome. */+ function canonical(path) {+ try { return realpathSync(path); } catch { return resolve(path); }+ }++ /** Find a bare command through PATH the way the spawn would, or null when it is not there. */+ function onPath(command, pathValue) {+ for (const directory of String(pathValue ?? '').split(delimiter)) {+ const candidate = resolve(directory || '.', command);+ try { if (statSync(candidate).isFile()) return candidate; } catch { /* not in this PATH entry */ }+ }+ return null;+ }++ /**+ * Whether one executable word names a browser: by basename, by PATH, or as PULLBOARD_CHROME's value or a+ * known install path once symlinks are resolved.+ *+ * @param {unknown} word+ * @param {{cwd?: string | URL, env?: Record<string, string | undefined>}} [options]+ * @returns {boolean}+ */+ export function isBrowserExecutable(word, { cwd, env } = {}) {+ if (typeof word !== 'string' && !(word instanceof URL)) return false;+ const text = word instanceof URL ? word.pathname : word;+ if (!text) return false;+ if (BROWSER_NAME.test(basename(text))) return true;+ const base = cwd instanceof URL ? cwd.pathname : (cwd ?? process.cwd());+ const path = text.includes('/') ? resolve(String(base), text) : onPath(text, env?.PATH ?? process.env.PATH);+ if (!path) return false;+ const real = canonical(path);+ if (BROWSER_NAME.test(basename(real))) return true;+ const targets = [process.env.PULLBOARD_CHROME, env?.PULLBOARD_CHROME, ...KNOWN_BROWSERS].filter(Boolean).map(canonical);+ return targets.includes(real);+ }++ /**+ * The words of a shell command string, quotes removed, split at blanks and shell operators. A reference+ * to $PULLBOARD_CHROME expands to its value. It errs toward finding a browser, never toward missing one.+ *+ * @param {string} command+ * @returns {string[]}+ */+ function shellWords(command) {+ const chrome = process.env.PULLBOARD_CHROME ?? '';+ const expanded = String(command).replace(/\$\{PULLBOARD_CHROME\}|\$PULLBOARD_CHROME\b/gu, () => (chrome ? `'${chrome}'` : 'google-chrome'));+ const words = [];+ let word = '';+ let quote = '';+ for (const character of expanded) {+ if (quote) {+ if (character === quote) quote = '';+ else word += character;+ } else if (character === '"' || character === "'") quote = character;+ else if (/[\s;&|()<>`]/u.test(character)) { if (word) words.push(word); word = ''; }+ else if (character !== '\\') word += character;+ }+ if (word) words.push(word);+ return words;+ }++ /** Whether a shell command string starts a browser in any word position. */+ function shellStartsBrowser(command, options) {+ return shellWords(command).some(word => isBrowserExecutable(word, options));+ }++ /**+ * What browser a child_process call would start, or null: the executable itself, a shell's -c string,+ * a command run with shell: true, or fork's execPath.+ *+ * @param {string} method+ * @param {unknown[]} input+ * @returns {string | null}+ */+ export function browserInCall(method, input) {+ const [first, second, third] = input;+ if (method === 'exec' || method === 'execSync') {+ const options = second && typeof second === 'object' ? second : {};+ return typeof first === 'string' && shellStartsBrowser(first, options) ? first : null;+ }+ const args = Array.isArray(second) ? second.map(String) : [];+ const raw = Array.isArray(second) ? third : second;+ const options = raw && typeof raw === 'object' ? raw : {};+ if (method === 'fork') return options.execPath && isBrowserExecutable(options.execPath, options) ? String(options.execPath) : null;+ if (isBrowserExecutable(first, options)) return String(first);+ if (options.shell && shellStartsBrowser([first, ...args].join(' '), options)) return [first, ...args].join(' ');+ if (typeof first === 'string' && SHELLS.has(basename(first))) {+ const flag = args.findIndex(arg => /^-[a-z]*c[a-z]*$/iu.test(arg));+ if (flag >= 0 && args[flag + 1] !== undefined && shellStartsBrowser(args[flag + 1], options)) return args[flag + 1];+ }+ if (typeof options.shell === 'string' && isBrowserExecutable(options.shell, options)) return options.shell;+ return null;+ }++ /**+ * Wrap node:child_process so a browser-free test file cannot start a browser, and publish the wrapped+ * functions to ES module importers. Idempotent; inert unless the marker says none.+ *+ * @returns {boolean} whether the guard is installed+ */+ export function installBrowserSlotGuard() {+ if (process.env[BROWSER_SLOT_ENV] !== 'none') return false;+ if (globalThis[INSTALLED]) return true;+ globalThis[INSTALLED] = true;+ for (const method of ['spawn', 'spawnSync', 'exec', 'execSync', 'execFile', 'execFileSync', 'fork']) {+ const original = childProcess[method];+ /** Refuse a browser before the original call can start it; anything else runs unchanged. */+ const guarded = function guardedChildProcess(...input) {+ const browser = browserInCall(method, input);+ if (browser) throw browserSlotRefusal(browser);+ return original.apply(this, input);+ };+ const custom = original[promisify.custom];+ if (custom) {+ /** The promisified form takes the same arguments, so it gets the same check. */+ guarded[promisify.custom] = function guardedPromisified(...input) {+ const browser = browserInCall(method, input);+ if (browser) return Promise.reject(browserSlotRefusal(browser));+ return custom.apply(this, input);+ };+ }+ childProcess[method] = guarded;+ }+ syncBuiltinESMExports();+ return true;+ }++ installBrowserSlotGuard();diff --cc src/check-accept.jsindex 00000000,74431057..62e7b9c2mode 000000,100644..100644--- a/src/check-accept.js+++ b/src/check-accept.js@@@ -1,0 -1,134 +1,140 @@@+ /**+ * A check that already passes on main proves nothing, so a board that asks for it holds the item+ * until the person accepts that exact check [V2,V4,B26].+ */+ import { createHash } from 'node:crypto';-import { PERSON, atomic, getItem, itemById, logEvent } from './board.js';++import {++ PERSON,++ atomic,++ getItem,++ itemById,++ logEvent,++} from './board.js';+ import { COORDINATOR } from './config.js';+ import { requirePersonChannel } from './person.js';+ import { Refused } from './refused.js';+ import { mainPolicy } from './trusted-policy.js';++ /** The engine that first replays a person's check acceptance; older engines refuse the move unread [H16]. */+ export const CHECK_ACCEPT_ENGINE = 24;++ /** The setting value that turns today's warning into a hold. */+ export const PROVES_NOTHING_HOLD = 'hold';++ /**+ * Digest one check's exact text. An acceptance names this digest, so it binds to the words the+ * person read and cannot carry over to a different check.+ *+ * @param {string} command+ * @returns {string}+ */+ export function checkDigest(command) {+ return createHash('sha256').update(String(command)).digest('hex');+ }++ /**+ * Record the person's acceptance of an item's current check, as an ordered board move.+ * Only the person, from the terminal or the view, may make it; the digest must match the check+ * the item carries now, so an acceptance prepared for one check cannot land on another.+ *+ * @param {any} board+ * @param {number} id+ * @param {{ agentId: string, channel: string, digest: string }} who+ * @returns {{ id: number, digest: string, check: string }}+ */+ export function acceptCheck(board, id, { agentId, channel, digest }) {+ if (agentId !== PERSON) throw new Refused('CHECK_ACCEPT_PERSON_ONLY', 'only the person accepts a check that already passes on main; ask the coordinator to bring it to the person');+ if (!['terminal', 'view'].includes(channel)) throw new Refused('B26_PERSON_CHANNEL', 'a check acceptance uses the person’s terminal or view; run pullboard view');+ return atomic(board, () => {+ const item = itemById(board, id);+ if (!item.item_check) throw new Refused('NO_CHECK', `#${id} has no check command to accept; its proof is the project gate`);+ if (typeof digest !== 'string' || digest !== checkDigest(item.item_check)) {+ throw new Refused('CHECK_ACCEPT_STALE', `#${id}'s check changed since this acceptance was prepared; read the current check with pullboard show ${id} and accept it again`);+ }+ logEvent(board, PERSON, 'check_accept', id, { digest, channel });+ return { id, digest, check: item.item_check };+ });+ }++ /**+ * The person's live acceptance of the item's current check, or null.+ * It counts only when its digest names the current check text and no later edit set a+ * different check, so changing the check (even back to an old one) needs a new acceptance.+ *+ * @param {any} board+ * @param {any} item+ * @returns {{ event: number, digest: string } | null}+ */+ export function checkAcceptance(board, item) {+ if (!item?.item_check) return null;+ const digest = checkDigest(item.item_check);+ const rows = board.db.prepare("SELECT event_id, event_by, event_kind, event_detail FROM event WHERE item_id = ? AND event_kind IN ('check_accept', 'edit') ORDER BY event_id").all(item.item_id);+ let accepted = null;+ for (const row of rows) {+ const detail = JSON.parse(row.event_detail);+ if (row.event_kind === 'check_accept' && row.event_by === PERSON && detail.digest === digest) accepted = { event: row.event_id, digest };+ else if (row.event_kind === 'edit' && Object.hasOwn(detail, 'check') && detail.check !== item.item_check) accepted = null;+ }+ return accepted;+ }++ /**+ * Refuse a claim or submit whose check already passes on main, when the board's+ * checks.provesNothing setting is "hold" and the person has not accepted that check.+ * With no setting the green baseline stays a warning, as on boards made before the setting.+ *+ * @param {() => any} mainConfig - reads accepted main's config, so a worktree's uncommitted edit cannot+ * lift the hold; called only for a green, unaccepted check, so other claims never read main for it+ * @param {any} board+ * @param {any} item - as getItem returns it, with item_check_baseline+ */+ export function refuseProvesNothing(mainConfig, board, item) {+ const base = item?.item_check_baseline;+ if (base?.result !== 'green' || base.command !== item.item_check || checkAcceptance(board, item)) return;+ if (mainConfig()?.checks?.provesNothing !== PROVES_NOTHING_HOLD) return;+ throw new Refused('CRITERION_PROVES_NOTHING',+ `#${item.item_id} is held: its check already passes on main ${String(base.main).slice(0, 12)}, so it proves nothing: ${base.command}`,+ `the coordinator sets a check that fails before the work (pullboard edit ${item.item_id} --check "<command>"), or the person accepts this one: pullboard check accept ${item.item_id}`);+ }++ /**+ * Refuse any claim of an open or claimed item whose check is held, reading accepted main's setting.+ * Claim, next, next --build and pullboard run all order their claim through the CLI's one claim+ * helper, which calls this first, so no route records a claim on a held item.+ *+ * @param {string} root+ * @param {any} board+ * @param {number} id+ */+ export function refuseClaimProvesNothing(root, board, id) {+ const item = getItem(board, id);+ if (['open', 'claimed'].includes(item.item_status)) refuseProvesNothing(() => mainPolicy(root).config, board, item);+ }++ /**+ * Run pullboard check accept <id>: the person accepts an item's check as it reads now, which lifts a+ * hold on a check already green on main. A person-only move (P6): an agent shell, a remote shell, a+ * worktree, the API and MCP are refused, and the move carries the check's digest so a changed+ * check needs a new acceptance. The CLI passes its own context, board and ordered-move helpers.+ *+ * @param {any} io+ * @param {string | undefined} first - the item id+ * @param {string[]} rest+ * @param {{ context: Function, withBoard: Function, whoAmI: Function, ordered: Function, idArg: Function }} cli+ * @returns {Promise<number>}+ */+ export async function checkAcceptCommand(io, first, rest, { context, withBoard, whoAmI, ordered, idArg }) {+ requirePersonChannel(io.personChannel);+ if (!/^#?\d+$/u.test(first ?? '') || rest.length) throw new Refused('USAGE', 'pullboard check accept <id>');+ const ctx = context(io);+ return withBoard(ctx, async (board) => {+ if (!ctx.info.isMain || whoAmI(ctx, board).id !== COORDINATOR) throw new Refused('B26_PERSON_APPROVAL', 'only the person accepts a check, from the main checkout or the view', 'ask the person to accept it in pullboard view, or in their own terminal at the main checkout');+ const item = getItem(board, idArg(first));+ if (!item.item_check) throw new Refused('NO_CHECK', `#${item.item_id} has no check command to accept; its proof is the project gate: pullboard gate`);+ const accepted = await ordered(ctx, board, 'acceptCheck', [item.item_id, { agentId: PERSON, channel: io.personChannel ?? 'terminal', digest: checkDigest(item.item_check) }]);+ io.result?.({ id: accepted.id, digest: accepted.digest, check: accepted.check });+ io.say(`accepted #${accepted.id}'s check as it reads now: ${accepted.check}`);+ io.say('a changed check needs the person to accept it again');+ return 0;+ });+ }diff --cc src/cli.jsindex 1f4048d2,7f708afa..992dbab0--- a/src/cli.js+++ b/src/cli.js@@@ -2,112 -2,26 +2,115 @@@* 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,+ readFileSync,+ realpathSync,+ writeFileSync,+} from 'node:fs';+import { 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 { agentDoctrine, proposeDoctrine, resumeDoctrineNotes, staleDoctrineRows } from './doctrine-rulings.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, pendingAnswers, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';-import { digestOf, gateReport, refuseSandboxBlocked, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';-import { checkNeedsBrowser, explicitCheckFiles } 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 {+ doctrineHistory,+ loadDoctrine,+} from './doctrine.js';+import {+ agentDoctrine,+ proposeDoctrine,+ resumeDoctrineNotes,+ staleDoctrineRows,+} from './doctrine-rulings.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,+ pendingAnswers,+ 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 {++ checkNeedsBrowser,++ explicitCheckFiles,++} 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 {FIX_NOTE,applyFixers,@@@ -184,179 -62,44 +187,185 @@@ 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, refuseCheckSyntax, sayCheckBaseline } from './check-baseline.js';-import { checkAcceptCommand, refuseClaimProvesNothing, refuseProvesNothing } from './check-accept.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,++ sayCheckBaseline,+} from './check-baseline.js';++import {++ checkAcceptCommand,++ refuseClaimProvesNothing,++ refuseProvesNothing,++} from './check-accept.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 { watchCommand } from './watch.js';import { serveMcp } from './mcp.js';-import { doctorProblems, doctrineProblems } from './doctor.js';-import { boardHealth, healthLines } from './health.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 {+ boardHealth,+ healthLines,+} from './health.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, gateShortSlots, loadMachineSettings, memoryFloorMB, setBrowserSlots, setGateShortSlots, 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 {+ browserFreeChecksEnabled,+ gateQueueSettings,++ gateShortSlots,+ loadMachineSettings,+ memoryFloorMB,+} from './settings.js';+import {+ 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, landingRemote, landingSubject } from './land.js';+import {+ boardSetup,+ recordSetupState,+ recordViewBind,+ recordViewReuse,+ setupIdentity,+ viewSetupComplete,+} from './setup-card.js';+import { formatSnapshotLimit } from './relay-messages.js';+import { privateNames } from './private-names.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();diff --cc src/engine.jsindex 52f5ecb4,ccf5a337..0eac20f3--- a/src/engine.js+++ b/src/engine.js@@@ -1,31 -1,16 +1,32 @@@/** 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 { CHECK_ACCEPT_ENGINE } from './check-accept.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']);+ const ITEM_ID_FIRST_ARGUMENT = new Set(['acceptCheck', 'editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze', 'reopen', 'appendFact']);/** Only these public board operations may be requested by an encrypted move. */export const ENGINE_OPERATIONS = Object.freeze([diff --cc src/gate.jsindex b0e7c2c3,39192b48..9c48bdd1--- a/src/gate.js+++ b/src/gate.js@@@ -4,69 -4,26 +4,75 @@@* 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, statSync, writeFileSync } from 'node:fs';-import { dirname, isAbsolute, join, relative, 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, gateShortSlots, loadMachineSettings, memoryFloorMB } from './settings.js';+import {+ GATE_SLOT_HELD_ENV,+ gateSlotEnvironment,+ inheritedGateSlot,+ memoryAdmission,+ readMachineMemory,+ takeResource,+} from './resources.js';+import {+ browserFreeChecksEnabled,+ gateQueueSettings,++ gateShortSlots,+ 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 { sandboxBlockedOperation, sandboxBlockedScanner } from './sandbox-denial.js';+import {+ RunnerDropped,+ runOnRunner,+ runOnRunnerAsync,+ runnerSource,+} from './runners.js';++import {++ sandboxBlockedOperation,++ sandboxBlockedScanner,++} from './sandbox-denial.js';++ // Callers keep importing the classifier from the gate; the runner worker imports it directly.+ export { sandboxBlockedOperation, sandboxBlockedScanner };const STAMP = 'pullboard-gate-green';const LOG = 'pullboard-gate.log';diff --cc src/init.jsindex 0f510bc3,17df72fb..46ca31a1--- a/src/init.js+++ b/src/init.js@@@ -5,39 -5,20 +5,51 @@@* write.*/import {- accessSync, appendFileSync, constants as fsConstants, existsSync, lstatSync, mkdirSync,- readdirSync, readFileSync, realpathSync, statSync, writeFileSync,+ accessSync,+ appendFileSync,+ constants as fsConstants,+ existsSync,++ lstatSync,+ mkdirSync,+ readdirSync,+ readFileSync,++ realpathSync,+ statSync,+ writeFileSync,} from 'node:fs';-import { delimiter, basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path';+import {+ delimiter,+ basename,++ dirname,++ isAbsolute,+ join,++ parse,++ relative,+ resolve,++ sep,+} from 'node:path';+ import { userInfo } from 'node:os';-import { CONFIG_FILE, COORDINATOR, doctrineFile, loadConfig } from './config.js';+import {+ CONFIG_FILE,+ COORDINATOR,+ doctrineFile,+ loadConfig,+} from './config.js';import { loadDoctrine } from './doctrine.js';import { installHooks } from './hooks.js';+ import { machineHome } from './machine-home.js';import { Refused } from './refused.js';import { installSkills } from './skills.js';import {- AGENTS_END, AGENTS_START, agentsBlock, claudeLoopRules, codexLoopRules, configTemplate,- plainGateWords, practiceTemplate, specTemplate,+ AGENTS_END,+ AGENTS_START,+ agentsBlock,++ claudeLoopRules,++ codexLoopRules,+ configTemplate,++ plainGateWords,+ practiceTemplate,+ specTemplate,} from './templates.js';const NPM_DEFAULT_TEST = 'echo "Error: no test specified" && exit 1';diff --cc src/machine-commands.jsindex 4d8fc0a9,00000000..3bba204emode 100644,000000..100644--- a/src/machine-commands.js+++ b/src/machine-commands.js@@@ -1,54 -1,0 +1,67 @@@+/**+ * 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,++ gateShortSlots,+ loadMachineSettings,+ memoryFloorMB,+ setBrowserSlots,++ setGateShortSlots,+ 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() });++ const shortSlots = gateShortSlots();++ io.result?.({ settings: { ...settings, gate: { ...settings.gate, queue: { ...settings.gate?.queue, ...queue }, shortSlots } }, 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)'}`);++ io.say(`gate.shortSlots: ${shortSlots}${shortSlots ? '' : ' (off; runs that name their test files wait for a gate slot)'}`);+ return 0;+ }- if (!['gateSlots', 'browserSlots'].includes(first) || !second || rest.length) {- throw new Refused('USAGE', 'pullboard settings gateSlots <n> | browserSlots <n>');++ if (!['gateSlots', 'browserSlots', 'gate.shortSlots'].includes(first) || !second || rest.length) {++ throw new Refused('USAGE', 'pullboard settings gateSlots <n> | browserSlots <n> | gate.shortSlots <n>');++ }++ if (first === 'gate.shortSlots') {++ if (!/^(?:0|[1-9]\d*)$/u.test(second) || !Number.isSafeInteger(Number(second))) {++ throw new Refused('BAD_SHORT_SLOTS', 'gate.shortSlots must be a whole number, 0 or more; run pullboard settings gate.shortSlots <n>');++ }++ const settings = setGateShortSlots(Number(second));++ io.result?.({ settings });++ io.say(`gate.shortSlots set to ${settings.gate.shortSlots}`);++ return 0;+ }+ 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/runner-worker.jsindex ad901fcb,04fe01df..ccb98cee--- a/src/runner-worker.js+++ b/src/runner-worker.js@@@ -1,39 -1,13 +1,40 @@@/** SSH runner entry point in a pinned capsule with a static trusted resource graph. */-import { spawn, spawnSync } from 'node:child_process';+import {+ spawn,+ spawnSync,+} from 'node:child_process';import { createHash } from 'node:crypto';-import { chmodSync, closeSync, createReadStream, createWriteStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';+import {+ chmodSync,+ closeSync,+ createReadStream,+ createWriteStream,+ existsSync,+ mkdirSync,+ mkdtempSync,+ openSync,+ readFileSync,+ readdirSync,+ readSync,+ renameSync,+ rmSync,+ statSync,+ writeFileSync,+} from 'node:fs';import { userInfo } from 'node:os';-import { delimiter, dirname, isAbsolute, join } from 'node:path';-import { fileURLToPath, pathToFileURL } from 'node:url';+import {+ delimiter,+ dirname,+ isAbsolute,+ join,+} from 'node:path';+import {+ fileURLToPath,+ pathToFileURL,+} from 'node:url';import * as resourceApi from './resources.js';import { parseProcessCensus } from './process-census.js';+ import { fileDenialWatcher } from './sandbox-denial.js';import { once } from 'node:events';import { pipeline } from 'node:stream/promises';diff --cc src/runners.jsindex 9ff81ac5,c5c04b2c..d3060ad9--- a/src/runners.js+++ b/src/runners.js@@@ -1,56 -1,17 +1,57 @@@/** Exact committed source and bounded, credential-free SSH execution for machine runners [C7]. */-import { spawn, spawnSync } from 'node:child_process';-import { createHash, randomUUID } from 'node:crypto';-import { chmodSync, closeSync, createReadStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import {+ spawn,+ spawnSync,+} from 'node:child_process';+import {+ createHash,+ randomUUID,+} from 'node:crypto';+import {+ chmodSync,+ closeSync,+ createReadStream,+ existsSync,+ mkdirSync,+ mkdtempSync,+ openSync,+ readFileSync,+ readSync,+ realpathSync,+ renameSync,+ rmSync,+ writeFileSync,+} from 'node:fs';import { tmpdir } from 'node:os';-import { dirname, isAbsolute, join } from 'node:path';+import {+ dirname,+ isAbsolute,+ join,+} from 'node:path';import { fileURLToPath } from 'node:url';import { pipeline } from 'node:stream/promises';-import { gunzipSync, gzipSync } from 'node:zlib';-import { configFromSource, defaults } from './config.js';-import { blockedPaths, secretsIn } from './hooks.js';-import { cleanGitEnvironment, headCommit, headTree, isClean, repoInfo, untracked } from './git.js';+import {+ gunzipSync,+ gzipSync,+} from 'node:zlib';+import {+ configFromSource,+ defaults,+} from './config.js';+import {+ blockedPaths,+ secretsIn,+} from './hooks.js';+import {+ cleanGitEnvironment,+ headCommit,+ headTree,+ isClean,+ repoInfo,+ untracked,+} from './git.js';import { Refused } from './refused.js';+ import { remoteFileDenial } from './sandbox-denial.js';// Budget: 64 MiB bounds worst-case JSON bridge escaping below Node string limits.const MAX_OUTPUT_BYTES = 64 * 1024 ** 2;diff --cc src/sandbox-denial.jsindex 00000000,a44b7d40..6b9a709cmode 000000,100644..100644--- a/src/sandbox-denial.js+++ b/src/sandbox-denial.js@@@ -1,0 -1,198 +1,203 @@@+ /**+ * Sandbox denials (I1, C7): the one classifier for an operating-system permission refusal in gate+ * output, shared by the local gate and the remote runner worker. It ships to runners as a trusted+ * runtime file, so a file denial is resolved against the worktree it happened in, on the machine+ * it happened on, and only its evidence travels.+ */+ import { realpathSync } from 'node:fs';-import { dirname, isAbsolute, relative, resolve } from 'node:path';++import {++ dirname,++ isAbsolute,++ relative,++ resolve,++} from 'node:path';++ /** Resolve existing path prefixes so a symlink cannot hide an outside-worktree operation. */+ function diagnosticPath(path) {+ let current = resolve(path);+ const missing = [];+ for (;;) {+ try { return resolve(realpathSync(current), ...missing); }+ catch (error) {+ if (!['ENOENT', 'ENOTDIR'].includes(error.code)) return null;+ const parent = dirname(current);+ if (parent === current) return null;+ missing.unshift(relative(parent, current));+ current = parent;+ }+ }+ }++ /** Describe one OS permission message, resolving file targets against the command's worktree. */+ function permissionOperation(root, message, { includeFilePaths = true } = {}) {+ const network = /^(listen|bind) (EPERM|EACCES)\b/u.exec(message);+ if (network) return { code: network[2], syscall: network[1], operation: `${network[1]} (${network[2]})` };+ if (!includeFilePaths) return null;+ const file = /^(EPERM|EACCES): [^\n]*?, (open|mkdir|read|write|rename|unlink|scandir|access) (['"])([^\n]+?)\3(?= -> |$)/u.exec(message);+ const python = /^PermissionError: \[Errno (?:1|13)\] [^\n]*?: ['"]([^'"\n]+)['"]/u.exec(message);+ if (!file && !python) return null;+ const path = diagnosticPath(resolve(root, file ? file[4] : python[1]));+ const tree = diagnosticPath(root);+ if (!path || !tree) return null;+ const within = relative(tree, path);+ if (within !== '..' && !within.startsWith('../') && !isAbsolute(within)) return null;+ const code = file ? file[1] : 'EACCES';+ return { code, path, syscall: file ? file[2] : null,+ operation: `${file ? file[2] : 'file access'} ${JSON.stringify(path)} (${code})` };+ }++ /** Decode the single-line quoted YAML scalars emitted by Node's TAP reporter. */+ function tapScalar(value) {+ if (value.startsWith('"')) {+ try { return JSON.parse(value); } catch { return null; }+ }+ if (value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1).replace(/''/gu, "'");+ return /^[A-Z_]+$/u.test(value) ? value : null;+ }++ /**+ * Scan complete lines with bounded TAP state so assertion messages cannot impersonate OS codes.+ * With `evidence`, a hit is the whole denial (code, syscall, path, operation) rather than its words.+ */+ export function sandboxBlockedScanner(root, { includeFilePaths = true, evidence = false } = {}) {+ const hit = denial => evidence ? denial : denial.operation;+ let failureIndent = null;+ let fieldIndent = null;+ let permission = null;+ let code = null;+ let comment = null;+ let startup = null;+ let failureMessage = null;+ let failureType = false;+ let exitCode = null;+ /** Retain one pending fatal diagnostic and the current failed TAP record. */+ return (raw) => {+ const line = raw.trim().replace(/^#\s*/u, '');+ const indent = raw.length - raw.trimStart().length;+ // Node's TAP reporter prints test-console output as comments and assertion details+ // as indented YAML. Neither is a standalone gate diagnostic, even when it contains+ // text that looks exactly like an operating-system denial.+ if (indent === 0 && !raw.startsWith('#') && /^(?:Error: |PermissionError: )/u.test(line)) {+ const direct = permissionOperation(root, line.replace(/^Error: /u, ''), { includeFilePaths });+ if (direct) return hit(direct);+ }+ if (/^TAP version \d+$/u.test(raw)) {+ comment = null; startup = null;+ failureIndent = null; fieldIndent = null; permission = null; code = null;+ failureMessage = null; failureType = false; exitCode = null;+ }+ // Uncaught module-load errors are comments too. Keep their complete Node fatal+ // diagnostic pending; it is evidence only if the following file record failed+ // to start. A test logging a caught error and then asserting is not that record.+ if (indent === 0 && raw.startsWith('#')) {+ if (line.startsWith('Error: ')) {+ const operation = permissionOperation(root, line.slice('Error: '.length), { includeFilePaths });+ comment = operation ? { operation, code: null, syscall: null, path: null, closed: false, fatal: false } : null;+ } else if (comment) {+ const field = /^(code|syscall|path): (.*)$/u.exec(line);+ if (field) comment[field[1]] = tapScalar(field[2].replace(/,$/u, ''));+ else if (line === '}') comment.closed = true;+ else if (/^Node\.js v\d+\./u.test(line)) comment.fatal = true;+ else if (line && !/^at |^errno: |^address: |^port: /u.test(line)+ && !(comment.closed && comment.fatal && line.startsWith('Subtest: '))) comment = null;+ }+ }+ if (/^(?:not )?ok \d+\b/u.test(line)) {+ failureIndent = /^not ok /u.test(line) ? indent : null;+ const operation = comment?.operation;+ startup = failureIndent !== null && comment?.closed && comment.fatal+ && comment.code === operation.code && comment.syscall === operation.syscall+ && (!operation.path || (typeof comment.path === 'string'+ && diagnosticPath(resolve(root, comment.path)) === operation.path)) ? operation : null;+ comment = null;+ fieldIndent = null; permission = null; code = null;+ failureMessage = null; failureType = false; exitCode = null;+ } else if (line === '---' && failureIndent !== null && indent === failureIndent + 2) {+ fieldIndent = indent;+ } else if (line === '...' && indent === fieldIndent) {+ failureIndent = null; fieldIndent = null; permission = null; code = null;+ startup = null; comment = null;+ failureMessage = null; failureType = false; exitCode = null;+ } else if (fieldIndent !== null && indent === fieldIndent) {+ const field = /^(error|code|failureType|exitCode): (.*)$/u.exec(line);+ if (field) {+ const value = tapScalar(field[2]);+ if (field[1] === 'error') {+ failureMessage = value;+ permission = typeof value === 'string' ? permissionOperation(root, value, { includeFilePaths }) : null;+ } else if (field[1] === 'code') {+ code = value;+ if (code !== 'ERR_TEST_FAILURE') startup = null;+ } else if (field[1] === 'failureType') failureType = value === 'testCodeFailure' || field[2] === 'testCodeFailure';+ else exitCode = /^[1-9]\d*$/u.test(field[2]) && Number.isSafeInteger(Number(field[2])) ? Number(field[2]) : null;+ if (permission && permission.code === code) return hit(permission);+ if (startup && code === 'ERR_TEST_FAILURE' && failureMessage === 'test failed'+ && failureType && exitCode !== null) return hit(startup);+ }+ }+ return null;+ };+ }++ /** Recognize concrete OS permission diagnostics, keeping ordinary assertion failures ordinary. */+ export function sandboxBlockedOperation(root, output, options) {+ const scan = sandboxBlockedScanner(root, options);+ for (const line of output.split('\n')) {+ const operation = scan(line);+ if (operation) return operation;+ }+ return null;+ }++ const FILE_OPERATIONS = new Set(['open', 'mkdir', 'read', 'write', 'rename', 'unlink', 'scandir', 'access', 'file access']);+ const LINE_LIMIT = 64 * 1024;++ /**+ * Watch streamed command output on the machine that ran it for a file denial outside `root`.+ * Only the evidence leaves: the operation, that its path was outside the worktree, and the errno.+ * Why here: a path can be resolved only on its own machine, so a controller never realpaths a+ * remote path. An over-long line is skipped whole, as the local scanner never sees one either.+ */+ export function fileDenialWatcher(root) {+ const scan = sandboxBlockedScanner(root, { evidence: true });+ const decoder = new TextDecoder();+ let pending = '';+ let skipping = false;+ let found = null;+ /** Classify one complete line unless a denial is already in hand. */+ const take = line => {+ const denial = found || skipping ? null : scan(line);+ if (denial?.path) found = { operation: denial.syscall ?? 'file access', outside: true, errno: denial.code };+ };+ return {+ /** Feed one raw output chunk. */+ push(chunk) {+ if (found) return;+ pending += decoder.decode(chunk, { stream: true });+ let newline;+ while ((newline = pending.indexOf('\n')) >= 0) {+ take(pending.slice(0, newline));+ pending = pending.slice(newline + 1);+ skipping = false;+ }+ if (pending.length > LINE_LIMIT) { pending = ''; skipping = true; }+ },+ /** Finish the stream and return the evidence, or null for an ordinary failure. */+ end() {+ pending += decoder.decode();+ if (pending) take(pending);+ pending = '';+ return found;+ },+ };+ }++ /**+ * Name a runner's file denial from its evidence alone, with the runner host; null when the+ * evidence is not a well-formed denial, so a malformed receipt cannot pass as one.+ */+ export function remoteFileDenial(denial, host) {+ if (!denial || typeof denial !== 'object' || Object.keys(denial).sort().join() !== 'errno,operation,outside'+ || !FILE_OPERATIONS.has(denial.operation) || !['EACCES', 'EPERM'].includes(denial.errno) || denial.outside !== true) return null;+ return `${denial.operation} outside its worktree (${denial.errno}) on runner ${host}`;+ }