Skip to content

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.

fix: account for waived remote gate failures [B3,R3,C7]

Corey Olson0b54447b4ba1
diff --git a/src/gate-stages.js b/src/gate-stages.js
new file mode 100644
index 00000000..1cfcbbc5
--- /dev/null
+++ b/src/gate-stages.js
@@ -0,0 +1,130 @@
+/** Shared local and registered-runner gate accounting [B3,R3,C7]. */
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+
+/**
+ * Split a gate command into its top-level stages, the commands joined by `&&`, `||`, `;` or a newline,
+ * and each stage into its pipeline components, the commands joined by `|`. Anything the split cannot
+ * read for certain (a subshell, a group, command substitution, a heredoc, a comment, a background job,
+ * `|&` or an open quote) returns null, so no stage or component is ever guessed [B3,R3].
+ *
+ * @param {string} command
+ * @returns {Array<{ text: string, op: string, pipeline: string[] }> | null}
+ */
+export function gateStages(command) {
+ const source = String(command).trim();
+ const stages = [];
+ let current = '';
+ let segment = '';
+ let pipeline = [];
+ let quote = null;
+ let variable = 0;
+ /** Append text to both the stage and its current pipeline component. */
+ const add = (text) => { current += text; segment += text; };
+ /** Close the current pipeline component; an empty or line-continued component is unreadable. */
+ const pipe = () => {
+ if (!segment.trim() || /\\$/u.test(segment.trim())) return false;
+ pipeline.push(segment.trim());
+ segment = '';
+ return true;
+ };
+ /** Close the current stage with the operator that follows it; an empty stage is unreadable. */
+ const close = (op) => {
+ if (!current.trim() || /\\$/u.test(current.trim()) || !pipe()) return false;
+ stages.push({ text: current.trim(), op, pipeline });
+ current = '';
+ pipeline = [];
+ return true;
+ };
+ for (let at = 0; at < source.length; at += 1) {
+ const char = source[at];
+ const next = source[at + 1];
+ if (quote === "'") { add(char); if (char === "'") quote = null; continue; }
+ if (char === '\\') { add(next === '\n' ? ' ' : char + (next ?? '')); at += 1; continue; }
+ if (char === '`' || (char === '$' && next === '(')) return null;
+ if (quote === '"') { add(char); if (char === '"') quote = null; continue; }
+ if (char === "'" || char === '"') { quote = char; add(char); continue; }
+ if (char === '$' && next === '{') { variable += 1; add('${'); at += 1; continue; }
+ if (char === '}' && variable) { variable -= 1; add(char); continue; }
+ if ('(){}#'.includes(char) || (char === '<' && (next === '<' || next === '('))) return null;
+ if (char === '&') {
+ if (next === '&') { if (!close('&&')) return null; at += 1; continue; }
+ if (next === '>' || source[at - 1] === '>' || source[at - 1] === '<') { add(char); continue; }
+ return null;
+ }
+ if (char === '|' && next === '|') { if (!close('||')) return null; at += 1; continue; }
+ if (char === '|') {
+ if (source[at - 1] === '>') { add(char); continue; }
+ if (next === '&' || variable || !pipe()) return null;
+ current += char;
+ continue;
+ }
+ if (char === ';') { if (next === ';' || !close(';')) return null; continue; }
+ if (char === '\n') { if (current.trim() && !close(';')) return null; continue; }
+ add(char);
+ }
+ if (quote || variable || !current.trim() || /\\$/u.test(current.trim()) || !close('')) return null;
+ return stages;
+}
+
+/**
+ * Wrap each stage so the shell prints its start and its exit status between private marker lines.
+ * Control flow is unchanged: each wrapper exits with its stage's status, and an `exit` inside a
+ * stage still ends the run, which leaves that stage without an end marker and so unaccounted.
+ * A pipeline's components each keep their own exit status and their own standard output in
+ * private files instead of the run's output, since a marker written into a pipe would land in the
+ * next component's input. A failure is then credited only to the component that printed it [B3,R3].
+ */
+export function stagedScript(stages, marker, pipes) {
+ /** Quote one private file of a component for the shell. */
+ const file = (index, at, kind) => `'${join(String(pipes), `${index}-${at}.${kind}`).replaceAll("'", "'\\''")}'`;
+ /** One component that records its own status and output, then exits with that status. */
+ const component = (text, index, at) => `{ { {\n${text}\n}; printf '%s\\n' "$?" >> ${file(index, at, 'status')}; } | tee ${file(index, at, 'out')}; `
+ + `pullboard_pipe_status=$(tail -n 1 ${file(index, at, 'status')} 2>/dev/null); (exit "\${pullboard_pipe_status:-125}"); }`;
+ return stages.map((stage, index) => {
+ const body = stage.pipeline.length > 1 ? stage.pipeline.map((text, at) => component(text, index, at)).join(' | ') : stage.text;
+ return `{ printf '\\n${marker} begin ${index}\\n'; {\n${body}\n}; pullboard_stage_status=$?; `
+ + `printf '\\n${marker} end ${index} %s\\n' "$pullboard_stage_status"; (exit "$pullboard_stage_status"); } ${stage.op}`;
+ }).join('\n');
+}
+
+/**
+ * Read each pipeline component's own status and, when it failed, its own output. A component that
+ * recorded no status, or more than one, has a null status, so a line forged into its private file
+ * can only make its stage unaccounted [B3,R3].
+ */
+export function readPipes(split, pipes, limit = Infinity) {
+ /** Read one private component file, or null when the component never wrote it. */
+ const read = (index, at, kind) => {
+ const path = join(pipes, `${index}-${at}.${kind}`);
+ return existsSync(path) && statSync(path).size <= limit ? readFileSync(path, 'utf8') : null;
+ };
+ return split.map((stage, index) => (stage.pipeline.length > 1 ? stage.pipeline.map((_, at) => {
+ const lines = (read(index, at, 'status') ?? '').split('\n').filter(Boolean);
+ const status = lines.length === 1 && /^\d+$/u.test(lines[0]) ? Number(lines[0]) : null;
+ return { status, output: status ? read(index, at, 'out') : null };
+ }) : null));
+}
+
+/** Cut a staged run's output back to the command's own lines and each stage's lines and status. */
+export function readStages(output, marker, count) {
+ const stages = Array.from({ length: count }, () => ({ status: null, lines: [], began: false }));
+ const kept = [];
+ let open = null;
+ const lines = output.split('\n');
+ for (const [index, line] of lines.entries()) {
+ const found = line.startsWith(`${marker} `) ? /^(?:\S+) (begin|end) (\d+)(?: (\d+))?$/u.exec(line) : null;
+ if (found) {
+ if (kept.length && kept.at(-1) === '' && lines[index - 1] === '') kept.pop();
+ const stage = stages[Number(found[2])];
+ if (!stage) { open = null; continue; }
+ if (found[1] === 'begin') { stage.began = true; open = stage; }
+ else { stage.status = found[3] === undefined ? null : Number(found[3]); open = null; }
+ continue;
+ }
+ kept.push(line);
+ if (open) open.lines.push(line);
+ }
+ return { output: kept.join('\n'), stages: stages.map(({ status, lines: own, began }) => ({ status: began ? status : null, output: own.join('\n') })) };
+}
+
diff --git a/src/gate.js b/src/gate.js
index a9504b4d..f70bfcf0 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -19,6 +19,8 @@ import { selectAffectedTests } from './affected-tests.js';
import { checkNeedsBrowser, testsNeedBrowser } from './browser-admission.js';
import { timingFromOutput, timingRunner } from './timing.js';
import { landingShardProfile } from './landing-shards.js';
+import { gateStages, stagedScript, readPipes, readStages } from './gate-stages.js';
+export { gateStages } from './gate-stages.js';
import { RunnerDropped, runOnRunner, runOnRunnerAsync, runnerSource } from './runners.js';
import { sandboxBlockedOperation, sandboxBlockedScanner } from './sandbox-denial.js';
@@ -152,132 +154,6 @@ export function isStampedGreen(root) {
return tree !== null && existsSync(file) && readFileSync(file, 'utf8').trim() === tree;
}
-/**
- * Split a gate command into its top-level stages, the commands joined by `&&`, `||`, `;` or a newline,
- * and each stage into its pipeline components, the commands joined by `|`. Anything the split cannot
- * read for certain (a subshell, a group, command substitution, a heredoc, a comment, a background job,
- * `|&` or an open quote) returns null, so no stage or component is ever guessed [B3,R3].
- *
- * @param {string} command
- * @returns {Array<{ text: string, op: string, pipeline: string[] }> | null}
- */
-export function gateStages(command) {
- const source = String(command).trim();
- const stages = [];
- let current = '';
- let segment = '';
- let pipeline = [];
- let quote = null;
- let variable = 0;
- /** Append text to both the stage and its current pipeline component. */
- const add = (text) => { current += text; segment += text; };
- /** Close the current pipeline component; an empty or line-continued component is unreadable. */
- const pipe = () => {
- if (!segment.trim() || /\\$/u.test(segment.trim())) return false;
- pipeline.push(segment.trim());
- segment = '';
- return true;
- };
- /** Close the current stage with the operator that follows it; an empty stage is unreadable. */
- const close = (op) => {
- if (!current.trim() || /\\$/u.test(current.trim()) || !pipe()) return false;
- stages.push({ text: current.trim(), op, pipeline });
- current = '';
- pipeline = [];
- return true;
- };
- for (let at = 0; at < source.length; at += 1) {
- const char = source[at];
- const next = source[at + 1];
- if (quote === "'") { add(char); if (char === "'") quote = null; continue; }
- if (char === '\\') { add(next === '\n' ? ' ' : char + (next ?? '')); at += 1; continue; }
- if (char === '`' || (char === '$' && next === '(')) return null;
- if (quote === '"') { add(char); if (char === '"') quote = null; continue; }
- if (char === "'" || char === '"') { quote = char; add(char); continue; }
- if (char === '$' && next === '{') { variable += 1; add('${'); at += 1; continue; }
- if (char === '}' && variable) { variable -= 1; add(char); continue; }
- if ('(){}#'.includes(char) || (char === '<' && (next === '<' || next === '('))) return null;
- if (char === '&') {
- if (next === '&') { if (!close('&&')) return null; at += 1; continue; }
- if (next === '>' || source[at - 1] === '>' || source[at - 1] === '<') { add(char); continue; }
- return null;
- }
- if (char === '|' && next === '|') { if (!close('||')) return null; at += 1; continue; }
- if (char === '|') {
- if (source[at - 1] === '>') { add(char); continue; }
- if (next === '&' || variable || !pipe()) return null;
- current += char;
- continue;
- }
- if (char === ';') { if (next === ';' || !close(';')) return null; continue; }
- if (char === '\n') { if (current.trim() && !close(';')) return null; continue; }
- add(char);
- }
- if (quote || variable || !current.trim() || /\\$/u.test(current.trim()) || !close('')) return null;
- return stages;
-}
-
-/**
- * Wrap each stage so the shell prints its start and its exit status between private marker lines.
- * Control flow is unchanged: each wrapper exits with its stage's status, and an `exit` inside a
- * stage still ends the run, which leaves that stage without an end marker and so unaccounted.
- * A pipeline's components each keep their own exit status and their own standard output in
- * private files instead of the run's output, since a marker written into a pipe would land in the
- * next component's input. A failure is then credited only to the component that printed it [B3,R3].
- */
-function stagedScript(stages, marker, pipes) {
- /** Quote one private file of a component for the shell. */
- const file = (index, at, kind) => `'${join(String(pipes), `${index}-${at}.${kind}`).replaceAll("'", "'\\''")}'`;
- /** One component that records its own status and output, then exits with that status. */
- const component = (text, index, at) => `{ { {\n${text}\n}; printf '%s\\n' "$?" >> ${file(index, at, 'status')}; } | tee ${file(index, at, 'out')}; `
- + `pullboard_pipe_status=$(tail -n 1 ${file(index, at, 'status')} 2>/dev/null); (exit "\${pullboard_pipe_status:-125}"); }`;
- return stages.map((stage, index) => {
- const body = stage.pipeline.length > 1 ? stage.pipeline.map((text, at) => component(text, index, at)).join(' | ') : stage.text;
- return `{ printf '\\n${marker} begin ${index}\\n'; {\n${body}\n}; pullboard_stage_status=$?; `
- + `printf '\\n${marker} end ${index} %s\\n' "$pullboard_stage_status"; (exit "$pullboard_stage_status"); } ${stage.op}`;
- }).join('\n');
-}
-
-/**
- * Read each pipeline component's own status and, when it failed, its own output. A component that
- * recorded no status, or more than one, has a null status, so a line forged into its private file
- * can only make its stage unaccounted [B3,R3].
- */
-function readPipes(split, pipes) {
- /** Read one private component file, or null when the component never wrote it. */
- const read = (index, at, kind) => {
- const path = join(pipes, `${index}-${at}.${kind}`);
- return existsSync(path) ? readFileSync(path, 'utf8') : null;
- };
- return split.map((stage, index) => (stage.pipeline.length > 1 ? stage.pipeline.map((_, at) => {
- const lines = (read(index, at, 'status') ?? '').split('\n').filter(Boolean);
- const status = lines.length === 1 && /^\d+$/u.test(lines[0]) ? Number(lines[0]) : null;
- return { status, output: status ? read(index, at, 'out') : null };
- }) : null));
-}
-
-/** Cut a staged run's output back to the command's own lines and each stage's lines and status. */
-function readStages(output, marker, count) {
- const stages = Array.from({ length: count }, () => ({ status: null, lines: [], began: false }));
- const kept = [];
- let open = null;
- const lines = output.split('\n');
- for (const [index, line] of lines.entries()) {
- const found = line.startsWith(`${marker} `) ? /^(?:\S+) (begin|end) (\d+)(?: (\d+))?$/u.exec(line) : null;
- if (found) {
- if (kept.length && kept.at(-1) === '' && lines[index - 1] === '') kept.pop();
- const stage = stages[Number(found[2])];
- if (!stage) { open = null; continue; }
- if (found[1] === 'begin') { stage.began = true; open = stage; }
- else { stage.status = found[3] === undefined ? null : Number(found[3]); open = null; }
- continue;
- }
- kept.push(line);
- if (open) open.lines.push(line);
- }
- return { output: kept.join('\n'), stages: stages.map(({ status, lines: own, began }) => ({ status: began ? status : null, output: own.join('\n') })) };
-}
-
/**
* Run a shell command in a checkout for a digest: both streams in one pipe, in order, read whole
* however long, stdin closed so nothing waits on a person. With `stages`, each top-level stage's
@@ -351,9 +227,9 @@ export function runProfiledShell(root, command, { waitMs = 0, artifactDirectory,
[LANDING_RUN_ENV]: landing ? '1' : '0',
[LANDING_WAIVERS_ENV]: landing ? JSON.stringify(waivers) : '[]',
};
- // A remote run keeps no per-stage record, so it is never waivable: stages null fails closed [B3,R3].
+ // The registered worker returns the same complete stage/component accounting as a local run.
const run = gateLease?.runner ? { ...runOnRunner(root, command, { runner: gateLease.runner, source: gateLease.source,
- browser: gateLease.browser, pipefail, metadata: { ...(gateLease.runMetadata ?? {}), landing } }), ...(stages ? { stages: null } : {}) }
+ browser: gateLease.browser, pipefail, stages, waivers: landing ? waivers : [], metadata: { ...(gateLease.runMetadata ?? {}), landing } }) }
: runShell(root, command, { pipefail, env: inherited, stages });
const sandboxBlocked = run.isGreen ? null : run.sandboxBlocked ?? (run.executionRunner
// The controller cannot realpath remote files; retain the network denial signal without treating remote paths as local paths.
@@ -608,7 +484,7 @@ function fullGateRun(root, config, trustStamp = false, { waitMs = 0, log = gitPa
writeFileSync(log, output);
refuseSandboxBlocked(run);
if (isGreen && before !== null && committedTree(root) === before) writeFileSync(gitPath(root, STAMP), `${before}\n`);
- return { isGreen, isCached: false, output, seconds, log, profile, profilePath, ...(stages ? { stages: run.stages } : {}) };
+ return { isGreen, isCached: false, output, seconds, log, profile, profilePath, ...(run.executionRoot ? { executionRoot: run.executionRoot } : {}), ...(stages ? { stages: run.stages } : {}) };
}
/** Quote a fixed executable or selected path without permitting shell expansion. */
diff --git a/src/land.js b/src/land.js
index 0dfdbd07..a11d30c7 100644
--- a/src/land.js
+++ b/src/land.js
@@ -283,18 +283,20 @@ export function tapFailures(output, root) {
*/
export function accountedFailures(gate, root) {
if (gate.isGreen || !Array.isArray(gate.stages) || !gate.stages.length) return null;
+ // Only the authenticated worker checkout may relocate remote failure locations.
+ const executionRoot = gate.executionRoot ?? root;
const failures = [];
for (const stage of gate.stages) {
if (!Number.isInteger(stage.status)) return null;
if (stage.pipeline !== undefined) {
// In a pipeline each failing component must explain itself; a forwarded account credits no one else [B3,R3].
- const own = pipelineFailures(stage.pipeline, root);
+ const own = pipelineFailures(stage.pipeline, executionRoot);
if (!own || (stage.status === 0) !== (own.length === 0)) return null;
failures.push(...own);
continue;
}
if (stage.status === 0) continue;
- const own = stage.status === 1 ? tapFailures(stage.output ?? '', root) : null;
+ const own = stage.status === 1 ? tapFailures(stage.output ?? '', executionRoot) : null;
if (!own) return null;
failures.push(...own);
}
diff --git a/src/runner-worker.js b/src/runner-worker.js
index 04fe01df..0b707e06 100644
--- a/src/runner-worker.js
+++ b/src/runner-worker.js
@@ -7,6 +7,7 @@ import { delimiter, dirname, isAbsolute, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import * as resourceApi from './resources.js';
import { parseProcessCensus } from './process-census.js';
+import { gateStages, stagedScript, readPipes } from './gate-stages.js';
import { fileDenialWatcher } from './sandbox-denial.js';
import { once } from 'node:events';
import { pipeline } from 'node:stream/promises';
@@ -107,6 +108,8 @@ async function readSpec() {
|| 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.stageMarker !== undefined && !/^PULLBOARD_STAGE_[a-f0-9]{32}$/u.test(value.stageMarker)) throw new Error('invalid stage marker');
+ if (value.waivers !== undefined && (!Array.isArray(value.waivers) || value.waivers.some(entry => !entry || !['file', 'name'].includes(entry.kind) || typeof entry.test !== 'string' || !entry.test || Object.keys(entry).some(key => !['kind', 'test'].includes(key))))) throw new Error('invalid continuation projection');
if (value.origin !== undefined) {
if (typeof value.origin !== 'string') throw new Error('invalid work specification');
let origin;
@@ -132,7 +135,7 @@ async function readSpec() {
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', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js'];
+ const runtimeNames = ['resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js', 'gate-stages.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');
@@ -1045,12 +1048,15 @@ async function stopOwnedGroup(pid, closed, tracker) {
* A failed command also carries any file denial's evidence, classified here against this checkout (#706).
*/
async function runCommand(spec, root, env, sink, tracker) {
+ const split = spec.stageMarker ? gateStages(spec.command) : null;
+ const pipes = split?.some(stage => stage.pipeline.length > 1) ? mkdtempSync(join(dirname(root), 'gate-pipes-')) : null;
+ const command = split ? `(\n${stagedScript(split, spec.stageMarker, pipes)}\n) 2>&1` : spec.command;
let shell = '/bin/sh';
- let args = ['-c', spec.command];
+ let args = ['-c', 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]; }
+ if (probe.status === 0) args = ['-c', `set -o pipefail\n${command}`];
+ else if (existsSync('/bin/bash')) { shell = '/bin/bash'; args = ['-o', 'pipefail', '-c', 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'] });
@@ -1082,7 +1088,10 @@ async function runCommand(spec, root, env, sink, tracker) {
if (result.error) throw result.error;
const code = Number.isInteger(result.code) ? result.code : 1;
const denial = code === 0 && !result.signal ? null : denials.end();
- return { code, signal: result.signal ?? null, ...(denial ? { denial } : {}) };
+ let pipeStatuses = pipes ? readPipes(split, pipes, 8 * 1024 ** 2) : null;
+ // Accounting beyond this bound fails closed; it never turns an unaccounted failure green.
+ if (Buffer.byteLength(JSON.stringify(pipeStatuses)) > 8 * 1024 ** 2) pipeStatuses = null;
+ return { code, signal: result.signal ?? null, ...(spec.stageMarker ? { pipeStatuses } : {}), ...(denial ? { denial } : {}) };
}
/** Send the single nonce-bound result line after the complete merged output has drained. */
@@ -1090,7 +1099,7 @@ 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),
- ...(fields.refused ? { refused: fields.refused } : {}), ...(fields.denial ? { denial: fields.denial } : {}) };
+ ...(spec.stageMarker ? { pipeStatuses: fields.pipeStatuses ?? null } : {}), ...(fields.refused ? { refused: fields.refused } : {}), ...(fields.denial ? { denial: fields.denial } : {}) };
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()));
}
@@ -1182,7 +1191,7 @@ async function main() {
const env = scopedEnvironment(privateHome, temporary, canonicalMachineHome, lease, api, tracker.nodeOptions);
await checkoutHistory(api, runnerRoot, root, packFile, spec, env);
await installDependencies(root, runnerRoot, env, tracker);
- final = { ...(await runCommand(spec, root, { ...env, PULLBOARD_LANDING_RUN: spec.landing === true ? '1' : '0' }, sink, tracker)), root };
+ final = { ...(await runCommand(spec, root, { ...env, PULLBOARD_LANDING_RUN: spec.landing === true ? '1' : '0', PULLBOARD_LANDING_WAIVERS: JSON.stringify(spec.landing === true ? spec.waivers ?? [] : []) }, sink, tracker)), root };
} catch (error) {
const refused = setupRefusalCode(error);
const message = refused ? `${safeSetupMessage(error)} [${refused}]` : safeSetupMessage(error);
diff --git a/src/runners.js b/src/runners.js
index c5c04b2c..b2d1812e 100644
--- a/src/runners.js
+++ b/src/runners.js
@@ -11,6 +11,7 @@ import { configFromSource, defaults } from './config.js';
import { blockedPaths, secretsIn } from './hooks.js';
import { cleanGitEnvironment, headCommit, headTree, isClean, repoInfo, untracked } from './git.js';
import { Refused } from './refused.js';
+import { gateStages, readStages } from './gate-stages.js';
import { remoteFileDenial } from './sandbox-denial.js';
// Budget: 64 MiB bounds worst-case JSON bridge escaping below Node string limits.
@@ -19,7 +20,7 @@ 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', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js'];
+const RUNTIME_NAMES = ['resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js', 'gate-stages.js'];
/** Validate an SSH destination as one argument, never a command or an SSH option. */
export function validateRunner(value) {
@@ -377,7 +378,7 @@ function anonymousOrigin(root) {
}
/** Prepare the pinned request before negotiating history; cleanup owns only its scratch directory. */
-function requestFor(root, command, { runner, source, browser = false, pipefail = false, metadata = {} }) {
+function requestFor(root, command, { runner, source, browser = false, pipefail = false, stages = false, waivers = [], metadata = {} }) {
runner = validateRunner(runner);
const current = runnerSource(root);
if (!current || (source && (current.commit !== source.commit || current.tree !== source.tree))) {
@@ -395,8 +396,11 @@ function requestFor(root, command, { runner, source, browser = false, pipefail =
const directory = mkdtempSync(join(tmpdir(), 'pullboard-runner-send-'));
try {
const { worker, tooling, runtime } = trustedTooling();
+ const projection = metadata.landing === true && Array.isArray(waivers) ? waivers.filter(entry => ['file', 'name'].includes(entry?.kind) && typeof entry.test === 'string' && entry.test).map(({ kind, test }) => ({ kind, test })) : [];
+ if (secretsIn([{ path: 'runner continuation', line: 1, text: JSON.stringify(projection) }]).length) throw new Refused('RUNNER_SECRET', 'the continuation projection contains a possible secret; keep this run local');
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,
+ ...(stages ? { stageMarker: `PULLBOARD_STAGE_${randomUUID().replaceAll('-', '')}` } : {}), waivers: projection,
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));
@@ -438,7 +442,20 @@ function resultFrom(request, result) {
// The runner classified any file denial against its own checkout; only its evidence is trusted here.
const sandboxBlocked = receipt.denial === undefined ? null : remoteFileDenial(receipt.denial, request.runner.host);
if (receipt.denial !== undefined && (!sandboxBlocked || receipt.code === 0)) throw new RunnerDropped(request.runner.host);
- return { isGreen: receipt.code === 0 && !receipt.signal, output: output.toString('utf8'), sandboxBlocked,
+ let staged = null;
+ if (request.spec.stageMarker && !receipt.signal) {
+ const split = gateStages(request.spec.command);
+ if (split) {
+ const parsed = readStages(output.toString('utf8'), request.spec.stageMarker, split.length);
+ const pipes = receipt.pipeStatuses;
+ staged = { ...parsed, stages: parsed.stages.map((stage, index) => split[index].pipeline.length > 1
+ ? { ...stage, pipeline: Array.isArray(pipes) && pipes.length === split.length && Array.isArray(pipes[index])
+ && pipes[index].length === split[index].pipeline.length && pipes[index].every(entry => entry && (entry.status === null || Number.isInteger(entry.status) && entry.status >= 0 && entry.status <= 255) && (entry.output === null || typeof entry.output === 'string'))
+ ? pipes[index] : null } : stage) };
+ }
+ }
+ return { isGreen: receipt.code === 0 && !receipt.signal, output: staged?.output ?? output.toString('utf8'), sandboxBlocked,
+ ...(request.spec.stageMarker ? { stages: staged?.stages ?? null } : {}),
seconds: Math.round(receipt.wallMs / 1000), exitCode: receipt.code,
executionRunner: request.runner.host, executionRoot: receipt.root, remoteWallMs: receipt.wallMs,
executionSource: { commit: receipt.commit, tree: receipt.tree, tooling: request.spec.tooling } };
@@ -495,7 +512,8 @@ export async function runOnRunnerAsync(root, command, options) {
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; }
+ // Budget: eight MiB of component receipts plus base64/JSON framing, inside the total 64-MiB bound.
+ if (control.length > 16 * 1024 ** 2) { 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);