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
feat(runners): negotiate cached history for unchanged gates [C7,A1,I1]
Corey Olson5caf7de071dc
diff --git a/docs/api.md b/docs/api.mdindex eb3b2781..e342c72f 100644--- a/docs/api.md+++ b/docs/api.md@@ -318,3 +318,5 @@ A `pullboard serve` key grants access to a board; it does not identify the persoThe view's own page retains its person channel. The standalone API refuses `POST /api/v1/boards/:board/requests` with `B26_PERSON_CHANNEL`; the view continues to record the person's coordinator request. Residual: an agent that starts `pullboard view` itself also holds that view's link; this change does not isolate that link from the agent. Signed person moves (#408) address that separate boundary.`runner add` registers machine-local SSH capacity. Optional `--node` and `--root` select absolute remote paths when Node is outside the SSH login path or runner storage needs a specific location. The default storage root is `~/.pullboard-runner`; runner work shares the remote machine resource pool.++Runner storage keeps one repository object cache and creates an isolated checkout per run. A locked inventory handshake transfers only missing committed objects after scanning their blobs, paths and commit metadata, including ancestors. Credential-free HTTPS origins may seed the cache anonymously; caller credentials are never forwarded.diff --git a/src/runner-worker.js b/src/runner-worker.jsindex 5f8a41e7..4a2ccb30 100644--- a/src/runner-worker.js+++ b/src/runner-worker.js@@ -1,7 +1,7 @@/** 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, cpSync, createReadStream, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, cpSync, createReadStream, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, 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';@@ -63,12 +63,21 @@ async function readSpec() {|| !/^(?:[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');+ }+ }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');@@ -104,6 +113,7 @@ function childEnvironment(home, temporary, machineHomePath = '') {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'),@@ -243,38 +253,129 @@ async function git(root, args, env) {return Buffer.concat(output).toString('utf8').trim();}-/** Receive the entire stdin pack before queueing so a capacity wait cannot back up the SSH input pipe. */+/** 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' }));}-/** Index the received pack, then attach only its exact commit as shallow history. */-async function unpackSource(root, packFile, spec, env) {- const index = spawnOwned('git', ['index-pack', '--stdin'], { cwd: root, env, stdio: ['pipe', 'ignore', 'ignore'] });+/** 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 {- 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 pack could not be indexed');- } catch (error) {- await drainOwned(index, true);- throw error;+ if (!existsSync(cache)) {+ const build = mkdtempSync(join(repositories, `.repo-${spec.repoId}-`));+ const staged = join(build, 'cache.git');+ try {+ let cloned = false;+ if (spec.origin) {+ const clone = spawnOwned('git', ['clone', '--bare', '--no-hardlinks', '--origin=origin', spec.origin, staged], {+ cwd: build, env, stdio: ['ignore', 'ignore', 'ignore'],+ });+ const result = await clone.closed;+ await drainOwned(clone);+ cloned = !result.error && result.code === 0 && !result.signal;+ if (cloned) {+ try {+ cloned = await git(staged, ['rev-parse', '--is-bare-repository'], env) === 'true'+ && await git(staged, ['rev-parse', '--show-object-format'], env) === (spec.commit.length === 64 ? 'sha256' : 'sha1')+ && !existsSync(join(staged, 'shallow'))+ && !existsSync(join(staged, 'objects', 'info', 'alternates'));+ } catch { cloned = false; }+ }+ if (!cloned) rmSync(staged, { recursive: true, force: true });+ }+ if (!cloned) {+ 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');+ }+ 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/heads', 'refs/pullboard/candidates'], env);+ const tips = [];+ if (refLines) for (const line of refLines.split(/\r?\n/u)) {+ const split = /^(refs\/(?:heads|pullboard\/candidates)\/.+) ([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].startsWith('refs/pullboard/candidates/')+ && split[1].slice('refs/pullboard/candidates/'.length) !== 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');+ 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. */ }}- writeFileSync(join(root, '.git', 'shallow'), `${spec.commit}\n`, { mode: 0o600 });- await git(root, ['update-ref', 'refs/heads/pullboard-run', spec.commit], env);- await git(root, ['checkout', '--detach', spec.commit], env);- if (await git(root, ['rev-parse', `${spec.commit}^{tree}`], env) !== spec.tree) throw new Error('source tree did not match the requested commit');- if (await git(root, ['rev-parse', 'HEAD'], env) !== spec.commit) throw new Error('source commit did not match the requested commit');- if (await git(root, ['rev-list', '--count', 'HEAD'], env) !== '1') throw new Error('source pack included commit history');- const reachable = new Set((await git(root, ['rev-list', '--objects', 'HEAD'], env)).split(/\r?\n/u)- .map(line => line.match(/^([a-f0-9]{40,64})(?:\s|$)/u)?.[1]).filter(Boolean));- reachable.add(spec.commit);- const packDirectory = join(root, '.git', 'objects', 'pack');- const indexes = readdirSync(packDirectory).filter(name => name.endsWith('.idx'));- if (indexes.length !== 1) throw new Error('source pack was not the single requested object set');- const packed = new Set((await git(root, ['verify-pack', '-v', join(packDirectory, indexes[0])], env))- .split(/\r?\n/u).map(line => line.match(/^([a-f0-9]{40,64})\s+(?:commit|tree|blob|tag)\s/u)?.[1]).filter(Boolean));- if (packed.size !== reachable.size || [...packed].some(object => !reachable.has(object))) throw new Error('source pack contains objects outside the requested tree');rmSync(packFile, { force: true });}@@ -474,7 +575,6 @@ async function main() {writeFileSync(join(privateHome, 'npm-userconfig'), '', { mode: 0o600 });writeFileSync(join(privateHome, 'npm-globalconfig'), '', { mode: 0o600 });const packFile = join(runDirectory, 'source.pack');- await receivePack(packFile);lease = await acquireResourceApi(api, {name: 'gate', capacity: gateCapacity, scope: 'machine', root: runnerRoot,repo: runnerRoot, agent: `pullboard-ssh-${spec.id}`,@@ -485,13 +585,7 @@ async function main() {}, machineHomePath);const canonicalMachineHome = machineHomePath;const env = scopedEnvironment(privateHome, temporary, canonicalMachineHome, lease, api);- const init = spawnOwned('git', ['init', '-q', `--object-format=${spec.commit.length === 64 ? 'sha256' : 'sha1'}`, root], {- cwd: runDirectory, env, stdio: ['ignore', 'ignore', 'ignore'],- });- const initResult = await init.closed;- await drainOwned(init);- if (initResult.error || initResult.code !== 0 || initResult.signal) throw new Error('source checkout could not be initialized');- await unpackSource(root, packFile, spec, env);+ await checkoutHistory(api, runnerRoot, root, packFile, spec, env);await installDependencies(api, root, runnerRoot, privateHome, env, spec.tree);final = { ...(await runCommand(spec, root, env, sink)), root };} catch (error) {diff --git a/src/runners.js b/src/runners.jsindex 70502976..de625b49 100644--- a/src/runners.js+++ b/src/runners.js@@ -1,13 +1,14 @@/** 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, existsSync, mkdtempSync, openSync, readFileSync, rmSync, writeSync } from 'node:fs';+import { closeSync, createReadStream, existsSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';+import { pipeline } from 'node:stream/promises';import { configFromSource, defaults } from './config.js';import { blockedPaths, secretsIn } from './hooks.js';-import { cleanGitEnvironment, headCommit, headTree, isClean, untracked } from './git.js';+import { cleanGitEnvironment, headCommit, headTree, isClean, repoInfo, untracked } from './git.js';import { Refused } from './refused.js';const MAX_OUTPUT_BYTES = 1024 ** 3;@@ -65,7 +66,6 @@ function sourceObjects(root, source) {const configRecord = records.find(record => record.endsWith('\tpullboard.json'));const configObject = configRecord?.match(/^\d+ blob ([a-f0-9]{40,64})\t/u)?.[1];const config = configObject ? configFromSource(sourceGit(root, ['cat-file', 'blob', configObject])) : defaults();- const blobs = [];for (const record of records) {const match = /^(\d+) (\w+) ([a-f0-9]{40,64})\t([\s\S]+)$/u.exec(record);if (!match || match[2] !== 'blob') throw new Refused('RUNNER_SOURCE', 'runner source contains a submodule or unsupported object; keep this run local');@@ -80,16 +80,112 @@ function sourceObjects(root, source) {const text = sourceGit(root, ['cat-file', 'blob', object]);const findings = secretsIn(text.split(/\r?\n/u).map((line, index) => ({ path, line: index + 1, text: line })));if (findings.length) throw new Refused('RUNNER_SECRET', `source leak scan refused ${findings[0]}; remove the secret before remote execution`);- blobs.push(object);}const commit = sourceGit(root, ['cat-file', 'commit', source.commit]);if (secretsIn(commit.split('\n').map((text, index) => ({ path: 'commit', line: index + 1, text }))).length) {throw new Refused('RUNNER_SECRET', 'the commit metadata contains a possible secret; keep this run local and correct the metadata');}- // Tree traversal includes all current trees and blobs, but never follows commit parents.- const objects = sourceGit(root, ['rev-list', '--objects', `${source.commit}^{tree}`])- .split('\n').filter(Boolean).map(line => line.split(' ')[0]);- return [...new Set([source.commit, ...objects, ...blobs])];++}++/** Reject blocked historical paths as well as current ones before an object pack crosses SSH. */+function protectedHistoryPath(path, protect) {+ return blockedPaths([path], protect).length || /(?:^|\/)board\.sqlite(?:-(?:wal|shm))?$/u.test(path);+}++/** Read one exact cat-file record without loading a repository's history into memory. */+function objectRecord(descriptor) {+ const header = [];+ const byte = Buffer.alloc(1);+ while (readSync(descriptor, byte, 0, 1, null)) {+ if (byte[0] === 10) break;+ if (header.length > 200) throw new Refused('RUNNER_SOURCE', 'invalid source object header; keep this run local');+ header.push(byte[0]);+ }+ const match = /^([a-f0-9]{40,64}) (blob|tree|commit|tag) (\d+)$/u.exec(Buffer.from(header).toString('ascii'));+ if (!match) throw new Refused('RUNNER_SOURCE', 'cannot scan the selected history objects; keep this run local');+ const size = Number(match[3]);+ if (!Number.isSafeInteger(size) || size > MAX_BLOB_BYTES) throw new Refused('RUNNER_SCAN_LIMIT', 'a historical object exceeds the safe runner scan limit; keep this run local');+ const data = Buffer.alloc(size);+ let offset = 0;+ while (offset < size) {+ const read = readSync(descriptor, data, offset, size - offset, null);+ if (!read) throw new Refused('RUNNER_SOURCE', 'incomplete history object; retry from the committed repository');+ offset += read;+ }+ if (readSync(descriptor, byte, 0, 1, null) !== 1 || byte[0] !== 10) throw new Refused('RUNNER_SOURCE', 'incomplete history object; retry from the committed repository');+ return { object: match[1], type: match[2], data };+}++/** Scan and pack exactly the candidate objects absent from the locked remote cache inventory. */+function historyPack(root, source, tips, directory) {+ const known = sourceGit(root, ['cat-file', '--batch-check'], { input: tips.map(tip => `${tip}\n`).join('') })+ .split('\n').map(line => /^([a-f0-9]{40,64}) commit \d+$/u.exec(line)?.[1]).filter(Boolean);+ const records = sourceGit(root, ['rev-list', '--objects', source.commit, '--not', ...known])+ .split('\n').filter(Boolean).map(line => {+ const match = /^([a-f0-9]{40,64})(?: (.*))?$/u.exec(line);+ if (!match) throw new Refused('RUNNER_SOURCE', 'unsupported history path; keep this run local');+ return { object: match[1], path: match[2] ?? '' };+ });+ const objects = [...new Set(records.map(record => record.object))];+ const names = new Map(records.map(record => [record.object, record.path]));+ const historicalTrees = new Set();+ const config = sourceGit(root, ['ls-tree', '--name-only', source.commit, '--', 'pullboard.json']).trim()+ ? configFromSource(sourceGit(root, ['show', `${source.commit}:pullboard.json`])) : defaults();+ const metadata = sourceGit(root, ['cat-file', '--batch-check'], { input: objects.map(object => `${object}\n`).join('') });+ for (const line of metadata.split('\n').filter(Boolean)) {+ const match = /^[a-f0-9]{40,64} (blob|tree|commit|tag) (\d+)$/u.exec(line);+ if (!match || Number(match[2]) > MAX_BLOB_BYTES) throw new Refused('RUNNER_SCAN_LIMIT', 'a historical object exceeds the safe runner scan limit; keep this run local');+ }+ if (objects.length) {+ const scanFile = join(directory, 'history.scan');+ const output = openSync(scanFile, 'wx', 0o600);+ try { sourceGit(root, ['cat-file', '--batch'], { input: `${objects.join('\n')}\n`, stdio: ['pipe', output, 'pipe'] }); }+ finally { closeSync(output); }+ const input = openSync(scanFile, 'r');+ try {+ for (let index = 0; index < objects.length; index++) {+ const { object, type, data } = objectRecord(input);+ const path = names.get(object) || `history/${object}`;+ if (type === 'commit') {+ const tree = /^tree ([a-f0-9]{40,64})$/mu.exec(data.toString('utf8'))?.[1];+ if (!tree) throw new Refused('RUNNER_SOURCE', 'invalid historical commit; keep this run local');+ historicalTrees.add(tree);+ }+ if (type === 'tree') {+ let cursor = 0;+ while (cursor < data.length) {+ const space = data.indexOf(32, cursor), nul = data.indexOf(0, space + 1);+ if (space < cursor || nul < 0) throw new Refused('RUNNER_SOURCE', 'invalid historical tree; keep this run local');+ const mode = data.subarray(cursor, space).toString('ascii');+ const name = data.subarray(space + 1, nul).toString('utf8');+ const full = names.get(object) ? `${names.get(object)}/${name}` : name;+ if (mode === '160000' || protectedHistoryPath(full, config.protect)+ || secretsIn([{path:'historical tree',line:1,text:name}]).length) throw new Refused('RUNNER_SECRET', 'historical source includes a blocked private path or submodule; keep this run local');+ cursor = nul + 1 + source.commit.length / 2;+ }+ if (cursor !== data.length) throw new Refused('RUNNER_SOURCE', 'invalid historical tree; keep this run local');+ } else if (protectedHistoryPath(path, config.protect)+ || secretsIn(data.toString('utf8').split(/\r?\n/u).map((text, line) => ({ path, line: line + 1, text }))).length) {+ throw new Refused('RUNNER_SECRET', 'historical source failed its transfer scan; remove the private history or keep this run local');+ }+ }+ } finally { closeSync(input); rmSync(scanFile, { force: true }); }+ }+ // Check every full historical path, including reused cached blobs moved beneath a newly blocked prefix.+ for (const tree of historicalTrees) {+ for (const record of sourceGit(root, ['ls-tree', '-r', '-z', '--full-tree', tree]).split('\0').filter(Boolean)) {+ const match = /^(\d+) (\w+) [a-f0-9]{40,64}\t([\s\S]+)$/u.exec(record);+ if (!match || match[2] !== 'blob' || protectedHistoryPath(match[3], config.protect)) {+ throw new Refused('RUNNER_SECRET', 'historical source includes a blocked private path or submodule; keep this run local');+ }+ }+ }+ const pack = join(directory, 'source.pack');+ const output = openSync(pack, 'wx', 0o600);+ try { sourceGit(root, ['pack-objects', '--stdout'], { input: objects.map(object => `${object}\n`).join(''), stdio: ['pipe', output, 'pipe'] }); }+ finally { closeSync(output); }+ return pack;}/** Quote one remote shell argument without permitting substitutions or expansion. */@@ -132,7 +228,22 @@ function trustedTooling() {runtime: { files: runtimeFiles, sha256: createHash('sha256').update(JSON.stringify(runtimeFiles)).digest('hex') } };}-/** Prepare a single shallow object pack and an explicit worker request; cleanup owns only its scratch directory. */+/** Use only a credential-free anonymous HTTPS origin; SSH authentication is never forwarded. */+function anonymousOrigin(root) {+ const result = spawnSync('git', ['config', '--get', 'remote.origin.url'], { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 4096 });+ if (result.status !== 0) return undefined;+ let address = result.stdout.trim();+ const ssh = /^git@([A-Za-z0-9][A-Za-z0-9.-]*):([^\s?#]+)$/u.exec(address);+ if (ssh) address = `https://${ssh[1]}/${ssh[2]}`;+ try {+ const url = new URL(address);+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || !url.hostname || address.length > 2048) return undefined;+ if (secretsIn([{path:'anonymous origin',line:1,text:address}]).length) return undefined;+ return url.href;+ } catch { return undefined; }+}++/** Prepare the pinned request before negotiating history; cleanup owns only its scratch directory. */function requestFor(root, command, { runner, source, browser = false, pipefail = false, metadata = {} }) {runner = validateRunner(runner);const current = runnerSource(root);@@ -142,33 +253,24 @@ function requestFor(root, command, { runner, source, browser = false, pipefail =if (secretsIn(command.split('\n').map((text, index) => ({ path: 'run command', line: index + 1, text }))).length) {throw new Refused('RUNNER_SECRET', 'the run command contains a possible secret; use a command that does not transfer credentials');}- const objects = sourceObjects(root, current);+ sourceObjects(root, current);+ const repoId = createHash('sha256').update(realpathSync(repoInfo(root).commonDir)).digest('hex');const directory = mkdtempSync(join(tmpdir(), 'pullboard-runner-send-'));- let descriptor;try {const { worker, tooling, runtime } = trustedTooling();- const spec = { version: 1, id: randomUUID(), runtime, tooling, ...current, command, pipefail, slots: runner.slots,+ const spec = { version: 1, id: randomUUID(), repoId, origin: anonymousOrigin(root), runtime, tooling, ...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 framed = join(directory, 'request.bin');- const requestOutput = openSync(framed, 'wx', 0o600);- try {- writeSync(requestOutput, Buffer.from(`${encodedSpec.length}\n`));- writeSync(requestOutput, encodedSpec);- sourceGit(root, ['pack-objects', '--stdout'], { input: `${objects.join('\n')}\n`, stdio: ['pipe', requestOutput, 'pipe'] });- } finally { closeSync(requestOutput); }- descriptor = openSync(framed, 'r');const remote = `${shellWord(runner.node ?? 'node')} --input-type=module -e ${shellWord(worker)}`;// These are transport hang ceilings, independent of the command's execution budget.return { spec, runner, args: ['-T', '-o', 'BatchMode=yes', '-o', 'ForwardAgent=no', '-o', 'ClearAllForwardings=yes','-o', 'SendEnv=-*', '-o', 'ConnectTimeout=10', '-o', 'ServerAliveInterval=10', '-o', 'ServerAliveCountMax=3',- '--', runner.host, remote], descriptor, env: sshEnvironment(),- cleanup() { closeSync(descriptor); rmSync(directory, { recursive: true, force: true }); } };+ '--', runner.host, remote], root, source: current, directory, frame: Buffer.concat([Buffer.from(`${encodedSpec.length}\n`), encodedSpec]), env: sshEnvironment(),+ cleanup() { rmSync(directory, { recursive: true, force: true }); } };} catch (error) {- if (descriptor !== undefined) closeSync(descriptor);rmSync(directory, { recursive: true, force: true });throw error;}@@ -197,32 +299,69 @@ function resultFrom(request, result) {executionSource: { commit: receipt.commit, tree: receipt.tree, tooling: request.spec.tooling } };}-/** Execute one committed command over SSH; an authentic test failure remains a test failure. */+/** Keep synchronous gate callers on the same negotiated transport as asynchronous comparisons. */export function runOnRunner(root, command, options) {- const request = requestFor(root, command, options);- try {- const result = spawnSync('ssh', request.args, { env: request.env, stdio: [request.descriptor, 'pipe', 'pipe'], maxBuffer: MAX_OUTPUT_BYTES });- return resultFrom(request, result);- } finally { request.cleanup(); }+ const script = `import { runOnRunnerAsync } from ${JSON.stringify(import.meta.url)};+let input=''; for await (const chunk of process.stdin) input+=chunk;+const request=JSON.parse(input);+try { process.stdout.write(JSON.stringify({result:await runOnRunnerAsync(request.root,request.command,request.options)})); }+catch(error) { process.stdout.write(JSON.stringify({error:{name:error.name,code:error.code,message:error.message,host:error.host}})); process.exitCode=1; }`;+ const child = spawnSync(process.execPath, ['--input-type=module', '-e', script], {+ cwd: root, input: JSON.stringify({ root, command, options }), encoding: 'utf8', maxBuffer: MAX_OUTPUT_BYTES * 2,+ stdio: ['pipe', 'pipe', 'pipe'],+ });+ let reply;+ try { reply = JSON.parse(child.stdout); } catch { throw new RunnerDropped(options.runner.host); }+ if (reply.error?.name === 'Refused') {+ const prefix = `[${reply.error.code}] `;+ throw new Refused(reply.error.code, reply.error.message.startsWith(prefix) ? reply.error.message.slice(prefix.length) : reply.error.message);+ }+ if (reply.error || child.error || child.status !== 0) throw new RunnerDropped(options.runner.host);+ return reply.result;}-/** Execute a comparison asynchronously without blocking other local queue holders. */+/** Negotiate missing history objects while the remote cache lease stays held in one SSH session. */export async function runOnRunnerAsync(root, command, options) {const request = requestFor(root, command, options);try {- const child = spawn('ssh', request.args, { env: request.env, stdio: [request.descriptor, 'pipe', 'pipe'] });+ const child = spawn('ssh', request.args, { env: request.env, stdio: ['pipe', 'pipe', 'pipe'] });const output = [], diagnostics = [];- let bytes = 0, error;- /** Bound both protocol streams before appending buffers to a result. */+ let bytes = 0, error, control = '', requested = false, transfer = null;+ /** Bound both protocol streams before retaining a complete result. */const capture = (target, chunk) => {bytes += chunk.length;if (bytes > MAX_OUTPUT_BYTES) { error = new Error('runner output exceeded limit'); child.kill(); }else target.push(chunk);};child.stdout.on('data', chunk => capture(output, chunk));- child.stderr.on('data', chunk => capture(diagnostics, chunk));+ child.stderr.on('data', chunk => {+ capture(diagnostics, chunk);+ control += chunk.toString('utf8');+ if (control.length > 256 * 1024) { error = new Error('runner control frame exceeded limit'); child.kill(); return; }+ let newline;+ while ((newline = control.indexOf('\n')) >= 0) {+ const line = control.slice(0, newline); control = control.slice(newline + 1);+ const prefix = `PULLBOARD_RUNNER_NEED ${request.spec.id} `;+ if (!line.startsWith(prefix)) continue;+ if (requested) { error = new Error('duplicate runner inventory'); child.kill(); return; }+ requested = true;+ transfer = (async () => {+ const inventory = JSON.parse(Buffer.from(line.slice(prefix.length), 'base64').toString('utf8'));+ if (!Array.isArray(inventory.tips) || inventory.tips.length > 1024+ || inventory.tips.some(tip => typeof tip !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(tip))) {+ throw new Error('invalid runner inventory');+ }+ const pack = historyPack(root, request.source, inventory.tips, request.directory);+ await pipeline(createReadStream(pack), child.stdin);+ })().catch(failure => { error = failure; child.stdin.destroy(); child.kill(); });+ }+ });+ child.stdin.on('error', failure => { if (failure.code !== 'EPIPE') error ??= failure; });child.once('error', failure => { error = failure; });+ child.stdin.write(request.frame);const status = await new Promise(resolve => child.once('close', resolve));+ if (transfer) await transfer;+ if (error instanceof Refused) throw error;return resultFrom(request, { status, error, stdout: Buffer.concat(output), stderr: Buffer.concat(diagnostics) });} finally { request.cleanup(); }}diff --git a/test/runners.test.js b/test/runners.test.jsindex 43198647..66bef305 100644--- a/test/runners.test.js+++ b/test/runners.test.js@@ -90,9 +90,10 @@ if (host !== ${JSON.stringify(HOST)} && host !== ${JSON.stringify(`${HOST}-drop`record({ refused: true, stdinBytes }); process.exit(255);}${dropFirst ? `if (host.endsWith('-drop') && call === 1) {- process.stdin.resume(); process.stdin.on('end', () => {+ 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' };@@ -130,7 +131,7 @@ ${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 }) {+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';@@ -142,6 +143,7 @@ test('runner executed the committed source in its private checkout', () => {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);@@ -152,8 +154,9 @@ test('runner executed the committed source in its private checkout', () => {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, 'true');- assert.equal(count, '1', 'the worker has the selected commit without history');+ 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);@@ -183,7 +186,7 @@ test('runner executed the committed source in its private checkout', () => {}/** Build a committed probe for the cache copy of one local workspace dependency. */-function writeCacheProbe(repo, { remoteStateRoot, nodePath }) {+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';@@ -196,6 +199,12 @@ test('a cached workspace link resolves inside this fresh runner checkout', () =>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 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');@@ -204,7 +213,7 @@ test('a cached workspace link resolves inside this fresh runner checkout', () =>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 }));+ console.log('RUNNER_CACHE_FACT ' + JSON.stringify({ root, link, target, commit, tree, shallow, count, history }));});`;writeFileSync(join(repo, 'runner-cache-probe.test.js'), probe);@@ -360,9 +369,13 @@ test('a queued run executes on a registered runner and its result comes back [C7assert.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');+ 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}');@@ -370,7 +383,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,+ 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]');@@ -449,6 +462,19 @@ test('a queued run executes on a registered runner and its result comes back [C7const 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, historicalRed.context);+ assert.match(historicalRed.stdout + historicalRed.stderr, /RUNNER_SECRET/u);+ assert.doesNotMatch(historicalRed.stdout + historicalRed.stderr, new RegExp(SECRET, 'u'));+assert.equal(commit.length, 40);assert.equal(tree.length, 40);} finally {@@ -721,6 +747,7 @@ test('a queued run executes on a registered runner and its result comes back [C7name: '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;@@ -735,8 +762,11 @@ appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');cwd: repo, env, encoding: 'utf8',});assert.equal(lock.status, 0, lock.context);- git(repo, env, 'add', '.gitignore', 'pullboard.json', 'package.json', 'package-lock.json', 'packages/runner-fixture-dep');+ git(repo, env, 'add', '.gitignore', 'pullboard.json', 'package.json', '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');@@ -754,7 +784,7 @@ appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');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 });+ 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');@@ -764,6 +794,8 @@ appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');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(readFileSync(installWitnesses, 'utf8'), 'postinstall\n', 'the first exact-tree run installs the committed workspace dependency');@@ -773,6 +805,8 @@ appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');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(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');@@ -781,6 +815,8 @@ appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');assert.equal(readFileSync(installWitnesses, 'utf8'), 'postinstall\n', 'the second run reuses the dependency cache without a second install witness');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 cache hit sends fewer Git-pack bytes for the same selected candidate');assert.ok(requestsSeen.every(request => request.remoteStartsWithConfiguredNode), 'both remote workers use the configured absolute Node path');} finally {if (held) held.release();