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): preserve scanned release refs and static tooling [C7]
Corey Olson541f54caae74
diff --git a/src/runner-worker.js b/src/runner-worker.jsindex 500a0f96..7e01c2ef 100644--- a/src/runner-worker.js+++ b/src/runner-worker.js@@ -1,10 +1,11 @@-/** Standalone SSH runner worker source; intentionally imports only Node built-ins. */+/** SSH runner entry point in a pinned capsule with a static trusted resource graph. */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 { fileURLToPath, pathToFileURL } from 'node:url';+import * as resourceApi from './resources.js';import { once } from 'node:events';import { pipeline } from 'node:stream/promises';@@ -115,12 +116,25 @@ async function readSpec() {if (value.originBase !== undefined&& (typeof value.originBase !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(value.originBase)|| value.originBase.length !== value.commit.length || !value.origin)) throw new Error('invalid work specification');+ if (!Array.isArray(value.tags) || value.tags.length > 1_024) throw new Error('invalid tag manifest');+ const tagNames = new Set();+ for (const tag of value.tags) {+ if (!tag || typeof tag.name !== 'string' || !tag.name.startsWith('refs/tags/') || tag.name.length > 1_024+ || /[\u0000-\u001f\u007f]/u.test(tag.name) || tagNames.has(tag.name)+ || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(tag.object ?? '')+ || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(tag.peeledCommit ?? '')+ || tag.object.length !== value.commit.length || tag.peeledCommit.length !== value.commit.length+ || !Array.isArray(tag.chain) || tag.chain.length > 8+ || tag.chain.some(object => typeof object !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(object)+ || object.length !== value.commit.length)) throw new Error('invalid tag manifest');+ tagNames.add(tag.name);+ if (tag.chain.length ? tag.chain[0] !== tag.object : tag.object !== tag.peeledCommit) throw new Error('invalid tag manifest');+ }const runtimeNames = ['resources.js', 'git.js', 'machine-home.js', 'refused.js'];if (Object.keys(value.runtime.files).length !== runtimeNames.length|| runtimeNames.some(name => typeof value.runtime.files[name] !== 'string')) throw new Error('invalid work specification');if (createHash('sha256').update(JSON.stringify(value.runtime.files)).digest('hex') !== value.runtime.sha256) throw new Error('invalid trusted runtime');- const workerFlag = process.execArgv.indexOf('-e');- const workerSource = workerFlag >= 0 ? process.execArgv[workerFlag + 1] : null;+ const workerSource = readFileSync(fileURLToPath(import.meta.url), 'utf8');const toolingFiles = { ...value.runtime.files, 'runner-worker.js': workerSource };if (!workerSource || !value.tooling || !['git-checkout', 'installed-package'].includes(value.tooling.kind)|| value.tooling.name !== 'pullboard' || typeof value.tooling.version !== 'string'@@ -168,29 +182,13 @@ function scopedEnvironment(home, temporary, machineHomePath, gateLease, resource};}-/** 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);+/** Check that this already installed capsule matches the controller before using its static API. */+function loadResourceApi(runtime) {+ const sourceDirectory = dirname(fileURLToPath(import.meta.url));+ if (Object.entries(runtime.files).some(([name, source]) => readFileSync(join(sourceDirectory, name), 'utf8') !== source)) {+ throw new Error('trusted runtime cache does not match the request');+ }+ return resourceApi;}/** Start a subprocess in a private process group so this worker can drain only its own descendants. */@@ -769,11 +767,16 @@ async function acquireResourceApi(api, options, machineHomePath) {}/** 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'] });+async function git(root, args, env, input) {+ const owned = spawnOwned('git', args, { cwd: root, env, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'] });const output = [];let bytes = 0;let overflow = false;+ let inputError;+ if (input !== undefined) {+ owned.child.stdin.on('error', error => { inputError ??= error; });+ owned.child.stdin.end(input);+ }owned.child.stdout.on('data', chunk => {bytes += chunk.length;if (bytes > 128 * 1024 * 1024) {@@ -782,7 +785,7 @@ async function git(root, args, env) {});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');+ if (overflow || inputError || result.error || result.code !== 0 || result.signal) throw new Error('source checkout could not be verified');return Buffer.concat(output).toString('utf8').trim();}@@ -802,6 +805,7 @@ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {repo: runnerRoot, agent: `pullboard-ssh-cache-${spec.id}`, kind: 'source-cache',onWait: () => assertTransportLive(),}, join(runnerRoot, 'cache', 'resource-pool'));+ const deliveryRefs = [];try {if (!existsSync(cache)) {const build = mkdtempSync(join(repositories, `.repo-${spec.repoId}-`));@@ -860,8 +864,22 @@ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {}const uniqueTips = [...new Set(tips)];if (uniqueTips.length > 1_024) throw new Error('source history cache needs maintenance');+ const requestedTagObjects = [...new Set(spec.tags.flatMap(tag => tag.chain))];+ const knownTagObjects = [];+ if (requestedTagObjects.length) {+ const checks = await git(cache, ['cat-file', '--batch-check'], env, `${requestedTagObjects.join('\n')}\n`);+ const lines = checks.split(/\r?\n/u).filter(Boolean);+ if (lines.length !== requestedTagObjects.length) throw new Error('source tag inventory is incomplete');+ for (let index = 0; index < lines.length; index++) {+ const match = /^([a-f0-9]{40,64}) tag \d+$/u.exec(lines[index]);+ if (match && match[1] === requestedTagObjects[index]) knownTagObjects.push(match[1]);+ else if (!new RegExp(`^${requestedTagObjects[index]} missing$`, 'u').test(lines[index])) {+ throw new Error('source tag inventory contains an invalid object');+ }+ }+ }await new Promise((resolveWrite, rejectWrite) => process.stderr.write(- `PULLBOARD_RUNNER_NEED ${spec.id} ${Buffer.from(JSON.stringify({ tips: uniqueTips })).toString('base64')}\n`,+ `PULLBOARD_RUNNER_NEED ${spec.id} ${Buffer.from(JSON.stringify({ tips: uniqueTips, tagObjects: knownTagObjects })).toString('base64')}\n`,error => error ? rejectWrite(error) : resolveWrite()));await receivePack(packFile);@@ -886,6 +904,7 @@ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {const closure = new Set((await git(cache, ['rev-list', '--objects', spec.commit], env)).split(/\r?\n/u).map(line => line.match(/^([a-f0-9]{40,64})(?:\s|$)/u)?.[1]).filter(Boolean));closure.add(spec.commit);+ const tagObjects = new Set(spec.tags.flatMap(tag => tag.chain));const packDirectory = join(cache, 'objects', 'pack');const newIndexes = readdirSync(packDirectory).filter(name => name.endsWith('.idx') && !priorIndexes.has(name));const received = new Set();@@ -895,13 +914,50 @@ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {if (object) received.add(object);}}- if ([...received].some(object => !closure.has(object))) {+ if ([...received].some(object => !closure.has(object) && !tagObjects.has(object))) {throw new Error('source history pack contains missing or unrelated objects');}+ for (const tag of spec.tags) {+ await git(cache, ['check-ref-format', tag.name], env);+ if (tag.chain.length) {+ let target = tag.object;+ for (let index = 0; index < tag.chain.length; index++) {+ const object = tag.chain[index];+ if (target !== object || (!received.has(object) && !knownTagObjects.includes(object))+ || await git(cache, ['cat-file', '-t', object], env) !== 'tag') {+ throw new Error('source tag chain is incomplete or unrelated');+ }+ const body = await git(cache, ['cat-file', '-p', object], env);+ const header = body.split(/\r?\n\r?\n/u, 1)[0];+ const next = /^object ([a-f0-9]{40,64})$/mu.exec(header)?.[1];+ const type = /^type (commit|tag|tree|blob)$/mu.exec(header)?.[1];+ const expectedNext = tag.chain[index + 1] ?? tag.peeledCommit;+ const expectedType = index + 1 < tag.chain.length ? 'tag' : 'commit';+ if (!next || next !== expectedNext || type !== expectedType || next.length !== spec.commit.length) {+ throw new Error('source tag chain failed validation');+ }+ target = next;+ }+ } else if (await git(cache, ['cat-file', '-t', tag.object], env) !== 'commit'+ || tag.object !== tag.peeledCommit || !closure.has(tag.object)) {+ throw new Error('lightweight source tag does not point into candidate history');+ }+ await git(cache, ['merge-base', '--is-ancestor', tag.peeledCommit, spec.commit], env);+ }await git(cache, ['update-ref', `refs/pullboard/candidates/${spec.commit}`, spec.commit], env);await git(root, ['init', '-q', `--object-format=${spec.commit.length === 64 ? 'sha256' : 'sha1'}`], env);await git(root, ['-c', 'protocol.file.allow=always', 'fetch', '--no-tags', cache, `refs/pullboard/candidates/${spec.commit}`], env);await git(root, ['checkout', '--detach', 'FETCH_HEAD'], env);+ for (let index = 0; index < spec.tags.length; index++) {+ const tag = spec.tags[index];+ const deliveryRef = `refs/pullboard/tag-delivery/${spec.id}/${index}`;+ await git(cache, ['update-ref', deliveryRef, tag.object], env);+ deliveryRefs.push(deliveryRef);+ await git(root, ['-c', 'protocol.file.allow=always', 'fetch', '--no-tags', cache, `${deliveryRef}:${tag.name}`], env);+ if (await git(root, ['rev-parse', `${tag.name}^{}`], env) !== tag.peeledCommit) {+ throw new Error('isolated source checkout has an invalid tag ref');+ }+ }if (await git(root, ['rev-parse', 'HEAD'], env) !== spec.commit|| await git(root, ['rev-parse', 'HEAD^{tree}'], env) !== spec.tree|| await git(root, ['rev-parse', '--is-shallow-repository'], env) !== 'false'@@ -909,6 +965,9 @@ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {throw new Error('isolated source checkout does not contain the complete requested history');}} finally {+ for (const ref of deliveryRefs) {+ try { await git(cache, ['update-ref', '-d', ref], env); } catch { /* Leave cache refs only if Git refuses safe removal. */ }+ }try { cacheLease.release(); } catch { /* Retaining the lease on cleanup error is safer than speculative deletion. */ }}rmSync(packFile, { force: true });@@ -1068,7 +1127,7 @@ async function main() {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);+ api = loadResourceApi(spec.runtime);const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;let resources;try {diff --git a/src/runners.js b/src/runners.jsindex ef8f92e4..fb263ece 100644--- a/src/runners.js+++ b/src/runners.js@@ -1,11 +1,12 @@/** Exact committed source and bounded, credential-free SSH execution for machine runners [C7]. */import { spawn, spawnSync } from 'node:child_process';import { createHash, randomUUID } from 'node:crypto';-import { closeSync, createReadStream, existsSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, rmSync } from 'node:fs';+import { chmodSync, closeSync, createReadStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { dirname, isAbsolute, join } from 'node:path';import { fileURLToPath } from 'node:url';import { pipeline } from 'node:stream/promises';+import { gunzipSync, gzipSync } from 'node:zlib';import { configFromSource, defaults } from './config.js';import { blockedPaths, secretsIn } from './hooks.js';import { cleanGitEnvironment, headCommit, headTree, isClean, repoInfo, untracked } from './git.js';@@ -14,6 +15,8 @@ import { Refused } from './refused.js';// Budget: 64 MiB bounds worst-case JSON bridge escaping below Node string limits.const MAX_OUTPUT_BYTES = 64 * 1024 ** 2;const MAX_BLOB_BYTES = 8 * 1024 ** 2;+const MAX_HISTORY_TAGS = 1_024;+const MAX_TAG_CHAIN = 8;const TOOL_ROOT = fileURLToPath(new URL('../', import.meta.url));const RUNTIME_NAMES = ['resources.js', 'git.js', 'machine-home.js', 'refused.js'];@@ -115,6 +118,66 @@ function originAncestor(root, source) {return result.status === 0 && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(base) ? base : undefined;}+/** Select safe tags that point to commits in the exact candidate ancestry. */+function candidateTags(root, source) {+ const rows = sourceGit(root, ['for-each-ref', '--format=%(refname)%00%(objectname)%00%(objecttype)', 'refs/tags'])+ .split('\n').filter(Boolean);+ if (rows.length > MAX_HISTORY_TAGS) throw new Refused('RUNNER_SCAN_LIMIT', 'too many local tags to transfer safely; keep this run local');+ const selected = [];+ for (const row of rows) {+ const fields = row.split('\0');+ if (fields.length !== 3) throw new Refused('RUNNER_SOURCE', 'cannot read local tag refs safely; keep this run local');+ const [name, object, declaredType] = fields;+ if (!name.startsWith('refs/tags/') || name.length > 1_024 || /[\u0000-\u001f\u007f]/u.test(name)+ || !/^[a-f0-9]{40,64}$/u.test(object) || object.length !== source.commit.length) {+ throw new Refused('RUNNER_SECRET', 'a local tag ref failed the safe transfer check; keep this run local');+ }+ sourceGit(root, ['check-ref-format', name]);+ let type = sourceGit(root, ['cat-file', '-t', object]).trim();+ if (type !== declaredType) throw new Refused('RUNNER_SOURCE', 'a local tag ref changed while preparing the run; retry');+ const peeledCommit = sourceGit(root, ['rev-parse', `${name}^{}`]).trim();+ if (!/^[a-f0-9]{40,64}$/u.test(peeledCommit) || peeledCommit.length !== source.commit.length+ || sourceGit(root, ['cat-file', '-t', peeledCommit]).trim() !== 'commit') continue;+ const ancestor = spawnSync('git', ['--no-replace-objects', '-c', 'core.hooksPath=/dev/null', 'merge-base', '--is-ancestor', peeledCommit, source.commit], {+ cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 4096,+ });+ if (ancestor.status === 1) continue;+ if (ancestor.status !== 0) throw new Refused('RUNNER_SOURCE', 'cannot validate tag ancestry; keep this run local');+ if (secretsIn([{ path: 'tag ref', line: 1, text: name }]).length) {+ throw new Refused('RUNNER_SECRET', 'a selected tag ref failed the safe transfer check; keep this run local');+ }+ const chain = [];+ if (type === 'tag') {+ let current = object;+ const seen = new Set();+ while (type === 'tag') {+ if (chain.length >= MAX_TAG_CHAIN || seen.has(current)) {+ throw new Refused('RUNNER_SCAN_LIMIT', 'an annotated tag chain exceeds the safe transfer limit; keep this run local');+ }+ seen.add(current);+ const tagBody = sourceGit(root, ['cat-file', '-p', current]);+ if (Buffer.byteLength(tagBody) > MAX_BLOB_BYTES) throw new Refused('RUNNER_SCAN_LIMIT', 'a tag annotation exceeds the safe transfer limit; keep this run local');+ if (secretsIn(tagBody.split(/\r?\n/u).map((text, line) => ({ path: name, line: line + 1, text }))).length) {+ throw new Refused('RUNNER_SECRET', 'an annotated tag failed the source privacy scan; keep this run local');+ }+ const header = tagBody.split(/\r?\n\r?\n/u, 1)[0];+ const target = /^object ([a-f0-9]{40,64})$/mu.exec(header)?.[1];+ const targetType = /^type (commit|tag|tree|blob)$/mu.exec(header)?.[1];+ if (!target || target.length !== source.commit.length || !targetType+ || sourceGit(root, ['cat-file', '-t', target]).trim() !== targetType) {+ throw new Refused('RUNNER_SOURCE', 'an annotated tag has an invalid object chain; keep this run local');+ }+ chain.push(current);+ current = target;+ type = targetType;+ }+ if (type !== 'commit' || current !== peeledCommit) throw new Refused('RUNNER_SOURCE', 'an annotated tag did not peel to its declared commit');+ } else if (type !== 'commit' || object !== peeledCommit) continue;+ selected.push({ name, object, peeledCommit, chain });+ }+ return selected;+}+/** Read one exact cat-file record without loading a repository's history into memory. */function objectRecord(descriptor) {const header = [];@@ -140,7 +203,8 @@ function objectRecord(descriptor) {}/** Scan and pack exactly the candidate objects absent from the locked remote cache inventory. */-function historyPack(root, source, tips, directory) {+function historyPack(root, source, tips, directory, tags = [], knownTagObjects = []) {+ const knownTags = new Set(knownTagObjects);const known = sourceGit(root, ['cat-file', '--batch-check'], { input: tips.map(tip => `${tip}\n`).join('') }).split('\n').map(line => /^([a-f0-9]{40,64}) commit \d+$/u.exec(line)?.[1]).filter(Boolean);const records = sourceGit(root, ['rev-list', '--objects', source.commit, '--not', ...known])@@ -149,8 +213,9 @@ function historyPack(root, source, tips, directory) {if (!match) throw new Refused('RUNNER_SOURCE', 'unsupported history path; keep this run local');return { object: match[1], path: match[2] ?? '' };});- const objects = [...new Set(records.map(record => record.object))];+ const objects = [...new Set([...records.map(record => record.object), ...tags.flatMap(tag => tag.chain).filter(object => !knownTags.has(object))])];const names = new Map(records.map(record => [record.object, record.path]));+ for (const tag of tags) for (const object of tag.chain) names.set(object, tag.name);const historicalTrees = new Set();const config = sourceGit(root, ['ls-tree', '--name-only', source.commit, '--', 'pullboard.json']).trim()? configFromSource(sourceGit(root, ['show', `${source.commit}:pullboard.json`])) : defaults();@@ -250,6 +315,48 @@ function trustedTooling() {runtime: { files: runtimeFiles, sha256: createHash('sha256').update(JSON.stringify(runtimeFiles)).digest('hex') } };}+/** Install a complete immutable module capsule without reading the job's stdin stream. */+function installRuntime(payload, expected, configuredRoot) {+ const bytes = gunzipSync(Buffer.from(payload, 'base64'), { maxOutputLength: 1_048_576 });+ if (createHash('sha256').update(bytes).digest('hex') !== expected) throw new Error('invalid capsule identity');+ const files = JSON.parse(bytes);+ const home = process.env.HOME;+ if (!configuredRoot && (!home || !isAbsolute(home))) throw new Error('runner home must be absolute');+ const root = configuredRoot || join(home, '.pullboard-runner');+ const directory = join(root, 'runtime', expected);+ mkdirSync(root, { recursive: true, mode: 0o700 });+ chmodSync(root, 0o700);+ mkdirSync(dirname(directory), { recursive: true, mode: 0o700 });+ const build = mkdtempSync(join(dirname(directory), `${expected}.build-`));+ try {+ mkdirSync(join(build, 'src'), { mode: 0o700 });+ writeFileSync(join(build, 'package.json'), '{"type":"module"}\n', { mode: 0o600 });+ for (const [name, source] of Object.entries(files)) writeFileSync(join(build, 'src', name), source, { mode: 0o600 });+ try { renameSync(build, directory); }+ catch (error) { if (!['EEXIST', 'ENOTEMPTY'].includes(error.code)) throw error; }+ if (readFileSync(join(directory, 'package.json'), 'utf8') !== '{"type":"module"}\n'+ || Object.entries(files).some(([name, source]) => readFileSync(join(directory, 'src', name), 'utf8') !== source)) {+ throw new Error('trusted capsule does not match the request');+ }+ } finally { rmSync(build, { recursive: true, force: true }); }+}++/** Install pinned bytes first, then replace the SSH shell with the file-based worker. */+function remoteWorkerCommand(runner, worker, tooling, runtime) {+ const files = { ...runtime.files, 'runner-worker.js': worker };+ const payload = gzipSync(Buffer.from(JSON.stringify(files))).toString('base64');+ const installer = `import { chmodSync, mkdirSync, mkdtempSync, writeFileSync, readFileSync, renameSync, rmSync } from 'node:fs';+import { dirname, isAbsolute, join } from 'node:path';+import { createHash } from 'node:crypto';+import { gunzipSync } from 'node:zlib';+${installRuntime.toString()}+installRuntime(${JSON.stringify(payload)}, ${JSON.stringify(tooling.sha256)}, ${JSON.stringify(runner.root ?? '')});`;+ const node = shellWord(runner.node ?? 'node');+ const suffix = `/runtime/${tooling.sha256}/src/runner-worker.js`;+ const entry = runner.root ? shellWord(runner.root + suffix) : `"$HOME"${shellWord('/.pullboard-runner' + suffix)}`;+ return `${node} --input-type=module -e ${shellWord(installer)} && exec ${node} ${entry}`;+}+/** Use only a credential-free anonymous HTTPS origin; SSH authentication is never forwarded. */function anonymousOrigin(root) {const result = spawnSync('git', ['config', '--get', 'remote.origin.url'], { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 4096 });@@ -279,17 +386,18 @@ function requestFor(root, command, { runner, source, browser = false, pipefail =protectHistory(root, current, protect);const origin = anonymousOrigin(root);const originBase = origin ? originAncestor(root, current) : undefined;+ const tags = candidateTags(root, current);const repoId = createHash('sha256').update(realpathSync(repoInfo(root).commonDir)).digest('hex');const directory = mkdtempSync(join(tmpdir(), 'pullboard-runner-send-'));try {const { worker, tooling, runtime } = trustedTooling();- const spec = { version: 1, id: randomUUID(), repoId, ...(originBase ? { origin, originBase } : {}), runtime, tooling, ...current, command, pipefail, slots: runner.slots,+ const spec = { version: 1, id: randomUUID(), repoId, ...(originBase ? { origin, originBase } : {}), runtime, tooling, tags, ...current, command, pipefail, slots: runner.slots,browser: runner.browser, browserRequired: browser, landing: metadata.landing === true,itemCheck: metadata.itemCheck === true, diagnostic: metadata.diagnostic === true,item: String(metadata.item ?? ''), kind: String(metadata.kind ?? ''), ...(runner.root ? { root: runner.root } : {}) };const encodedSpec = Buffer.from(JSON.stringify(spec));if (encodedSpec.length > 1024 ** 2) throw new Refused('RUNNER_REQUEST_LIMIT', 'runner tooling request exceeds its safe transfer limit; keep this run local');- const remote = `${shellWord(runner.node ?? 'node')} --input-type=module -e ${shellWord(worker)}`;+ const remote = remoteWorkerCommand(runner, worker, tooling, runtime);// These are transport hang ceilings, independent of the command's execution budget.return { spec, runner, args: ['-T', '-o', 'BatchMode=yes', '-o', 'ForwardAgent=no', '-o', 'ClearAllForwardings=yes','-o', 'SendEnv=-*', '-o', 'ConnectTimeout=10', '-o', 'ServerAliveInterval=10', '-o', 'ServerAliveCountMax=3',@@ -395,7 +503,11 @@ export async function runOnRunnerAsync(root, command, options) {|| inventory.tips.some(tip => typeof tip !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(tip))) {throw new Error('invalid runner inventory');}- const pack = historyPack(root, request.source, inventory.tips, request.directory);+ if (!Array.isArray(inventory.tagObjects) || inventory.tagObjects.length > 8_192+ || inventory.tagObjects.some(object => typeof object !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(object))) {+ throw new Error('invalid runner tag inventory');+ }+ const pack = historyPack(root, request.source, inventory.tips, request.directory, request.spec.tags, inventory.tagObjects);await pipeline(createReadStream(pack), child.stdin);})().catch(failure => { error = failure; child.stdin.destroy(); child.kill(); });}diff --git a/test/machine.test.js b/test/machine.test.jsindex 4736c022..244fe35e 100644--- a/test/machine.test.js+++ b/test/machine.test.js@@ -41,7 +41,7 @@ const NOT_MOVES = {RUNNER_TOOLING_IDENTITY: 'runner tooling comes from an identified Pullboard installation',RUNNER_TOOLING_CHANGED: 'runner tooling matches its selected committed revision',NOT_A_REPO: 'the remote source root must be a Git repository before transport starts',- GATE_SLOT_LEASE_REQUIRED: 'a nested runner must receive its live machine gate lease before starting',+ GATE_SLOT_LEASE_REQUIRED: 'a child process must receive its live machine gate lease before starting',GATE_SLOT_MARKER_INVALID: 'an inherited machine gate capability is validated before nested work starts',GATE_SLOT_TOKEN_REQUIRED: 'an inherited machine gate capability needs its exact lease token',GATE_SLOT_LEASE_LOST: 'the exact machine gate lease must still be live before nested work starts',@@ -72,7 +72,11 @@ const ENTRY_POINTS = [];/** Setup refusals have no item move, but stay in the same reachability audit. */-const NON_MOVE_ENTRY_POINTS = ['cli.js#refuseRemoteCoordinatorModel'];+const NON_MOVE_ENTRY_POINTS = [+ 'cli.js#refuseRemoteCoordinatorModel',+ // Child-process commands may be serialized into scripts, so audit this exported setup guard directly.+ 'resources.js#gateSlotEnvironment',+];/** Board functions handed a function to call, and the one the CLI and the runner hand them. */const CALLBACKS = { 'board.js': { freeze: 'cli.js#freezer' } };diff --git a/test/resources.test.js b/test/resources.test.jsindex 7d8d81d0..7c4f6960 100644--- a/test/resources.test.js+++ b/test/resources.test.js@@ -356,8 +356,9 @@ test('a non-browser check does not wait for the browser slot [C7]', async () =>const { repo, base } = checkProject(box);const itemCheck = 'node bin/run-tests.js --test-name-pattern "item check marker" test/cpu-check.test.js';const submitCheck = 'node bin/run-tests.js --test-name-pattern "submit check marker" test/cpu-check.test.js';- assert.equal(await checkNeedsBrowser(repo, itemCheck), false, 'an explicit CPU-only test file is classifiable');- assert.equal(await checkNeedsBrowser(repo, 'node bin/run-tests.js test/cockpit/brief.test.js'), true,+ const classifyEnv = { ...process.env, NODE_OPTIONS: '' };+ assert.equal(await checkNeedsBrowser(repo, itemCheck, { env: classifyEnv }), false, 'an explicit CPU-only test file is classifiable');+ assert.equal(await checkNeedsBrowser(repo, 'node bin/run-tests.js test/cockpit/brief.test.js', { env: classifyEnv }), true,'known browser suites remain browser-gated');const added = runFixtureChild(process.execPath, [BIN, 'add', 'coordinator', 'CPU check item', '--check', itemCheck, '--wait', '--json'], {cwd: repo, env: box.env, encoding: 'utf8',diff --git a/test/runners.test.js b/test/runners.test.jsindex 51eb6948..c391afa8 100644--- a/test/runners.test.js+++ b/test/runners.test.js@@ -136,7 +136,8 @@ ${dropFirst ? `if (host.endsWith('-drop') && call === 1) {}/** Build one committed probe that observes the actual checkout and remote process environment. */-function writeProbe(repo, { remoteStateRoot, remoteMachineHome, sourceHome, sourceMachineHome, callerPool, callerToken, historyBaseCommit }) {+function writeProbe(repo, { remoteStateRoot, remoteMachineHome, sourceHome, sourceMachineHome, callerPool, callerToken,+ historyBaseCommit, annotatedTagObject, lightweightTagObject }) {const probe = `import assert from 'node:assert/strict';import { execFileSync } from 'node:child_process';import { existsSync } from 'node:fs';@@ -162,6 +163,20 @@ test('runner executed the committed source in its private checkout', () => {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', ['rev-parse', 'refs/tags/runner-release'], { encoding: 'utf8' }).trim(),+ ${JSON.stringify(annotatedTagObject)}, 'the annotated tag ref keeps its original object identity');+ assert.equal(execFileSync('git', ['rev-parse', 'refs/tags/runner-lightweight'], { encoding: 'utf8' }).trim(),+ ${JSON.stringify(lightweightTagObject)}, 'the lightweight tag ref points to its original commit');+ const annotation = execFileSync('git', ['cat-file', '-p', 'refs/tags/runner-release'], { encoding: 'utf8' });+ assert.match(annotation, /runner release annotation witness/u);+ const annotatedArchive = execFileSync('git', ['archive', '--format=tar', 'refs/tags/runner-release', 'history-original.txt']);+ const lightweightArchive = execFileSync('git', ['archive', '--format=tar', 'refs/tags/runner-lightweight', 'history-original.txt']);+ assert.ok(annotatedArchive.length > 512 && annotatedArchive.includes(Buffer.from('history-original.txt')),+ 'the annotated archive can read the tagged historical file');+ assert.ok(lightweightArchive.length > 512 && lightweightArchive.includes(Buffer.from('history-original.txt')),+ 'the lightweight archive can read the tagged historical file');+ assert.deepEqual(execFileSync('git', ['tag', '--list', 'runner-unrelated'], { encoding: 'utf8' }).trim(), '',+ 'a tag outside candidate ancestry is not copied');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);@@ -303,28 +318,6 @@ function processIsAlive(pid) {}}-/** 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;@@ -407,6 +400,12 @@ test('a queued run executes on a registered runner and its result comes back [C7git(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, 'tag', '-a', 'runner-release', '-m', 'runner release annotation witness', historyBaseCommit);+ git(repo, env, 'tag', 'runner-lightweight', historyBaseCommit);+ const annotatedTagObject = git(repo, env, 'rev-parse', 'refs/tags/runner-release');+ const lightweightTagObject = git(repo, env, 'rev-parse', 'refs/tags/runner-lightweight');+ const unrelatedCommit = git(repo, env, 'commit-tree', `${historyBaseCommit}^{tree}`, '-m', 'unrelated tag target');+ git(repo, env, 'tag', 'runner-unrelated', unrelatedCommit);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);@@ -417,6 +416,7 @@ test('a queued run executes on a registered runner and its result comes back [C7const ssh = installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests });assert.ok(existsSync(ssh));writeProbe(repo, { remoteStateRoot, remoteMachineHome, sourceHome: home, sourceMachineHome: machineHome, historyBaseCommit,+ annotatedTagObject, lightweightTagObject,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]');@@ -526,6 +526,15 @@ console.log('RUNNER_JOURNAL_FILES ' + readdirSync(journal).filter(name => /^chilconst callsAfterManyJournals = readFileSync(requests, 'utf8').trim().split('\n').length;assert.equal(callsAfterManyJournals, 3, 'the large-journal command ran remotely exactly once');+ git(repo, env, 'tag', '-a', 'runner-private-tag', '-m', SECRET, 'HEAD');+ const privateTag = runThroughGate(repo, env, 'node -e "process.stdout.write(\'PRIVATE_TAG_SCAN_REACHED\\n\')"');+ assert.equal(privateTag.status, 1, fixtureResultContext(privateTag));+ assert.match(privateTag.stdout + privateTag.stderr, /RUNNER_SECRET/u);+ assert.doesNotMatch(privateTag.stdout + privateTag.stderr, new RegExp(SECRET, 'u'));+ assert.equal(readFileSync(requests, 'utf8').trim().split('\n').length, callsAfterManyJournals,+ 'a secret annotated tag is refused before opening an SSH request');+ git(repo, env, 'tag', '-d', 'runner-private-tag');+// 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');@@ -608,7 +617,8 @@ while(!fs.existsSync(${JSON.stringify(releaseFirst)})) await sleep(5); })().catcawait waitForMarker(olderQueued);first = observe(startQueueController(repo, env, `node -e ${shellQuote(firstCode)}`,{ item: 'retry-first', queueMarker: queueReady, firstItem: 'older-local' }));- await waitForRequestCount(requests, 1);+ // The SSH stand-in creates this file only after appending its first request record.+ await waitForMarker(requests);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);diff --git a/test/test-resources.test.js b/test/test-resources.test.jsindex dbf004f2..8888962c 100644--- a/test/test-resources.test.js+++ b/test/test-resources.test.js@@ -125,10 +125,13 @@ test('frozen checks classify only explicit source-backed test commands [C7]', aswriteFileSync(join(root, 'package.json'), '{"type":"module"}\n');writeFileSync(join(root, 'test/resources.test.js'), "import { test } from 'node:test'; test('a non-browser check does not wait for the browser slot', () => {});\n");const command = 'out=$(node bin/run-tests.js --test-name-pattern "a non-browser check does not wait for the browser slot" test/resources.test.js 2>&1); printf "%s\\n" "$out"; printf "%s\\n" "$out" | grep -Eq "^[[:space:]]*ok [0-9]+ - .*a non-browser check does not wait for the browser slot" && printf "%s\\n" "$out" | grep -Eq "^# fail 0$"';- const classifyEnv = { ...process.env, PATH: [dirname(process.execPath), '/usr/bin', '/bin'].join(delimiter) };+ const classifyEnv = { ...process.env, NODE_OPTIONS: '', PATH: [dirname(process.execPath), '/usr/bin', '/bin'].join(delimiter) };assert.equal(await checkNeedsBrowser(root, command, { env: classifyEnv }), false);assert.equal(await checkNeedsBrowser(root, command, { env: classifyEnv }), false,'the supported captured runner form remains statically classifiable');+ assert.equal(await checkNeedsBrowser(root, command, {+ env: { ...classifyEnv, NODE_OPTIONS: '--import=unclassified-loader.mjs' },+ }), true, 'an unknown Node preload still fails closed to browser admission');const runnerPath = join(root, 'bin/run-tests.js');rmSync(runnerPath);