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
fix(runners): compose landing cleanup and observe stopped transport [C7]
Corey Olsona906ac941356
diff --cc bin/run-tests.jsindex 35296a64,7ffdfcef..76320c87--- a/bin/run-tests.js+++ b/bin/run-tests.js@@@ -2,11 -2,10 +2,10 @@@/*** Run the test suite with a private home, no inherited Git identity or config, and a refusing CLI shim.*/- import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';- import { delimiter, join, relative, resolve, sep } from 'node:path';+ import { appendFileSync, chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';-import { basename, delimiter, dirname, join, resolve } from 'node:path';++import { basename, delimiter, dirname, join, relative, resolve, sep } from 'node:path';import { fileURLToPath } from 'node:url';- import { execFileSync, spawnSync } from 'node:child_process';- import { randomUUID } from 'node:crypto';+ import { execFile, execFileSync, spawnSync } from 'node:child_process';import { tmpdir } from 'node:os';import { after, afterEach, beforeEach } from 'node:test';import { Worker } from 'node:worker_threads';diff --cc src/gate.jsindex a67a003d,54c70c30..965dfe18--- a/src/gate.js+++ b/src/gate.js@@@ -172,11 -171,13 +173,14 @@@ export function runProfiledShell(root,const profilePath = profileFile ?? join(directory, `${artifactPrefix}-${id}.profile.json`);const logPath = persistLog ? join(directory, `${artifactPrefix}-${id}.log`) : null;const started = Date.now();- const inherited = gateLease && !gateLease.runner ? gateSlotEnvironment(gateLease) : gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {};+ const inherited = {- ...(gateLease ? gateSlotEnvironment(gateLease) : gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {}),++ ...(gateLease && !gateLease.runner ? gateSlotEnvironment(gateLease) : gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {}),+ [LANDING_RUN_ENV]: landing ? '1' : '0',+ };- const run = runShell(root, command, { pipefail, env: inherited });+ const run = gateLease?.runner ? runOnRunner(root, command, { runner: gateLease.runner, source: gateLease.source,- browser: gateLease.browser, pipefail, metadata: gateLease.runMetadata }) : runShell(root, command, { pipefail, env: inherited });++ browser: gateLease.browser, pipefail, metadata: { ...(gateLease.runMetadata ?? {}), landing } }) : runShell(root, command, { pipefail, env: inherited });const profile = writeTimingProfile(profilePath, {- ...timingFromOutput(run.output, timingRunner(command)),+ ...runTiming(run, command),waitMs: Math.max(0, Math.round(waitMs)), wallMs: Math.max(0, Date.now() - started),});if (logPath) writeFileSync(logPath, safeLog(run.output), { mode: 0o600 });@@@ -186,20 -187,15 +190,23 @@@/** Run an independent focused comparison without blocking other holders of the machine pool.* @param {string} root* @param {string} command- * @param {{ waitMs?: number, gateSlotHeld?: boolean, gateLease?: object }} [options]+ * @param {{ waitMs?: number, gateSlotHeld?: boolean, gateLease?: object, landing?: boolean }} [options]* @returns {Promise<object>} The unchanged shell verdict and its private timing profile.*/- export async function runProfiledShellAsync(root, command, { waitMs = 0, gateSlotHeld = false, gateLease } = {}) {+ export async function runProfiledShellAsync(root, command, { waitMs = 0, gateSlotHeld = false, gateLease, landing = false } = {}) {const started = Date.now();+ if (gateLease?.runner) {+ const run = await runOnRunnerAsync(root, command, { runner: gateLease.runner, source: gateLease.source,- browser: gateLease.browser, metadata: gateLease.runMetadata });++ browser: gateLease.browser, metadata: { ...(gateLease.runMetadata ?? {}), landing } });+ const wallMs = Math.max(0, Date.now() - started);+ const profilePath = join(dirname(gitPath(root, LOG)), `pullboard-gate-${randomUUID()}.profile.json`);+ const profile = writeTimingProfile(profilePath, { ...runTiming(run, command), waitMs, wallMs });+ return { ...run, seconds: Math.round(wallMs / 1000), profile, profilePath, logPath: null };+ }- const inherited = gateLease ? gateSlotEnvironment(gateLease) : gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {};+ const inherited = {+ ...(gateLease ? gateSlotEnvironment(gateLease) : gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {}),+ [LANDING_RUN_ENV]: landing ? '1' : '0',+ };const env = { ...gitChildEnv(root), ...inherited };const child = spawn(`(\n${command}\n) 2>&1`, { cwd: root, env, shell: true, stdio: ['ignore', 'pipe', 'pipe'] });const chunks = [];diff --cc src/runner-worker.jsindex 2d22df43,00000000..8a8c8256mode 100644,000000..100644--- a/src/runner-worker.js+++ b/src/runner-worker.js@@@ -1,1100 -1,0 +1,1100 @@@+/** Standalone SSH runner worker source; intentionally imports only Node built-ins. */+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 { userInfo } from 'node:os';+import { delimiter, dirname, isAbsolute, join } from 'node:path';+import { pathToFileURL } from 'node:url';+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;++/** 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;+ 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');+ 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 workerFlag = process.execArgv.indexOf('-e');+ const workerSource = workerFlag >= 0 ? process.execArgv[workerFlag + 1] : null;+ 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),+ };+}++/** Install the trusted resource implementation supplied and hashed by the controller. */+async function loadResourceApi(runnerRoot, runtime) {+ const directory = join(runnerRoot, 'runtime', runtime.sha256);+ const parent = dirname(directory);+ mkdirSync(parent, { recursive: true, mode: 0o700 });+ const build = mkdtempSync(join(parent, `${runtime.sha256}.build-`));+ try {+ const sourceDirectory = join(build, 'src');+ mkdirSync(sourceDirectory, { mode: 0o700 });+ writeFileSync(join(build, 'package.json'), '{"type":"module"}\n', { mode: 0o600 });+ for (const [name, source] of Object.entries(runtime.files)) writeFileSync(join(sourceDirectory, name), source, { mode: 0o600 });+ try { renameSync(build, directory); }+ catch (error) {+ if (!['EEXIST', 'ENOTEMPTY'].includes(error.code)) throw error;+ }+ // Concurrent workers reuse only a complete, byte-identical trusted module graph.+ if (readFileSync(join(directory, 'package.json'), 'utf8') !== '{"type":"module"}\n'+ || Object.entries(runtime.files).some(([name, source]) => readFileSync(join(directory, 'src', name), 'utf8') !== source)) {+ throw new Error('trusted runtime cache does not match the request');+ }+ } finally { rmSync(build, { recursive: true, force: true }); }+ const sourceDirectory = join(directory, 'src');+ return import(pathToFileURL(join(sourceDirectory, 'resources.js')).href);+}++/** 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 busy = false;+ let warned = false;+ let timer = null;+ let stoppingPromise = null;++ function readJournal() {+ if (existsSync(overflowPath)) { uncertain = true; reason ||= 'child spawn journal overflow or write failure'; }+ let total = 0;+ const files = readdirSync(journal.journalDirectory).filter(name => /^children-\d+\.jsonl$/u.test(name)).sort();+ if (files.length > 10_000) { uncertain = true; reason ||= '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 { uncertain = true; reason ||= 'child spawn journal could not be inspected'; continue; }+ total += size;+ if (!Number.isSafeInteger(size) || size > 131_072 || total > 8 * 1024 * 1024) {+ uncertain = true; reason ||= 'child spawn journal size limit exceeded'; continue;+ }+ const offset = offsets.get(name) ?? 0;+ if (size < offset) { uncertain = true; reason ||= '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) { uncertain = true; reason ||= '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) { uncertain = true; reason ||= 'child spawn journal record is oversized'; continue; }+ let record;+ try { record = JSON.parse(line); } catch { uncertain = true; reason ||= '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) { uncertain = true; reason ||= 'child spawn journal event limit exceeded'; return; }+ } else { uncertain = true; reason ||= '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}`)) {+ uncertain = true; reason ||= '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}`)) { uncertain = true; reason ||= '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}`)) { uncertain = true; reason ||= '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}`)) { uncertain = true; reason ||= '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) {+ uncertain = true; reason ||= 'detached process group identity was reused';+ continue;+ }+ const prior = known.get(row.pid);+ if (retired.has(`${row.pid}:${row.birth}`)) { uncertain = true; reason ||= '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) { uncertain = true; reason ||= '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) { uncertain = true; reason ||= 'descendant lacks a safe process-group identity'; break; }+ try { process.kill(identity.pid, 'SIGTERM'); }+ catch (error) { if (error.code !== 'ESRCH') { uncertain = true; reason ||= '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) { uncertain = true; reason ||= 'descendant lacks a safe process-group identity'; break; }+ try { process.kill(identity.pid, 'SIGKILL'); }+ catch (error) { if (error.code !== 'ESRCH') { uncertain = true; reason ||= '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,+ 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) {+ const owned = spawnOwned('git', args, { cwd: root, env, stdio: ['ignore', 'pipe', 'ignore'] });+ const output = [];+ let bytes = 0;+ let overflow = false;+ 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 || 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'));+ 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');+ await new Promise((resolveWrite, rejectWrite) => process.stderr.write(+ `PULLBOARD_RUNNER_NEED ${spec.id} ${Buffer.from(JSON.stringify({ tips: uniqueTips })).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 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))) {+ throw new Error('source history pack contains missing or unrelated objects');+ }+ 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);+ 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 {+ 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();+ await writes;+ await tracker.stopDescendants();+ 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 = await loadResourceApi(runnerRoot, 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}-`));+ 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);+ 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, sink, tracker)), root };++ 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();+ if (tracker) await tracker.stopDescendants();+ await drainAllOwned();+ if (tracker) {+ await tracker.verifyAfterGroups();+ tracker.stopMonitoring();+ activeDescendantTracker = null;+ }+ if (lease) {+ try { lease.release(); } catch { /* Retaining a lease on cleanup error is safer than speculative deletion. */ }+ }+ if (runDirectory) { try { rmSync(runDirectory, { recursive: true, force: true }); } catch {} }+ }+ if (transportLost || cleanupTimedOut) { clearTimeout(cleanupTimer); process.exitCode = 1; return; }+ await receipt(spec, final, sink);+ clearTimeout(cleanupTimer);+ process.exitCode = 0;+}++main().catch(() => { process.exitCode = 1; });diff --cc test/runners.test.jsindex 25ed5c6f,00000000..1ec28586mode 100644,000000..100644--- a/test/runners.test.js+++ b/test/runners.test.js@@@ -1,1224 -1,0 +1,1230 @@@+/** Registered SSH runner execution stays inside a committed, secret-free worker checkout [C7]. */+import assert from 'node:assert/strict';+import { basename, dirname, join, relative, resolve, sep } from 'node:path';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, watch, writeFileSync } from 'node:fs';+import { spawn } from 'node:child_process';+import { once } from 'node:events';+import { DatabaseSync } from 'node:sqlite';+import { tmpdir } from 'node:os';+import { test } from 'node:test';+import { takeResource } from '../src/resources.js';+import { listResources as listPreRunnerResources, takeResource as takePreRunnerResource } from './fixtures/resources-pre-runners.js';+import { runFixtureChild, startFixtureChild } from './fixture-child.js';++const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+const TEMP = [];+const SECRET = ['fixture', 'runner', 'secret', 'must', 'stay', 'local'].join('-');+const HOST = 'fixture-host';++/** Quote one literal value for the fixture's POSIX shell command. */+function shellQuote(value) {+ return `'${String(value).replaceAll("'", "'\\''")}'`;+}++/** Run Git in the private source repository and preserve useful failure context. */+function git(repo, env, ...args) {+ const result = runFixtureChild('git', args, { cwd: repo, env, encoding: 'utf8' });+ assert.equal(result.status, 0, result.context);+ return result.stdout.trim();+}++/** Spawn the exact checked-in CLI from a fixture checkout. */+function cli(repo, env, ...args) {+ return runFixtureChild(process.execPath, [BIN, ...args], { cwd: repo, env, encoding: 'utf8' });+}++/** Make a local ssh stand-in that executes the actual worker command in a second private machine. */- function installSshStandIn({ bin, worker, home, machineHome, requests, nodeCommand = 'node', dropFirst = false, dropAfterMarker }) {++function installSshStandIn({ bin, worker, home, machineHome, requests, starts, nodeCommand = 'node', dropFirst = false, dropAfterMarker }) {+ const ssh = join(bin, 'ssh');+ const source = `#!/usr/bin/env node+import { appendFileSync, existsSync, readFileSync, watch, writeFileSync } from 'node:fs';+import { spawn } from 'node:child_process';+import { createHash } from 'node:crypto';+import { basename, dirname, join } from 'node:path';+const argv = process.argv.slice(2);+const divider = argv.indexOf('--');+const host = divider >= 0 ? argv[divider + 1] : '';+const remoteCommand = divider >= 0 ? argv[divider + 2] : '';+const requests = ${JSON.stringify(requests)};++const starts = ${JSON.stringify(starts ?? '')};+const worker = ${JSON.stringify(worker)};+const home = ${JSON.stringify(home)};+const machineHome = ${JSON.stringify(machineHome)};+const configuredNode = ${JSON.stringify(`${shellQuote(nodeCommand)} --input-type=module -e `)};+const dropAfterMarker = ${JSON.stringify(dropAfterMarker ?? '')};+const secret = ${JSON.stringify(SECRET)};+const call = existsSync(requests) ? readFileSync(requests, 'utf8').split('\\n').filter(Boolean).length + 1 : 1;+const stdinHash = createHash('sha256');+let stdinBytes = 0;+process.stdin.on('data', part => { stdinBytes += part.length; stdinHash.update(part); });+const record = extra => appendFileSync(requests, JSON.stringify({ call, host,+ options: divider < 0 ? [] : argv.slice(0, divider), remoteHasSecret: remoteCommand.includes(secret),+ framed: divider >= 0 && argv[divider] === '--', remoteCommandPresent: Boolean(remoteCommand),+ remoteStartsWithConfiguredNode: remoteCommand.startsWith(configuredNode),+ remoteHasLocalPath: remoteCommand.includes(${JSON.stringify(worker)}),+ remoteHasSourceHome: remoteCommand.includes(${JSON.stringify(home)}),+ remoteHasSourceMachineHome: remoteCommand.includes(${JSON.stringify(machineHome)}), ...extra }) + '\\n');+const waitForMarker = path => {+ let cancel = () => {};+ const promise = new Promise((resolve, reject) => {+ if (existsSync(path)) return resolve(true);+ const watcher = watch(dirname(path), { persistent: false });+ let timer;+ let settled = false;+ const finish = (error, found = true) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer); watcher.close(); error ? reject(error) : resolve(found);+ };+ cancel = () => finish(null, false);+ const check = (_event, filename) => {+ if ((filename === null || String(filename) === basename(path)) && existsSync(path)) finish();+ };+ watcher.on('change', check);+ watcher.once('error', finish);+ timer = setTimeout(() => finish(new Error('setup marker hang ceiling exceeded')), 20_000); // budget: bound the SSH-to-setup disconnect handshake.+ check('rename', basename(path));+ });+ return { promise, cancel: () => cancel() };+};+let cancelDropWait = () => {};+if (host !== ${JSON.stringify(HOST)} && host !== ${JSON.stringify(`${HOST}-drop`)} && host !== ${JSON.stringify(`${HOST}-setup`)}) {+ record({ refused: true, stdinBytes }); process.exit(255);+}++if (starts) appendFileSync(starts, JSON.stringify({ call, host }) + '\\n');+${dropFirst ? `if (host.endsWith('-drop') && call === 1) {+ process.stdin.once('data', () => {+ record({ dropped: true, stdinBytes, stdinSha256: stdinHash.digest('hex') }); process.exit(255);+ });+ process.stdin.resume();+} else` : ''} {+ const env = { PATH: process.env.PATH, HOME: home, TMPDIR: process.env.TMPDIR,+ PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome, LANG: 'C', LC_ALL: 'C', TZ: 'UTC' };+ // Replace the marker-driven shell so the injected HUP reaches the actual worker process.+ const child = spawn('/bin/sh', ['-c', dropAfterMarker ? 'exec ' + remoteCommand : remoteCommand], { cwd: worker, env,+ stdio: ['pipe', 'pipe', 'pipe'] });+ child.stdout.pipe(process.stdout);+ child.stderr.pipe(process.stderr);+ process.stdin.pipe(child.stdin);+ let droppedAfterSetup = false;+ if (dropAfterMarker) {+ const waiting = waitForMarker(dropAfterMarker);+ cancelDropWait = waiting.cancel;+ waiting.promise.then(found => {+ if (found === false) return;+ droppedAfterSetup = true;+ process.kill(child.pid, 'SIGHUP');+ }, error => { record({ setupMarkerError: error.message }); child.kill('SIGKILL'); });+ }+ child.once('error', error => { record({ spawnError: error.code ?? error.name, stdinBytes }); process.exitCode = 255; });+ child.once('close', (code, signal) => {+ cancelDropWait();+ record({ workerStarted: true, code, signal, stdinBytes, stdinSha256: stdinHash.digest('hex'),+ droppedAfterSetup,+ secretInLocalSshEnv: Object.hasOwn(process.env, 'PULLBOARD_RUNNER_FIXTURE_SECRET'),+ localPoolMarkerInLocalSshEnv: Object.hasOwn(process.env, 'PULLBOARD_GATE_SLOT_POOL'),+ localHeldMarkerInLocalSshEnv: Object.hasOwn(process.env, 'PULLBOARD_GATE_SLOT_HELD'),+ localTokenMarkerInLocalSshEnv: Object.hasOwn(process.env, 'PULLBOARD_GATE_SLOT_TOKEN'),+ localMachineHomeInSshEnv: Object.hasOwn(process.env, 'PULLBOARD_MACHINE_HOME') });+ process.exitCode = signal ? 128 : (code ?? 255);+ });+}+`;+ writeFileSync(ssh, source, { mode: 0o700 });+ chmodSync(ssh, 0o700);+ return ssh;+}++/** Build one committed probe that observes the actual checkout and remote process environment. */+function writeProbe(repo, { remoteStateRoot, remoteMachineHome, sourceHome, sourceMachineHome, callerPool, callerToken, historyBaseCommit }) {+ const probe = `import assert from 'node:assert/strict';+import { execFileSync } from 'node:child_process';+import { existsSync } from 'node:fs';+import { isAbsolute, join, relative, sep } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { test } from 'node:test';+test('runner executed the committed source in its private checkout', () => {+ const commit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();+ const tree = execFileSync('git', ['rev-parse', 'HEAD^{tree}'], { encoding: 'utf8' }).trim();+ const shallow = execFileSync('git', ['rev-parse', '--is-shallow-repository'], { encoding: 'utf8' }).trim();+ const count = execFileSync('git', ['rev-list', '--count', 'HEAD'], { encoding: 'utf8' }).trim();+ const history = execFileSync('git', ['log', '--follow', '--format=%H', '--', 'history-renamed.txt'], { encoding: 'utf8' }).trim().split(/\\r?\\n/u);+ const runnerHome = process.env.HOME;+ const privateHomeRelative = relative(${JSON.stringify(remoteStateRoot)}, runnerHome);+ assert.ok(privateHomeRelative && !privateHomeRelative.startsWith('..' + sep) && privateHomeRelative !== '..', runnerHome);+ const checkoutRelative = relative(${JSON.stringify(remoteStateRoot)}, process.cwd());+ assert.equal(checkoutRelative.split(sep)[0], 'jobs', checkoutRelative);+ assert.notEqual(process.cwd(), ${JSON.stringify(sourceHome)});+ assert.ok(checkoutRelative && !checkoutRelative.startsWith('..' + sep) && checkoutRelative !== '..', process.cwd());+ assert.ok(isAbsolute(process.env.HOME));+ assert.equal(relative(process.cwd(), runnerHome), join('..', 'home'));+ assert.equal(process.env.PULLBOARD_MACHINE_HOME, ${JSON.stringify(remoteMachineHome)});+ assert.equal(shallow, 'false', 'the worker receives full selected-candidate history');+ assert.equal(count, '3', 'the full selected candidate has the fixture base, rename, and probe commits');+ assert.ok(history.includes(${JSON.stringify(historyBaseCommit)}), 'the rename retains its original committed file in history');+ assert.equal(execFileSync('git', ['status', '--porcelain'], { encoding: 'utf8' }).trim(), '');+ assert.equal(existsSync('.env'), false, 'ignored, untracked caller files are not transferred');+ assert.equal(process.env.PULLBOARD_RUNNER_FIXTURE_SECRET, undefined);+ assert.equal(process.env.PULLBOARD_GATE_SLOT_HELD, '1');+ assert.ok(process.env.PULLBOARD_GATE_SLOT_POOL.endsWith('/resources.sqlite'));+ assert.notEqual(process.env.PULLBOARD_GATE_SLOT_POOL, ${JSON.stringify(callerPool)});+ assert.ok(process.env.PULLBOARD_GATE_SLOT_TOKEN);+ assert.notEqual(process.env.PULLBOARD_GATE_SLOT_TOKEN, ${JSON.stringify(callerToken)});+ assert.equal(process.env.PULLBOARD_BROWSER_SLOT_HELD, '1');+ const db = new DatabaseSync(process.env.PULLBOARD_GATE_SLOT_POOL, { readOnly: true });+ try {+ const holder = db.prepare('SELECT pid, browser, kind FROM holder WHERE token = ?').get(process.env.PULLBOARD_GATE_SLOT_TOKEN);+ assert.ok(holder, 'the child inherited a live remote parent lease');+ assert.notEqual(holder.pid, process.pid);+ assert.equal(holder.browser, 1);+ assert.equal(holder.kind, 'check');+ } finally { db.close(); }+ assert.equal(process.env.SSH_AUTH_SOCK, undefined);+ assert.notEqual(process.env.PULLBOARD_HOME, ${JSON.stringify(sourceHome)});+ assert.notEqual(process.env.PULLBOARD_MACHINE_HOME, ${JSON.stringify(sourceMachineHome)});+ console.log('RUNNER_FACT ' + JSON.stringify({ commit, tree, cwd: process.cwd(), home: process.env.HOME,+ runnerHome, stateRoot: ${JSON.stringify(remoteStateRoot)}, machineHome: process.env.PULLBOARD_MACHINE_HOME, gatePool: process.env.PULLBOARD_GATE_SLOT_POOL,- gateToken: process.env.PULLBOARD_GATE_SLOT_TOKEN, browser: process.env.PULLBOARD_BROWSER_SLOT_HELD }));++ gateToken: process.env.PULLBOARD_GATE_SLOT_TOKEN, browser: process.env.PULLBOARD_BROWSER_SLOT_HELD,++ landing: process.env.PULLBOARD_LANDING_RUN }));+});+`;+ writeFileSync(join(repo, 'runner-probe.test.js'), probe);+}++/** Build a committed probe for the cache copy of one local workspace dependency. */+function writeCacheProbe(repo, { remoteStateRoot, nodePath, historyBaseCommit }) {+ const probe = `import assert from 'node:assert/strict';+import { execFileSync } from 'node:child_process';+import { readFileSync, readlinkSync, realpathSync } from 'node:fs';+import { isAbsolute, join, relative, sep } from 'node:path';+import { test } from 'node:test';+test('a cached workspace link resolves inside this fresh runner checkout', () => {+ const root = process.cwd();+ const stateRelative = relative(${JSON.stringify(remoteStateRoot)}, root);+ assert.ok(stateRelative && !stateRelative.startsWith('..' + sep) && stateRelative !== '..');+ assert.equal(process.execPath, ${JSON.stringify(nodePath)}, 'the configured runner Node executes the command');+ const commit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();+ const tree = execFileSync('git', ['rev-parse', 'HEAD^{tree}'], { encoding: 'utf8' }).trim();+ const generated = JSON.parse(readFileSync(join(root, 'generated/config.json'), 'utf8'));+ assert.equal(generated.root, root, 'root prepare ran in this fresh checkout and generated a job-local file');+ const shallow = execFileSync('git', ['rev-parse', '--is-shallow-repository'], { encoding: 'utf8' }).trim();+ const count = execFileSync('git', ['rev-list', '--count', 'HEAD'], { encoding: 'utf8' }).trim();+ const history = execFileSync('git', ['log', '--follow', '--format=%H', '--', 'history-renamed.txt'], { encoding: 'utf8' }).trim().split(/\\r?\\n/u);+ assert.equal(shallow, 'false', 'the cache contains full candidate history');+ assert.equal(count, '3', 'the cache preserves the complete selected history');+ assert.ok(history.includes(${JSON.stringify(historyBaseCommit)}), 'cached history follows the original filename through the rename');+ const committed = execFileSync('git', ['show', 'HEAD:packages/runner-fixture-dep/witness.txt'], { encoding: 'utf8' });+ assert.equal(readFileSync('node_modules/.runner-cache-witness', 'utf8'), committed);+ const link = readlinkSync('node_modules/runner-fixture-dep');+ assert.equal(isAbsolute(link), false, 'the cached workspace symlink stays relative');+ const target = realpathSync(join(root, 'node_modules/runner-fixture-dep'));+ assert.equal(target, join(root, 'packages/runner-fixture-dep'));+ const targetRelative = relative(root, target);+ assert.ok(targetRelative && !targetRelative.startsWith('..' + sep) && targetRelative !== '..');+ console.log('RUNNER_CACHE_FACT ' + JSON.stringify({ root, link, target, commit, tree, shallow, count, history, generatedRoot: generated.root }));+});+`;+ writeFileSync(join(repo, 'runner-cache-probe.test.js'), probe);+}++/** Run a gate command through its real lease and return the profile/result emitted by the API child. */- function runThroughGate(repo, env, command, { browser = true, item = '663', kind = 'check' } = {}) {++function runThroughGate(repo, env, command, { browser = true, item = '663', kind = 'check', landing = false } = {}) {+ const gateUrl = new URL('../src/gate.js', import.meta.url).href;+ const script = `const { runProfiledShell, withGateSlot } = await import(${JSON.stringify(gateUrl)});- const result = await withGateSlot(${JSON.stringify(repo)}, lease => runProfiledShell(${JSON.stringify(repo)}, ${JSON.stringify(command)}, { gateLease: lease }),- { browser: ${browser}, item: ${JSON.stringify(item)}, kind: ${JSON.stringify(kind)}, agent: 'runner-fixture' });++const result = await withGateSlot(${JSON.stringify(repo)}, lease => runProfiledShell(${JSON.stringify(repo)}, ${JSON.stringify(command)}, { gateLease: lease, landing: ${landing} }),++ { browser: ${browser}, item: ${JSON.stringify(item)}, kind: ${JSON.stringify(kind)}, landing: ${landing}, agent: 'runner-fixture' });+process.stdout.write(result.output);+process.stdout.write('PULLBOARD_RUN_RESULT ' + JSON.stringify({ isGreen: result.isGreen, runner: result.profile.executionRunner, profile: result.profile }) + '\\n');+process.exitCode = result.isGreen ? 0 : 1;+`;+ return runFixtureChild(process.execPath, ['--input-type=module', '-e', script], {+ cwd: repo, env, encoding: 'utf8',+ });+}++/** Parse the bounded final API line without rewriting the command's raw TAP output. */+function gateResult(stdout) {+ const line = stdout.split(/\r?\n/u).findLast(value => value.startsWith('PULLBOARD_RUN_RESULT '));+ assert.ok(line, stdout);+ return JSON.parse(line.slice('PULLBOARD_RUN_RESULT '.length));+}++/** Include bounded command output when a remote fixture assertion fails. */+function fixtureResultContext(result) {+ return `${result.context}\nstdout tail:\n${String(result.stdout ?? '').slice(-4_000)}\nstderr tail:\n${String(result.stderr ?? '').slice(-4_000)}`;+}++/** Read the remote machine's live gate holders without changing its shared admission state. */+function readRemoteGateHolders(file) {+ const db = new DatabaseSync(file, { readOnly: true });+ try {++ db.exec('PRAGMA busy_timeout = 10000');+ return db.prepare("SELECT token, pid, agent, browser, item, kind FROM holder WHERE name = 'gate'").all();+ } finally { db.close(); }+}++/** Wait for a marker from an external queue observer, with a ceiling for a broken fixture. */+async function waitForMarker(path) {+ if (existsSync(path)) return;+ const watcher = watch(dirname(path), { persistent: false });+ let timer;+ try {+ const changed = new Promise((resolve, reject) => {+ const check = (_event, filename) => {+ if ((filename === null || String(filename) === basename(path)) && existsSync(path)) resolve();+ };+ watcher.on('change', check);+ watcher.once('error', reject);+ check('rename', basename(path));+ });+ if (existsSync(path)) return;+ await Promise.race([changed, new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error(`fixture marker did not arrive: ${path}`)), 20_000); // budget: hang ceiling for the queue-to-parent handoff.+ })]);+ } finally { clearTimeout(timer); watcher.close(); }+}++/** Poll a concrete process/resource state; the deadline only bounds a broken cleanup handshake. */+async function waitForCondition(check, label) {+ const deadline = Date.now() + 20_000;+ while (!check()) {+ if (Date.now() >= deadline) throw new Error(`fixture cleanup state did not arrive: ${label}`);+ await new Promise(resolve => setTimeout(resolve, 20)); // budget: polling interval for an observable cleanup condition.+ }+}++/** Check exact PID presence without signalling or treating permission denial as absence. */+function processIsAlive(pid) {+ try { process.kill(pid, 0); return true; }+ catch (error) {+ if (error.code === 'ESRCH') return false;+ if (error.code === 'EPERM') return true;+ throw error;+ }+}++/** Wait for the stand-in to record a particular invocation count, not for elapsed time. */+async function waitForRequestCount(path, count) {+ if (existsSync(path) && readFileSync(path, 'utf8').trim().split('\n').length >= count) return;+ const watcher = watch(dirname(path), { persistent: false });+ let timer;+ try {+ const hasCount = () => existsSync(path) && readFileSync(path, 'utf8').trim().split('\n').length >= count;+ const changed = new Promise((resolve, reject) => {+ const check = (_event, filename) => {+ if ((filename === null || String(filename) === basename(path)) && hasCount()) resolve();+ };+ watcher.on('change', check);+ watcher.once('error', reject);+ check('change', basename(path));+ });+ if (hasCount()) return;+ await Promise.race([changed, new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error(`runner request ${count} did not arrive`)), 20_000); // budget: hang ceiling for the fake SSH request handshake.+ })]);+ } finally { clearTimeout(timer); watcher.close(); }+}++/** Start an API child that requeues only an incomplete runner transport on its original ticket. */+function startQueueController(repo, env, command, { item, queueMarker, firstItem = 'retry-first', remote = true } = {}) {+ const gateUrl = new URL('../src/gate.js', import.meta.url).href;+ const script = `import { writeFileSync } from 'node:fs';+const { runProfiledShell, withGateSlot } = await import(${JSON.stringify(gateUrl)});+const root = ${JSON.stringify(repo)};+const command = ${JSON.stringify(command)};+const queueMarker = ${JSON.stringify(queueMarker)};+const firstItem = ${JSON.stringify(firstItem)};+const result = await withGateSlot(root, async lease => {+ const run = await runProfiledShell(root, command, { gateLease: lease });+ process.stdout.write(run.output);+ process.stdout.write('PULLBOARD_RUN_RESULT ' + JSON.stringify({ isGreen: run.isGreen, runner: run.profile.executionRunner }) + '\\n');+ return run;+},+ { browser: true, remote: ${remote}, item: ${JSON.stringify(item)}, kind: 'runner-retry-test', agent: ${JSON.stringify(item)},+ onWait(state) {+ const rows = state.line ?? [];+ if (queueMarker && rows.some(row => row.item === ${JSON.stringify(item)}) && (firstItem === null || rows.some(row => row.item === firstItem))) {+ writeFileSync(${JSON.stringify(queueMarker)}, 'both retry tickets are queued\\n');+ }+ }+});+process.exitCode = result.isGreen ? 0 : 1;+`;+ return startFixtureChild(process.execPath, ['--input-type=module', '-e', script], {+ cwd: repo, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'],+ });+}++/** Observe a running fixture child without hiding stdout, stderr, or its exit status. */+function observe(child) {+ let stdout = '', stderr = '';+ child.stdout.setEncoding('utf8').on('data', part => { stdout += part; });+ child.stderr.setEncoding('utf8').on('data', part => { stderr += part; });+ const closed = once(child, 'close').then(([status, signal]) => ({ status, signal, stdout, stderr }));+ return { child, closed };+}++test('a queued run executes on a registered runner and its result comes back [C7]', async (t) => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-')));+ TEMP.push(dir);+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const home = join(dir, 'home');+ const machineHome = join(home, '.pullboard');+ const remoteHome = join(dir, 'worker-home');+ const remoteStateRoot = join(remoteHome, '.pullboard-runner');+ const remoteMachineHome = join(remoteHome, '.pullboard');+ const repo = join(dir, 'repo');+ const worker = join(dir, 'second-machine');+ const bin = join(dir, 'bin');+ const requests = join(dir, 'ssh-requests.jsonl');+ for (const folder of [repo, worker, bin, home, remoteHome, remoteStateRoot, remoteMachineHome, machineHome]) mkdirSync(folder, { recursive: true });+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 1 }));+ const env = {+ ...process.env,+ HOME: home,+ PULLBOARD_HOME: home,+ PULLBOARD_MACHINE_HOME: machineHome,+ PULLBOARD_GATE_SLOT_HELD: '1',+ PULLBOARD_GATE_SLOT_POOL: 'caller-pool-marker',+ PULLBOARD_GATE_SLOT_TOKEN: 'caller-token-marker',+ PULLBOARD_BROWSER_SLOT_HELD: '1',+ PULLBOARD_RUNNER_FIXTURE_SECRET: SECRET,+ SSH_AUTH_SOCK: join(dir, 'must-not-forward.sock'),+ PATH: `${bin}:${process.env.PATH}`,+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Runner Fixture',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Runner Fixture',+ GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });+ assert.equal(initialized.status, 0, initialized.context);+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));+ writeFileSync(join(repo, 'tracked.txt'), 'committed runner source\n');+ writeFileSync(join(repo, 'history-original.txt'), 'committed history witness\n');+ writeFileSync(join(repo, '.gitignore'), '.env\n');+ git(repo, env, 'add', '.gitignore', 'pullboard.json', 'tracked.txt', 'history-original.txt');+ git(repo, env, 'commit', '-q', '-m', 'test: prepare registered runner fixture');+ const historyBaseCommit = git(repo, env, 'rev-parse', 'HEAD');+ git(repo, env, 'mv', 'history-original.txt', 'history-renamed.txt');+ git(repo, env, 'commit', '-q', '-m', 'test: preserve renamed runner history witness');+ writeFileSync(join(repo, '.env'), SECRET);+ const commit = git(repo, env, 'rev-parse', 'HEAD');+ const tree = git(repo, env, 'rev-parse', 'HEAD^{tree}');+ assert.equal(git(repo, env, 'status', '--porcelain'), '', 'the ignored secret is not a dirty tracked change');++ const ssh = installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests });+ assert.ok(existsSync(ssh));+ writeProbe(repo, { remoteStateRoot, remoteMachineHome, sourceHome: home, sourceMachineHome: machineHome, historyBaseCommit,+ callerPool: 'caller-pool-marker', callerToken: 'caller-token-marker' });+ git(repo, env, 'add', 'runner-probe.test.js');+ git(repo, env, 'commit', '-q', '-m', 'test: add remote source probe [C7]');+ const selectedCommit = git(repo, env, 'rev-parse', 'HEAD');+ const selectedTree = git(repo, env, 'rev-parse', 'HEAD^{tree}');++ // This is the first behavior checked: on the old implementation the real CLI rejects `runner add`+ // before any new runner module/import is reached, giving a meaningful old-source red.+ const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '1', '--browser', '1', '--json');+ assert.equal(added.status, 0, added.context);+ const resources = cli(repo, env, 'resources', '--json');+ assert.equal(resources.status, 0, resources.context);+ const listed = JSON.parse(resources.stdout);+ assert.ok(listed.runners?.some(entry => entry.host === HOST && entry.slots === 1 && entry.browser === 1), resources.stdout);++ const previousHome = process.env.PULLBOARD_HOME;+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_HOME = home;+ process.env.PULLBOARD_MACHINE_HOME = machineHome;+ let held;+ try {+ held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,+ agent: 'fixture-local-holder', item: 'runner-local-holder', kind: 'force-registered-runner' });- const successful = runThroughGate(repo, env, 'node --test --test-reporter=tap runner-probe.test.js');++ const successful = runThroughGate(repo, env, 'node --test --test-reporter=tap runner-probe.test.js', { landing: true });+ assert.equal(successful.status, 0, fixtureResultContext(successful));+ assert.match(successful.stdout, /TAP version 13/);+ assert.match(successful.stdout, /RUNNER_FACT /);+ const fact = JSON.parse(/RUNNER_FACT (\{[^\n]+\})/u.exec(successful.stdout)?.[1] ?? 'null');+ assert.equal(fact.commit, selectedCommit);+ assert.equal(fact.tree, selectedTree);++ assert.equal(fact.landing, '1', 'the remote landing command receives the trusted landing marker');+ assert.notEqual(fact.cwd, repo);+ const remotePath = relative(remoteStateRoot, fact.cwd);+ assert.ok(remotePath && !remotePath.startsWith('..' + sep) && remotePath !== '..');+ assert.ok(fact.home.startsWith(fact.cwd.slice(0, fact.cwd.indexOf('/checkout'))));+ assert.notEqual(fact.gatePool, 'caller-pool-marker');+ assert.notEqual(fact.gateToken, 'caller-token-marker');+ assert.equal(fact.browser, '1');+ const result = gateResult(successful.stdout);+ assert.equal(result.isGreen, true);+ assert.equal(result.runner, HOST);+ assert.equal(result.profile.executionRunner, HOST);+ assert.equal(result.profile.tests.length, 1, 'TAP results are retained in the ordinary profile');+ const source = result.profile.executionSource;+ assert.equal(source.commit, selectedCommit);+ assert.equal(source.tree, selectedTree);+ assert.equal(source.tooling.name, 'pullboard');+ assert.equal(source.tooling.kind, 'git-checkout');+ assert.match(source.tooling.sha256, /^[a-f0-9]{64}$/u);+ assert.notEqual(source.tooling.commit, selectedCommit, 'the tooling checkout has provenance separate from the tiny fixture project');+ const request = JSON.parse(readFileSync(requests, 'utf8').trim().split('\n')[0]);+ assert.equal(request.host, HOST);+ assert.equal(request.framed, true);+ assert.equal(request.remoteCommandPresent, true);+ for (const option of ['-T', 'BatchMode=yes', 'ForwardAgent=no', 'ClearAllForwardings=yes', 'SendEnv=-*',+ 'ConnectTimeout=10', 'ServerAliveInterval=10', 'ServerAliveCountMax=3']) {+ assert.ok(request.options.includes(option), `SSH includes ${option}`);+ }+ assert.equal(request.remoteHasSecret, false);+ assert.equal(request.remoteHasLocalPath, false);+ assert.equal(request.remoteHasSourceHome, false);+ assert.equal(request.remoteHasSourceMachineHome, false);+ assert.ok(request.stdinBytes > 0, 'the exact commit objects arrived through binary stdin');+ assert.equal(request.secretInLocalSshEnv, false);+ assert.equal(request.localPoolMarkerInLocalSshEnv, false);+ assert.equal(request.localHeldMarkerInLocalSshEnv, false);+ assert.equal(request.localTokenMarkerInLocalSshEnv, false);+ assert.equal(request.localMachineHomeInSshEnv, false);+ assert.doesNotMatch(successful.stdout + successful.stderr, new RegExp(SECRET, 'u'));+- const red = runThroughGate(repo, env, "node -e 'process.stdout.write(\"RUNNER_EXIT_7\\n\"); process.exit(7)'");++ const red = runThroughGate(repo, env, "node -e 'if (process.env.PULLBOARD_LANDING_RUN !== \"0\") process.exit(9); process.stdout.write(\"RUNNER_EXIT_7\\n\"); process.exit(7)'");+ assert.equal(red.status, 1, fixtureResultContext(red));+ assert.match(red.stdout, /RUNNER_EXIT_7/);+ const redResult = gateResult(red.stdout);+ assert.equal(redResult.isGreen, false);+ assert.equal(redResult.runner, HOST);+ const callsAfterExit7 = readFileSync(requests, 'utf8').trim().split('\n').length;+ assert.equal(callsAfterExit7, 2, 'a complete exit-7 receipt is a test failure, not a dropped-run retry');++ // The secret is absent from HEAD but remains in a reachable commit; full-history scanning must+ // refuse before transferring those historical objects to the registered worker.+ git(repo, env, 'add', '-f', '.env');+ git(repo, env, 'commit', '-q', '-m', 'test: add temporary historical private file');+ git(repo, env, 'rm', '--cached', '.env');+ git(repo, env, 'commit', '-q', '-m', 'test: remove current private file but retain history');+ assert.doesNotMatch(git(repo, env, 'ls-tree', '-r', '--name-only', 'HEAD'), /(?:^|\n)\.env(?:$|\n)/u);+ assert.equal(readFileSync(join(repo, '.env'), 'utf8'), SECRET, 'the ignored local fixture remains private');+ const historicalRed = runThroughGate(repo, env, 'node -e "process.stdout.write(\'HISTORICAL_SECRET_SCAN_REACHED\\n\')"');+ assert.equal(historicalRed.status, 1, fixtureResultContext(historicalRed));+ assert.match(historicalRed.stdout + historicalRed.stderr, /RUNNER_SECRET/u);+ assert.doesNotMatch(historicalRed.stdout + historicalRed.stderr, new RegExp(SECRET, 'u'));+ assert.equal(readFileSync(requests, 'utf8').trim().split('\n').length, callsAfterExit7,+ 'historical secret scanning refuses before opening an SSH request');++ assert.equal(commit.length, 40);+ assert.equal(tree.length, 40);+ } finally {+ if (held) held.release();+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;+ }+});++test('a queued run executes on a registered runner and its result comes back [C7] (dropped runner returns ticket before later work)', async (t) => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-retry-')));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const home = join(dir, 'home');+ const machineHome = join(home, '.pullboard');+ const remoteHome = join(dir, 'worker-home');+ const remoteMachineHome = join(remoteHome, '.pullboard');+ const repo = join(dir, 'repo');+ const worker = join(dir, 'second-machine');+ const bin = join(dir, 'bin');+ const requests = join(dir, 'ssh-requests.jsonl');+ const queueReady = join(dir, 'both-waiters-queued');+ const firstStarted = join(dir, 'first-started');+ const releaseFirst = join(dir, 'release-first');+ const olderStarted = join(dir, 'older-local-started');+ const olderQueued = join(dir, 'older-local-queued');+ const order = join(dir, 'execution-order');+ for (const folder of [repo, worker, bin, home, remoteHome, remoteMachineHome, machineHome]) mkdirSync(folder, { recursive: true });+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 1 }));+ const env = {+ ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,+ PULLBOARD_RUNNER_FIXTURE_SECRET: SECRET, SSH_AUTH_SOCK: join(dir, 'must-not-forward.sock'),+ PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Runner Fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Runner Fixture', GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });+ assert.equal(initialized.status, 0, initialized.context);+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));+ writeFileSync(join(repo, 'tracked.txt'), 'committed runner source\n');+ git(repo, env, 'add', 'pullboard.json', 'tracked.txt');+ git(repo, env, 'commit', '-q', '-m', 'test: prepare dropped-runner fixture');+ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests, dropFirst: true });+ const host = `${HOST}-drop`;+ const added = cli(repo, env, 'runner', 'add', host, '--slots', '1', '--browser', '1', '--json');+ assert.equal(added.status, 0, added.context);++ const previousHome = process.env.PULLBOARD_HOME;+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_HOME = home;+ process.env.PULLBOARD_MACHINE_HOME = machineHome;+ let held;+ let first;+ let second;+ try {+ held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,+ agent: 'fixture-local-holder', item: 'local-holder', kind: 'controlled-hold' });+ const olderCode = `require('node:fs').appendFileSync(${JSON.stringify(order)}, 'older-local\\n'); require('node:fs').writeFileSync(${JSON.stringify(olderStarted)}, 'started\\n');`;+ const firstCode = `const fs=require('node:fs'); const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));+(async()=>{ fs.writeFileSync(${JSON.stringify(firstStarted)}, 'started\\n'); fs.appendFileSync(${JSON.stringify(order)}, 'retry-first\\n');+while(!fs.existsSync(${JSON.stringify(releaseFirst)})) await sleep(5); })().catch(error=>{console.error(error);process.exitCode=2});`;+ second = observe(startQueueController(repo, env, `node -e ${shellQuote(olderCode)}`,+ { item: 'older-local', queueMarker: olderQueued, firstItem: null, remote: false }));+ await waitForMarker(olderQueued);+ first = observe(startQueueController(repo, env, `node -e ${shellQuote(firstCode)}`,+ { item: 'retry-first', queueMarker: queueReady, firstItem: 'older-local' }));+ await waitForRequestCount(requests, 1);+ const dropped = JSON.parse(readFileSync(requests, 'utf8').trim().split('\n')[0]);+ assert.equal(dropped.dropped, true, 'the first SSH connection drops without a completion receipt');+ await waitForMarker(queueReady);+ held.release();+ held = null;+ await waitForMarker(firstStarted);+ assert.equal(readFileSync(order, 'utf8'), 'retry-first\n', 'the returned remote ticket jumps ahead of the older local-only waiter');+ writeFileSync(releaseFirst, 'continue\n');+ const [firstResult, secondResult] = await Promise.all([first.closed, second.closed]);+ assert.equal(firstResult.status, 0, `${firstResult.stdout}${firstResult.stderr}`);+ assert.equal(secondResult.status, 0, `${secondResult.stdout}${secondResult.stderr}`);+ assert.equal(readFileSync(order, 'utf8'), 'retry-first\nolder-local\n');+ assert.ok(existsSync(olderStarted), 'the older local-only waiter runs after the returned remote ticket');+ assert.equal(readFileSync(requests, 'utf8').trim().split('\n').length, 1,+ 'the quarantined host is not contacted again for the front-of-queue local retry');+ const retried = gateResult(firstResult.stdout);+ assert.equal(retried.isGreen, true, `${firstResult.stdout}${firstResult.stderr}`);+ assert.notEqual(retried.runner, host, 'the retried command completes after the failed runner is quarantined');+ } finally {+ if (held) held.release();+ writeFileSync(releaseFirst, 'cleanup-release\n');+ for (const child of [first?.child, second?.child]) {+ if (child && child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');+ }+ await Promise.all([first?.closed, second?.closed].filter(Boolean));+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;+ }+});++test('a queued run executes on a registered runner and its result comes back [C7] (disconnect drains an npm setup child before releasing its gate holder)', async (t) => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-setup-disconnect-')));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const home = join(dir, 'home');+ const machineHome = join(home, '.pullboard');+ const remoteHome = join(dir, 'worker-home');+ const remoteMachineHome = join(remoteHome, '.pullboard');+ const repo = join(dir, 'repo');+ const packageDirectory = join(repo, 'packages', 'setup-fixture-dep');+ const worker = join(dir, 'second-machine');+ const bin = join(dir, 'bin');+ const requests = join(dir, 'ssh-requests.jsonl');+ const setupReady = join(dir, 'setup-ready');+ const setupPid = join(dir, 'setup-pid');+ const setupTerm = join(dir, 'setup-term');+ const releaseSetup = join(dir, 'release-setup');+ const setupGone = join(dir, 'setup-gone');+ const remoteDatabase = join(remoteMachineHome, 'resources.sqlite');+ for (const folder of [repo, worker, bin, home, machineHome, remoteHome, remoteMachineHome, packageDirectory]) mkdirSync(folder, { recursive: true });+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 1 }));+ const env = {+ ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,+ PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Runner Setup Fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Runner Setup Fixture', GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });+ assert.equal(initialized.status, 0, initialized.context);+ writeFileSync(join(repo, '.gitignore'), 'node_modules/\n');+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));+ writeFileSync(join(repo, 'package.json'), JSON.stringify({+ name: 'runner-setup-fixture', version: '1.0.0', private: true, type: 'module',+ workspaces: ['packages/setup-fixture-dep'], dependencies: { 'setup-fixture-dep': '1.0.0' },+ }, null, 2) + '\n');+ writeFileSync(join(packageDirectory, 'package.json'), JSON.stringify({+ name: 'setup-fixture-dep', version: '1.0.0', scripts: { postinstall: 'node postinstall.js' },+ }, null, 2) + '\n');+ writeFileSync(join(packageDirectory, 'witness.txt'), 'setup fixture package source\n');+ writeFileSync(join(packageDirectory, 'postinstall.js'), `import { existsSync, watch, writeFileSync } from 'node:fs';+import { basename, dirname } from 'node:path';+const ready = ${JSON.stringify(setupReady)};+const pidFile = ${JSON.stringify(setupPid)};+const term = ${JSON.stringify(setupTerm)};+const release = ${JSON.stringify(releaseSetup)};+const gone = ${JSON.stringify(setupGone)};+const waitForRelease = new Promise((resolve, reject) => {+ if (existsSync(release)) return resolve();+ const watcher = watch(dirname(release), { persistent: false });+ let timer;+ const finish = error => { clearTimeout(timer); watcher.close(); error ? reject(error) : resolve(); };+ const check = (_event, filename) => {+ if ((filename === null || String(filename) === basename(release)) && existsSync(release)) finish();+ };+ watcher.on('change', check);+ watcher.once('error', finish);+ timer = setTimeout(() => finish(new Error('postinstall release hang ceiling exceeded')), 20_000); // budget: bound a broken fixture handshake.+ check('rename', basename(release));+});+let stopping = false;+process.on('SIGTERM', () => {+ if (stopping) return;+ stopping = true;+ writeFileSync(term, 'term received\\n');+ waitForRelease.then(() => { writeFileSync(gone, 'setup child exited\\n'); process.exit(0); }, error => {+ console.error(error.message); process.exit(2);+ });+});+writeFileSync(pidFile, String(process.pid) + '\\n');+writeFileSync(ready, 'setup started\\n');+`);+ const npmPathResult = runFixtureChild('which', ['npm'], { cwd: repo, env, encoding: 'utf8' });+ assert.equal(npmPathResult.status, 0, npmPathResult.context);+ const packageLock = runFixtureChild(npmPathResult.stdout.trim(), ['install', '--package-lock-only', '--ignore-scripts', '--offline'], {+ cwd: repo, env, encoding: 'utf8',+ });+ assert.equal(packageLock.status, 0, packageLock.context);+ git(repo, env, 'add', '.gitignore', 'pullboard.json', 'package.json', 'package-lock.json', 'packages/setup-fixture-dep');+ git(repo, env, 'commit', '-q', '-m', 'test: prepare disconnect during runner setup');++ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests, dropAfterMarker: setupReady });+ const host = `${HOST}-setup`;+ const added = cli(repo, env, 'runner', 'add', host, '--slots', '1', '--browser', '1', '--json');+ assert.equal(added.status, 0, added.context);++ const previousHome = process.env.PULLBOARD_HOME;+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_HOME = home;+ process.env.PULLBOARD_MACHINE_HOME = machineHome;+ let held;+ let run;+ try {+ held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,+ agent: 'fixture-local-holder', item: 'setup-local-holder', kind: 'force-registered-runner' });+ const code = `process.stdout.write('SETUP_RETRY_LOCAL\\n')`;+ run = observe(startQueueController(repo, env, `node -e ${shellQuote(code)}`,+ { item: 'setup-disconnect', firstItem: null }));++ await waitForMarker(setupReady);+ const childPid = Number(readFileSync(setupPid, 'utf8').trim());+ assert.ok(Number.isSafeInteger(childPid) && childPid > 0);+ await waitForMarker(setupTerm);+ const liveHolders = readRemoteGateHolders(remoteDatabase);+ assert.equal(liveHolders.length, 1, 'the remote gate holder remains while its setup child is handling termination');+ assert.ok(liveHolders[0].agent.startsWith('pullboard-ssh-'));+ assert.equal(liveHolders[0].item, 'setup-disconnect');+ assert.equal(liveHolders[0].kind, 'runner-retry-test');+ assert.equal(liveHolders[0].browser, 1);+ assert.notEqual(liveHolders[0].pid, childPid, 'the holder belongs to the worker, not its npm setup child');+ assert.equal(existsSync(setupGone), false, 'the setup child has not exited before its release handshake');++ held.release();+ held = null;+ writeFileSync(releaseSetup, 'release setup child\\n');+ await waitForMarker(setupGone);+ const result = await run.closed;+ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);+ assert.match(result.stdout, /SETUP_RETRY_LOCAL/u, 'the transport drop requeues the run onto the local slot');+ assert.equal(gateResult(result.stdout).isGreen, true);+ assert.equal(readFileSync(requests, 'utf8').trim().split('\n').length, 1);+ const request = JSON.parse(readFileSync(requests, 'utf8').trim().split('\n')[0]);+ assert.equal(request.droppedAfterSetup, true, 'the stand-in drops the connection after npm setup actually starts');+ assert.equal(request.workerStarted, true);+ assert.notEqual(request.code, 0, 'the worker exits without a complete success receipt after HUP');+ assert.equal(readRemoteGateHolders(remoteDatabase).length, 0, 'the remote holder is released after the owned setup child exits');+ } finally {+ if (held) held.release();+ writeFileSync(releaseSetup, 'cleanup release\\n');+ if (run?.child && run.child.exitCode === null && run.child.signalCode === null) run.child.kill('SIGTERM');+ await run?.closed;+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;+ }+});++test('a queued run executes on a registered runner and its result comes back [C7] (cached source and npm content retain fresh checkout lifecycles)', async (t) => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-cache-')));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const home = join(dir, 'home');+ const machineHome = join(home, '.pullboard');+ const remoteHome = join(dir, 'worker-home');+ const remoteStateRoot = join(remoteHome, 'private-runner-root');+ const remoteMachineHome = join(remoteHome, '.pullboard');+ const repo = join(dir, 'repo');+ const worker = join(dir, 'second-machine');+ const bin = join(dir, 'bin');+ const requests = join(dir, 'ssh-requests.jsonl');+ const installWitnesses = join(dir, 'remote-install-witnesses');+ const packageDirectory = join(repo, 'packages', 'runner-fixture-dep');+ for (const folder of [repo, worker, bin, home, machineHome, remoteHome, remoteStateRoot, remoteMachineHome, packageDirectory]) {+ mkdirSync(folder, { recursive: true });+ }+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 1 }));+ const env = {+ ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,+ PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Runner Cache Fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Runner Cache Fixture', GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });+ assert.equal(initialized.status, 0, initialized.context);+ writeFileSync(join(repo, '.gitignore'), 'node_modules/\ngenerated/\n');+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));+ writeFileSync(join(repo, 'package.json'), JSON.stringify({+ name: 'runner-cache-fixture', version: '1.0.0', private: true, type: 'module',+ scripts: { prepare: 'node prepare.js' },+ workspaces: ['packages/runner-fixture-dep'], dependencies: { 'runner-fixture-dep': '1.0.0' },+ }, null, 2) + '\n');+ writeFileSync(join(repo, 'prepare.js'), `import { mkdirSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+mkdirSync('generated', { recursive: true });+writeFileSync('generated/config.json', JSON.stringify({ root: resolve('.') }) + '\\n');+`);+ writeFileSync(join(packageDirectory, 'package.json'), JSON.stringify({+ name: 'runner-fixture-dep', version: '1.0.0', type: 'module', scripts: { postinstall: 'node postinstall.js' },+ }, null, 2) + '\n');+ writeFileSync(join(packageDirectory, 'witness.txt'), 'committed workspace witness\n');+ writeFileSync(join(repo, 'history-original.txt'), 'committed cache history witness\n');+ writeFileSync(join(packageDirectory, 'postinstall.js'), `import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+const prefix = process.env.INIT_CWD;+if (!prefix) throw new Error('npm did not provide the install root');+writeFileSync(join(prefix, 'node_modules', '.runner-cache-witness'), readFileSync(new URL('./witness.txt', import.meta.url)));+appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');+`);+ const npmPathResult = runFixtureChild('which', ['npm'], { cwd: repo, env, encoding: 'utf8' });+ assert.equal(npmPathResult.status, 0, npmPathResult.context);+ const npmPath = npmPathResult.stdout.trim();+ const lock = runFixtureChild(npmPath, ['install', '--package-lock-only', '--ignore-scripts', '--offline'], {+ cwd: repo, env, encoding: 'utf8',+ });+ assert.equal(lock.status, 0, lock.context);+ git(repo, env, 'add', '.gitignore', 'pullboard.json', 'package.json', 'prepare.js', 'package-lock.json', 'packages/runner-fixture-dep', 'history-original.txt');+ git(repo, env, 'commit', '-q', '-m', 'test: prepare cached local workspace dependency');+ const historyBaseCommit = git(repo, env, 'rev-parse', 'HEAD');+ git(repo, env, 'mv', 'history-original.txt', 'history-renamed.txt');+ git(repo, env, 'commit', '-q', '-m', 'test: preserve cached runner history witness');+ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests, nodeCommand: process.execPath });+ const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '1', '--browser', '1', '--node', process.execPath,+ '--root', remoteStateRoot, '--json');+ assert.equal(added.status, 0, added.context);+ const registered = JSON.parse(added.stdout);+ assert.equal(registered.runner.node, process.execPath);+ assert.equal(registered.runner.root, remoteStateRoot);++ const previousHome = process.env.PULLBOARD_HOME;+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_HOME = home;+ process.env.PULLBOARD_MACHINE_HOME = machineHome;+ let held;+ try {+ held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,+ agent: 'fixture-cache-local-holder', item: 'cache-local-holder', kind: 'force-registered-runner' });+ const command = 'node --test --test-reporter=tap runner-cache-probe.test.js';+ writeCacheProbe(repo, { remoteStateRoot, nodePath: process.execPath, historyBaseCommit });+ git(repo, env, 'add', 'runner-cache-probe.test.js');+ git(repo, env, 'commit', '-q', '-m', 'test: assert cache symlink stays job-local');+ const cacheCommit = git(repo, env, 'rev-parse', 'HEAD');+ const cacheTree = git(repo, env, 'rev-parse', 'HEAD^{tree}');+ const first = runThroughGate(repo, env, command, { item: 'cache-first' });+ assert.equal(first.status, 0, fixtureResultContext(first));+ const firstFact = JSON.parse(/RUNNER_CACHE_FACT (\{[^\n]+\})/u.exec(first.stdout)?.[1] ?? 'null');+ assert.equal(firstFact.commit, cacheCommit);+ assert.equal(firstFact.tree, cacheTree);+ assert.equal(firstFact.shallow, 'false');+ assert.ok(firstFact.history.includes(historyBaseCommit));+ assert.equal(firstFact.root, firstFact.target.slice(0, firstFact.target.indexOf('/packages/runner-fixture-dep')));+ assert.equal(gateResult(first.stdout).runner, HOST);+ assert.equal(firstFact.generatedRoot, firstFact.root, 'the first fresh checkout ran root prepare');+ assert.equal(readFileSync(installWitnesses, 'utf8'), 'postinstall\n', 'the first fresh checkout runs the committed workspace postinstall');++ const second = runThroughGate(repo, env, command, { item: 'cache-second' });+ assert.equal(second.status, 0, fixtureResultContext(second));+ const secondFact = JSON.parse(/RUNNER_CACHE_FACT (\{[^\n]+\})/u.exec(second.stdout)?.[1] ?? 'null');+ assert.equal(secondFact.commit, cacheCommit);+ assert.equal(secondFact.tree, cacheTree);+ assert.equal(secondFact.shallow, 'false');+ assert.ok(secondFact.history.includes(historyBaseCommit));+ assert.equal(secondFact.generatedRoot, secondFact.root, 'the second fresh checkout reran root prepare');+ assert.equal(gateResult(second.stdout).runner, HOST);+ assert.equal(secondFact.root, secondFact.target.slice(0, secondFact.target.indexOf('/packages/runner-fixture-dep')));+ assert.notEqual(firstFact.root, secondFact.root, 'each run unpacks a fresh checkout');+ assert.equal(git(repo, env, 'rev-parse', 'HEAD'), cacheCommit);+ assert.equal(git(repo, env, 'rev-parse', 'HEAD^{tree}'), cacheTree);+ assert.equal(readFileSync(installWitnesses, 'utf8'), 'postinstall\npostinstall\n', 'the second fresh checkout runs its own workspace postinstall');+ const requestsSeen = readFileSync(requests, 'utf8').trim().split('\n').map(line => JSON.parse(line));+ assert.equal(requestsSeen.length, 2);+ assert.ok(requestsSeen[0].stdinBytes > requestsSeen[1].stdinBytes,+ 'the same candidate sends fewer Git-pack bytes after its first cache import');+ assert.ok(requestsSeen.every(request => request.remoteStartsWithConfiguredNode), 'both remote workers use the configured absolute Node path');+ } finally {+ if (held) held.release();+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;+ }+});++test('a queued run executes on a registered runner and its result comes back [C7] (older resource clients keep local capacity separate)', async (t) => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-old-resource-client-')));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const home = join(dir, 'home');+ const machineHome = join(home, '.pullboard');+ const remoteHome = join(dir, 'worker-home');+ const remoteMachineHome = join(remoteHome, '.pullboard');+ const repo = join(dir, 'repo');+ const worker = join(dir, 'second-machine');+ const bin = join(dir, 'bin');+ const requests = join(dir, 'ssh-requests.jsonl');+ const remoteReady = join(dir, 'remote-ready');+ const releaseRemote = join(dir, 'release-remote');+ const secondBrowserQueued = join(dir, 'second-browser-queued');+ const secondBrowserAcquired = join(dir, 'second-browser-acquired');+ const resourceDatabase = join(machineHome, 'resources.sqlite');+ for (const folder of [repo, worker, bin, home, machineHome, remoteHome, remoteMachineHome]) {+ mkdirSync(folder, { recursive: true });+ }+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 2 }));+ const env = {+ ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,+ PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Legacy Resource Fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Legacy Resource Fixture', GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });+ assert.equal(initialized.status, 0, initialized.context);+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));+ writeFileSync(join(repo, 'tracked.txt'), 'registered runner fixture\n');+ git(repo, env, 'add', 'pullboard.json', 'tracked.txt');+ git(repo, env, 'commit', '-q', '-m', 'test: prepare mixed-version resource fixture');+ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests });+ const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '1', '--browser', '1', '--json');+ assert.equal(added.status, 0, added.context);++ const previousHome = process.env.PULLBOARD_HOME;+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_HOME = home;+ process.env.PULLBOARD_MACHINE_HOME = machineHome;+ let initialBrowser;+ let localBrowser;+ let localCpu;+ let secondBrowser;+ let secondBrowserPromise;+ let remoteRun;+ const inspectCapacity = expectedLocal => {+ const db = new DatabaseSync(resourceDatabase, { readOnly: true });+ try {+ const local = db.prepare("SELECT name, runner, browser FROM holder WHERE name = 'gate'").all();+ const remote = db.prepare('SELECT name, runner, browser FROM holder WHERE runner = ?').all(HOST);+ assert.equal(db.prepare("SELECT capacity FROM resource WHERE name = 'gate'").get()?.capacity, 2);+ assert.equal(db.prepare("SELECT capacity FROM resource WHERE name = 'browser'").get()?.capacity, 1);+ const browserCount = local.filter(holder => holder.browser === 1).length;+ assert.ok(local.length <= 2, 'local gate holders stay within the real SQLite gate capacity');+ assert.ok(browserCount <= 1, 'local browser holders stay within the real SQLite browser capacity');+ assert.equal(local.length, expectedLocal);+ assert.equal(remote.length, 1, 'the remote runner holder remains independent of local capacity');+ assert.equal(remote[0].name, `runner:${HOST}`);+ return { local, remote, browserCount };+ } finally { db.close(); }+ };+ try {+ initialBrowser = await takePreRunnerResource({ name: 'gate', capacity: 2, scope: 'machine', root: repo,+ agent: 'pre-runner-initial-browser', item: 'pre-runner-initial-browser', kind: 'fixture-hold', browser: true });+ const remoteCode = `const fs=require('node:fs'); const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));+(async()=>{ fs.writeFileSync(${JSON.stringify(remoteReady)}, 'ready\\n'); while(!fs.existsSync(${JSON.stringify(releaseRemote)})) await sleep(5); })().catch(error=>{console.error(error);process.exitCode=2});`;+ remoteRun = observe(startQueueController(repo, env, `node -e ${shellQuote(remoteCode)}`,+ { item: 'remote-capacity-holder', queueMarker: null, firstItem: null }));+ await waitForMarker(remoteReady);++ const heldBesideRemote = inspectCapacity(1);+ assert.equal(heldBesideRemote.browserCount, 1, 'the remote lease leaves the legacy local browser holder unchanged');++ initialBrowser.release();+ initialBrowser = null;+ localBrowser = await takePreRunnerResource({ name: 'gate', capacity: 2, scope: 'machine', root: repo,+ agent: 'pre-runner-browser-one', item: 'pre-runner-browser-one', kind: 'fixture-browser', browser: true });+ localCpu = await takePreRunnerResource({ name: 'gate', capacity: 2, scope: 'machine', root: repo,+ agent: 'pre-runner-cpu', item: 'pre-runner-cpu', kind: 'fixture-cpu' });+ secondBrowserPromise = takePreRunnerResource({ name: 'gate', capacity: 2, scope: 'machine', root: repo,+ agent: 'pre-runner-browser-two', item: 'pre-runner-browser-two', kind: 'fixture-browser', browser: true,+ onWait(state) {+ if (state.line?.some(waiter => waiter.item === 'pre-runner-browser-two')) {+ writeFileSync(secondBrowserQueued, 'queued\n');+ }+ },+ }).then(lease => {+ secondBrowser = lease;+ writeFileSync(secondBrowserAcquired, 'acquired\n');+ return lease;+ });+ await waitForMarker(secondBrowserQueued);+ assert.equal(existsSync(secondBrowserAcquired), false, 'a second local browser waits even while its first slot is held');++ const duringRemote = listPreRunnerResources({ scope: 'machine', root: repo });+ const localGate = duringRemote.find(resource => resource.name === 'gate');+ const runnerResource = duringRemote.find(resource => resource.name === `runner:${HOST}`);+ assert.equal(localGate.holders.length, 2, 'the old API admits one local browser and one local CPU lease');+ assert.equal(localGate.holders.filter(holder => holder.browser).length, 1);+ assert.equal(runnerResource.holders.length, 1, 'the registered runner remains held independently');+ assert.equal(inspectCapacity(2).browserCount, 1);+ assert.equal(existsSync(secondBrowserAcquired), false, 'local browser capacity remains one');++ localCpu.release();+ localCpu = null;+ localBrowser.release();+ localBrowser = null;+ await waitForMarker(secondBrowserAcquired);+ secondBrowser = await secondBrowserPromise;+ const afterHandoff = listPreRunnerResources({ scope: 'machine', root: repo });+ assert.equal(afterHandoff.find(resource => resource.name === 'gate').holders.length, 1);+ assert.equal(afterHandoff.find(resource => resource.name === `runner:${HOST}`).holders.length, 1,+ 'the remote run is still live while the old API hands off the local browser slot');+ assert.equal(inspectCapacity(1).browserCount, 1);+ secondBrowser.release();+ secondBrowser = null;+ writeFileSync(releaseRemote, 'release\n');+ const completed = await remoteRun.closed;+ remoteRun = null;+ assert.equal(completed.status, 0, fixtureResultContext(completed));+ assert.equal(gateResult(completed.stdout).runner, HOST);+ } finally {+ for (const lease of [initialBrowser, localBrowser, localCpu, secondBrowser]) lease?.release();+ writeFileSync(releaseRemote, 'cleanup-release\n');+ if (secondBrowserPromise && !secondBrowser) {+ try { secondBrowser = await secondBrowserPromise; secondBrowser.release(); secondBrowser = null; } catch {}+ }+ if (remoteRun) {+ await remoteRun.closed;+ }+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;+ }+});++test('a queued run executes on a registered runner and its result comes back [C7] (parent death drains a detached worker descendant before releasing its lease)', async (t) => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-parent-death-')));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const home = join(dir, 'home');+ const machineHome = join(home, '.pullboard');+ const remoteHome = join(dir, 'worker-home');+ const remoteMachineHome = join(remoteHome, '.pullboard');+ const remoteDatabase = join(remoteMachineHome, 'resources.sqlite');+ const repo = join(dir, 'repo');+ const worker = join(dir, 'second-machine');+ const bin = join(dir, 'bin');+ const requests = join(dir, 'ssh-requests.jsonl');+ const childReady = join(dir, 'detached-child-ready');+ const childPidFile = join(dir, 'detached-child-pid');+ const childTerm = join(dir, 'detached-child-term');+ const releaseChild = join(dir, 'release-detached-child');+ const childGone = join(dir, 'detached-child-gone');+ for (const folder of [repo, worker, bin, home, machineHome, remoteHome, remoteMachineHome]) {+ mkdirSync(folder, { recursive: true });+ }+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 1 }));+ const env = {+ ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,+ PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Parent Death Fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Parent Death Fixture', GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });+ assert.equal(initialized.status, 0, initialized.context);+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));+ writeFileSync(join(repo, 'tracked.txt'), 'parent-death runner fixture\n');+ writeFileSync(join(repo, 'remote-parent-death-launcher.js'), `const { spawn } = require('node:child_process');+const child = spawn(process.execPath, [require.resolve('./remote-detached-child.js'), ...process.argv.slice(2)], {+ detached: true, stdio: 'ignore', env: process.env,+});+child.unref();+setInterval(() => {}, 1_000);+`);+ writeFileSync(join(repo, 'remote-detached-child.js'), `const { existsSync, writeFileSync } = require('node:fs');+const [ready, pidFile, term, release, gone] = process.argv.slice(2);+let handlingTerm = false;+process.on('SIGTERM', () => {+ if (handlingTerm) return;+ handlingTerm = true;+ writeFileSync(term, 'term\\n');+ const wait = setInterval(() => {+ if (!existsSync(release)) return;+ clearInterval(wait);+ writeFileSync(gone, 'gone\\n');+ process.exit(0);+ }, 5);+});+writeFileSync(pidFile, String(process.pid));+writeFileSync(ready, 'ready\\n');+setInterval(() => {}, 1_000);+`);+ git(repo, env, 'add', 'pullboard.json', 'tracked.txt', 'remote-parent-death-launcher.js', 'remote-detached-child.js');+ git(repo, env, 'commit', '-q', '-m', 'test: prepare committed detached-child launchers');+ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests });+ const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '1', '--browser', '1', '--json');+ assert.equal(added.status, 0, added.context);++ const previousHome = process.env.PULLBOARD_HOME;+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_HOME = home;+ process.env.PULLBOARD_MACHINE_HOME = machineHome;+ let localHold;+ let remoteRun;+ let detachedPid;+ let remoteAgent;+ try {+ localHold = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,+ agent: 'parent-death-local-holder', item: 'parent-death-local-holder', kind: 'fixture-hold', browser: true });+ const command = ['node remote-parent-death-launcher.js', ...[childReady, childPidFile, childTerm, releaseChild, childGone].map(shellQuote)].join(' ');+ remoteRun = observe(startQueueController(repo, env, command,+ { item: 'parent-death-remote-holder', queueMarker: null, firstItem: null }));+ await waitForMarker(childReady);+ detachedPid = Number(readFileSync(childPidFile, 'utf8').trim());+ assert.ok(Number.isSafeInteger(detachedPid) && detachedPid > 0);+ assert.notEqual(detachedPid, remoteRun.child.pid, 'the committed launcher owns a separate detached child');+ assert.equal(processIsAlive(detachedPid), true);+ const held = readRemoteGateHolders(remoteDatabase);+ assert.equal(held.length, 1, 'the remote worker keeps its physical gate holder while the launcher is live');+ remoteAgent = held[0].agent;+ assert.match(remoteAgent, /^pullboard-ssh-/u);++ remoteRun.child.kill('SIGTERM');+ await waitForMarker(childTerm);+ assert.equal(processIsAlive(detachedPid), true, 'the detached child remains alive in its controlled TERM handler');+ const duringDrain = readRemoteGateHolders(remoteDatabase);+ assert.equal(duringDrain.length, 1);+ assert.equal(duringDrain[0].agent, remoteAgent, 'the physical runner lease remains held during descendant cleanup');++ writeFileSync(releaseChild, 'release\n');+ await waitForMarker(childGone);+ await waitForCondition(() => !processIsAlive(detachedPid), 'the detached child PID exits');+ await waitForCondition(() => readRemoteGateHolders(remoteDatabase).every(holder => holder.agent !== remoteAgent),+ 'the remote physical gate holder is released after child exit');+ const controller = await remoteRun.closed;+ remoteRun = null;+ assert.equal(controller.signal, 'SIGTERM', 'the owned API controller alone received SIGTERM');+ } finally {+ if (localHold) localHold.release();+ writeFileSync(releaseChild, 'cleanup-release\n');+ if (remoteRun && remoteRun.child.exitCode === null && remoteRun.child.signalCode === null) {+ remoteRun.child.kill('SIGTERM');+ }+ if (detachedPid && processIsAlive(detachedPid)) {+ try { process.kill(detachedPid, 'SIGTERM'); } catch (error) { if (error.code !== 'ESRCH') throw error; }+ }+ if (remoteRun) await remoteRun.closed;+ if (detachedPid) await waitForCondition(() => !processIsAlive(detachedPid), 'fixture detached child cleanup');+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;+ }+});++test('a queued run executes on a registered runner and its result comes back [C7] (unverified cleanup times out as a named red result)', { timeout: 90_000 }, async (t) => { // budget: bounded 30-second remote cleanup timeout plus startup, transport and fixture cleanup ceiling.+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-cleanup-timeout-')));+ const home = join(dir, 'home');+ const machineHome = join(home, '.pullboard');+ const remoteHome = join(dir, 'worker-home');+ const remoteStateRoot = join(remoteHome, '.pullboard-runner');+ const remoteMachineHome = join(remoteHome, '.pullboard');+ const remoteDatabase = join(remoteMachineHome, 'resources.sqlite');+ const repo = join(dir, 'repo');+ const worker = join(dir, 'second-machine');+ const bin = join(dir, 'bin');+ const requests = join(dir, 'ssh-requests.jsonl');+ const bodyRan = join(remoteStateRoot, 'cleanup-timeout-body-ran');++ const starts = join(dir, 'ssh-starts.jsonl');+ let commandChild;+ t.after(async () => {+ if (commandChild && commandChild.exitCode === null && commandChild.signalCode === null) {+ try { process.kill(-commandChild.pid, 'SIGTERM'); }+ catch (error) { if (error.code !== 'ESRCH') t.diagnostic(`fixture process-group cleanup: ${error.message}`); }+ await once(commandChild, 'close').catch(error => t.diagnostic(`fixture child close: ${error.message}`));+ }+ if (existsSync(remoteDatabase)) {+ try { await waitForCondition(() => readRemoteGateHolders(remoteDatabase).length === 0,+ 'fixture remote physical gate holder cleanup'); }+ catch (error) { t.diagnostic(error.message); }+ }+ rmSync(dir, { recursive: true, force: true });+ });+ for (const folder of [repo, worker, bin, home, machineHome, remoteHome, remoteStateRoot, remoteMachineHome]) {+ mkdirSync(folder, { recursive: true });+ }+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 1 }));+ const env = {+ ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,+ PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Runner Cleanup Fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Runner Cleanup Fixture', GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });+ assert.equal(initialized.status, 0, initialized.context);+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'node runner-cleanup-timeout.js' }));+ writeFileSync(join(repo, 'tracked.txt'), 'cleanup timeout fixture\n');+ writeFileSync(join(repo, 'runner-cleanup-timeout.js'), `import { existsSync, mkdirSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+const option = /(?:^|\\s)--import=(?:"([^"]+)"|'([^']+)'|(\\S+))/u.exec(process.env.NODE_OPTIONS || '');+if (!option) throw new Error('runner preload path was not passed to the committed job');+const preload = fileURLToPath(option[1] || option[2] || option[3]);+const runDirectory = dirname(preload);+const journalDirectory = join(runDirectory, 'child-journal');+const runnerRoot = dirname(dirname(runDirectory));+if (!existsSync(journalDirectory)) throw new Error('private child journal is missing');+mkdirSync(runnerRoot, { recursive: true });+writeFileSync(join(journalDirectory, 'overflow'), 'fixture journal overflow\\n');+writeFileSync(join(runnerRoot, 'cleanup-timeout-body-ran'), 'ran\\n');+console.log('RUNNER_CLEANUP_TIMEOUT_BODY_RAN');+`);+ git(repo, env, 'add', 'pullboard.json', 'tracked.txt', 'runner-cleanup-timeout.js');+ git(repo, env, 'commit', '-q', '-m', 'test: prepare runner cleanup timeout fixture');- installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests });++ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests, starts });+ const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '1', '--browser', '1', '--json');+ assert.equal(added.status, 0, added.context);++ const previousHome = process.env.PULLBOARD_HOME;+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_HOME = home;+ process.env.PULLBOARD_MACHINE_HOME = machineHome;+ let held;+ try {+ held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,+ agent: 'cleanup-timeout-local-holder', item: 'cleanup-timeout-local-holder', kind: 'fixture-hold', browser: true });+ // The real CLI must refuse this one response as RUNNER_CLEANUP_TIMEOUT; a missing or+ // incomplete transport result would take the retry path and could incorrectly run locally.+ commandChild = startFixtureChild(process.execPath, [BIN, 'gate', '--json'], {+ cwd: repo, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'],+ });+ const command = observe(commandChild);+ const completed = await command.closed;+ assert.equal(completed.status, 1, `${completed.stderr}\n${completed.stdout}`);+ const response = JSON.parse(completed.stdout.trim());+ assert.equal(response.error?.code, 'RUNNER_CLEANUP_TIMEOUT', JSON.stringify(response));+ assert.ok(existsSync(bodyRan), 'the committed command ran to completion and wrote its own overflow marker');- assert.equal(readFileSync(requests, 'utf8').trim().split('\n').length, 1, 'the refused cleanup result is not retried or sent to a local runner');++ assert.equal(readFileSync(starts, 'utf8').trim().split('\n').length, 1, 'the refused cleanup result is not retried or sent to a local runner');+ await waitForCondition(() => readRemoteGateHolders(remoteDatabase).length === 0,+ 'remote physical gate holder releases after the named cleanup timeout');+ assert.equal(readRemoteGateHolders(join(machineHome, 'resources.sqlite')).length, 1,+ 'the separate local fixture holder remains intact until explicitly released');+ } finally {+ if (commandChild && commandChild.exitCode === null && commandChild.signalCode === null) {+ try { process.kill(-commandChild.pid, 'SIGTERM'); }+ catch (error) { if (error.code !== 'ESRCH') throw error; }+ await once(commandChild, 'close').catch(() => {});+ }+ if (held) held.release();+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;+ }+});