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
chore(core): merge main into derived help [C7,N37]
Corey Olsondcaa76862e3d
diff --cc src/blueprints.jsindex 00000000,184a0efd..7f3a86d0mode 000000,100644..100644--- a/src/blueprints.js+++ b/src/blueprints.js@@@ -1,0 -1,495 +1,505 @@@+ /**+ * Blueprints: a starter spec as one JSON file (I1). A blueprint's rules become draft rows with their+ * reasons, its questions become pending rows with their defaults filled in, and its starter items+ * become open items citing those rows, all in one new SPEC.md section named after it. Nothing is+ * approved: the person approves rows the usual way.+ *+ * Format 1, one JSON object:+ *+ * blueprint 1 required, the format version+ * name "web-app" required, lowercase letters, digits and dashes+ * title "Web app" required, one line; the section heading+ * version 1 required, a positive integer, the blueprint's own version+ * kind "product" optional: product, infrastructure, practice or beyond-code+ * by "Pullboard" optional, who made it+ * summary "..." optional, one line+ * prefix "W" optional, the row id prefix it prefers; a free one is used if taken+ * gate "npm test" optional, set in pullboard.json only when it has no gate+ * rules [{ key, text, why, tier?, gate? }] tier must|aim (must), gate (review)+ * questions [{ key, ask, choices, default }] default is one of choices+ * items [{ key, title, cites?, after?, lane?, route?, criterion?, brief?, check? }]+ *+ * An item's route is light, mid or strong (strong when left out), as pullboard add takes it. Its+ * brief, criterion and check pass through to add unchanged, so a light or mid item is filed when it+ * carries what add requires for that route and refused with add's own refusal when it does not.+ * A check is stored on the item and never run during add: no check baseline starts, so nothing a+ * blueprint supplies executes. A blueprint is read from the bundled set or a local path, never a URL.+ *+ * 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, resolve } from 'node:path';++import {++ existsSync,++ readdirSync,++ readFileSync,++} from 'node:fs';++import {++ basename,++ 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;++ /** The kinds the gallery files blueprints under. */+ export const BLUEPRINT_KINDS = ['product', 'infrastructure', 'practice', 'beyond-code'];++ const BUNDLED_DIR = fileURLToPath(new URL('./blueprints/', import.meta.url));+ const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;+ const KEY_RE = /^[A-Za-z0-9]+$/u;+ const PREFIX_RE = /^[A-Z][A-Z0-9]*$/u;+ const ROUTES = ['light', 'mid', 'strong'];++ /**+ * The names of the blueprints shipped with Pullboard, sorted.+ *+ * @returns {string[]}+ */+ export function bundledBlueprints() {+ if (!existsSync(BUNDLED_DIR)) return [];+ return readdirSync(BUNDLED_DIR).filter((file) => file.endsWith('.json')).map((file) => file.slice(0, -5)).sort();+ }++ /**+ * Read and check a blueprint: a bundled name such as web-app, or a path to a JSON file.+ * A bare name is looked up among the bundled ones first, so a stray file cannot shadow it.+ *+ * @param {string} reference+ * @param {string} cwd+ * @returns {Blueprint}+ */+ export function readBlueprint(reference, cwd) {+ const text = String(reference ?? '').trim();+ if (!text) throw new Refused('USAGE', `name a blueprint: pullboard blueprint add <name or file>; bundled: ${bundledBlueprints().join(', ')}`);+ // Only the bundled set or a local file: nothing is fetched from a URL (P5).+ if (/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(text)) {+ throw new Refused('BLUEPRINT_URL', `a blueprint is read from the bundled set or a local file, never a URL; download ${text} yourself, read it, then run pullboard blueprint add <file>`);+ }+ const bundled = NAME_RE.test(text) && bundledBlueprints().includes(text);+ const file = bundled ? resolve(BUNDLED_DIR, `${text}.json`) : resolve(cwd, text);+ if (!bundled && !existsSync(file)) {+ throw new Refused('NO_BLUEPRINT', `no blueprint "${text}"; use a bundled one (${bundledBlueprints().join(', ')}) or a path to a blueprint JSON file`);+ }+ let value;+ try { value = JSON.parse(readFileSync(file, 'utf8')); }+ catch (error) {+ throw new Refused('BAD_BLUEPRINT', `${bundled ? text : file} is not readable JSON (${error.message.split('\n')[0]}); fix the file and run pullboard blueprint add again`);+ }+ const blueprint = validateBlueprint(value, bundled ? text : basename(file));+ if (bundled && blueprint.name !== text) throw new Refused('BAD_BLUEPRINT', `${text}.json names itself "${blueprint.name}"; its name and file name must match`);+ return blueprint;+ }++ /**+ * @typedef {object} Blueprint+ * @property {number} blueprint+ * @property {string} name+ * @property {string} title+ * @property {number} version+ * @property {string} [kind]+ * @property {string} [by]+ * @property {string} [summary]+ * @property {string} [prefix]+ * @property {string} [gate]+ * @property {{ key: string, text: string, why: string, tier: string, gate: string }[]} rules+ * @property {{ key: string, ask: string, choices: string[], default: string }[]} questions+ * @property {{ key: string, title: string, cites: string[], after: string[], lane?: string, route: string, criterion: string, brief: string }[]} items+ */++ /**+ * Check a parsed blueprint against format 1 and return it with optional fields filled in.+ * Every problem is named with its field path, so a hand-written file can be fixed in one pass.+ *+ * @param {any} value+ * @param {string} source - How to name the file in a refusal.+ * @returns {Blueprint}+ */+ export function validateBlueprint(value, source = 'blueprint') {+ const problems = [];+ const fail = (path, message) => problems.push(`${path} ${message}`);+ const line = (path, text, { required = true } = {}) => {+ if (text === undefined && !required) return;+ if (typeof text !== 'string' || !text.trim()) fail(path, 'must be nonempty text');+ else if (/[\r\n|]/u.test(text)) fail(path, 'must be one line without a | character');+ };+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ throw new Refused('BAD_BLUEPRINT', `${source} is not a blueprint: it must be one JSON object with blueprint, name, title, version and rules or questions; fix it and run pullboard blueprint add again`);+ }+ if (value.blueprint !== BLUEPRINT_FORMAT) fail('blueprint', `must be ${BLUEPRINT_FORMAT}, the format this Pullboard reads`);+ if (typeof value.name !== 'string' || !NAME_RE.test(value.name)) fail('name', 'must be lowercase letters, digits and dashes, such as web-app');+ line('title', value.title);+ if (!Number.isInteger(value.version) || value.version < 1) fail('version', 'must be a positive integer');+ if (value.kind !== undefined && !BLUEPRINT_KINDS.includes(value.kind)) fail('kind', `must be one of ${BLUEPRINT_KINDS.join(', ')}`);+ line('by', value.by, { required: false });+ line('summary', value.summary, { required: false });+ line('gate', value.gate, { required: false });+ if (value.prefix !== undefined && (typeof value.prefix !== 'string' || !PREFIX_RE.test(value.prefix))) fail('prefix', 'must be capital letters, such as W');+ const rules = Array.isArray(value.rules) ? value.rules : (value.rules === undefined ? [] : (fail('rules', 'must be an array'), []));+ const questions = Array.isArray(value.questions) ? value.questions : (value.questions === undefined ? [] : (fail('questions', 'must be an array'), []));+ const items = Array.isArray(value.items) ? value.items : (value.items === undefined ? [] : (fail('items', 'must be an array'), []));+ if (!rules.length && !questions.length) fail('rules', 'or questions must hold at least one entry');+ const keys = new Set();+ const key = (path, text, seen) => {+ if (typeof text !== 'string' || !KEY_RE.test(text)) fail(path, 'must be letters and digits, such as W1');+ else if (seen.has(text)) fail(path, `repeats the key ${text}`);+ else seen.add(text);+ };+ rules.forEach((rule, index) => {+ const at = `rules[${index}]`;+ if (!rule || typeof rule !== 'object') return fail(at, 'must be an object');+ key(`${at}.key`, rule.key, keys);+ line(`${at}.text`, rule.text);+ line(`${at}.why`, rule.why);+ if (rule.tier !== undefined && !['must', 'aim'].includes(rule.tier)) fail(`${at}.tier`, 'must be must or aim');+ line(`${at}.gate`, rule.gate, { required: false });+ });+ questions.forEach((question, index) => {+ const at = `questions[${index}]`;+ if (!question || typeof question !== 'object') return fail(at, 'must be an object');+ key(`${at}.key`, question.key, keys);+ line(`${at}.ask`, question.ask);+ if (!Array.isArray(question.choices) || question.choices.length < 2) fail(`${at}.choices`, 'must list at least two answers');+ else question.choices.forEach((choice, n) => line(`${at}.choices[${n}]`, choice));+ line(`${at}.default`, question.default);+ if (Array.isArray(question.choices) && !question.choices.includes(question.default)) fail(`${at}.default`, 'must be one of its choices');+ });+ const itemKeys = new Set();+ items.forEach((item, index) => {+ const at = `items[${index}]`;+ if (!item || typeof item !== 'object') return fail(at, 'must be an object');+ key(`${at}.key`, item.key, itemKeys);+ line(`${at}.title`, item.title);+ if (item.cites !== undefined && !Array.isArray(item.cites)) fail(`${at}.cites`, 'must be an array of rule or question keys');+ for (const cited of item.cites ?? []) if (!keys.has(cited)) fail(`${at}.cites`, `names ${JSON.stringify(cited)}, which is no rule or question key here`);+ if (item.after !== undefined && !Array.isArray(item.after)) fail(`${at}.after`, 'must be an array of earlier item keys');+ for (const before of item.after ?? []) {+ if (!itemKeys.has(before) || before === item.key) fail(`${at}.after`, `names ${JSON.stringify(before)}, which is no earlier item key`);+ }+ line(`${at}.lane`, item.lane, { required: false });+ if (item.route !== undefined && !ROUTES.includes(item.route)) fail(`${at}.route`, `must be one of ${ROUTES.join(', ')}`);+ line(`${at}.check`, item.check, { required: false });+ line(`${at}.criterion`, item.criterion, { required: false });+ if (item.brief !== undefined && typeof item.brief !== 'string') fail(`${at}.brief`, 'must be text');+ });+ if (problems.length) {+ throw new Refused('BAD_BLUEPRINT', `${source} is not a valid blueprint: ${problems.slice(0, 5).join('; ')}${problems.length > 5 ? `; and ${problems.length - 5} more` : ''}; fix the file and run pullboard blueprint add again`);+ }+ return {+ ...value,+ rules: rules.map((rule) => ({ ...rule, tier: rule.tier ?? 'must', gate: rule.gate ?? 'review' })),+ questions,+ items: items.map((item) => ({ ...item, cites: item.cites ?? [], after: item.after ?? [], route: item.route ?? 'strong', criterion: item.criterion ?? '', brief: item.brief ?? '' })),+ };+ }++ /**+ * The marker line a blueprint leaves after its rows once everything is added, so the same version+ * adds nothing twice even after the person rewords or declines its rows.+ *+ * @param {{ name: string, version: number }} blueprint+ * @returns {string}+ */+ export function blueprintMarker(blueprint) {+ return `<!-- pullboard-blueprint ${blueprint.name} ${blueprint.version} -->`;+ }++ /**+ * The marker line written with the rows while an add is under way: it records which row id each+ * rule and question key got, so a retry after a failure part way files no row twice and finds the+ * starter items already added by those ids. The finished add replaces it with blueprintMarker.+ *+ * @param {{ name: string, version: number }} blueprint+ * @param {Record<string, string>} ids - Row id by rule or question key.+ * @returns {string}+ */+ export function blueprintAddingMarker(blueprint, ids) {+ return `<!-- pullboard-blueprint ${blueprint.name} ${blueprint.version} adding ${Object.entries(ids).map(([key, id]) => `${key}=${id}`).join(' ')} -->`;+ }++ /**+ * Read an under-way marker line for this blueprint version, or null.+ *+ * @param {string} line+ * @param {{ name: string, version: number }} blueprint+ * @returns {Record<string, string> | null}+ */+ function addingIds(line, blueprint) {+ const match = /^<!-- pullboard-blueprint (\S+) (\d+) adding ((?:[A-Za-z0-9]+=[A-Za-z0-9.]+ ?)+) -->$/u.exec(line.trim());+ if (!match || match[1] !== blueprint.name || Number(match[2]) !== blueprint.version) return null;+ return Object.fromEntries(match[3].trim().split(' ').map((pair) => pair.split('=')));+ }++ /**+ * One rule's row text: the rule, then its reason.+ *+ * @param {{ text: string, why: string }} rule+ * @returns {string}+ */+ export function ruleText(rule) {+ return `${rule.text.trim()} Why: ${rule.why.trim()}`;+ }++ /**+ * One question's row text: the question with its default as the answer, then every choice.+ *+ * @param {{ ask: string, choices: string[], default: string }} question+ * @returns {string}+ */+ export function questionText(question) {+ return `${question.ask.trim()}: ${question.default.trim()}. Choices: ${question.choices.map((choice) => choice.trim()).join(', ')}.`;+ }++ /**+ * Work out what adding a blueprint changes, without writing anything. A first add files every rule+ * as a new draft row and every question as a new pending row, whatever the spec already says, in+ * the blueprint's section (found by title, or new), and plans every starter item. A retry after a+ * failure part way (the under-way marker is there) files no rows and plans only the starters not+ * yet on the board, found by title and the row ids they cite. A finished add (the marker is there)+ * plans nothing.+ *+ * @param {Blueprint} blueprint+ * @param {{ source: string, spec: any, doctrine: any, existingItems: { id: number, title: string, specIds: string[] }[], gate: string }} board+ * source is SPEC.md's text and spec its parse; doctrine is loadDoctrine's result; existingItems+ * are the items on the board; gate is pullboard.json's gate now.+ * @returns {{ marked: boolean, resumed: boolean, section: { prefix: string, name: string, isNew: boolean }, rows: { key: string, id: string, status: string, text: string, line: string }[], specRows: string, specAfter: string, ids: Record<string, string>, items: { key: string, title: string, specIds: string[], after: string[], lane?: string, route: string, criterion: string, brief: string }[], existing: Record<string, number>, gate: string | null }}+ * specRows is the text to write before the items (rows and the under-way marker), specAfter the+ * text once they are all added (the finished marker); existing maps starter keys already on the+ * board to their item ids.+ */+ export function planBlueprint(blueprint, { source, spec, doctrine, existingItems = [], gate }) {+ const marker = blueprintMarker(blueprint);+ const lines = source.split(/\r?\n/u);+ const marked = lines.some((text) => text.trim() === marker);+ const addingLine = lines.find((text) => addingIds(text, blueprint));+ const resumed = !marked && Boolean(addingLine);+ const allRows = [...spec.rows, ...(doctrine?.rows ?? []), ...(doctrine?.repo?.rows ?? [])];+ const prefixOf = (name) => /^([A-Z][A-Z0-9]*)\s*[·.:-]/u.exec(name)?.[1];+ const existingSection = spec.sections.find((section) => section.name.replace(/^[A-Z][A-Z0-9]*\s*[·.:-]\s*/u, '') === blueprint.title.trim() && prefixOf(section.name));+ const taken = new Set([+ ...allRows.map((row) => /^[A-Za-z]+/u.exec(row.id)?.[0].toUpperCase()),+ ...spec.sections.map((section) => prefixOf(section.name)),+ ...(doctrine?.sections ?? []).map((section) => prefixOf(section.name)),+ ].filter(Boolean));+ const prefix = existingSection ? prefixOf(existingSection.name) : freePrefix(blueprint, taken);+ const name = existingSection ? existingSection.name : `${prefix} · ${blueprint.title.trim()}`;+ const section = { prefix, name, isNew: !existingSection };+ const gateToSet = !gate?.trim() && blueprint.gate ? blueprint.gate : null;+ if (marked) return { marked, resumed: false, section, rows: [], specRows: source, specAfter: source, ids: {}, items: [], existing: {}, gate: null };+ const rows = [];+ let ids;+ let specRows = source;+ if (resumed) ids = addingIds(addingLine, blueprint);+ else {+ // The same rows spec draft numbers against: SPEC.md and the repo's own doctrine.+ const numberedRows = [...spec.rows, ...(doctrine?.repo?.rows ?? [])];+ const allocate = () => {+ const id = nextRowId(prefix, numberedRows);+ numberedRows.push({ id });+ return id;+ };+ ids = {};+ for (const rule of blueprint.rules) {+ const id = allocate();+ const text = ruleText(rule);+ ids[rule.key] = id;+ rows.push({ key: rule.key, id, status: 'draft', text, line: `- ${id} [draft, ${rule.tier}] ${text} | gate: ${rule.gate}` });+ }+ for (const question of blueprint.questions) {+ const id = allocate();+ const text = questionText(question);+ ids[question.key] = id;+ rows.push({ key: question.key, id, status: 'pending', text, line: `- ${id} [pending, must] ${text} | gate: review` });+ }+ specRows = insertSection(source, spec, { existing: existingSection, name, lines: [...rows.map((row) => row.line), blueprintAddingMarker(blueprint, ids)] });+ }+ const underWay = blueprintAddingMarker(blueprint, ids);+ const specAfter = specRows.split(/(\r?\n)/u).map((part) => (part.trim() === underWay || (resumed && part === addingLine) ? part.replace(part.trim(), marker) : part)).join('');+ const existing = {};+ const items = [];+ for (const item of blueprint.items) {+ const specIds = item.cites.map((cited) => ids[cited]).filter(Boolean);+ const found = resumed && existingItems.find((entry) => entry.title === item.title.trim() && entry.specIds.join(',') === specIds.join(','));+ if (found) { existing[item.key] = found.id; continue; }+ items.push({ key: item.key, title: item.title.trim(), specIds, after: item.after,+ ...(item.lane ? { lane: item.lane } : {}), ...(item.check ? { check: item.check } : {}), route: item.route, criterion: item.criterion, brief: item.brief });+ }+ return { marked, resumed, section, rows, specRows, specAfter, ids, items, existing, gate: gateToSet };+ }++ /**+ * Choose the section's id prefix: the blueprint's own if free, then the title's initials, then any+ * free capital letter, then the preferred prefix with a letter added. Ids are unique across SPEC.md+ * and the doctrine, so a prefix either file uses is taken.+ *+ * @param {{ prefix?: string, title: string }} blueprint+ * @param {Set<string>} taken+ * @returns {string}+ */+ function freePrefix(blueprint, taken) {+ const initials = blueprint.title.split(/\s+/u).map((word) => word[0]?.toUpperCase()).filter((letter) => /[A-Z]/u.test(letter ?? ''));+ const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');+ const base = blueprint.prefix ?? initials[0] ?? 'B';+ const candidates = [blueprint.prefix, ...initials, initials.join(''), ...letters, ...letters.map((letter) => `${base}${letter}`)];+ return candidates.find((candidate) => candidate && !taken.has(candidate)) ?? `${base}${taken.size}`;+ }++ /**+ * Put lines into SPEC.md text: into the blueprint's existing section the way spec draft does, or+ * as a new section at the end.+ *+ * @param {string} source+ * @param {any} spec+ * @param {{ existing: any, name: string, lines: string[] }} change+ * @returns {string}+ */+ function insertSection(source, spec, { existing, name, lines: added }) {+ if (existing) return insertSectionRows(source, spec, existing, added);+ const newline = source.includes('\r\n') ? '\r\n' : '\n';+ const lines = source.split(/\r?\n/u);+ while (lines.length && !lines.at(-1).trim()) lines.pop();+ lines.push('', `## ${name}`, '', ...added, '');+ return lines.join(newline);+ }++ // A row naming a file or a place on disk: any token with a slash or backslash between characters,+ // or a home-relative path. Bare names such as Next.js are words, not paths.+ const PATH_RE = /(?:^|[\s(`'"[])(?:~\/|\.{1,2}\/|\/)?[^\s/\\`'"()[\]]+[/\\][^\s`'"()[\]]+|(?:^|[\s(`'"[])~\//u;+ const EMAIL_RE = /[^\s@<>()[\]`'"]+@[^\s@<>()[\]`'"]+\.[^\s@<>()[\]`'"]+/u;+ const CHOICES = '. Choices: ';+ const WHY = ' Why: ';+ const MOST_CHOICE_PARTS = 12;++ /** Every index where a separator starts in the text. */+ function positions(text, separator) {+ const found = [];+ for (let at = text.indexOf(separator); at !== -1; at = text.indexOf(separator, at + 1)) found.push(at);+ return found;+ }++ /**+ * Read an approved question row back into its ask, choices and answer, or say why it cannot be.+ * The ask and the choices may hold ": " and ", ", so every split is tried: a reading counts only if+ * its answer is one of two or more choices and questionText gives back the exact row text. One+ * reading is kept; none or several leave the row out, so a save never changes a question [S1].+ *+ * @param {string} text+ * @returns {{ question?: { ask: string, choices: string[], default: string }, reason?: string } | null} null when the row is no question+ */+ function readQuestion(text) {+ if (!text.endsWith('.') || !text.includes(CHOICES)) return null;+ const readings = new Map();+ for (const at of positions(text, CHOICES)) {+ const head = text.slice(0, at);+ const tokens = text.slice(at + CHOICES.length, -1).split(', ');+ if (tokens.length > MOST_CHOICE_PARTS) return { reason: 'its choices are too many to read back exactly' };+ for (const colon of positions(head, ': ')) {+ const ask = head.slice(0, colon);+ const answer = head.slice(colon + 2);+ for (let mask = 0; mask < 2 ** (tokens.length - 1); mask += 1) {+ const choices = [tokens[0]];+ for (let index = 1; index < tokens.length; index += 1) {+ if (mask & (2 ** (index - 1))) choices[choices.length - 1] += `, ${tokens[index]}`;+ else choices.push(tokens[index]);+ }+ const question = { ask, choices, default: answer };+ if (choices.length < 2 || !choices.includes(answer) || [ask, ...choices].some((part) => !part.trim() || part !== part.trim())) continue;+ if (questionText(question) === text) readings.set(JSON.stringify(question), question);+ }+ }+ }+ if (readings.size === 1) return { question: [...readings.values()][0] };+ return { reason: readings.size ? 'its question can be read more than one way' : 'its answer is not one of its choices, or its choices cannot be read back exactly' };+ }++ /**+ * Name why a piece of text may not leave this board, or return null when it may. Text that holds+ * a path, an email or any private name (a person, an agent, a model label or a machine) stays.+ *+ * @param {string} text+ * @param {string[]} names - Every private name known on this board and machine, matched in any case.+ * @param {string[]} [parts] - Parts of people's names, matched only as written.+ * @returns {string | null}+ */+ export function privateTextReason(text, names, parts = []) {+ if (PATH_RE.test(text)) return 'a file path';+ if (EMAIL_RE.test(text)) return 'an email address';+ /** True when the name stands as its own word in the text, in either case or exactly as written. */+ const holds = (name, cased) => {+ const wanted = String(name ?? '').trim();+ if (wanted.length < 3) return false;+ const escaped = (cased ? wanted : wanted.toLowerCase()).replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');+ return new RegExp(`(?:^|[^\\p{L}\\p{N}_-])${escaped}(?:$|[^\\p{L}\\p{N}_-])`, 'u').test(cased ? text : text.toLowerCase());+ };+ // A whole name matches in any case; a part of a person's name only as written, so the person+ // "Test Agent" keeps "Test" out without losing every rule about a test.+ if (names.some((name) => holds(name, false)) || parts.some((part) => holds(part, true))) return 'a private name';+ return null;+ }++ /**+ * Turn a board's approved spec rows into a blueprint, writing only fields on an explicit+ * allow-list: the format, a name and title, a version, the gate when it is clean, each approved+ * rule's text, reason, tier and a review gate, and each answered question's ask, choices and+ * answer. Items, shouts, notes, decisions, signers, row gates, files, emails and the names of+ * people, agents and machines are never read into it. A row that would carry any of them, or a+ * rule with no "Why:" reason to carry, is left out and named in `left`, never rewritten [S1].+ *+ * @param {{ rows: any[] }} spec - The parsed SPEC.md.+ * @param {{ name?: string, title?: string, gate?: string, names: string[], parts?: string[] }} board - name and title are the person's own choice, never the project's+ * @returns {{ blueprint: Blueprint, left: { id: string, reason: string }[] }}+ */+ export function saveBlueprint(spec, { name, title, gate, names, parts = [] }) {+ const rules = [];+ const questions = [];+ const left = [];+ for (const row of spec.rows) {+ if (row.status !== 'approved') continue;+ const text = String(row.text ?? '').trim();+ const privacy = privateTextReason(text, names, parts);+ if (privacy) { left.push({ id: row.id, reason: `it holds ${privacy}` }); continue; }+ const asked = readQuestion(text);+ if (asked) {+ if (asked.reason) left.push({ id: row.id, reason: asked.reason });+ else questions.push({ key: row.id, ...asked.question });+ continue;+ }+ // A rule carries exactly one reason, so the split is never a guess.+ const reasons = positions(text, WHY);+ if (reasons.length !== 1) { left.push({ id: row.id, reason: reasons.length ? 'it has more than one "Why:", so its reason cannot be read back exactly' : 'it has no "Why:" reason to carry' }); continue; }+ const rule = { text: text.slice(0, reasons[0]), why: text.slice(reasons[0] + WHY.length) };+ if (!rule.text.trim() || !rule.why.trim() || ruleText(rule) !== text) { left.push({ id: row.id, reason: 'its rule cannot be read back exactly' }); continue; }+ rules.push({ key: row.id, ...rule, tier: row.tier === 'aim' ? 'aim' : 'must', gate: 'review' });+ }+ // The project's name never goes in (decision de849661): the person names the blueprint, or it+ // gets a neutral default to edit. A chosen name still may not carry anything private.+ const safeName = name ?? 'my-blueprint';+ const safeTitle = title ?? 'My blueprint';+ if (typeof safeName !== 'string' || !NAME_RE.test(safeName)) throw new Refused('USAGE', 'a blueprint name is lowercase letters, digits and dashes; run pullboard blueprint save --name my-rules');+ if (typeof safeTitle !== 'string' || !safeTitle.trim() || /[\r\n|]/u.test(safeTitle)) throw new Refused('USAGE', 'a blueprint title is one line without a | character; run pullboard blueprint save --title "My rules"');+ const strict = [...names, ...parts];+ for (const [flag, text] of [['--name', safeName.replaceAll('-', ' ')], ['--title', safeTitle]]) {+ const privacy = privateTextReason(text, strict);+ if (privacy) throw new Refused('PRIVATE_BLUEPRINT', `${flag} holds ${privacy}; choose a name that names no one: pullboard blueprint save ${flag} "..."`);+ }+ const value = {+ blueprint: BLUEPRINT_FORMAT,+ name: safeName,+ title: safeTitle.trim(),+ version: 1,+ ...(gate?.trim() && !/[\r\n|]/u.test(gate) && !privateTextReason(gate.trim(), names, parts) ? { gate: gate.trim() } : {}),+ ...(rules.length ? { rules } : {}),+ ...(questions.length ? { questions } : {}),+ };+ if (!rules.length && !questions.length) {+ throw new Refused('EMPTY_BLUEPRINT', `no approved row can leave this board${left.length ? ` (${left.length} left out: ${left.slice(0, 3).map((entry) => `${entry.id}, ${entry.reason}`).join('; ')})` : ''}; approve rules written as "<rule> Why: <reason>", then run pullboard blueprint save again`);+ }+ // Checked against the format blueprint add reads, then written exactly as allow-listed above.+ validateBlueprint(value, `${safeName}.blueprint.json`);+ return { blueprint: value, left };+ }diff --cc src/cli.jsindex b2b1a725,062d6c58..8b8dea9e--- a/src/cli.js+++ b/src/cli.js@@@ -2,96 -2,24 +2,99 @@@* 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, 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,+ writeFileSync,+} from 'node:fs';- import { loadavg } from 'node:os';++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 { agentSessionDigest, requirePersonChannel } from './person.js';-import { bindLocalSession, localSessionMatches } from './agent-session.js';-import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';-import { digestOf, gateReport, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';+import {+ doctrineHistory,+ loadDoctrine,+} from './doctrine.js';+import {+ agentSessionDigest,+ requirePersonChannel,+} from './person.js';+import {+ bindLocalSession,+ localSessionMatches,+} from './agent-session.js';+import {+ decisionProjection,+ planRowApply,+ prepareRowDecisions,+ restoreRowApply,+ writeRowApply,+} from './row-decisions.js';+import {+ digestOf,+ gateReport,+ 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,@@@ -148,123 -56,36 +153,133 @@@ importstandings,unmetRows,} from './spec.js';-import { bundledBlueprints, planBlueprint, readBlueprint, saveBlueprint } from './blueprints.js';++import {++ bundledBlueprints,++ planBlueprint,++ readBlueprint,++ saveBlueprint,++} from './blueprints.js';import { briefFiles } from './brief.js';-import { checkBaseline, prepareCheckBaseline, sayCheckBaseline } from './check-baseline.js';-import { retryCheckBaselines, startCheckBaseline } from './check-baseline-worker.js';-import { compareMainFailures, mainRedMessage, mainRedReworkItems } from './main-red.js';+import {+ checkBaseline,+ prepareCheckBaseline,+ sayCheckBaseline,+} 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 } from './projects.js';+import {+ commandOutput,+ refusalDocument,+} from './json.js';+import {+ forgetProject,+ listApiProjects,+ registerProjectAndLink,+} from './projects.js';import { milestoneRoadmap } from './roadmap.js';- import { listResources } from './resources.js';-import { listResources, runnerResourceStatus } from './resources.js';-import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';-import { exportView, serveView } from './serve.js';-import { forgetView, rememberView, runningView } from './view-session.js';++import {++ listResources,++ runnerResourceStatus,++} from './resources.js';+import {+ citedTestFiles,+ rowEvidence,+ rowStage,+} from './evidence.js';+import {+ exportView,+ serveView,+} from './serve.js';+import {+ forgetView,+ rememberView,+ runningView,+} from './view-session.js';import { serveApi } from './api.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, loadMachineSettings, 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,+ loadMachineSettings,+ 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 { 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';diff --cc src/gate.jsindex b88a48a3,d605a9a3..26ecb764--- a/src/gate.js+++ b/src/gate.js@@@ -4,51 -4,21 +4,62 @@@* 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,++ statSync,+ writeFileSync,+} from 'node:fs';+import {+ dirname,++ isAbsolute,+ join,++ relative,++ 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, takeResource } from './resources.js';-import { browserFreeChecksEnabled, loadMachineSettings } from './settings.js';+import {+ GATE_SLOT_HELD_ENV,+ gateSlotEnvironment,+ inheritedGateSlot,+ takeResource,+} from './resources.js';+import {+ browserFreeChecksEnabled,+ loadMachineSettings,+} from './settings.js';import { selectAffectedTests } from './affected-tests.js';-import { checkNeedsBrowser, testsNeedBrowser } from './browser-admission.js';-import { timingFromOutput, timingRunner } from './timing.js';-import { RunnerDropped, runOnRunner, runOnRunnerAsync, runnerSource } from './runners.js';+import {+ checkNeedsBrowser,+ testsNeedBrowser,+} from './browser-admission.js';+import {+ timingFromOutput,+ timingRunner,+} from './timing.js';++import {++ RunnerDropped,++ runOnRunner,++ runOnRunnerAsync,++ runnerSource,++} from './runners.js';const STAMP = 'pullboard-gate-green';const LOG = 'pullboard-gate.log';diff --cc src/init.jsindex 5e6542ab,7c22c502..a1991598--- a/src/init.js+++ b/src/init.js@@@ -4,23 -4,9 +4,28 @@@* the main checkout as the coordinator. It runs again safely and never overwrites a file it did not* write.*/-import { accessSync, appendFileSync, constants as fsConstants, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';-import { delimiter, basename, join, resolve } from 'node:path';-import { CONFIG_FILE, COORDINATOR, doctrineFile, loadConfig } from './config.js';+import {++ accessSync,+ appendFileSync,++ constants as fsConstants,+ existsSync,+ mkdirSync,+ readFileSync,++ statSync,+ writeFileSync,+} from 'node:fs';+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/machine-home.jsindex 24b9a0a3,878c3790..f8dfcd8a--- a/src/machine-home.js+++ b/src/machine-home.js@@@ -1,9 -1,7 +1,10 @@@/** Resolve the per-account directory for machine-wide Pullboard state. */import { userInfo } from 'node:os';-import { join, resolve } from 'node:path';+import {+ join,+ resolve,+} from 'node:path';+ import { Refused } from './refused.js';/** Use the OS account home unless a caller explicitly selects a private machine pool. */export function machineHome() {diff --cc src/resources.jsindex 9ad937b0,f52a4931..212afdb6--- a/src/resources.js+++ b/src/resources.js@@@ -13,7 -5,7 +13,10 @@@ importimport { randomUUID } from 'node:crypto';import { DatabaseSync } from 'node:sqlite';import { repoInfo } from './git.js';- import { machineHome } from './machine-home.js';-import { machineHome, withMachineHomeWrite } from './machine-home.js';++import {++ machineHome,++ withMachineHomeWrite,++} from './machine-home.js';import { Refused } from './refused.js';const LEASE_MS = 20_000;diff --cc src/runner-worker.jsindex 00000000,7e01c2ef..c83710d9mode 000000,100644..100644--- a/src/runner-worker.js+++ b/src/runner-worker.js@@@ -1,0 -1,1199 +1,1226 @@@+ /** 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 { once } from 'node:events';+ import { pipeline } from 'node:stream/promises';++ const RECEIPT = 'PULLBOARD_RUNNER_RESULT';+ const safePath = [dirname(process.execPath), process.env.PATH || '/usr/local/bin:/usr/bin:/bin'].join(delimiter);+ const ownedChildren = new Map();+ let transportLost = false;+ let transportDrain = null;+ let signalCustodyInstalled = false;+ let transportDrop = () => {};+ let heartbeatTimer = null;+ let workerId = 'starting';+ let rejectPendingFrame = null;+ let activeDescendantTracker = null;+ // Budget: report a named failure within 30 seconds after command exit or transport cancellation.+ const CLEANUP_BUDGET_MS = 30_000;+ let cleanupDeadline = Infinity;+ let cleanupTimedOut = false;+ let cleanupTimer = null;+ let cleanupStage = 'command exit';+ let cleanupDirectory = null;+ let cleanupDetails = null;++ /** Start the post-run budget once; later cleanup phases cannot extend it. */+ function beginCleanup() {+ if (Number.isFinite(cleanupDeadline)) return;+ cleanupDeadline = Math.min(cleanupDeadline, Date.now() + CLEANUP_BUDGET_MS);+ cleanupTimer = setTimeout(reportCleanupTimeout, CLEANUP_BUDGET_MS);+ cleanupTimer.unref();+ }++ /** Report an unresolved cleanup once so the controller can fail without retrying the command. */+ function reportCleanupTimeout() {+ if (cleanupTimedOut || Date.now() < cleanupDeadline) return;+ cleanupTimedOut = true;+ const details = { id: workerId, stage: cleanupStage, ...(cleanupDetails?.() ?? {}) };+ // A timeout may arrive after ordinary job deletion while output is still flushing.+ // Keep a small diagnostic even then; it never contains command arguments or credentials.+ if (cleanupDirectory) {+ try {+ mkdirSync(cleanupDirectory, { recursive: true, mode: 0o700 });+ writeFileSync(join(cleanupDirectory, 'cleanup-timeout.json'), JSON.stringify(details) + '\n', { mode: 0o600 });+ } catch { /* The named red result remains authoritative if diagnostic storage fails. */ }+ }+ process.stderr.write(`PULLBOARD_RUNNER_CLEANUP_UNVERIFIED ${workerId} ${details.reason || cleanupStage}\n`);+ process.stderr.write(`PULLBOARD_RUNNER_CLEANUP_TIMEOUT ${workerId}\n`);+ }++ /** Parse and strictly validate the controller's one-shot work specification. */+ async function readSpec() {+ let buffered = Buffer.alloc(0);+ let expected = null;+ let headerLength = null;+ const spec = await new Promise((resolve, reject) => {+ const cleanup = () => { process.stdin.off('data', onData); process.stdin.off('end', onEnd); process.stdin.off('error', onError); };+ rejectPendingFrame = error => { cleanup(); reject(error); };+ const onError = error => { cleanup(); reject(error); };+ const onEnd = () => { cleanup(); reject(new Error('incomplete work specification')); };+ const onData = chunk => {+ if (transportLost) { cleanup(); reject(new Error('runner transport was lost')); return; }+ buffered = Buffer.concat([buffered, chunk]);+ if (expected === null) {+ const newline = buffered.indexOf(10);+ if (newline < 0) {+ if (buffered.length > 9 || !/^\d*$/u.test(buffered.toString('ascii'))) { cleanup(); reject(new Error('invalid work specification frame')); }+ return;+ }+ const header = buffered.subarray(0, newline).toString('ascii');+ if (!/^\d{1,8}$/u.test(header)) { cleanup(); reject(new Error('invalid work specification frame')); return; }+ expected = Number(header);+ headerLength = newline + 1;+ if (!expected || expected > 1_048_576) { cleanup(); reject(new Error('invalid work specification frame')); return; }+ }+ if (buffered.length < headerLength + expected) return;+ const body = buffered.subarray(headerLength, headerLength + expected);+ const rest = buffered.subarray(headerLength + expected);+ cleanup();+ rejectPendingFrame = null;+ process.stdin.pause();+ if (rest.length) process.stdin.unshift(rest);+ try { resolve(JSON.parse(body.toString('utf8'))); } catch (error) { reject(error); }+ };+ process.stdin.on('data', onData);+ process.stdin.once('end', onEnd);+ process.stdin.once('error', onError);+ process.stdin.resume();+ });+ const value = spec;+ if (!value || value.version !== 1 || !/^[A-Za-z0-9_-]{1,100}$/u.test(value.id)+ || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(value.commit)+ || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(value.tree)+ || value.commit.length !== value.tree.length+ || !/^[a-f0-9]{64}$/u.test(value.repoId ?? '')+ || typeof value.command !== 'string' || !value.command.trim()+ || typeof value.pipefail !== 'boolean' || !Number.isSafeInteger(value.slots) || value.slots < 1+ || !Number.isSafeInteger(value.browser) || value.browser < 0+ || typeof value.browserRequired !== 'boolean'+ || !value.runtime || typeof value.runtime !== 'object' || !value.runtime.files || typeof value.runtime.files !== 'object'+ || typeof value.runtime.sha256 !== 'string') throw new Error('invalid work specification');+ if (value.origin !== undefined) {+ if (typeof value.origin !== 'string') throw new Error('invalid work specification');+ let origin;+ try { origin = new URL(value.origin); } catch { throw new Error('invalid work specification'); }+ if (origin.protocol !== 'https:' || !origin.hostname || origin.username || origin.password || origin.search || origin.hash) {+ throw new Error('invalid work specification');+ }+ }+ if (value.originBase !== undefined+ && (typeof value.originBase !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(value.originBase)+ || value.originBase.length !== value.commit.length || !value.origin)) throw new Error('invalid work specification');+ if (!Array.isArray(value.tags) || value.tags.length > 1_024) throw new Error('invalid tag manifest');+ const tagNames = new Set();+ for (const tag of value.tags) {+ if (!tag || typeof tag.name !== 'string' || !tag.name.startsWith('refs/tags/') || tag.name.length > 1_024+ || /[\u0000-\u001f\u007f]/u.test(tag.name) || tagNames.has(tag.name)+ || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(tag.object ?? '')+ || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(tag.peeledCommit ?? '')+ || tag.object.length !== value.commit.length || tag.peeledCommit.length !== value.commit.length+ || !Array.isArray(tag.chain) || tag.chain.length > 8+ || tag.chain.some(object => typeof object !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(object)+ || object.length !== value.commit.length)) throw new Error('invalid tag manifest');+ tagNames.add(tag.name);+ if (tag.chain.length ? tag.chain[0] !== tag.object : tag.object !== tag.peeledCommit) throw new Error('invalid tag manifest');+ }+ const runtimeNames = ['resources.js', 'git.js', 'machine-home.js', 'refused.js'];+ if (Object.keys(value.runtime.files).length !== runtimeNames.length+ || runtimeNames.some(name => typeof value.runtime.files[name] !== 'string')) throw new Error('invalid work specification');+ if (createHash('sha256').update(JSON.stringify(value.runtime.files)).digest('hex') !== value.runtime.sha256) throw new Error('invalid trusted runtime');+ const workerSource = readFileSync(fileURLToPath(import.meta.url), 'utf8');+ const toolingFiles = { ...value.runtime.files, 'runner-worker.js': workerSource };+ if (!workerSource || !value.tooling || !['git-checkout', 'installed-package'].includes(value.tooling.kind)+ || value.tooling.name !== 'pullboard' || typeof value.tooling.version !== 'string'+ || createHash('sha256').update(JSON.stringify(toolingFiles)).digest('hex') !== value.tooling.sha256) {+ throw new Error('invalid trusted tooling identity');+ }+ for (const field of ['landing', 'itemCheck', 'diagnostic']) {+ if (value[field] !== undefined && typeof value[field] !== 'boolean') throw new Error('invalid work specification');+ }+ for (const field of ['item', 'kind']) {+ if (value[field] !== undefined && typeof value[field] !== 'string') throw new Error('invalid work specification');+ }+ if (value.root !== undefined && (typeof value.root !== 'string' || !isAbsolute(value.root))) throw new Error('invalid work specification');+ return value;+ }++ /** Construct a minimal environment from runner-owned values, excluding caller credentials and markers. */+ function childEnvironment(home, temporary, machineHomePath = '', nodeOptions = '') {+ return {+ PATH: safePath,+ HOME: home,+ TMPDIR: temporary,+ TMP: temporary,+ TEMP: temporary,+ LANG: process.env.LANG || 'C.UTF-8',+ TZ: process.env.TZ || 'UTC',+ CI: '1',+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_NO_REPLACE_OBJECTS: '1',+ GIT_TERMINAL_PROMPT: '0',+ GIT_OPTIONAL_LOCKS: '0',+ NPM_CONFIG_USERCONFIG: join(home, 'npm-userconfig'),+ NPM_CONFIG_GLOBALCONFIG: join(home, 'npm-globalconfig'),+ ...(nodeOptions ? { NODE_OPTIONS: nodeOptions } : {}),+ ...(machineHomePath ? { PULLBOARD_MACHINE_HOME: machineHomePath } : {}),+ };+ }++ /** Add this worker's remote gate lease so nested test runners reuse the remote slot instead of deadlocking. */+ function scopedEnvironment(home, temporary, machineHomePath, gateLease, resourcesApi, nodeOptions = '') {+ return {+ ...childEnvironment(home, temporary, machineHomePath, nodeOptions),+ ...resourcesApi.gateSlotEnvironment(gateLease),+ };+ }++ /** Check that this already installed capsule matches the controller before using its static API. */+ function loadResourceApi(runtime) {+ const sourceDirectory = dirname(fileURLToPath(import.meta.url));+ if (Object.entries(runtime.files).some(([name, source]) => readFileSync(join(sourceDirectory, name), 'utf8') !== source)) {+ throw new Error('trusted runtime cache does not match the request');+ }+ return resourceApi;+ }++ /** Start a subprocess in a private process group so this worker can drain only its own descendants. */+ function spawnOwned(command, args, options = {}) {+ assertTransportLive();+ const child = spawn(command, args, { ...options, detached: true });+ let settle;+ const closed = new Promise(resolveClose => { settle = resolveClose; });+ const record = { child, pid: child.pid, closed, drainPromise: null };+ ownedChildren.set(child, record);+ activeDescendantTracker?.registerRoot(child.pid);+ child.once('error', error => settle({ error }));+ child.once('close', (code, signal) => settle({ code, signal }));+ return record;+ }++ /** Read one all-process POSIX census; a failed or malformed census is never interpreted as an empty machine. */+ function processCensus() {+ const result = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], {+ encoding: 'utf8', timeout: 2_000, maxBuffer: 8 * 1024 * 1024,+ env: { PATH: safePath, LANG: 'C', LC_ALL: 'C', TZ: 'UTC' },+ });+ if (result.error || result.status !== 0 || typeof result.stdout !== 'string') return null;+ const rows = new Map();+ for (const line of result.stdout.split(/\r?\n/u)) {+ if (!line.trim()) continue;+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+([A-Z][a-z]{2})\s+([A-Z][a-z]{2})\s+(\d{1,2})\s+(\d{2}:\d{2}:\d{2})\s+(\d{4})\s+(\S+)\s+(.+?)\s*$/u.exec(line);+ if (!match) return null;+ const pid = Number(match[1]);+ const ppid = Number(match[2]);+ const pgid = Number(match[3]);+ if (![pid, ppid, pgid].every(Number.isSafeInteger) || pid < 1 || ppid < 0 || pgid < 1 || rows.has(pid)) return null;+ const started = `${match[4]} ${match[5]} ${match[6]} ${match[7]} ${match[8]}`;+ const processSha256 = createHash('sha256').update(match[10]).digest('hex');+ rows.set(pid, { pid, ppid, pgid, started, state: match[9], processSha256 });+ }+ return rows.size ? rows : null;+ }++ /** Add a kernel start-time identity when procfs is available; otherwise retain a conservative census tuple. */+ function processIdentity(row) {+ let birth = '';+ let exact = false;+ try {+ const stat = readFileSync(`/proc/${row.pid}/stat`, 'utf8');+ const close = stat.lastIndexOf(')');+ const fields = stat.slice(close + 2).trim().split(/\s+/u);+ if (close > 0 && Number(fields[1]) === row.ppid && Number(fields[2]) === row.pgid && /^\d+$/u.test(fields[19] ?? '')) {+ birth = `proc:${fields[19]}`;+ exact = true;+ }+ } catch { /* macOS and other POSIX hosts use the validated census tuple below. */ }+ if (!birth) birth = `ps:${row.started}`;+ return { ...row, birth, exact };+ }++ /** Make a private Node preload that records only child identity and a one-way command digest. */+ function writeChildJournalPreload(directory) {+ const journalDirectory = join(directory, 'child-journal');+ mkdirSync(journalDirectory, { mode: 0o700 });+ const overflowPath = join(journalDirectory, 'overflow');+ const source = `+ import diagnostics from 'node:diagnostics_channel';+ import { closeSync, openSync, statSync, writeSync, writeFileSync } from 'node:fs';+ import { join } from 'node:path';+ import { createHash, randomUUID } from 'node:crypto';+ const directory = ${JSON.stringify(journalDirectory)};+ const overflowPath = ${JSON.stringify(overflowPath)};+ const instance = randomUUID();+ process.env.PULLBOARD_RUNNER_INSTANCE = instance;+ const file = join(directory, 'children-' + process.pid + '.jsonl');+ const fd = openSync(file, 'a', 0o600);+ let bytes = statSync(file).size;+ let overflow = false;+ const limit = 131072;+ function record(value) {+ if (overflow) return;+ try {+ const line = JSON.stringify(value) + '\\n';+ const size = Buffer.byteLength(line);+ if (bytes + size > limit) {+ overflow = true;+ try { writeFileSync(overflowPath, 'journal limit reached\\n', { flag: 'wx', mode: 0o600 }); } catch {}+ return;+ }+ writeSync(fd, line);+ bytes += size;+ } catch {+ try { writeFileSync(overflowPath, 'journal write failed\\n', { flag: 'wx', mode: 0o600 }); } catch {}+ overflow = true;+ }+ }+ record({ type: 'boot', pid: process.pid, ppid: process.ppid, instance });+ const channel = diagnostics.channel('child_process');+ const seen = new WeakSet();+ channel.subscribe(message => {+ try {+ const child = message?.process;+ if (!child || typeof child.once !== 'function' || seen.has(child)) return;+ seen.add(child);+ const writeReceipt = () => {+ if (!Number.isSafeInteger(child.pid) || child.pid < 1) return;+ const commandSha256 = createHash('sha256').update(JSON.stringify({ command: child.spawnfile ?? '', args: child.spawnargs ?? [] })).digest('hex');+ record({ type: 'spawn', pid: child.pid, ppid: process.pid, instance, commandSha256 });+ };+ if (Number.isSafeInteger(child.pid)) writeReceipt();+ else child.once('spawn', writeReceipt);+ } catch {+ try { writeFileSync(overflowPath, 'child receipt could not be recorded\\n', { flag: 'wx', mode: 0o600 }); } catch {}+ }+ });+ process.once('exit', () => { try { closeSync(fd); } catch {} });+ `;+ const preload = join(directory, 'child-spawn-preload.mjs');+ writeFileSync(preload, source, { mode: 0o600, flag: 'wx' });+ return { preload, journalDirectory, overflowPath, nodeOptions: `--import=${pathToFileURL(preload).href}` };+ }++ /** Track job descendants by PID plus OS start identity, joining spawn receipts with fresh census rows. */+ function createDescendantTracker(directory) {+ const initial = processCensus();+ if (!initial) throw new Error('initial process identity census failed');+ const baseline = new Map([...initial].map(([pid, row]) => [pid, processIdentity(row)]));+ const journal = writeChildJournalPreload(directory);+ const roots = new Set();+ const rootLaunchIdentities = new Map();+ const known = new Map();+ const retired = new Set();+ const eventsByChild = new Map();+ const pendingIdentities = new Map();+ const consumedEvents = new Set();+ let eventCount = 0;+ const detachedGroups = new Map();+ const offsets = new Map();+ const partial = new Map();+ const instancePids = new Map();+ const overflowPath = journal.overflowPath;+ let current = baseline;+ let uncertain = false;+ let censusFailure = false;+ let reason = '';+ let uncertainReason = '';+ let busy = false;+ let warned = false;+ let timer = null;+ let stoppingPromise = null;++ /** Keep permanent custody failures distinct from earlier, potentially resolved pending observations. */+ function markUncertain(message) {+ uncertain = true;+ uncertainReason ||= message;+ reason ||= message;+ }++ function readJournal() {+ if (existsSync(overflowPath)) { markUncertain('child spawn journal overflow or write failure'); }+ let total = 0;+ const files = readdirSync(journal.journalDirectory).filter(name => /^children-\d+\.jsonl$/u.test(name)).sort();+ // A full suite creates one journal per Node process; align this count with+ // the event and identity bounds while retaining the byte bounds below.+ if (files.length > 100_000) { markUncertain('child spawn journal file limit exceeded'); return; }+ for (const name of files) {+ const file = join(journal.journalDirectory, name);+ let size;+ try { size = statSync(file).size; } catch { markUncertain('child spawn journal could not be inspected'); continue; }+ total += size;+ if (!Number.isSafeInteger(size) || size > 131_072 || total > 8 * 1024 * 1024) {+ markUncertain('child spawn journal size limit exceeded'); continue;+ }+ const offset = offsets.get(name) ?? 0;+ if (size < offset) { markUncertain('child spawn journal changed unexpectedly'); continue; }+ if (size === offset) continue;+ const length = size - offset;+ const fd = openSync(file, 'r');+ let text;+ try {+ const bytes = Buffer.alloc(length);+ const read = readSync(fd, bytes, 0, length, offset);+ if (read !== length) { markUncertain('child spawn journal read was incomplete'); continue; }+ text = (partial.get(name) ?? '') + bytes.toString('utf8');+ } finally { closeSync(fd); }+ offsets.set(name, size);+ const lines = text.split('\n');+ partial.set(name, lines.pop() ?? '');+ for (const line of lines) {+ if (!line) continue;+ if (line.length > 4_096) { markUncertain('child spawn journal record is oversized'); continue; }+ let record;+ try { record = JSON.parse(line); } catch { markUncertain('child spawn journal record is invalid'); continue; }+ if (record.type === 'boot' && Number.isSafeInteger(record.pid) && record.pid > 0 && typeof record.instance === 'string') {+ instancePids.set(record.instance, record.pid);+ } else if (record.type === 'spawn' && Number.isSafeInteger(record.pid) && record.pid > 0+ && Number.isSafeInteger(record.ppid) && record.ppid > 0+ && typeof record.instance === 'string' && /^[a-f0-9]{64}$/u.test(record.commandSha256)) {+ const childEvents = eventsByChild.get(record.pid) ?? [];+ eventCount += 1;+ childEvents.push({ ...record, eventId: `${name}:${eventCount}` });+ eventsByChild.set(record.pid, childEvents);+ if (eventCount > 100_000) { markUncertain('child spawn journal event limit exceeded'); return; }+ } else { markUncertain('child spawn journal identity is invalid'); }+ }+ }+ }++ function observe() {+ if (busy) return current;+ busy = true;+ try {+ readJournal();+ const rawCensus = processCensus();+ if (!rawCensus) { censusFailure = true; return null; }+ censusFailure = false;+ const census = new Map([...rawCensus].map(([pid, row]) => [pid, processIdentity(row)]));+ current = census;+ // A process first seen without its recorded parent stays unowned while alive.+ // Once a later census proves that exact birth identity gone, retire its receipts+ // so a reused PID cannot be adopted from stale launch evidence.+ for (const [pid, pending] of pendingIdentities) {+ const row = current.get(pid);+ if (row?.birth === pending.birth && !/^Z/u.test(row.state)) continue;+ for (const eventId of pending.eventIds) consumedEvents.add(eventId);+ pendingIdentities.delete(pid);+ }+ for (const [pid, identity] of known) {+ const row = current.get(pid);+ if (!row || row.birth !== identity.birth) retired.add(`${pid}:${identity.birth}`);+ else if (retired.has(`${pid}:${identity.birth}`)) {+ markUncertain('a previously observed process identity reappeared');+ }+ }+ const ownedPids = new Set();+ for (const pid of roots) {+ const row = current.get(pid);+ if (!row) continue;+ const prior = known.get(pid);+ const launched = rootLaunchIdentities.get(pid);+ if (prior && prior.birth !== row.birth) continue;+ if (launched && launched.birth !== row.birth) continue;+ if (!launched && row.ppid !== process.pid) continue;+ if (!launched && row.pgid !== pid) continue;+ if (retired.has(`${pid}:${row.birth}`)) { markUncertain('a retired process identity reappeared'); continue; }+ if (!launched) rootLaunchIdentities.set(pid, row);+ known.set(pid, { ...row, commandSha256: prior?.commandSha256 ?? '', root: true, group: pid });+ ownedPids.add(pid);+ }++ for (const row of current.values()) {+ if (/^Z/u.test(row.state)) continue;+ for (const event of eventsByChild.get(row.pid) ?? []) {+ if (consumedEvents.has(event.eventId)) continue;+ const parentPid = instancePids.get(event.instance);+ // A preload instance exists only in the private job environment. The receipt+ // binds its child to that exact process instance even after the parent exits.+ if (!parentPid || parentPid !== event.ppid) continue;+ const prior = known.get(row.pid);+ if (retired.has(`${row.pid}:${row.birth}`)) { markUncertain('a retired process identity reappeared'); continue; }+ if (prior && prior.birth === row.birth) { consumedEvents.add(event.eventId); ownedPids.add(row.pid); continue; }+ if (!prior && baseline.get(row.pid)?.birth === row.birth) { consumedEvents.add(event.eventId); continue; }+ // A spawn receipt must be observed while its exact parent instance still owns it.+ // A same-numbered PID first seen after reparenting is ambiguous and never adopted.+ if (row.ppid !== event.ppid) {+ const pending = pendingIdentities.get(row.pid);+ if (!pending || pending.birth !== row.birth) pendingIdentities.set(row.pid, { birth: row.birth, eventIds: new Set() });+ pendingIdentities.get(row.pid).eventIds.add(event.eventId);+ consumedEvents.add(event.eventId);+ reason ||= 'spawned process was first observed after reparenting';+ continue;+ }+ if (!ownedPids.has(event.ppid)) {+ pendingIdentities.set(row.pid, { birth: row.birth, eventIds: new Set([event.eventId]) });+ consumedEvents.add(event.eventId);+ reason ||= 'spawn receipt parent has not been independently identified';+ continue;+ }+ const parent = known.get(event.ppid);+ const inheritedGroup = parent?.group ?? [...roots].find(rootPid => known.get(rootPid)?.group === row.pgid);+ const group = row.pgid === row.pid ? row.pid : inheritedGroup;+ if (group === undefined) {+ pendingIdentities.set(row.pid, { birth: row.birth, eventIds: new Set([event.eventId]) });+ consumedEvents.add(event.eventId);+ reason ||= 'spawned process group has no owned parent';+ continue;+ }+ if (row.pgid === row.pid) detachedGroups.set(row.pid, row.birth);+ known.set(row.pid, { ...row, commandSha256: event.commandSha256, root: false, group });+ consumedEvents.add(event.eventId);+ pendingIdentities.delete(row.pid);+ ownedPids.add(row.pid);+ }+ }++ // Process ancestry captures non-Node children; journal receipts retain ownership after reparenting.+ let changed = true;+ while (changed) {+ changed = false;+ for (const row of current.values()) {+ if (!ownedPids.has(row.ppid)) continue;+ const prior = known.get(row.pid);+ if (retired.has(`${row.pid}:${row.birth}`)) { markUncertain('a retired process identity reappeared'); continue; }+ if (prior && prior.birth === row.birth) { ownedPids.add(row.pid); continue; }+ if (!prior && baseline.get(row.pid)?.birth === row.birth) continue;+ const parent = known.get(row.ppid);+ const group = row.pgid === row.pid ? row.pid : parent?.group;+ if (group === undefined) {+ pendingIdentities.set(row.pid, { birth: row.birth, eventIds: new Set() });+ reason ||= 'descendant process group has no owned parent';+ continue;+ }+ if (row.pgid === row.pid) detachedGroups.set(row.pid, row.birth);+ known.set(row.pid, { ...row, commandSha256: '', root: false, group });+ pendingIdentities.delete(row.pid);+ ownedPids.add(row.pid); changed = true;+ }+ }+ // Detached children establish a private process group; census every member even+ // after the original launcher is reparented or exits.+ for (const row of current.values()) {+ if (/^Z/u.test(row.state)) continue;+ const leaderStarted = detachedGroups.get(row.pgid);+ if (!leaderStarted) continue;+ const leader = current.get(row.pgid);+ if (leader && leader.birth !== leaderStarted) {+ markUncertain('detached process group identity was reused');+ continue;+ }+ const prior = known.get(row.pid);+ if (retired.has(`${row.pid}:${row.birth}`)) { markUncertain('a retired process identity reappeared'); continue; }+ if (prior && prior.birth === row.birth) { ownedPids.add(row.pid); continue; }+ if (!prior && baseline.get(row.pid)?.birth === row.birth) continue;+ if ((!prior || prior.birth !== row.birth) && !ownedPids.has(row.ppid)) {+ pendingIdentities.set(row.pid, { birth: row.birth, eventIds: new Set() });+ reason ||= 'detached process group contains an unidentified member';+ continue;+ }+ known.set(row.pid, { ...row, commandSha256: '', root: false, group: row.pgid });+ ownedPids.add(row.pid);+ }+ // A recorded PGID does not prove an unseen member belongs to this job. Keep+ // the lease fail-closed when a root group contains a process lacking identity evidence.+ for (const rootPid of roots) {+ for (const row of current.values()) {+ if (row.pgid !== rootPid || /^Z/u.test(row.state)) continue;+ const identity = known.get(row.pid);+ if (identity?.birth === row.birth) continue;+ if (baseline.get(row.pid)?.birth === row.birth) continue;+ pendingIdentities.set(row.pid, { birth: row.birth, eventIds: new Set() });+ reason ||= 'owned process group contains an unidentified member';+ }+ }+ if (known.size > 100_000) { markUncertain('owned process identity limit exceeded'); }+ // Refresh live PGID/start data only when the PID still has the same start identity.+ for (const pid of ownedPids) {+ const row = current.get(pid);+ const prior = known.get(pid);+ if (row && prior?.birth === row.birth) Object.assign(prior, row);+ }+ return current;+ } catch {+ censusFailure = true; return null;+ } finally { busy = false; }+ }++ function registerRoot(pid) {+ if (!Number.isSafeInteger(pid) || pid < 1) return;+ roots.add(pid);+ // Bind the spawned leader while its actual parent is still this worker; later+ // group membership alone is never sufficient to adopt an unknown process.+ const census = processCensus();+ const row = census?.get(pid);+ if (row && row.ppid === process.pid && row.pgid === pid) rootLaunchIdentities.set(pid, processIdentity(row));+ }++ function liveDescendants() {+ const active = [];+ for (const [pid, identity] of known) {+ if (identity.root) continue;+ const row = current.get(pid);+ if (row && row.birth === identity.birth && !retired.has(`${pid}:${identity.birth}`) && !/^Z/u.test(row.state)) active.push({ ...identity });+ }+ return active;+ }++ function signalOwnedGroup(pgid, signal) {+ const census = observe();+ reportCleanupTimeout();+ if (!census || censusFailure) return null;+ // A journal error does not revoke known ownership, but an unidentified live+ // member prevents signaling the whole group until its identity is resolved.+ if ([...pendingIdentities].some(([pid, identity]) => {+ const row = current.get(pid);+ return row?.pgid === pgid && row.birth === identity.birth && !/^Z/u.test(row.state);+ })) return null;+ const ownedMember = [...known].some(([pid, identity]) => {+ const row = current.get(pid);+ return row && row.pgid === pgid && row.birth === identity.birth && !/^Z/u.test(row.state);+ });+ if (!ownedMember) return false;+ try { process.kill(-pgid, signal); }+ catch (error) { if (error.code === 'ESRCH') return false; throw error; }+ return true;+ }++ async function stopDescendantsLoop() {+ // Retry through ambiguous censuses rather than releasing the host lease on an unproven drain.+ for (;;) {+ const census = observe();+ reportCleanupTimeout();+ if (!census) {+ if (!warned) { process.stderr.write(`PULLBOARD_RUNNER_CLEANUP_UNVERIFIED ${workerId} ${reason}\n`); warned = true; }+ await new Promise(resolvePause => setTimeout(resolvePause, 1_000));+ continue;+ }+ if (censusFailure) { await new Promise(resolvePause => setTimeout(resolvePause, 250)); continue; }+ const live = liveDescendants();+ if (!live.length && !pendingIdentities.size && (!uncertain || cleanupTimedOut)) return;+ if ((pendingIdentities.size || uncertain) && !warned) {+ process.stderr.write(`PULLBOARD_RUNNER_CLEANUP_UNVERIFIED ${workerId} ${reason || 'unresolved process identity remains live'}\n`);+ warned = true;+ }+ if (!live.length) { await new Promise(resolvePause => setTimeout(resolvePause, 250)); continue; }+ // Signal each confirmed owned process group once; use PID signals only with exact kernel identity.+ const signaledGroups = new Set();+ for (const identity of live) {+ const row = current.get(identity.pid);+ if (!row || row.birth !== identity.birth || retired.has(`${identity.pid}:${identity.birth}`) || /^Z/u.test(row.state)) continue;+ const ownedGroup = identity.group;+ if (Number.isSafeInteger(ownedGroup) && row.pgid === ownedGroup && !signaledGroups.has(ownedGroup)) {+ const result = signalOwnedGroup(ownedGroup, 'SIGTERM');+ if (result === null) { censusFailure = true; break; }+ if (result) signaledGroups.add(ownedGroup);+ continue;+ }+ if (!identity.exact) { markUncertain('descendant lacks a safe process-group identity'); break; }+ try { process.kill(identity.pid, 'SIGTERM'); }+ catch (error) { if (error.code !== 'ESRCH') { markUncertain('owned descendant could not be stopped safely'); } }+ }+ const deadline = Date.now() + 2_000;+ while (Date.now() < deadline) {+ await new Promise(resolvePause => setTimeout(resolvePause, 50));+ if (!observe()) break;+ if (!liveDescendants().length) break;+ }+ if (!current || !liveDescendants().length) continue;+ const killedGroups = new Set();+ for (const identity of liveDescendants()) {+ const row = current.get(identity.pid);+ if (!row || row.birth !== identity.birth || retired.has(`${identity.pid}:${identity.birth}`) || /^Z/u.test(row.state)) continue;+ const ownedGroup = identity.group;+ if (Number.isSafeInteger(ownedGroup) && row.pgid === ownedGroup && !killedGroups.has(ownedGroup)) {+ const result = signalOwnedGroup(ownedGroup, 'SIGKILL');+ if (result === null) { censusFailure = true; break; }+ if (result) killedGroups.add(ownedGroup);+ continue;+ }+ if (!identity.exact) { markUncertain('descendant lacks a safe process-group identity'); break; }+ try { process.kill(identity.pid, 'SIGKILL'); }+ catch (error) { if (error.code !== 'ESRCH') { markUncertain('owned descendant could not be killed safely'); } }+ }+ await new Promise(resolvePause => setTimeout(resolvePause, 100));+ }+ }++ function stopDescendants() {+ if (!stoppingPromise) {+ stoppingPromise = stopDescendantsLoop().finally(() => { stoppingPromise = null; });+ }+ return stoppingPromise;+ }++ async function verifyAfterGroups() {+ for (;;) {+ const census = observe();+ reportCleanupTimeout();+ if (census && (!uncertain || cleanupTimedOut) && !censusFailure) {+ const liveRoots = [...roots].some(pid => {+ const row = current.get(pid);+ const knownRoot = known.get(pid);+ return row && knownRoot?.birth === row.birth && !/^Z/u.test(row.state);+ });+ if (!liveRoots && !liveDescendants().length && !pendingIdentities.size) return;+ }+ if (!warned) { process.stderr.write(`PULLBOARD_RUNNER_CLEANUP_UNVERIFIED ${workerId} ${reason || 'owned process identity remains live'}\n`); warned = true; }+ await new Promise(resolvePause => setTimeout(resolvePause, 1_000));+ }+ }++ timer = setInterval(() => { if (!busy) observe(); }, 250);+ timer.unref();+ return {+ nodeOptions: journal.nodeOptions,+ /** Describe the last observed cleanup state without treating it as a fresh ownership proof. */+ cleanupState() {+ return { reason: uncertainReason || reason, uncertain, censusFailure, knownCount: known.size,+ pending: [...pendingIdentities].slice(0, 16).map(([pid, identity]) => ({ pid, birth: identity.birth })),+ live: liveDescendants().slice(0, 16).map(({ pid, birth, group }) => ({ pid, birth, group })) };+ },+ registerRoot,+ stopDescendants,+ /** Revalidate a process group immediately before signaling; null means census ambiguity. */+ signalOwnedGroup,+ verifyAfterGroups,+ stopMonitoring() { clearInterval(timer); },+ };+ }++ /** Stop and fully drain one owned process group before its gate lease can be released. */+ function drainOwned(record, terminate = false, tracker = activeDescendantTracker) {+ if (!record) return Promise.resolve();+ record.drainPromise ??= (async () => {+ if (terminate) await stopOwnedGroup(record.pid, record.closed, tracker);+ else {+ await record.closed;+ await stopOwnedGroup(record.pid, record.closed, tracker);+ }+ ownedChildren.delete(record.child);+ })();+ return record.drainPromise;+ }++ /** Install disconnect custody before receiving the pack or starting any setup subprocess. */+ function installSignalCustody() {+ if (signalCustodyInstalled) return;+ signalCustodyInstalled = true;+ const disconnected = () => {+ if (transportLost) return;+ transportLost = true;+ beginCleanup();+ rejectPendingFrame?.(new Error('runner transport was lost'));+ clearInterval(heartbeatTimer);+ const active = [...ownedChildren.values()];+ transportDrain = (async () => {+ await activeDescendantTracker?.stopDescendants();+ await Promise.all(active.map(record => drainOwned(record, true)));+ await activeDescendantTracker?.verifyAfterGroups();+ })();+ transportDrain.catch(() => {});+ };+ transportDrop = disconnected;+ process.on('SIGHUP', disconnected);+ process.on('SIGTERM', disconnected);+ process.stdin.on('error', disconnected);+ process.stdout.on('error', disconnected);+ process.stderr.on('error', disconnected);+ let heartbeatPending = false;+ heartbeatTimer = setInterval(() => {+ if (transportLost || heartbeatPending) return;+ heartbeatPending = true;+ process.stderr.write(`PULLBOARD_RUNNER_HEARTBEAT ${workerId}\n`, error => {+ heartbeatPending = false;+ if (error) disconnected();+ });+ }, 5_000);+ heartbeatTimer.unref();+ }++ /** Stop queue/setup work promptly after the controller's transport disappears. */+ function assertTransportLive() {+ if (transportLost) throw new Error('runner transport was lost');+ }++ /** Wait for every owned group, terminating any still present after its leader exits. */+ async function drainAllOwned() {+ await Promise.all([...ownedChildren.values()].map(record => drainOwned(record, transportLost)));+ if (transportDrain) await transportDrain;+ }++ /** Select only the explicit pool while acquiring its lease; restore the worker environment afterward. */+ async function acquireResourceApi(api, options, machineHomePath) {+ const previous = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_MACHINE_HOME = machineHomePath;+ try { return await api.takeResource(options); }+ finally {+ if (previous === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previous;+ }+ }++ /** Invoke one bounded Git command in an owned group and return its exact stdout. */+ async function git(root, args, env, input) {+ const owned = spawnOwned('git', args, { cwd: root, env, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'] });+ const output = [];+ let bytes = 0;+ let overflow = false;+ let inputError;+ if (input !== undefined) {+ owned.child.stdin.on('error', error => { inputError ??= error; });+ owned.child.stdin.end(input);+ }+ owned.child.stdout.on('data', chunk => {+ bytes += chunk.length;+ if (bytes > 128 * 1024 * 1024) {+ if (!overflow) { overflow = true; drainOwned(owned, true).catch(() => {}); }+ } else if (!overflow) output.push(chunk);+ });+ const result = await owned.closed;+ await drainOwned(owned);+ if (overflow || inputError || result.error || result.code !== 0 || result.signal) throw new Error('source checkout could not be verified');+ return Buffer.concat(output).toString('utf8').trim();+ }++ /** Receive the negotiated history pack after the worker announces the cache's candidate tips. */+ async function receivePack(packFile) {+ await pipeline(process.stdin, createWriteStream(packFile, { mode: 0o600, flags: 'wx' }));+ }++ /** Receive only missing ancestry, validate the full graph, then copy the exact commit into a clean job repository. */+ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {+ const repositories = join(runnerRoot, 'repos');+ mkdirSync(repositories, { recursive: true, mode: 0o700 });+ chmodSync(repositories, 0o700);+ const cache = join(repositories, `${spec.repoId}.git`);+ const cacheLease = await acquireResourceApi(api, {+ name: `repo-${spec.repoId}`, capacity: 1, scope: 'machine', root: runnerRoot,+ repo: runnerRoot, agent: `pullboard-ssh-cache-${spec.id}`, kind: 'source-cache',+ onWait: () => assertTransportLive(),+ }, join(runnerRoot, 'cache', 'resource-pool'));+ const deliveryRefs = [];+ try {+ if (!existsSync(cache)) {+ const build = mkdtempSync(join(repositories, `.repo-${spec.repoId}-`));+ const staged = join(build, 'cache.git');+ try {+ const initialize = async () => {+ const initialized = spawnOwned('git', ['init', '--bare', `--object-format=${spec.commit.length === 64 ? 'sha256' : 'sha1'}`, staged], {+ cwd: build, env, stdio: ['ignore', 'ignore', 'ignore'],+ });+ const result = await initialized.closed;+ await drainOwned(initialized);+ if (result.error || result.code !== 0 || result.signal) throw new Error('source history cache could not be initialized');+ };+ await initialize();+ if (spec.origin && spec.originBase) {+ let seeded = false;+ try {+ const fetch = spawnOwned('git', ['-c', 'protocol.version=2', 'fetch', '--no-tags', '--no-recurse-submodules', spec.origin, spec.originBase], {+ cwd: staged, env, stdio: ['ignore', 'ignore', 'ignore'],+ });+ const result = await fetch.closed;+ await drainOwned(fetch);+ seeded = !result.error && result.code === 0 && !result.signal+ && await git(staged, ['cat-file', '-t', spec.originBase], env) === 'commit'+ && Number(await git(staged, ['rev-list', '--count', spec.originBase], env)) > 0+ && !existsSync(join(staged, 'shallow'));+ if (seeded) await git(staged, ['update-ref', `refs/pullboard/published/${spec.originBase}`, spec.originBase], env);+ } catch { seeded = false; }+ if (!seeded) {+ rmSync(staged, { recursive: true, force: true });+ await initialize();+ }+ }+ renameSync(staged, cache);+ } finally { rmSync(build, { recursive: true, force: true }); }+ }+ if (await git(cache, ['rev-parse', '--is-bare-repository'], env) !== 'true'+ || await git(cache, ['rev-parse', '--show-object-format'], env) !== (spec.commit.length === 64 ? 'sha256' : 'sha1')+ || existsSync(join(cache, 'shallow')) || existsSync(join(cache, 'objects', 'info', 'alternates'))) {+ throw new Error('source history cache has an incompatible format');+ }+ const refLines = await git(cache, ['for-each-ref', '--format=%(refname) %(objectname)', 'refs/pullboard/candidates', 'refs/pullboard/published'], env);+ const tips = [];+ if (refLines) for (const line of refLines.split(/\r?\n/u)) {+ const split = /^(refs\/pullboard\/(?:candidates|published)\/.+) ([a-f0-9]{40,64})$/u.exec(line);+ if (!split || split[2].length !== spec.commit.length) {+ throw new Error('source history cache contains an invalid candidate ref');+ }+ if (split[1].slice(split[1].lastIndexOf('/') + 1) !== split[2]) {+ throw new Error('source history cache contains an invalid candidate ref');+ }+ if (await git(cache, ['cat-file', '-t', split[2]], env) !== 'commit') {+ throw new Error('source history cache contains a non-commit tip');+ }+ tips.push(split[2]);+ }+ const uniqueTips = [...new Set(tips)];+ if (uniqueTips.length > 1_024) throw new Error('source history cache needs maintenance');+ const requestedTagObjects = [...new Set(spec.tags.flatMap(tag => tag.chain))];+ const knownTagObjects = [];+ if (requestedTagObjects.length) {+ const checks = await git(cache, ['cat-file', '--batch-check'], env, `${requestedTagObjects.join('\n')}\n`);+ const lines = checks.split(/\r?\n/u).filter(Boolean);+ if (lines.length !== requestedTagObjects.length) throw new Error('source tag inventory is incomplete');+ for (let index = 0; index < lines.length; index++) {+ const match = /^([a-f0-9]{40,64}) tag \d+$/u.exec(lines[index]);+ if (match && match[1] === requestedTagObjects[index]) knownTagObjects.push(match[1]);+ else if (!new RegExp(`^${requestedTagObjects[index]} missing$`, 'u').test(lines[index])) {+ throw new Error('source tag inventory contains an invalid object');+ }+ }+ }+ await new Promise((resolveWrite, rejectWrite) => process.stderr.write(+ `PULLBOARD_RUNNER_NEED ${spec.id} ${Buffer.from(JSON.stringify({ tips: uniqueTips, tagObjects: knownTagObjects })).toString('base64')}\n`,+ error => error ? rejectWrite(error) : resolveWrite()));+ await receivePack(packFile);++ const priorIndexes = new Set(readdirSync(join(cache, 'objects', 'pack')).filter(name => name.endsWith('.idx')));+ if (statSync(packFile).size < 12 + spec.commit.length / 2) throw new Error('source history pack is incomplete');+ {+ const index = spawnOwned('git', ['index-pack', '--stdin'], { cwd: cache, env, stdio: ['pipe', 'ignore', 'ignore'] });+ try {+ await pipeline(createReadStream(packFile), index.child.stdin);+ const result = await index.closed;+ await drainOwned(index);+ if (result.error || result.code !== 0 || result.signal) throw new Error('source history pack could not be indexed');+ } catch (error) { await drainOwned(index, true); throw error; }+ }+ const objectType = await git(cache, ['cat-file', '-t', spec.commit], env);+ if (objectType !== 'commit' || await git(cache, ['rev-parse', `${spec.commit}^{tree}`], env) !== spec.tree) {+ throw new Error('source history does not match the requested commit and tree');+ }+ const historyCount = Number(await git(cache, ['rev-list', '--count', spec.commit], env));+ if (!Number.isSafeInteger(historyCount) || historyCount < 1) throw new Error('source history is incomplete');+ if (spec.originBase) await git(cache, ['merge-base', '--is-ancestor', spec.originBase, spec.commit], env);+ const closure = new Set((await git(cache, ['rev-list', '--objects', spec.commit], env)).split(/\r?\n/u)+ .map(line => line.match(/^([a-f0-9]{40,64})(?:\s|$)/u)?.[1]).filter(Boolean));+ closure.add(spec.commit);+ const tagObjects = new Set(spec.tags.flatMap(tag => tag.chain));+ const packDirectory = join(cache, 'objects', 'pack');+ const newIndexes = readdirSync(packDirectory).filter(name => name.endsWith('.idx') && !priorIndexes.has(name));+ const received = new Set();+ for (const indexName of newIndexes) {+ for (const line of (await git(cache, ['verify-pack', '-v', join(packDirectory, indexName)], env)).split(/\r?\n/u)) {+ const object = line.match(/^([a-f0-9]{40,64})\s+(?:commit|tree|blob|tag)\s/u)?.[1];+ if (object) received.add(object);+ }+ }+ if ([...received].some(object => !closure.has(object) && !tagObjects.has(object))) {+ throw new Error('source history pack contains missing or unrelated objects');+ }+ for (const tag of spec.tags) {+ await git(cache, ['check-ref-format', tag.name], env);+ if (tag.chain.length) {+ let target = tag.object;+ for (let index = 0; index < tag.chain.length; index++) {+ const object = tag.chain[index];+ if (target !== object || (!received.has(object) && !knownTagObjects.includes(object))+ || await git(cache, ['cat-file', '-t', object], env) !== 'tag') {+ throw new Error('source tag chain is incomplete or unrelated');+ }+ const body = await git(cache, ['cat-file', '-p', object], env);+ const header = body.split(/\r?\n\r?\n/u, 1)[0];+ const next = /^object ([a-f0-9]{40,64})$/mu.exec(header)?.[1];+ const type = /^type (commit|tag|tree|blob)$/mu.exec(header)?.[1];+ const expectedNext = tag.chain[index + 1] ?? tag.peeledCommit;+ const expectedType = index + 1 < tag.chain.length ? 'tag' : 'commit';+ if (!next || next !== expectedNext || type !== expectedType || next.length !== spec.commit.length) {+ throw new Error('source tag chain failed validation');+ }+ target = next;+ }+ } else if (await git(cache, ['cat-file', '-t', tag.object], env) !== 'commit'+ || tag.object !== tag.peeledCommit || !closure.has(tag.object)) {+ throw new Error('lightweight source tag does not point into candidate history');+ }+ await git(cache, ['merge-base', '--is-ancestor', tag.peeledCommit, spec.commit], env);+ }+ await git(cache, ['update-ref', `refs/pullboard/candidates/${spec.commit}`, spec.commit], env);+ await git(root, ['init', '-q', `--object-format=${spec.commit.length === 64 ? 'sha256' : 'sha1'}`], env);+ await git(root, ['-c', 'protocol.file.allow=always', 'fetch', '--no-tags', cache, `refs/pullboard/candidates/${spec.commit}`], env);+ await git(root, ['checkout', '--detach', 'FETCH_HEAD'], env);+ for (let index = 0; index < spec.tags.length; index++) {+ const tag = spec.tags[index];+ const deliveryRef = `refs/pullboard/tag-delivery/${spec.id}/${index}`;+ await git(cache, ['update-ref', deliveryRef, tag.object], env);+ deliveryRefs.push(deliveryRef);+ await git(root, ['-c', 'protocol.file.allow=always', 'fetch', '--no-tags', cache, `${deliveryRef}:${tag.name}`], env);+ if (await git(root, ['rev-parse', `${tag.name}^{}`], env) !== tag.peeledCommit) {+ throw new Error('isolated source checkout has an invalid tag ref');+ }+ }+ if (await git(root, ['rev-parse', 'HEAD'], env) !== spec.commit+ || await git(root, ['rev-parse', 'HEAD^{tree}'], env) !== spec.tree+ || await git(root, ['rev-parse', '--is-shallow-repository'], env) !== 'false'+ || existsSync(join(root, '.git', 'objects', 'info', 'alternates'))) {+ throw new Error('isolated source checkout does not contain the complete requested history');+ }+ } finally {+ for (const ref of deliveryRefs) {+ try { await git(cache, ['update-ref', '-d', ref], env); } catch { /* Leave cache refs only if Git refuses safe removal. */ }+ }+ try { cacheLease.release(); } catch { /* Retaining the lease on cleanup error is safer than speculative deletion. */ }+ }+ rmSync(packFile, { force: true });+ }++ /** Install committed npm dependencies through an isolated content-addressed cache, refusing unknown lock managers. */+ async function installDependencies(root, runnerRoot, env, tracker) {+ const packageFile = join(root, 'package.json');+ if (!existsSync(packageFile)) return;+ const packageText = readFileSync(packageFile, 'utf8');+ const manifest = JSON.parse(packageText);+ const lockFile = join(root, 'package-lock.json');+ if (existsSync(join(root, 'pnpm-lock.yaml')) || existsSync(join(root, 'yarn.lock'))) {+ throw new Error('dependency setup requires a single committed npm lock manager');+ }+ if (!existsSync(lockFile)) {+ if (Object.keys(manifest.dependencies ?? {}).length || Object.keys(manifest.devDependencies ?? {}).length) {+ throw new Error('dependency setup requires a committed npm package-lock.json');+ }+ return;+ }+ const cacheRoot = join(runnerRoot, 'cache', 'npm');+ const contentCache = join(cacheRoot, 'content');+ mkdirSync(contentCache, { recursive: true, mode: 0o700 });+ chmodSync(cacheRoot, 0o700); chmodSync(contentCache, 0o700);+ // node_modules is job-local because package lifecycle scripts may create sibling artifacts.+ // Reuse only npm's content-addressed download cache, never a prior job's installed tree.+ rmSync(join(root, 'node_modules'), { recursive: true, force: true });+ const npm = spawnOwned('npm', ['ci', '--cache', contentCache], {+ cwd: root, env, stdio: ['ignore', 'ignore', 'ignore'],+ });+ const result = await npm.closed;+ await tracker.stopDescendants();+ await drainOwned(npm);+ if (result.error || result.code !== 0 || result.signal) throw new Error('committed npm dependencies could not be installed');+ }++ /** Wait until all bytes written to stdout have passed through the stream before publishing a receipt. */+ async function flushStdout() {+ if (process.stdout.writableNeedDrain) await once(process.stdout, 'drain');+ await new Promise((resolveFlush, rejectFlush) => process.stdout.write('', error => error ? rejectFlush(error) : resolveFlush()));+ }++ /** Emit command output through one stream while computing the receipt's byte-exact digest. */+ function outputSink() {+ const hash = createHash('sha256');+ const wallStart = Date.now();+ let pipeFailed = false;+ const write = part => {+ const bytes = Buffer.isBuffer(part) ? part : Buffer.from(part);+ hash.update(bytes);+ if (!process.stdout.write(bytes)) return once(process.stdout, 'drain');+ return Promise.resolve();+ };+ return { hash, write, get pipeFailed() { return pipeFailed; }, set pipeFailed(value) { pipeFailed = value; }, wallStart };+ }++ /** Stop only the detached command process group owned by this worker, then await its close event. */+ async function stopOwnedGroup(pid, closed, tracker) {+ if (!pid) return;+ const signal = async type => {+ for (;;) {+ const sent = tracker?.signalOwnedGroup(pid, type) ?? false;+ if (sent === true || sent === false) return sent;+ await new Promise(resolvePause => setTimeout(resolvePause, 250));+ }+ };+ await signal('SIGTERM');+ // Give the whole owned group two seconds to handle TERM, even if its leader exits first.+ const graceUntil = Date.now() + 2_000;+ while (Date.now() < graceUntil) {+ const sent = await signal('SIGTERM');+ if (!sent) break;+ await new Promise(resolvePause => setTimeout(resolvePause, 25));+ }+ for (;;) {+ const sent = await signal('SIGKILL');+ if (!sent) break;+ await new Promise(resolvePause => setTimeout(resolvePause, 50));+ }+ await closed;+ }++ /** Run the exact requested command in its isolated checkout, retaining raw output and real test exit status. */+ async function runCommand(spec, root, env, sink, tracker) {+ let shell = '/bin/sh';+ let args = ['-c', spec.command];+ if (spec.pipefail) {+ const probe = spawnSync(shell, ['-c', 'set -o pipefail'], { env, stdio: 'ignore' });+ if (probe.status === 0) args = ['-c', `set -o pipefail\n${spec.command}`];+ else if (existsSync('/bin/bash')) { shell = '/bin/bash'; args = ['-o', 'pipefail', '-c', spec.command]; }+ else if (/(?:^|[^|])\|(?:[^|]|$)/u.test(spec.command)) throw new Error('runner shell cannot enforce pipefail');+ }+ const owned = spawnOwned(shell, args, { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });+ const child = owned.child;+ // A surviving descendant can keep stdio open after the command leader exits.+ // Start the budget at exit rather than waiting for those pipes to close.+ child.once('exit', beginCleanup);+ let outputError = null;+ let writes = Promise.resolve();+ const closed = owned.closed;+ const onDrop = () => { sink.pipeFailed = true; transportDrop(); };+ const forward = stream => stream.on('data', part => {+ stream.pause();+ if (!outputError) writes = writes.then(() => sink.write(part)).then(() => stream.resume()).catch(error => { outputError = error; onDrop(); });+ });+ forward(child.stdout); forward(child.stderr);+ const result = await closed;+ beginCleanup();+ cleanupStage = 'command output';+ await writes;+ cleanupStage = 'command descendants';+ await tracker.stopDescendants();+ cleanupStage = 'command process group';+ await drainOwned(owned);+ if (transportDrain) await transportDrain;+ if (outputError) throw outputError;+ if (sink.pipeFailed) return { code: 1, signal: result.signal ?? 'SIGHUP' };+ if (result.error) throw result.error;+ return { code: Number.isInteger(result.code) ? result.code : 1, signal: result.signal ?? null };+ }++ /** Send the single nonce-bound result line after the complete merged output has drained. */+ async function receipt(spec, fields, sink) {+ await flushStdout();+ const body = { id: spec.id, commit: spec.commit, tree: spec.tree, code: fields.code, signal: fields.signal,+ runtimeSha256: spec.runtime.sha256, toolingSha256: spec.tooling.sha256, root: fields.root ?? '', outputSha256: sink.hash.digest('hex'), wallMs: Math.max(0, Date.now() - sink.wallStart) };+ const encoded = Buffer.from(JSON.stringify(body)).toString('base64');+ await new Promise((resolveWrite, rejectWrite) => process.stderr.write(`${RECEIPT} ${spec.id} ${encoded}\n`, error => error ? rejectWrite(error) : resolveWrite()));+ }++ /** Turn an internal setup failure into a fixed safe line rather than disclosing paths or runner state. */+ function safeSetupMessage(error) {+ const message = String(error?.message ?? '');+ if (message.includes('npm') || message.includes('dependency')) return 'runner setup refused: committed dependencies are unavailable';+ if (message.includes('capacity') || message.includes('queue')) return 'runner setup refused: remote capacity is unavailable';+ return 'runner setup refused: source checkout could not be prepared';+ }++ /** Execute one remote job end to end; stdout is reserved for raw command bytes and stderr for one receipt. */+ async function main() {+ installSignalCustody();+ const spec = await readSpec();+ workerId = spec.id;+ if (spec.browserRequired && spec.browser < 1) throw new Error('browser capacity is not configured');+ const sink = outputSink();+ let api;+ let lease = null;+ let tracker = null;+ let runDirectory;+ let final = { code: 1, signal: null, root: '' };+ try {+ const runnerHome = isAbsolute(process.env.HOME || '') ? process.env.HOME : userInfo().homedir;+ const runnerRoot = spec.root ?? join(runnerHome, '.pullboard-runner');+ mkdirSync(runnerRoot, { recursive: true, mode: 0o700 });+ chmodSync(runnerRoot, 0o700);+ const configuredMachineHome = process.env.PULLBOARD_MACHINE_HOME;+ if (configuredMachineHome !== undefined && !isAbsolute(configuredMachineHome)) throw new Error('machine home is invalid');+ const machineHomePath = configuredMachineHome ?? join(runnerHome, '.pullboard');+ api = loadResourceApi(spec.runtime);+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;+ let resources;+ try {+ process.env.PULLBOARD_MACHINE_HOME = machineHomePath;+ resources = api.listResources({ scope: 'machine', root: runnerRoot });+ } finally {+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;+ }+ const gateCapacity = resources.find(resource => resource.name === 'gate')?.capacity ?? Math.min(spec.slots, 2);+ const base = join(runnerRoot, 'jobs');+ mkdirSync(base, { recursive: true, mode: 0o700 });+ chmodSync(base, 0o700);+ runDirectory = mkdtempSync(join(base, `${spec.id}-`));+ cleanupDirectory = runDirectory;+ const root = join(runDirectory, 'checkout');+ const privateHome = join(runDirectory, 'home');+ const temporary = join(runDirectory, 'tmp');+ mkdirSync(root, { mode: 0o700 }); mkdirSync(privateHome, { mode: 0o700 }); mkdirSync(temporary, { mode: 0o700 });+ writeFileSync(join(privateHome, 'npm-userconfig'), '', { mode: 0o600 });+ writeFileSync(join(privateHome, 'npm-globalconfig'), '', { mode: 0o600 });+ const packFile = join(runDirectory, 'source.pack');+ lease = await acquireResourceApi(api, {+ name: 'gate', capacity: gateCapacity, scope: 'machine', root: runnerRoot,+ repo: runnerRoot, agent: `pullboard-ssh-${spec.id}`,+ landing: spec.landing === true, itemCheck: spec.itemCheck === true,+ diagnostic: spec.diagnostic === true, browser: spec.browserRequired,+ item: spec.item ?? '', kind: spec.kind ?? 'remote-command',+ onWait: () => assertTransportLive(),+ }, machineHomePath);+ const canonicalMachineHome = machineHomePath;+ tracker = createDescendantTracker(runDirectory);+ cleanupDetails = tracker.cleanupState;+ activeDescendantTracker = tracker;+ const env = scopedEnvironment(privateHome, temporary, canonicalMachineHome, lease, api, tracker.nodeOptions);+ await checkoutHistory(api, runnerRoot, root, packFile, spec, env);+ await installDependencies(root, runnerRoot, env, tracker);+ final = { ...(await runCommand(spec, root, { ...env, PULLBOARD_LANDING_RUN: spec.landing === true ? '1' : '0' }, sink, tracker)), root };+ } catch (error) {+ const message = safeSetupMessage(error);+ if (!transportLost) await sink.write(`${message}\n`);+ final = { code: 1, signal: transportLost ? 'SIGHUP' : null, error: message, root: '' };+ } finally {+ beginCleanup();+ cleanupStage = 'final descendants';+ if (tracker) await tracker.stopDescendants();+ cleanupStage = 'final process groups';+ await drainAllOwned();+ if (tracker) {+ cleanupStage = 'final verification';+ await tracker.verifyAfterGroups();+ tracker.stopMonitoring();+ activeDescendantTracker = null;+ }+ if (lease) {+ cleanupStage = 'lease release';+ try { lease.release(); } catch { /* Retaining a lease on cleanup error is safer than speculative deletion. */ }+ }+ cleanupStage = 'job files';+ if (runDirectory && !cleanupTimedOut) { try { rmSync(runDirectory, { recursive: true, force: true }); } catch {} }+ }+ if (transportLost || cleanupTimedOut) { clearTimeout(cleanupTimer); process.exitCode = 1; return; }+ cleanupStage = 'result receipt';+ await receipt(spec, final, sink);+ clearTimeout(cleanupTimer);+ process.exitCode = 0;+ }++ main().catch(() => { process.exitCode = 1; });diff --cc src/runners.jsindex 00000000,fb169328..ce184366mode 000000,100644..100644--- a/src/runners.js+++ b/src/runners.js@@@ -1,0 -1,526 +1,566 @@@+ /** 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';++ // Budget: 64 MiB bounds worst-case JSON bridge escaping below Node string limits.+ const MAX_OUTPUT_BYTES = 64 * 1024 ** 2;+ const MAX_BLOB_BYTES = 8 * 1024 ** 2;+ const MAX_HISTORY_TAGS = 1_024;+ const MAX_TAG_CHAIN = 8;+ const TOOL_ROOT = fileURLToPath(new URL('../', import.meta.url));+ const RUNTIME_NAMES = ['resources.js', 'git.js', 'machine-home.js', 'refused.js'];++ /** Validate an SSH destination as one argument, never a command or an SSH option. */+ export function validateRunner(value) {+ if (!value || typeof value.host !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.@:\[\]-]{0,254}$/u.test(value.host)+ || !Number.isSafeInteger(value.slots) || value.slots < 1+ || !Number.isSafeInteger(value.browser) || value.browser < 0 || value.browser > value.slots) {+ throw new Refused('BAD_RUNNER', 'use an SSH host or alias, positive --slots, and --browser from zero through slots');+ }+ for (const key of ['node', 'root']) {+ if (value[key] !== undefined && (typeof value[key] !== 'string' || /[\u0000-\u001f\u007f]/u.test(value[key])+ || !(value[key].startsWith('/') && value[key].length > 1 || key === 'node' && value[key] === 'node'))) {+ throw new Refused('BAD_RUNNER', `runner ${key} must be an absolute remote path${key === 'node' ? ' or node' : ''}`);+ }+ }+ return { host: value.host, slots: value.slots, browser: value.browser,+ ...(value.node ? { node: value.node } : {}), ...(value.root ? { root: value.root } : {}) };+ }++ /** Dirty or non-repository commands cannot claim to execute an exact committed source remotely. */+ export function runnerSource(root) {+ try {+ if (!isClean(root) || untracked(root).length) return null;+ return { commit: headCommit(root), tree: headTree(root) };+ } catch { return null; }+ }++ /** A missing authenticated completion receipt is a transport loss, never a passing test result. */+ export class RunnerDropped extends Error {+ constructor(host) {+ super(`runner ${host} disconnected before a complete result; the run returns to the queue`);+ this.name = 'RunnerDropped';+ this.host = host;+ }+ }++ /** Run a source-only Git read without inherited Git configuration, hooks or replacement objects. */+ function sourceGit(root, args, options = {}) {+ const result = spawnSync('git', ['--no-replace-objects', '-c', 'core.hooksPath=/dev/null', ...args], {+ cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: MAX_BLOB_BYTES, ...options,+ });+ if (result.status !== 0) throw new Refused('RUNNER_SOURCE', 'cannot read the exact committed source; check Git and retry the run');+ return result.stdout;+ }++ /** Scan every current blob and the commit message before any source bytes leave the controller. */+ function sourceObjects(root, source) {+ const records = sourceGit(root, ['ls-tree', '-r', '-z', '--full-tree', source.commit]).split('\0').filter(Boolean);+ // Protection is pinned to the admitted commit, never a concurrently edited working file.+ const configRecord = records.find(record => record.endsWith('\tpullboard.json'));+ const configObject = configRecord?.match(/^\d+ blob ([a-f0-9]{40,64})\t/u)?.[1];+ const config = configObject ? configFromSource(sourceGit(root, ['cat-file', 'blob', configObject])) : defaults();+ for (const record of records) {+ const match = /^(\d+) (\w+) ([a-f0-9]{40,64})\t([\s\S]+)$/u.exec(record);+ if (!match || match[2] !== 'blob') throw new Refused('RUNNER_SOURCE', 'runner source contains a submodule or unsupported object; keep this run local');+ const [, , , object, path] = match;+ if (blockedPaths([path], config.protect).length || /(?:^|\/)board\.sqlite(?:-(?:wal|shm))?$/u.test(path)) {+ throw new Refused('RUNNER_SECRET', 'committed runner source includes a blocked private file; remove it before remote execution');+ }+ const size = Number(sourceGit(root, ['cat-file', '-s', object]).trim());+ if (!Number.isSafeInteger(size) || size > MAX_BLOB_BYTES) {+ throw new Refused('RUNNER_SCAN_LIMIT', 'a committed blob exceeds the safe runner scan limit; keep the run local or reduce that file');+ }+ const text = sourceGit(root, ['cat-file', 'blob', object]);+ const findings = secretsIn(text.split(/\r?\n/u).map((line, index) => ({ path, line: index + 1, text: line })));+ if (findings.length) throw new Refused('RUNNER_SECRET', `source leak scan refused ${findings[0]}; remove the secret before remote execution`);+ }+ const commit = sourceGit(root, ['cat-file', 'commit', source.commit]);+ if (secretsIn(commit.split('\n').map((text, index) => ({ path: 'commit', line: index + 1, text }))).length) {+ throw new Refused('RUNNER_SECRET', 'the commit metadata contains a possible secret; keep this run local and correct the metadata');+ }+ return config.protect;+ }++ /** Reject blocked historical paths as well as current ones before an object pack crosses SSH. */+ function protectedHistoryPath(path, protect) {+ return blockedPaths([path], protect).length || /(?:^|\/)board\.sqlite(?:-(?:wal|shm))?$/u.test(path);+ }++ /** Apply current protection rules to all selected historical names before any anonymous cache seed. */+ function protectHistory(root, source, protect) {+ const paths = [...new Set(sourceGit(root, ['log', '--format=', '--name-only', '-z', '--no-renames', '--root', '-m', '--full-history', source.commit])+ .split('\0').filter(Boolean))];+ if (paths.some(path => protectedHistoryPath(path, protect))) {+ throw new Refused('RUNNER_SECRET', 'selected history includes a blocked private path; keep this run local or remove that private history');+ }+ }++ /** Select a locally known published ancestor, never an anonymous origin's unchecked latest tip. */+ function originAncestor(root, source) {+ const tip = sourceGit(root, ['for-each-ref', '--format=%(objectname)', 'refs/remotes/origin']).split('\n')+ .find(value => /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(value));+ if (!tip) return undefined;+ const result = spawnSync('git', ['--no-replace-objects', 'merge-base', source.commit, tip], {+ cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 4096,+ });+ const base = result.stdout?.trim();+ return result.status === 0 && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(base) ? base : undefined;+ }++ /** Select safe tags that point to commits in the exact candidate ancestry. */+ function candidateTags(root, source) {+ const rows = sourceGit(root, ['for-each-ref', '--format=%(refname)%00%(objectname)%00%(objecttype)', 'refs/tags'])+ .split('\n').filter(Boolean);+ if (rows.length > MAX_HISTORY_TAGS) throw new Refused('RUNNER_SCAN_LIMIT', 'too many local tags to transfer safely; keep this run local');+ const selected = [];+ // Budget: annotation scanning shares the 8 MiB object ceiling across all selected tag visits.+ let annotationBytes = 0;+ for (const row of rows) {+ const fields = row.split('\0');+ if (fields.length !== 3) throw new Refused('RUNNER_SOURCE', 'cannot read local tag refs safely; keep this run local');+ const [name, object, declaredType] = fields;+ if (!name.startsWith('refs/tags/') || name.length > 1_024 || /[\u0000-\u001f\u007f]/u.test(name)+ || !/^[a-f0-9]{40,64}$/u.test(object) || object.length !== source.commit.length) {+ throw new Refused('RUNNER_SECRET', 'a local tag ref failed the safe transfer check; keep this run local');+ }+ sourceGit(root, ['check-ref-format', name]);+ let type = sourceGit(root, ['cat-file', '-t', object]).trim();+ if (type !== declaredType) throw new Refused('RUNNER_SOURCE', 'a local tag ref changed while preparing the run; retry');+ const peeledCommit = sourceGit(root, ['rev-parse', `${name}^{}`]).trim();+ if (!/^[a-f0-9]{40,64}$/u.test(peeledCommit) || peeledCommit.length !== source.commit.length+ || sourceGit(root, ['cat-file', '-t', peeledCommit]).trim() !== 'commit') continue;+ const ancestor = spawnSync('git', ['--no-replace-objects', '-c', 'core.hooksPath=/dev/null', 'merge-base', '--is-ancestor', peeledCommit, source.commit], {+ cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 4096,+ });+ if (ancestor.status === 1) continue;+ if (ancestor.status !== 0) throw new Refused('RUNNER_SOURCE', 'cannot validate tag ancestry; keep this run local');+ if (secretsIn([{ path: 'tag ref', line: 1, text: name }]).length) {+ throw new Refused('RUNNER_SECRET', 'a selected tag ref failed the safe transfer check; keep this run local');+ }+ const chain = [];+ if (type === 'tag') {+ let current = object;+ const seen = new Set();+ while (type === 'tag') {+ if (chain.length >= MAX_TAG_CHAIN || seen.has(current)) {+ throw new Refused('RUNNER_SCAN_LIMIT', 'an annotated tag chain exceeds the safe transfer limit; keep this run local');+ }+ seen.add(current);+ const tagBody = sourceGit(root, ['cat-file', '-p', current]);+ annotationBytes += Buffer.byteLength(tagBody);+ if (annotationBytes > MAX_BLOB_BYTES) throw new Refused('RUNNER_SCAN_LIMIT', 'a tag annotation exceeds the safe transfer limit; keep this run local');+ if (secretsIn(tagBody.split(/\r?\n/u).map((text, line) => ({ path: name, line: line + 1, text }))).length) {+ throw new Refused('RUNNER_SECRET', 'an annotated tag failed the source privacy scan; keep this run local');+ }+ const header = tagBody.split(/\r?\n\r?\n/u, 1)[0];+ const target = /^object ([a-f0-9]{40,64})$/mu.exec(header)?.[1];+ const targetType = /^type (commit|tag|tree|blob)$/mu.exec(header)?.[1];+ if (!target || target.length !== source.commit.length || !targetType+ || sourceGit(root, ['cat-file', '-t', target]).trim() !== targetType) {+ throw new Refused('RUNNER_SOURCE', 'an annotated tag has an invalid object chain; keep this run local');+ }+ chain.push(current);+ current = target;+ type = targetType;+ }+ if (type !== 'commit' || current !== peeledCommit) throw new Refused('RUNNER_SOURCE', 'an annotated tag did not peel to its declared commit');+ } else if (type !== 'commit' || object !== peeledCommit) continue;+ selected.push({ name, object, peeledCommit, chain });+ }+ return selected;+ }++ /** Read one exact cat-file record without loading a repository's history into memory. */+ function objectRecord(descriptor) {+ const header = [];+ const byte = Buffer.alloc(1);+ while (readSync(descriptor, byte, 0, 1, null)) {+ if (byte[0] === 10) break;+ if (header.length > 200) throw new Refused('RUNNER_SOURCE', 'invalid source object header; keep this run local');+ header.push(byte[0]);+ }+ const match = /^([a-f0-9]{40,64}) (blob|tree|commit|tag) (\d+)$/u.exec(Buffer.from(header).toString('ascii'));+ if (!match) throw new Refused('RUNNER_SOURCE', 'cannot scan the selected history objects; keep this run local');+ const size = Number(match[3]);+ if (!Number.isSafeInteger(size) || size > MAX_BLOB_BYTES) throw new Refused('RUNNER_SCAN_LIMIT', 'a historical object exceeds the safe runner scan limit; keep this run local');+ const data = Buffer.alloc(size);+ let offset = 0;+ while (offset < size) {+ const read = readSync(descriptor, data, offset, size - offset, null);+ if (!read) throw new Refused('RUNNER_SOURCE', 'incomplete history object; retry from the committed repository');+ offset += read;+ }+ if (readSync(descriptor, byte, 0, 1, null) !== 1 || byte[0] !== 10) throw new Refused('RUNNER_SOURCE', 'incomplete history object; retry from the committed repository');+ return { object: match[1], type: match[2], data };+ }++ /** Scan and pack exactly the candidate objects absent from the locked remote cache inventory. */+ function historyPack(root, source, tips, directory, tags = [], knownTagObjects = []) {+ const knownTags = new Set(knownTagObjects);+ const known = sourceGit(root, ['cat-file', '--batch-check'], { input: tips.map(tip => `${tip}\n`).join('') })+ .split('\n').map(line => /^([a-f0-9]{40,64}) commit \d+$/u.exec(line)?.[1]).filter(Boolean);+ const records = sourceGit(root, ['rev-list', '--objects', source.commit, '--not', ...known])+ .split('\n').filter(Boolean).map(line => {+ const match = /^([a-f0-9]{40,64})(?: (.*))?$/u.exec(line);+ if (!match) throw new Refused('RUNNER_SOURCE', 'unsupported history path; keep this run local');+ return { object: match[1], path: match[2] ?? '' };+ });+ const objects = [...new Set([...records.map(record => record.object), ...tags.flatMap(tag => tag.chain).filter(object => !knownTags.has(object))])];+ const names = new Map(records.map(record => [record.object, record.path]));+ for (const tag of tags) for (const object of tag.chain) names.set(object, tag.name);+ const historicalTrees = new Set();+ const config = sourceGit(root, ['ls-tree', '--name-only', source.commit, '--', 'pullboard.json']).trim()+ ? configFromSource(sourceGit(root, ['show', `${source.commit}:pullboard.json`])) : defaults();+ const metadata = sourceGit(root, ['cat-file', '--batch-check'], { input: objects.map(object => `${object}\n`).join('') });+ for (const line of metadata.split('\n').filter(Boolean)) {+ const match = /^[a-f0-9]{40,64} (blob|tree|commit|tag) (\d+)$/u.exec(line);+ if (!match || Number(match[2]) > MAX_BLOB_BYTES) throw new Refused('RUNNER_SCAN_LIMIT', 'a historical object exceeds the safe runner scan limit; keep this run local');+ }+ if (objects.length) {+ const scanFile = join(directory, 'history.scan');+ const output = openSync(scanFile, 'wx', 0o600);+ try { sourceGit(root, ['cat-file', '--batch'], { input: `${objects.join('\n')}\n`, stdio: ['pipe', output, 'pipe'] }); }+ finally { closeSync(output); }+ const input = openSync(scanFile, 'r');+ try {+ for (let index = 0; index < objects.length; index++) {+ const { object, type, data } = objectRecord(input);+ const path = names.get(object) || `history/${object}`;+ if (type === 'commit') {+ const tree = /^tree ([a-f0-9]{40,64})$/mu.exec(data.toString('utf8'))?.[1];+ if (!tree) throw new Refused('RUNNER_SOURCE', 'invalid historical commit; keep this run local');+ historicalTrees.add(tree);+ }+ if (type === 'tree') {+ let cursor = 0;+ while (cursor < data.length) {+ const space = data.indexOf(32, cursor), nul = data.indexOf(0, space + 1);+ if (space < cursor || nul < 0) throw new Refused('RUNNER_SOURCE', 'invalid historical tree; keep this run local');+ const mode = data.subarray(cursor, space).toString('ascii');+ const name = data.subarray(space + 1, nul).toString('utf8');+ const full = names.get(object) ? `${names.get(object)}/${name}` : name;+ if (mode === '160000' || protectedHistoryPath(full, config.protect)+ || secretsIn([{path:'historical tree',line:1,text:name}]).length) throw new Refused('RUNNER_SECRET', 'historical source includes a blocked private path or submodule; keep this run local');+ cursor = nul + 1 + source.commit.length / 2;+ }+ if (cursor !== data.length) throw new Refused('RUNNER_SOURCE', 'invalid historical tree; keep this run local');+ } else if (protectedHistoryPath(path, config.protect)+ || secretsIn(data.toString('utf8').split(/\r?\n/u).map((text, line) => ({ path, line: line + 1, text }))).length) {+ throw new Refused('RUNNER_SECRET', 'historical source failed its transfer scan; remove the private history or keep this run local');+ }+ }+ } finally { closeSync(input); rmSync(scanFile, { force: true }); }+ }+ // Check every full historical path, including reused cached blobs moved beneath a newly blocked prefix.+ for (const tree of historicalTrees) {+ for (const record of sourceGit(root, ['ls-tree', '-r', '-z', '--full-tree', tree]).split('\0').filter(Boolean)) {+ const match = /^(\d+) (\w+) [a-f0-9]{40,64}\t([\s\S]+)$/u.exec(record);+ if (!match || match[2] !== 'blob' || protectedHistoryPath(match[3], config.protect)) {+ throw new Refused('RUNNER_SECRET', 'historical source includes a blocked private path or submodule; keep this run local');+ }+ }+ }+ const pack = join(directory, 'source.pack');+ const output = openSync(pack, 'wx', 0o600);+ try { sourceGit(root, ['pack-objects', '--stdout'], { input: objects.map(object => `${object}\n`).join(''), stdio: ['pipe', output, 'pipe'] }); }+ finally { closeSync(output); }+ return pack;+ }++ /** Quote one remote shell argument without permitting substitutions or expansion. */+ function shellWord(value) { return `'${String(value).replaceAll("'", "'\\''")}'`; }++ /** Give the SSH client connection necessities only; arbitrary caller secrets cannot be forwarded. */+ function sshEnvironment() {+ const env = {};+ for (const key of ['PATH', 'HOME', 'USER', 'LOGNAME', 'SSH_AUTH_SOCK', 'TMPDIR', 'SystemRoot', 'WINDIR']) {+ if (process.env[key] !== undefined) env[key] = process.env[key];+ }+ return { ...env, LC_ALL: 'C', LANG: 'C', TZ: 'UTC' };+ }++ /** Snapshot, scan and pin the actual tooling bytes independently of the project being tested. */+ function trustedTooling() {+ const files = Object.fromEntries([...RUNTIME_NAMES, 'runner-worker.js']+ .map(name => [name, readFileSync(fileURLToPath(new URL(`./${name}`, import.meta.url)), 'utf8')]));+ for (const [name, source] of Object.entries(files)) {+ if (Buffer.byteLength(source) > MAX_BLOB_BYTES+ || secretsIn(source.split(/\r?\n/u).map((text, index) => ({ path: `tooling/${name}`, line: index + 1, text }))).length) {+ throw new Refused('RUNNER_TOOLING_SECRET', 'the selected runner tooling failed its transfer scan; restore a trusted Pullboard installation');+ }+ }+ const manifest = JSON.parse(readFileSync(join(TOOL_ROOT, 'package.json'), 'utf8'));+ if (manifest.name !== 'pullboard' || typeof manifest.version !== 'string') {+ throw new Refused('RUNNER_TOOLING_IDENTITY', 'runner tooling must come from a named Pullboard installation; reinstall Pullboard');+ }+ let provenance = { kind: 'installed-package', name: manifest.name, version: manifest.version };+ if (existsSync(join(TOOL_ROOT, '.git'))) {+ const selected = runnerSource(TOOL_ROOT);+ if (!selected || Object.entries(files).some(([name, source]) => sourceGit(TOOL_ROOT, ['show', `${selected.commit}:src/${name}`]) !== source)) {+ throw new Refused('RUNNER_TOOLING_CHANGED', 'runner tooling differs from its selected committed revision; restore or commit the tooling before remote execution');+ }+ provenance = { ...provenance, kind: 'git-checkout', ...selected };+ }+ const tooling = { ...provenance, sha256: createHash('sha256').update(JSON.stringify(files)).digest('hex') };+ const runtimeFiles = Object.fromEntries(RUNTIME_NAMES.map(name => [name, files[name]]));+ return { worker: files['runner-worker.js'], tooling,+ runtime: { files: runtimeFiles, sha256: createHash('sha256').update(JSON.stringify(runtimeFiles)).digest('hex') } };+ }++ /** Install a complete immutable module capsule without reading the job's stdin stream. */+ function installRuntime(payload, expected, configuredRoot) {+ const bytes = gunzipSync(Buffer.from(payload, 'base64'), { maxOutputLength: 1_048_576 });+ if (createHash('sha256').update(bytes).digest('hex') !== expected) throw new Error('invalid capsule identity');+ const files = JSON.parse(bytes);+ const home = process.env.HOME;+ if (!configuredRoot && (!home || !isAbsolute(home))) throw new Error('runner home must be absolute');+ const root = configuredRoot || join(home, '.pullboard-runner');+ const directory = join(root, 'runtime', expected);+ mkdirSync(root, { recursive: true, mode: 0o700 });+ chmodSync(root, 0o700);+ mkdirSync(dirname(directory), { recursive: true, mode: 0o700 });+ const build = mkdtempSync(join(dirname(directory), `${expected}.build-`));+ try {+ mkdirSync(join(build, 'src'), { mode: 0o700 });+ writeFileSync(join(build, 'package.json'), '{"type":"module"}\n', { mode: 0o600 });+ for (const [name, source] of Object.entries(files)) writeFileSync(join(build, 'src', name), source, { mode: 0o600 });+ try { renameSync(build, directory); }+ catch (error) { if (!['EEXIST', 'ENOTEMPTY'].includes(error.code)) throw error; }+ if (readFileSync(join(directory, 'package.json'), 'utf8') !== '{"type":"module"}\n'+ || Object.entries(files).some(([name, source]) => readFileSync(join(directory, 'src', name), 'utf8') !== source)) {+ throw new Error('trusted capsule does not match the request');+ }+ } finally { rmSync(build, { recursive: true, force: true }); }+ }++ /** Install pinned bytes first, then replace the SSH shell with the file-based worker. */+ function remoteWorkerCommand(runner, worker, tooling, runtime) {+ const 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 { createHash } from 'node:crypto';+ import { gunzipSync } from 'node:zlib';+ ${installRuntime.toString()}+ installRuntime(${JSON.stringify(payload)}, ${JSON.stringify(tooling.sha256)}, ${JSON.stringify(runner.root ?? '')});`;+ const node = shellWord(runner.node ?? 'node');+ const suffix = `/runtime/${tooling.sha256}/src/runner-worker.js`;+ const entry = runner.root ? shellWord(runner.root + suffix) : `"$HOME"${shellWord('/.pullboard-runner' + suffix)}`;+ return `${node} --input-type=module -e ${shellWord(installer)} && exec ${node} ${entry}`;+ }++ /** Use only a credential-free anonymous HTTPS origin; SSH authentication is never forwarded. */+ function anonymousOrigin(root) {+ const result = spawnSync('git', ['config', '--get', 'remote.origin.url'], { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 4096 });+ if (result.status !== 0) return undefined;+ let address = result.stdout.trim();+ const ssh = /^git@([A-Za-z0-9][A-Za-z0-9.-]*):([^\s?#]+)$/u.exec(address);+ if (ssh) address = `https://${ssh[1]}/${ssh[2]}`;+ try {+ const url = new URL(address);+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || !url.hostname || address.length > 2048) return undefined;+ if (secretsIn([{path:'anonymous origin',line:1,text:address}]).length) return undefined;+ return url.href;+ } catch { return undefined; }+ }++ /** Prepare the pinned request before negotiating history; cleanup owns only its scratch directory. */+ function requestFor(root, command, { runner, source, browser = false, pipefail = false, metadata = {} }) {+ runner = validateRunner(runner);+ const current = runnerSource(root);+ if (!current || (source && (current.commit !== source.commit || current.tree !== source.tree))) {+ throw new Refused('RUNNER_SOURCE_CHANGED', 'the queued source changed; restore the committed tree and retry the run');+ }+ if (secretsIn(command.split('\n').map((text, index) => ({ path: 'run command', line: index + 1, text }))).length) {+ throw new Refused('RUNNER_SECRET', 'the run command contains a possible secret; use a command that does not transfer credentials');+ }+ const protect = sourceObjects(root, current);+ protectHistory(root, current, protect);+ const origin = anonymousOrigin(root);+ const originBase = origin ? originAncestor(root, current) : undefined;+ const tags = candidateTags(root, current);+ const repoId = createHash('sha256').update(realpathSync(repoInfo(root).commonDir)).digest('hex');+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-runner-send-'));+ try {+ const { worker, tooling, runtime } = trustedTooling();+ const spec = { version: 1, id: randomUUID(), repoId, ...(originBase ? { origin, originBase } : {}), runtime, tooling, tags, ...current, command, pipefail, slots: runner.slots,+ browser: runner.browser, browserRequired: browser, landing: metadata.landing === true,+ itemCheck: metadata.itemCheck === true, diagnostic: metadata.diagnostic === true,+ item: String(metadata.item ?? ''), kind: String(metadata.kind ?? ''), ...(runner.root ? { root: runner.root } : {}) };+ const encodedSpec = Buffer.from(JSON.stringify(spec));+ if (encodedSpec.length > 1024 ** 2) throw new Refused('RUNNER_REQUEST_LIMIT', 'runner tooling request exceeds its safe transfer limit; keep this run local');+ const remote = remoteWorkerCommand(runner, worker, tooling, runtime);+ // These are transport hang ceilings, independent of the command's execution budget.+ return { spec, runner, args: ['-T', '-o', 'BatchMode=yes', '-o', 'ForwardAgent=no', '-o', 'ClearAllForwardings=yes',+ '-o', 'SendEnv=-*', '-o', 'ConnectTimeout=10', '-o', 'ServerAliveInterval=10', '-o', 'ServerAliveCountMax=3',+ '--', runner.host, remote], root, source: current, directory, frame: Buffer.concat([Buffer.from(`${encodedSpec.length}\n`), encodedSpec]), env: sshEnvironment(),+ cleanup() { rmSync(directory, { recursive: true, force: true }); } };+ } catch (error) {+ rmSync(directory, { recursive: true, force: true });+ throw error;+ }+ }++ /** Verify exact source and complete raw output before accepting any remote status. */+ function resultFrom(request, result) {+ const output = result.stdout ?? Buffer.alloc(0);+ const lines = String(result.stderr ?? '').split(/\r?\n/u);+ const prefix = `PULLBOARD_RUNNER_RESULT ${request.spec.id} `;+ const receipts = lines.filter(line => line.startsWith(prefix));+ let receipt;+ try {+ if (receipts.length !== 1) throw new Error('missing receipt');+ receipt = JSON.parse(Buffer.from(receipts[0].slice(prefix.length), 'base64').toString('utf8'));+ } catch { throw new RunnerDropped(request.runner.host); }+ if (result.error || result.status !== 0 || receipt.id !== request.spec.id || receipt.commit !== request.spec.commit+ || receipt.tree !== request.spec.tree || receipt.runtimeSha256 !== request.spec.runtime.sha256 || receipt.toolingSha256 !== request.spec.tooling.sha256 || !Number.isInteger(receipt.code) || receipt.code < 0 || receipt.code > 255+ || typeof receipt.root !== 'string' || !Number.isFinite(receipt.wallMs) || receipt.wallMs < 0+ || receipt.outputSha256 !== createHash('sha256').update(output).digest('hex')) {+ throw new RunnerDropped(request.runner.host);+ }+ return { isGreen: receipt.code === 0 && !receipt.signal, output: output.toString('utf8'),+ seconds: Math.round(receipt.wallMs / 1000), exitCode: receipt.code,+ executionRunner: request.runner.host, executionRoot: receipt.root, remoteWallMs: receipt.wallMs,+ executionSource: { commit: receipt.commit, tree: receipt.tree, tooling: request.spec.tooling } };+ }++ /** Keep synchronous gate callers on the same negotiated transport as asynchronous comparisons. */+ export function runOnRunner(root, command, options) {+ const script = `import { runOnRunnerAsync } from ${JSON.stringify(import.meta.url)};+ let input=''; for await (const chunk of process.stdin) input+=chunk;+ const request=JSON.parse(input);+ const canceled=new AbortController();+ const abort=()=>canceled.abort();+ process.on('SIGTERM',abort); process.on('SIGHUP',abort); process.stdout.on('error',abort);+ // Budget: check actual parent identity every second while the negotiated SSH transport is active.+ const parentWatch=setInterval(()=>{if(process.ppid!==request.parentPid)abort();},1000);+ if(process.ppid!==request.parentPid)abort();+ try { process.stdout.write(JSON.stringify({result:await runOnRunnerAsync(request.root,request.command,{...request.options,signal:canceled.signal})})); }+ catch(error) { process.stdout.write(JSON.stringify({error:{name:error.name,code:error.code,message:error.message,host:error.host}})); process.exitCode=1; }+ finally {clearInterval(parentWatch);}`;+ const child = spawnSync(process.execPath, ['--input-type=module', '-e', script], {+ cwd: root, input: JSON.stringify({ root, command, options, parentPid: process.pid }), encoding: 'utf8', maxBuffer: MAX_OUTPUT_BYTES * 6 + 1024 ** 2,+ stdio: ['pipe', 'pipe', 'pipe'],+ });+ let reply;+ try { reply = JSON.parse(child.stdout); } catch { throw new RunnerDropped(options.runner.host); }+ if (reply.error?.name === 'Refused') {+ const prefix = `[${reply.error.code}] `;+ throw new Refused(reply.error.code, reply.error.message.startsWith(prefix) ? reply.error.message.slice(prefix.length) : reply.error.message);+ }+ if (reply.error || child.error || child.status !== 0) throw new RunnerDropped(options.runner.host);+ return reply.result;+ }++ /** Negotiate missing history objects while the remote cache lease stays held in one SSH session. */+ export async function runOnRunnerAsync(root, command, options) {+ if (options.signal?.aborted) throw new RunnerDropped(options.runner.host);+ const request = requestFor(root, command, options);+ let removeAbort = () => {};+ try {+ const child = spawn('ssh', request.args, { env: request.env, stdio: ['pipe', 'pipe', 'pipe'] });+ const output = [], diagnostics = [];+ let bytes = 0, error, control = '', requested = false, transfer = null, cleanupReason = '';+ const abort = () => { error ??= new Error('runner transport canceled'); child.stdin.destroy(); child.kill('SIGTERM'); };+ options.signal?.addEventListener('abort', abort, { once: true });+ removeAbort = () => options.signal?.removeEventListener('abort', abort);+ if (options.signal?.aborted) abort();+ /** Bound both protocol streams before retaining a complete result. */+ const capture = (target, chunk) => {+ bytes += chunk.length;+ if (bytes > MAX_OUTPUT_BYTES) { error = new Refused('RUNNER_OUTPUT_LIMIT', 'runner output exceeded 64 MiB; reduce command output or keep this run local'); child.kill(); }+ else target.push(chunk);+ };+ child.stdout.on('data', chunk => capture(output, chunk));+ child.stderr.on('data', chunk => {+ capture(diagnostics, chunk);+ control += chunk.toString('utf8');+ if (control.length > 256 * 1024) { error = new Error('runner control frame exceeded limit'); child.kill(); return; }+ let newline;+ while ((newline = control.indexOf('\n')) >= 0) {+ const line = control.slice(0, newline); control = control.slice(newline + 1);+ const cleanupPrefix = `PULLBOARD_RUNNER_CLEANUP_UNVERIFIED ${request.spec.id} `;+ if (line.startsWith(cleanupPrefix)) cleanupReason = line.slice(cleanupPrefix.length, cleanupPrefix.length + 240);+ if (line === `PULLBOARD_RUNNER_CLEANUP_TIMEOUT ${request.spec.id}`) {+ error = new Refused('RUNNER_CLEANUP_TIMEOUT', `runner ${request.runner.host} could not verify cleanup within 30 seconds${cleanupReason ? ': ' + cleanupReason : ''}; inspect job ${request.spec.id} under its runner namespace before another run`);+ child.stdin.destroy(); child.kill('SIGTERM'); return;+ }+ const prefix = `PULLBOARD_RUNNER_NEED ${request.spec.id} `;+ if (!line.startsWith(prefix)) continue;+ if (requested) { error = new Error('duplicate runner inventory'); child.kill(); return; }+ requested = true;+ transfer = (async () => {+ const inventory = JSON.parse(Buffer.from(line.slice(prefix.length), 'base64').toString('utf8'));+ if (!Array.isArray(inventory.tips) || inventory.tips.length > 1024+ || inventory.tips.some(tip => typeof tip !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(tip))) {+ throw new Error('invalid runner inventory');+ }+ if (!Array.isArray(inventory.tagObjects) || inventory.tagObjects.length > 8_192+ || inventory.tagObjects.some(object => typeof object !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(object))) {+ throw new Error('invalid runner tag inventory');+ }+ const pack = historyPack(root, request.source, inventory.tips, request.directory, request.spec.tags, inventory.tagObjects);+ await pipeline(createReadStream(pack), child.stdin);+ })().catch(failure => { error = failure; child.stdin.destroy(); child.kill(); });+ }+ });+ child.stdin.on('error', failure => { if (failure.code !== 'EPIPE') error ??= failure; });+ child.once('error', failure => { error = failure; });+ child.stdin.write(request.frame);+ const status = await new Promise(resolve => child.once('close', resolve));+ if (transfer) await transfer;+ if (error instanceof Refused) throw error;+ return resultFrom(request, { status, error, stdout: Buffer.concat(output), stderr: Buffer.concat(diagnostics) });+ } finally { removeAbort(); request.cleanup(); }+ }diff --cc src/settings.jsindex 1094e275,4169a4c6..9227aeeb--- a/src/settings.js+++ b/src/settings.js@@@ -1,19 -1,10 +1,23 @@@/** Machine-wide settings shared by every Pullboard checkout on this machine. */-import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';-import { dirname, join } from 'node:path';+import {+ existsSync,+ mkdirSync,+ readFileSync,+ renameSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import {+ dirname,+ join,+} from 'node:path';import { randomUUID } from 'node:crypto';import { machineHome } from './machine-home.js';- import { setResourceCapacity } from './resources.js';-import { setResourceCapacity, updateRunnerSettings } from './resources.js';++import {++ setResourceCapacity,++ updateRunnerSettings,++} from './resources.js';+ import { validateRunner } from './runners.js';import { Refused } from './refused.js';const DEFAULT_GATE_SLOTS = 2;