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): execute trusted private review checks on workers [C7,V4]
Corey Olson016090e3e04b
diff --git a/src/commands/verify.js b/src/commands/verify.jsindex d1231e0d..dadb12df 100644--- a/src/commands/verify.js+++ b/src/commands/verify.js@@ -43,6 +43,7 @@ import {} from '../relay.js';import {browserFreeChecksEnabled,+ gateRunnersFirstEnabled,} from '../settings.js';import {checkAtCommit,@@ -156,9 +157,9 @@ export async function verifyHere(ctx, id, { second, values }) {if (frozenCheck(item)) {const browser = !browserFreeChecksEnabled() || await checkNeedsBrowser(root, frozenCheck(item), { commit: checkedCommit, onFallback: browserAdmissionReporter(ctx.io, ctx.io.relayJson) });const gui = await checkNeedsGui(root, frozenCheck(item));- // A private checked composition needs this machine's live local gate markers [C7,V4].+ // Exact command classifiers still govern local and remote private-check admission [C7,V4].const shortEligible = Boolean(await explicitCheckFiles(root, frozenCheck(item), { commit: checkedCommit }));- check = await withGateSlot(root, async (lease) => { if (admitted) ({ trunk, review } = composeNow()); const ran = await nativeFlakes.verify(ctx, checkedItem, frozenCheck(item), { board, main: trunk.commit, commit: checkedCommit }, { ordered, withBoard, resourceAgent })(lease); return ran.state === 'pass' ? { ...ran, guardNote: guardRevertNote(root, checkedItem, lease) } : ran; }, { browser, gui, remote: false, agent: me.id, item: String(id), kind: 'review', itemCheck: true, shortEligible, onWait: queuedItemLease(ctx, item, me.id, 'review') });+ check = await withGateSlot(root, async (lease) => { if (admitted) ({ trunk, review } = composeNow()); const ran = await nativeFlakes.verify(ctx, checkedItem, frozenCheck(item), { board, main: trunk.commit, commit: checkedCommit }, { ordered, withBoard, resourceAgent })(lease); return ran.state === 'pass' ? { ...ran, guardNote: guardRevertNote(root, checkedItem, lease) } : ran; }, { browser, gui, remote: gateRunnersFirstEnabled(), agent: me.id, item: String(id), kind: 'review', itemCheck: true, shortEligible, onWait: queuedItemLease(ctx, item, me.id, 'review') });} else {check = checkAtCommit(root, checkedItem);}@@ -193,7 +194,7 @@ export async function verifyHere(ctx, id, { second, values }) {agentId: me.id,decision,reason: values.reason,- note: (textArg(ctx.io, values, 'note') ?? '') + unaffectedMove + (check?.guardNote ?? '') + (approvalNote ? `\n${approvalNote}` : ''),+ note: (textArg(ctx.io, values, 'note') ?? '') + unaffectedMove + (check?.guardNote ?? '') + (check?.executionNote ?? '') + (approvalNote ? `\n${approvalNote}` : ''),...(decision === 'REJECT' && values.cause !== undefined ? { cause: values.cause } : {}),head,digest,diff --git a/src/guard-revert.js b/src/guard-revert.jsindex 5eee3fe1..527bffbd 100644--- a/src/guard-revert.js+++ b/src/guard-revert.js@@ -70,7 +70,8 @@ export function guardRevertNote(root, item, lease) {const guard = guardOf(item);if (!guard) return '';let problem = '';- const run = checkAtCommit(root, item, { gateLease: lease, mutate: (directory) => { problem = revert(directory, guard); return problem; } });+ const run = checkAtCommit(root, item, { gateLease: lease, guard, mutate: (directory) => { problem = revert(directory, guard); return problem; } });+ problem ||= run.guardProblem ?? '';if (problem) throw new Refused('GUARD_NOT_FOUND', `#${item.item_id}'s guard ${guard.text} cannot be reverted: ${problem}`);if (run.state === 'pass') {throw new Refused('GUARD_CANNOT_FAIL', `#${item.item_id}'s check stays green with its guard ${guard.text} reverted, so the check does not test the guard`);diff --git a/src/native-flake-cli.js b/src/native-flake-cli.jsindex 1c7dddb6..27f32e0d 100644--- a/src/native-flake-cli.js+++ b/src/native-flake-cli.js@@ -75,7 +75,9 @@ export function verify(ctx, item, command, options, services) {pinRunMain(lease, observe);const result = checkAtCommit(ctx.info.root, item, { waitMs: lease.waitMs, gateLease: lease });if (result.state === 'red') await observe({ isGreen: false, output: result.outputPath ? readFileSync(result.outputPath, 'utf8') : result.output,- log: result.outputPath, profilePath: result.profilePath, executionRoot: result.executionRoot, executionSourceUnchanged: result.executionSourceUnchanged }, { root: ctx.info.root, command, lease });+ log: result.outputPath, profilePath: result.profilePath, executionRoot: result.executionRoot, executionSourceUnchanged: result.executionSourceUnchanged, executionRunner: result.executionRunner,+ executionLoad: result.executionLoad, executionMain: result.executionMain, executionSource: result.executionSource,+ environment: result.environment, profile: result.profile, rawOutputPath: result.rawOutputPath, rawOutputSha256: result.rawOutputSha256 }, { root: ctx.info.root, command, lease });return result;};}diff --git a/src/native-flakes.js b/src/native-flakes.jsindex d356240c..3f955841 100644--- a/src/native-flakes.js+++ b/src/native-flakes.js@@ -132,7 +132,10 @@ function privateProbe(root, commit, command, lease, policyCommit) {const check = checkAtCommit(root, item, { gateLease: lease });const output = check.outputPath ? readFileSync(check.outputPath, 'utf8') : '';return { isGreen: check.state === 'pass', unverified: check.state === 'unverified', output, log: check.outputPath,- executionRoot: check.executionRoot, executionSourceUnchanged: check.executionSourceUnchanged, profilePath: check.profilePath, profile: check.profile };+ executionRoot: check.executionRoot, executionSourceUnchanged: check.executionSourceUnchanged, profilePath: check.profilePath, profile: check.profile,+ executionRunner: check.executionRunner, executionLoad: check.executionLoad, executionMain: check.executionMain,+ executionSource: check.executionSource, environment: check.environment,+ rawOutputPath: check.rawOutputPath, rawOutputSha256: check.rawOutputSha256 };}/**diff --git a/src/runner-private-check.js b/src/runner-private-check.jsnew file mode 100644index 00000000..4f71f60d--- /dev/null+++ b/src/runner-private-check.js@@ -0,0 +1,90 @@+/** Controller-side private-check artifact custody; worker framing never comes from command text [C7,V4]. */+import { createHash } from 'node:crypto';+import { closeSync, mkdtempSync, openSync, readSync, writeSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runOnRunner } from './runners.js';+import { privateCheckEnvelope } from './runner-private-mode.js';+import { policyGit, trunkRef } from './trusted-policy-read.js';+import { timingFromLog, timingRunner } from './timing.js';++/** Copy one authenticated phase without buffering the full command output into controller memory. */+function phaseCopy(raw, phase, path) {+ const input = openSync(raw, 'r');+ const output = openSync(path, 'wx', 0o600);+ const hash = createHash('sha256');+ const buffer = Buffer.alloc(64 * 1024);+ let offset = 0;+ const captures = [];+ let captureBytes = 0;+ try {+ while (offset < phase.length) {+ const count = readSync(input, buffer, 0, Math.min(buffer.length, phase.length - offset), phase.offset + offset);+ if (!count) throw new Error('private-check phase capture is incomplete');+ const bytes = buffer.subarray(0, count);+ hash.update(bytes);+ let written = 0;+ while (written < count) {+ const progress = writeSync(output, bytes, written, count - written);+ if (!progress) throw new Error('private-check artifact write made no progress');+ written += progress;+ }+ captures.push(Buffer.from(bytes));+ captureBytes += count;+ while (captureBytes > 8 * 1024 * 1024) {+ const excess = captureBytes - 8 * 1024 * 1024;+ if (captures[0].length <= excess) captureBytes -= captures.shift().length;+ else { captures[0] = captures[0].subarray(excess); captureBytes -= excess; }+ }+ offset += count;+ }+ if (hash.digest('hex') !== phase.sha256) throw new Error('private-check phase digest does not match');+ return Buffer.concat(captures, captureBytes).toString('utf8');+ } finally { closeSync(input); closeSync(output); }+}++/** Run only under an actual runner lease, preserving raw evidence even when formatting or transport fails. */+export function runnerPrivateCheck(root, item, command, policy, lease, guard, waitMs, format) {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-private-runner-'));+ const ref = trunkRef(root);+ const mode = privateCheckEnvelope({ kind: 'private-check', version: 1, install: policy.config.check.install,+ check: command, timeoutMs: policy.config.check.timeoutMs, policyCommit: policy.commit,+ trunk: { ref, commit: policyGit(root, ['rev-parse', `${ref}^{commit}`]).trim() }, guard });+ const checkedSource = { commit: item.item_commit, tree: policyGit(root, ['rev-parse', `${item.item_commit}^{tree}`]).trim() };+ const started = Date.now();+ lease.tracker?.mark('runAt');+ const result = runOnRunner(root, command, { runner: lease.runner, source: lease.source, browser: lease.browser,+ metadata: lease.runMetadata, checkedSource, privateCheck: mode, rawOutputPath: join(directory, 'raw.log') });+ lease.tracker?.mark('ranAt');+ lease.environment = result.environment ?? null;+ lease.gui = result.executionCapabilities?.gui ?? null;+ lease.executionAdmission = result.executionAdmission ?? null;+ let installCapture = '';+ let checkCapture = '';+ let installLogPath = '';+ let checkLogPath = '';+ let captureProblem = false;+ try {+ for (const name of ['install', 'check']) {+ const phase = result.privateCheck.receipt.phases[name];+ if (!phase) continue;+ const path = join(directory, `${name}.log`);+ const capture = phaseCopy(result.rawOutputPath, phase, path);+ if (name === 'install') { installCapture = capture; installLogPath = path; }+ else { checkCapture = capture; checkLogPath = path; }+ }+ } catch { captureProblem = true; }+ const profile = checkLogPath ? timingFromLog(checkLogPath, timingRunner(command)) : { files: [], tests: [] };+ const formatted = format(captureProblem ? 'unverified' : result.privateCheck.state, captureProblem ? 'private-check output could not be authenticated or saved' : result.privateCheck.stage, installCapture, checkCapture,+ { root, item, commandRoot: result.executionRoot, installLogPath, checkLogPath, waitMs,+ timingProfile: { ...profile, wallMs: Date.now() - started, environment: result.environment,+ executionRunner: result.executionRunner, executionSource: result.executionSource, executionMain: result.executionMain,+ executionLoad: result.executionLoad, executionAdmission: result.executionAdmission,+ privateCheckPolicySha256: mode.sha256, rawOutputPath: result.rawOutputPath, rawOutputSha256: result.rawOutputSha256 },+ environment: result.environment, executionSourceUnchanged: result.privateCheck.receipt.sourceUnchanged });+ return { ...formatted, sandboxBlocked: result.sandboxBlocked ?? formatted.sandboxBlocked, executionRunner: result.executionRunner, executionSource: result.executionSource,+ executionLoad: result.executionLoad, executionMain: result.executionMain, executionAdmission: result.executionAdmission,+ rawOutputPath: result.rawOutputPath, rawOutputSha256: result.rawOutputSha256,+ guardProblem: result.privateCheck.receipt.guard?.problem ?? '',+ executionNote: `\nprivate check executed on runner ${result.executionRunner} at ${checkedSource.commit}; trusted policy ${policy.commit}; raw output ${result.rawOutputPath} sha256 ${result.rawOutputSha256}` };+}diff --git a/src/runner-private-mode.js b/src/runner-private-mode.jsnew file mode 100644index 00000000..56ddee85--- /dev/null+++ b/src/runner-private-mode.js@@ -0,0 +1,76 @@+/** Canonical controller-owned private-check policy shared by the authenticated runner endpoints [C7,V4]. */+import { createHash } from 'node:crypto';++/** Refuse unknown protocol fields rather than silently changing what the policy hash covers. */+function keys(value, allowed) {+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !allowed.includes(key))) throw new Error('invalid private-check fields');+}++/** Validate immutable Git object names without interpreting them as Git revisions or arguments. */+function object(value) {+ return typeof value === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(value);+}++/** Keep declarative guard paths inside the private checkout before the worker resolves symlinks. */+function guardPath(value) {+ return typeof value === 'string' && value.length > 0 && value.length <= 4096 && !value.startsWith('/') && !/[\\\u0000-\u001f\u007f]/u.test(value) && !value.split('/').some(part => part === '..' || part === '' || part === '.');+}++/** Normalize only the two existing frozen guard forms, never an executable callback or arbitrary patch command. */+export function privateGuard(value) {+ if (value == null) return null;+ if (typeof value.patch === 'string') {+ keys(value, ['text', 'patch']);+ if (!guardPath(value.patch) || value.text !== `patch ${value.patch}`) throw new Error('invalid private-check guard');+ return { text: value.text, patch: value.patch };+ }+ keys(value, ['text', 'path', 'from', 'to']);+ if (!guardPath(value.path) || !Number.isSafeInteger(value.from) || value.from < 1 || !Number.isSafeInteger(value.to) || value.to < value.from || value.text !== `${value.path}:${value.from}-${value.to}`) throw new Error('invalid private-check guard');+ return { text: value.text, path: value.path, from: value.from, to: value.to };+}++/** Bind every controller-selected policy input in one canonical envelope; checked source is separately receipt-bound. */+export function privateCheckEnvelope(value) {+ keys(value, ['kind', 'version', 'install', 'check', 'timeoutMs', 'policyCommit', 'trunk', 'guard', 'sha256']);+ if (value.kind !== 'private-check' || value.version !== 1 || typeof value.install !== 'string' || typeof value.check !== 'string' || !value.check.trim() || !Number.isSafeInteger(value.timeoutMs) || value.timeoutMs < 1 || value.timeoutMs > 2147483647 || !object(value.policyCommit)) throw new Error('invalid private-check policy');+ keys(value.trunk, ['ref', 'commit']);+ if (typeof value.trunk.ref !== 'string' || !value.trunk.ref.startsWith('refs/heads/') || /[\s\u0000-\u001f\u007f]/u.test(value.trunk.ref) || !object(value.trunk.commit) || value.policyCommit.length !== value.trunk.commit.length) throw new Error('invalid private-check trunk');+ const policy = { kind: 'private-check', version: 1, install: value.install, check: value.check, timeoutMs: value.timeoutMs, policyCommit: value.policyCommit, trunk: { ref: value.trunk.ref, commit: value.trunk.commit }, guard: privateGuard(value.guard) };+ const sha256 = createHash('sha256').update(JSON.stringify(policy)).digest('hex');+ if (value.sha256 !== undefined && value.sha256 !== sha256) throw new Error('private-check policy digest does not match');+ return { ...policy, sha256 };+}++/** Authenticate the complete phase layout before the controller copies any bytes into a named phase artifact. */+export function privateCheckPhases(mode, receipt, totalBytes) {+ keys(receipt, ['kind', 'version', 'requestSha256', 'phases', 'guard', 'sourceUnchanged', 'problem']);+ if (receipt.kind !== 'private-check' || receipt.version !== 1 || receipt.requestSha256 !== mode.sha256 || typeof receipt.sourceUnchanged !== 'boolean' || !Number.isSafeInteger(totalBytes) || totalBytes < 0) throw new Error('invalid private-check receipt');+ keys(receipt.phases, ['install', 'check']);+ let offset = 0;+ for (const name of ['install', 'check']) {+ const phase = receipt.phases[name];+ if (phase == null) continue;+ keys(phase, ['offset', 'length', 'sha256', 'code', 'signal', 'timedOut']);+ if (phase.offset !== offset || !Number.isSafeInteger(phase.length) || phase.length < 0 || !/^[a-f0-9]{64}$/u.test(phase.sha256 ?? '') || !Number.isInteger(phase.code) || phase.code < 0 || phase.code > 255 || phase.signal !== null && typeof phase.signal !== 'string' || typeof phase.timedOut !== 'boolean') throw new Error('invalid private-check phase');+ offset += phase.length;+ if (!Number.isSafeInteger(offset) || offset > totalBytes) throw new Error('private-check phase exceeds its output');+ }+ if (offset !== totalBytes || !mode.install && receipt.phases.install != null || mode.install && !receipt.phases.install && !receipt.problem) throw new Error('incomplete private-check phases');+ if (receipt.problem != null) {+ keys(receipt.problem, ['stage', 'message']);+ if (!['guard', 'install', 'check'].includes(receipt.problem.stage) || typeof receipt.problem.message !== 'string' || !receipt.problem.message || receipt.problem.message.length > 4096) throw new Error('invalid private-check problem');+ }+ if (mode.guard) {+ keys(receipt.guard, ['applied', 'problem']);+ if (typeof receipt.guard.applied !== 'boolean' || typeof receipt.guard.problem !== 'string' || receipt.guard.problem.length > 4096 || receipt.guard.applied && receipt.guard.problem || !receipt.guard.applied && !receipt.guard.problem || receipt.guard.applied && receipt.sourceUnchanged) throw new Error('invalid private-check guard receipt');+ } else if (receipt.guard != null) throw new Error('unexpected private-check guard receipt');+ const install = receipt.phases.install;+ const check = receipt.phases.check;+ if (install && (install.code !== 0 || install.signal || install.timedOut) && check) throw new Error('private check ran after a failed install');+ if (receipt.problem) return { state: 'unverified', stage: receipt.problem.message };+ if (mode.guard && !receipt.guard.applied) return { state: 'unverified', stage: 'guard could not be reverted' };+ if (install && (install.code !== 0 || install.signal || install.timedOut)) return { state: 'unverified', stage: install.timedOut ? 'install timed out' : 'install failed' };+ if (!check) throw new Error('missing private-check completion');+ if (check.timedOut || check.signal) return { state: 'unverified', stage: check.timedOut ? 'check timed out' : 'check could not complete' };+ return { state: check.code === 0 ? 'pass' : 'red', stage: check.code === 0 ? 'check' : `check failed (exit ${check.code})` };+}diff --git a/src/runner-worker.js b/src/runner-worker.jsindex 518a35da..cecff38e 100644--- a/src/runner-worker.js+++ b/src/runner-worker.js@@ -36,6 +36,7 @@ import * as resourceApi from './resources.js';import { createDescendantTracker } from './runner-custody.js';import { Refused } from './refused.js';import { guiSession } from './gui-session.js';+import { privateCheckEnvelope } from './runner-private-mode.js';import {gateStages,stagedScript,@@ -62,6 +63,8 @@ let activeDescendantTracker = null;// Budget: report a named failure within 30 seconds after command exit or transport cancellation.const CLEANUP_BUDGET_MS = 30_000;let cleanupDeadline = Infinity;+let phaseCleanupDeadline = Infinity;+let phaseCleanupTimer = null;let cleanupTimedOut = false;let cleanupTimer = null;let cleanupStage = 'command exit';@@ -77,9 +80,25 @@ function beginCleanup() {cleanupTimer.unref();}+/** Bound an intermediate install drain without starting or extending the final/disconnect budget. */+function beginPhaseCleanup() {+ if (Number.isFinite(phaseCleanupDeadline)) return;+ phaseCleanupDeadline = Date.now() + CLEANUP_BUDGET_MS;+ phaseCleanupTimer = setTimeout(reportCleanupTimeout, CLEANUP_BUDGET_MS);+ phaseCleanupTimer.unref();+}++/** A fully verified successful intermediate drain is the only boundary allowed to clear its own timer. */+function clearPhaseCleanup() {+ if (transportLost || cleanupTimedOut || Number.isFinite(cleanupDeadline) || ownedChildren.size) return;+ clearTimeout(phaseCleanupTimer);+ phaseCleanupTimer = null;+ phaseCleanupDeadline = Infinity;+}+/** Report an unresolved cleanup once so the controller can fail without retrying the command. */function reportCleanupTimeout() {- if (cleanupTimedOut || Date.now() < cleanupDeadline) return;+ if (cleanupTimedOut || Date.now() < Math.min(cleanupDeadline, phaseCleanupDeadline)) return;cleanupTimedOut = true;const details = { id: workerId, stage: cleanupStage, ...(cleanupDetails?.() ?? {}) };// A timeout may arrive after ordinary job deletion while output is still flushing.@@ -176,6 +195,11 @@ async function readSpec() {|| (value.browserByLaunch !== undefined && typeof value.browserByLaunch !== '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.trustedMode !== undefined) {+ const mode = privateCheckEnvelope(value.trustedMode);+ if (mode.policyCommit.length !== value.commit.length || value.command !== mode.check || value.landing === true || value.stageMarker !== undefined) throw new Error('invalid trusted private-check source');+ value.trustedMode = mode;+ }if (value.timeoutMs !== undefined && (value.landing !== true || !Number.isSafeInteger(value.timeoutMs) || value.timeoutMs < 1 || value.timeoutMs > 2_147_483_647)) throw new Error('invalid landing timeout');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');@@ -204,7 +228,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 = ['runner-custody.js', 'resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js', 'gate-stages.js', 'child-journal-preload.js', 'execution-environment.js', 'runner-load.js', 'gui-session.js'];+ const runtimeNames = ['runner-custody.js', 'resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js', 'gate-stages.js', 'child-journal-preload.js', 'execution-environment.js', 'runner-load.js', 'gui-session.js', 'runner-private-mode.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');@@ -532,7 +556,11 @@ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {const historyCount = Number(await git(cache, ['rev-list', '--count', spec.commit], env));if (!Number.isSafeInteger(historyCount) || historyCount < 1) throw new Error('source history is incomplete');if (spec.originBase) await git(cache, ['merge-base', '--is-ancestor', spec.originBase, spec.commit], env);- const closure = new Set((await git(cache, ['rev-list', '--objects', spec.commit], env)).split(/\r?\n/u)+ const roots = [...new Set([spec.commit, ...(spec.trustedMode ? [spec.trustedMode.policyCommit, spec.trustedMode.trunk.commit] : [])])];+ for (const commit of roots) {+ if (await git(cache, ['cat-file', '-t', commit], env) !== 'commit') throw new Error('trusted policy history is incomplete');+ }+ const closure = new Set((await git(cache, ['rev-list', '--objects', ...roots], 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));@@ -575,10 +603,18 @@ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {}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);+ for (const commit of roots) await git(cache, ['update-ref', `refs/pullboard/candidates/${commit}`, 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 (spec.trustedMode) {+ const mode = spec.trustedMode;+ await git(root, ['check-ref-format', mode.trunk.ref], env);+ await git(root, ['-c', 'protocol.file.allow=always', 'fetch', '--no-tags', cache,+ `refs/pullboard/candidates/${mode.policyCommit}:refs/pullboard/trusted-policy`,+ `refs/pullboard/candidates/${mode.trunk.commit}:${mode.trunk.ref}`], env);+ await git(root, ['config', '--local', '--replace-all', 'pullboard.trunk', mode.trunk.ref], env);+ }for (let index = 0; index < spec.tags.length; index++) {const tag = spec.tags[index];const deliveryRef = `refs/pullboard/tag-delivery/${spec.id}/${index}`;@@ -647,16 +683,18 @@ function outputSink() {const hash = createHash('sha256');const wallStart = Date.now();let pipeFailed = false;+ let length = 0;const write = part => {const bytes = Buffer.isBuffer(part) ? part : Buffer.from(part);hash.update(bytes);+ length += bytes.length;// A lost transport never drains. Discard instead of waiting: a paused command pipe never closes, its group never// finishes draining, and with only unref'd timers left the worker exits before releasing its lease (#888).if (transportLost || process.stdout.destroyed) return Promise.resolve();if (!process.stdout.write(bytes)) return Promise.race([once(process.stdout, 'drain'), transportGone]);return Promise.resolve();};- return { hash, write, get pipeFailed() { return pipeFailed; }, set pipeFailed(value) { pipeFailed = value; }, wallStart };+ return { hash, write, get length() { return length; }, get pipeFailed() { return pipeFailed; }, set pipeFailed(value) { pipeFailed = value; }, wallStart };}/** Stop only the detached command process group owned by this worker, then await its close event. */@@ -690,7 +728,8 @@ async function stopOwnedGroup(pid, closed, tracker) {* Run the exact requested command in its isolated checkout, retaining raw output and real test exit status.* A failed command also carries any file denial's evidence, classified here against this checkout (#706).*/-async function runCommand(spec, root, env, sink, tracker) {+async function runCommand(spec, root, env, sink, tracker, { continuation = false } = {}) {+ const commandCleanup = continuation ? beginPhaseCleanup : beginCleanup;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;@@ -706,7 +745,7 @@ async function runCommand(spec, root, env, sink, tracker) {const child = owned.child;// A surviving descendant can keep stdio open after the command leader exits.// Start the budget at exit rather than waiting for those pipes to close.- child.once('exit', beginCleanup);+ child.once('exit', commandCleanup);let outputError = null;let writes = Promise.resolve();const closed = owned.closed;@@ -727,7 +766,7 @@ async function runCommand(spec, root, env, sink, tracker) {const result = await closed;clearTimeout(timeout);if (timeoutDrain) await timeoutDrain;- beginCleanup();+ commandCleanup();cleanupStage = 'command output';await writes;cleanupStage = 'command descendants';@@ -739,6 +778,10 @@ async function runCommand(spec, root, env, sink, tracker) {if (sink.pipeFailed) return { code: 1, signal: result.signal ?? 'SIGHUP' };if (result.error) throw result.error;const code = Number.isInteger(result.code) ? result.code : 1;+ if (continuation && code === 0 && !result.signal && !timedOut && !outputError && !sink.pipeFailed) {+ await tracker.verifyAfterGroups();+ clearPhaseCleanup();+ }const denial = code === 0 && !result.signal ? null : denials.end();let pipeStatuses = pipes ? readPipes(split, pipes, 8 * 1024 ** 2) : null;// Accounting beyond this bound fails closed; it never turns an unaccounted failure green.@@ -746,6 +789,66 @@ async function runCommand(spec, root, env, sink, tracker) {return { code: timedOut ? 1 : code, signal: result.signal ?? null, ...(timedOut ? { timedOut: true } : {}), ...(spec.stageMarker ? { pipeStatuses } : {}), ...(denial ? { denial } : {}) };}+/** Apply only the frozen declarative guard inside this exact private checkout, never a controller callback. */+async function applyPrivateGuard(root, guard, env) {+ if (!guard) return null;+ try {+ const path = join(root, guard.patch ?? guard.path);+ const canonical = realpathSync(path);+ if (!canonical.startsWith(realpathSync(root) + '/')) throw new Error('guard escapes its private checkout');+ if (guard.patch) await git(root, ['apply', '-R', '--whitespace=nowarn', '--', guard.patch], env);+ else {+ const lines = readFileSync(path, 'utf8').split('\n');+ if (guard.to > lines.length) throw new Error('guard lines are absent');+ lines.splice(guard.from - 1, guard.to - guard.from + 1);+ writeFileSync(path, lines.join('\n'));+ }+ return { applied: true, problem: '' };+ } catch { return { applied: false, problem: `guard ${guard.text} cannot be reverted inside the submitted checkout` }; }+}++/** Execute the trusted phases against one absolute policy deadline, with worker-owned byte boundaries. */+async function runPrivateCheck(spec, root, env, sink, tracker) {+ const mode = spec.trustedMode;+ const phases = { install: null, check: null };+ const guard = await applyPrivateGuard(root, mode.guard, env);+ let problem = guard && !guard.applied ? { stage: 'guard', message: guard.problem } : null;+ const deadline = Date.now() + mode.timeoutMs;+ let denial = null;+ /** Capture phase framing outside command output, so candidate text cannot forge a phase receipt. */+ const phase = async (name, command, continuation) => {+ const offset = sink.length;+ const hash = createHash('sha256');+ const phaseSink = Object.create(sink);+ phaseSink.write = part => { const bytes = Buffer.isBuffer(part) ? part : Buffer.from(part); hash.update(bytes); return sink.write(bytes); };+ const remaining = deadline - Date.now();+ if (remaining <= 0) { problem = { stage: name, message: `${name} timed out` }; return null; }+ let result;+ try { result = await runCommand({ ...spec, command, stageMarker: undefined, timeoutMs: remaining, pipefail: false }, root, env, phaseSink, tracker, { continuation }); }+ catch {+ problem = { stage: name, message: `${name} could not start or its output could not be saved` };+ result = { code: 1, signal: null };+ }+ denial = result.denial ?? denial;+ const value = { offset, length: sink.length - offset, sha256: hash.digest('hex'), code: result.code, signal: result.signal ?? null, timedOut: result.timedOut === true };+ phases[name] = value;+ return value;+ };+ if (!problem && mode.install) await phase('install', mode.install, true);+ const installed = !mode.install || phases.install?.code === 0 && !phases.install.signal && !phases.install.timedOut;+ if (!problem && installed) await phase('check', mode.check, false);+ const last = phases.check ?? phases.install;+ let sourceUnchanged = false;+ if (!mode.guard) {+ try {+ const state = (await git(root, ['status', '--porcelain=v2', '--branch', '--untracked-files=normal'], env)).split('\n').filter(Boolean);+ sourceUnchanged = state.includes('# branch.oid ' + spec.commit) && state.every(line => line.startsWith('# '));+ } catch { sourceUnchanged = false; }+ }+ return { code: problem ? 1 : last?.code ?? 1, signal: last?.signal ?? null, ...(denial ? { denial } : {}),+ trustedMode: { kind: 'private-check', version: 1, requestSha256: mode.sha256, phases, guard, sourceUnchanged, ...(problem ? { problem } : {}) } };+}+/** Send the single nonce-bound result line after the complete merged output has drained. */async function receipt(spec, fields, sink) {await flushStdout();@@ -754,6 +857,7 @@ async function receipt(spec, fields, sink) {runtimeSha256: spec.runtime.sha256, toolingSha256: spec.tooling.sha256, root: fields.root ?? '', outputSha256: sink.hash.digest('hex'), wallMs: Math.max(0, Date.now() - sink.wallStart),// The execution host's load and the pinned main this run used, so a paired rerun here can be judged (#925).main: typeof spec.main === 'string' ? spec.main : null, load: { average: loadavg(), cpus: availableParallelism(), freeMB: Math.floor(freemem() / 1048576) },+ ...(fields.trustedMode ? { trustedMode: fields.trustedMode } : {}),...(spec.stageMarker ? { pipeStatuses: fields.pipeStatuses ?? null } : {}), ...(fields.timedOut ? { timedOut: true } : {}), ...(fields.refused ? { refused: fields.refused } : {}), ...(fields.browserRefused ? { browserRefused: true } : {}), ...(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()));@@ -856,17 +960,23 @@ async function main() {const env = scopedEnvironment(privateHome, temporary, canonicalMachineHome, lease, api, tracker.nodeOptions);setupStep = 'source history checkout';await checkoutHistory(api, runnerRoot, root, packFile, spec, env);- setupStep = 'committed dependencies';- await installDependencies(root, runnerRoot, env, tracker);+ if (!spec.trustedMode) {+ setupStep = 'committed dependencies';+ await installDependencies(root, runnerRoot, env, tracker);+ }setupStep = 'command start';const browserRefusal = join(runDirectory, 'browser-refusal.json');- final = { ...(await runCommand(spec, root, { ...env, PULLBOARD_LANDING_RUN: spec.landing === true ? '1' : '0', [api.BROWSER_REFUSAL_FILE_ENV]: browserRefusal, ...(typeof spec.browserByLaunch === 'boolean' ? { PULLBOARD_TEST_BROWSER_BY_LAUNCH: spec.browserByLaunch ? '1' : '0' } : {}), PULLBOARD_LANDING_WAIVERS: JSON.stringify(spec.landing === true ? spec.waivers ?? [] : []) }, sink, tracker)), root };+ const commandEnv = { ...env, PULLBOARD_LANDING_RUN: spec.landing === true ? '1' : '0', [api.BROWSER_REFUSAL_FILE_ENV]: browserRefusal, ...(typeof spec.browserByLaunch === 'boolean' ? { PULLBOARD_TEST_BROWSER_BY_LAUNCH: spec.browserByLaunch ? '1' : '0' } : {}), PULLBOARD_LANDING_WAIVERS: JSON.stringify(spec.landing === true ? spec.waivers ?? [] : []) };+ final = { ...(spec.trustedMode ? await runPrivateCheck(spec, root, commandEnv, sink, tracker) : await runCommand(spec, root, commandEnv, sink, tracker)), root };if (final.code !== 0 && existsSync(browserRefusal)) final.browserRefused = true;} catch (error) {const refused = setupRefusalCode(error);const message = refused ? `${safeSetupMessage(error, setupStep)} [${refused}]` : safeSetupMessage(error, setupStep);- if (!transportLost) await sink.write(`${message}\n`);- final = { code: 1, signal: transportLost ? 'SIGHUP' : null, error: message, root: '', ...(refused ? { refused } : {}) };+ if (!transportLost && !spec?.trustedMode) await sink.write(`${message}\n`);+ final = { code: 1, signal: transportLost ? 'SIGHUP' : null, error: message, root: '', ...(refused ? { refused } : {}),+ ...(spec?.trustedMode ? { trustedMode: { kind: 'private-check', version: 1, requestSha256: spec.trustedMode.sha256,+ phases: { install: null, check: null }, guard: spec.trustedMode.guard ? { applied: false, problem: message } : null,+ sourceUnchanged: false, problem: { stage: 'check', message } } } : {}) };} finally {beginCleanup();cleanupStage = 'final descendants';@@ -891,10 +1001,11 @@ async function main() {cleanupStage = 'job files';if (runDirectory && !cleanupTimedOut) { try { rmSync(runDirectory, { recursive: true, force: true }); } catch {} }}- if (transportLost || cleanupTimedOut) { clearTimeout(cleanupTimer); process.exitCode = 1; stopReading(); return; }+ if (transportLost || cleanupTimedOut) { clearTimeout(cleanupTimer); clearTimeout(phaseCleanupTimer); process.exitCode = 1; stopReading(); return; }cleanupStage = 'result receipt';await receipt(spec, { ...final, gui }, sink);clearTimeout(cleanupTimer);+ clearTimeout(phaseCleanupTimer);process.exitCode = 0;stopReading();}diff --git a/src/runners.js b/src/runners.jsindex f83ff1a3..d626fc0b 100644--- a/src/runners.js+++ b/src/runners.js@@ -21,7 +21,9 @@ import {realpathSync,renameSync,rmSync,+ statSync,writeFileSync,+ writeSync,} from 'node:fs';import { tmpdir } from 'node:os';import {@@ -54,6 +56,7 @@ import {} from './git.js';import { Refused } from './refused.js';import { recordRunnerGui } from './resources.js';+import { privateCheckEnvelope, privateCheckPhases } from './runner-private-mode.js';import {gateStages,readStages,@@ -70,7 +73,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 = ['runner-custody.js', 'resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js', 'gate-stages.js', 'child-journal-preload.js', 'execution-environment.js', 'runner-load.js', 'gui-session.js'];+const RUNTIME_NAMES = ['runner-custody.js', 'resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js', 'gate-stages.js', 'child-journal-preload.js', 'execution-environment.js', 'runner-load.js', 'gui-session.js', 'runner-private-mode.js'];/** Validate an SSH destination as one argument, never a command or an SSH option. */export function validateRunner(value) {@@ -123,11 +126,12 @@ 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 protect = source.protect ?? config.protect;const blobs = records.map(record => {const match = /^(\d+) (\w+) ([a-f0-9]{40,64})\t([\s\S]+)$/u.exec(record);if (!match || match[2] !== 'blob') throw new Refused('RUNNER_SOURCE', 'runner source contains a submodule or unsupported object; keep this run local');const [, , , object, path] = match;- if (blockedPaths([path], config.protect).length || /(?:^|\/)board\.sqlite(?:-(?:wal|shm))?$/u.test(path)) {+ if (blockedPaths([path], protect).length || /(?:^|\/)board\.sqlite(?:-(?:wal|shm))?$/u.test(path)) {throw new Refused('RUNNER_SECRET', 'committed runner source includes a blocked private file; remove it before remote execution');}return { object, path };@@ -185,7 +189,7 @@ function sourceObjects(root, source) {if (secretsIn(commit.split('\n').map((text, index) => ({ path: 'commit', line: index + 1, text }))).length) {throw new Refused('RUNNER_SECRET', 'the commit metadata contains a possible secret; keep this run local and correct the metadata');}- return config.protect;+ return protect;}/** Reject blocked historical paths as well as current ones before an object pack crosses SSH. */@@ -306,7 +310,7 @@ 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])+ const records = sourceGit(root, ['rev-list', '--objects', source.commit, ...(source.extraCommits ?? []), '--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');@@ -316,7 +320,7 @@ function historyPack(root, source, tips, directory, tags = [], knownTagObjects =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()+ const config = source.protect ? { protect: source.protect } : 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)) {@@ -472,27 +476,40 @@ function anonymousOrigin(root) {}/** Prepare the pinned request before negotiating history; cleanup owns only its scratch directory. */-function requestFor(root, command, { runner, source, browser = false, byLaunch, pipefail = false, stages = false, waivers = [], metadata = {} }) {+function requestFor(root, command, { runner, source, browser = false, byLaunch, pipefail = false, stages = false, waivers = [], metadata = {}, privateCheck, checkedSource, rawOutputPath }) {runner = validateRunner(runner);const current = runnerSource(root);if (!current || (source && (current.commit !== source.commit || current.tree !== source.tree))) {throw new Refused('RUNNER_SOURCE_CHANGED', 'the queued source changed; restore the committed tree and retry the run');}- if (secretsIn(command.split('\n').map((text, index) => ({ path: 'run command', line: index + 1, text }))).length) {+ const trustedMode = privateCheck ? privateCheckEnvelope(privateCheck) : null;+ let selected = current;+ if (trustedMode) {+ if (!checkedSource || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(checkedSource.commit ?? '')+ || sourceGit(root, ['rev-parse', `${checkedSource.commit}^{tree}`]).trim() !== checkedSource.tree+ || command !== trustedMode.check || typeof rawOutputPath !== 'string' || !isAbsolute(rawOutputPath)) {+ throw new Refused('RUNNER_SOURCE_CHANGED', 'the trusted private check source or output capture is invalid; restore its pinned commit and retry');+ }+ const owner = configFromSource(sourceGit(root, ['show', `${trustedMode.policyCommit}:pullboard.json`]));+ selected = { commit: checkedSource.commit, tree: checkedSource.tree,+ extraCommits: [...new Set([trustedMode.policyCommit, trustedMode.trunk.commit])], protect: owner.protect };+ }+ if (secretsIn([command, trustedMode?.install ?? ''].flatMap(value => value.split('\n')).map((text, index) => ({ path: 'run command', line: index + 1, text }))).length) {throw new Refused('RUNNER_SECRET', 'the run command contains a possible secret; use a command that does not transfer credentials');}- const protect = sourceObjects(root, current);- protectHistory(root, current, protect);+ const protect = sourceObjects(root, selected);+ for (const commit of [selected.commit, ...(selected.extraCommits ?? [])]) protectHistory(root, { commit }, protect);const origin = anonymousOrigin(root);- const originBase = origin ? originAncestor(root, current) : undefined;- const tags = candidateTags(root, current);+ const originBase = origin ? originAncestor(root, selected) : undefined;+ const tags = candidateTags(root, selected);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 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,+ const spec = { version: 1, id: randomUUID(), repoId, ...(originBase ? { origin, originBase } : {}), runtime, tooling, tags, commit: selected.commit, tree: selected.tree, command, pipefail, slots: runner.slots,+ ...(trustedMode ? { trustedMode } : {}),browser: runner.browser, browserRequired: browser, guiRequired: metadata.gui === true, landing: metadata.landing === true,...(metadata.landing === true && metadata.timeoutMs ? { timeoutMs: metadata.timeoutMs } : {}),// The classification this controller used, so the runner never reclassifies by its own settings (#1043).@@ -507,7 +524,7 @@ function requestFor(root, command, { runner, source, browser = false, byLaunch,// These are transport hang ceilings, independent of the command's execution budget.return { spec, runner, args: ['-T', '-o', 'BatchMode=yes', '-o', 'ForwardAgent=no', '-o', 'ClearAllForwardings=yes','-o', 'SendEnv=-*', '-o', 'ConnectTimeout=10', '-o', 'ServerAliveInterval=10', '-o', 'ServerAliveCountMax=3',- '--', runner.host, remote], root, source: current, directory, frame: Buffer.concat([Buffer.from(`${encodedSpec.length}\n`), encodedSpec]), env: sshEnvironment(),+ '--', runner.host, remote], root, source: selected, ...(trustedMode ? { rawOutputPath } : {}), directory, frame: Buffer.concat([Buffer.from(`${encodedSpec.length}\n`), encodedSpec]), env: sshEnvironment(),cleanup() { rmSync(directory, { recursive: true, force: true }); } };} catch (error) {rmSync(directory, { recursive: true, force: true });@@ -529,7 +546,7 @@ function resultFrom(request, result) {if (result.error || result.status !== 0 || receipt.id !== request.spec.id || receipt.commit !== request.spec.commit|| receipt.tree !== request.spec.tree || receipt.runtimeSha256 !== request.spec.runtime.sha256 || receipt.toolingSha256 !== request.spec.tooling.sha256 || !Number.isInteger(receipt.code) || receipt.code < 0 || receipt.code > 255|| typeof receipt.root !== 'string' || !Number.isFinite(receipt.wallMs) || receipt.wallMs < 0- || receipt.outputSha256 !== createHash('sha256').update(output).digest('hex')) {+ || receipt.outputSha256 !== (request.spec.trustedMode ? result.rawSha256 : createHash('sha256').update(output).digest('hex'))) {throw new RunnerDropped(request.runner.host);}if (receipt.gui !== undefined && ![true, false, null].includes(receipt.gui)) throw new RunnerDropped(request.runner.host);@@ -562,6 +579,14 @@ function resultFrom(request, result) {? pipes[index] : null } : stage) };}}+ let privateResult = null;+ if (request.spec.trustedMode) {+ try {+ if (result.rawOutputPath !== request.rawOutputPath || statSync(result.rawOutputPath).size !== result.rawBytes) throw new Error('missing complete private-check capture');+ privateResult = privateCheckPhases(request.spec.trustedMode, receipt.trustedMode, result.rawBytes);+ if ((privateResult.state === 'pass') !== (receipt.code === 0 && !receipt.signal)) throw new Error('inconsistent private-check completion');+ } catch { throw new RunnerDropped(request.runner.host); }+ } else if (receipt.trustedMode !== undefined) throw new RunnerDropped(request.runner.host);const text = staged?.output ?? output.toString('utf8');if (receipt.environment !== undefined && environmentProblem(receipt.environment)) throw new RunnerDropped(request.runner.host);if (receipt.browserRefused !== undefined && (receipt.browserRefused !== true || receipt.code === 0 || request.spec.browserRequired)) throw new RunnerDropped(request.runner.host);@@ -579,6 +604,7 @@ function resultFrom(request, result) {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 },+ ...(privateResult ? { privateCheck: { ...privateResult, receipt: receipt.trustedMode }, rawOutputPath: result.rawOutputPath, rawOutputSha256: result.rawSha256 } : {}),executionMain: request.spec.main && receipt.main === request.spec.main ? receipt.main : null, executionLoad: remoteLoad(receipt.load), executionAdmission: admission };}@@ -644,21 +670,41 @@ export async function runOnRunnerAsync(root, command, options) {if (options.signal?.aborted) throw new RunnerDropped(options.runner.host);const request = requestFor(root, command, options);let removeAbort = () => {};+ let rawFd = null;try {+ if (request.rawOutputPath) rawFd = openSync(request.rawOutputPath, 'wx', 0o600);const child = spawn('ssh', request.args, { env: request.env, stdio: ['pipe', 'pipe', 'pipe'] });const output = [], diagnostics = [];let bytes = 0, error, control = '', requested = false, transfer = null, cleanupReason = '';+ const rawHash = createHash('sha256');+ let rawBytes = 0, head = Buffer.alloc(0), tail = Buffer.alloc(0);+ const half = 4 * 1024 ** 2;const abort = () => { error ??= new Error('runner transport canceled'); child.stdin.destroy(); child.kill('SIGTERM'); };options.signal?.addEventListener('abort', abort, { once: true });removeAbort = () => options.signal?.removeEventListener('abort', abort);if (options.signal?.aborted) abort();/** Bound both protocol streams before retaining a complete result. */- const capture = (target, chunk) => {+ const capture = (target, chunk, raw = false) => {+ if (raw && rawFd !== null) {+ if (error) return;+ try {+ for (let offset = 0; offset < chunk.length;) {+ const written = writeSync(rawFd, chunk, offset, chunk.length - offset);+ if (written <= 0) throw new Error('private-check output made no capture progress');+ offset += written;+ }+ rawHash.update(chunk); rawBytes += chunk.length;+ const take = Math.min(chunk.length, half - head.length);+ if (take) head = Buffer.concat([head, chunk.subarray(0, take)]);+ if (chunk.length > take) tail = Buffer.concat([tail, chunk.subarray(take)]).subarray(-half);+ } catch { error = new Refused('RUNNER_OUTPUT_LIMIT', 'the full private-check output could not be captured; restore its artifact storage before retrying'); child.kill('SIGTERM'); }+ return;+ }bytes += chunk.length;if (bytes > MAX_OUTPUT_BYTES) { error = new Refused('RUNNER_OUTPUT_LIMIT', 'runner output exceeded 64 MiB; reduce command output or keep this run local'); child.kill(); }else target.push(chunk);};- child.stdout.on('data', chunk => capture(output, chunk));+ child.stdout.on('data', chunk => capture(output, chunk, true));child.stderr.on('data', chunk => {capture(diagnostics, chunk);control += chunk.toString('utf8');@@ -698,6 +744,9 @@ export async function runOnRunnerAsync(root, command, options) {const status = await new Promise(resolve => child.once('close', resolve));if (transfer) await transfer;if (error instanceof Refused) throw error;- return resultFrom(request, { status, error, stdout: Buffer.concat(output), stderr: Buffer.concat(diagnostics) });- } finally { removeAbort(); request.cleanup(); }+ if (rawFd !== null) { closeSync(rawFd); rawFd = null; }+ const bounded = request.rawOutputPath ? Buffer.concat([head, ...(rawBytes > half * 2 ? [Buffer.from('\n[output capped at 8 MiB; middle omitted]\n')] : []), tail]) : Buffer.concat(output);+ return resultFrom(request, { status, error, stdout: bounded, stderr: Buffer.concat(diagnostics),+ ...(request.rawOutputPath ? { rawOutputPath: request.rawOutputPath, rawBytes, rawSha256: rawHash.digest('hex') } : {}) });+ } finally { if (rawFd !== null) closeSync(rawFd); removeAbort(); request.cleanup(); }}diff --git a/src/trusted-policy.js b/src/trusted-policy.jsindex 8e615111..b532490f 100644--- a/src/trusted-policy.js+++ b/src/trusted-policy.js@@ -1,3 +1,4 @@+import { runnerPrivateCheck } from './runner-private-check.js';import {mainPolicy,policyAt,@@ -155,15 +156,20 @@ export function frozenCheck(item) {/** Run the frozen check at the exact submitted commit in a private clone, leaving live worktrees untouched.* @param {string} root* @param {object} item- * @param {{ waitMs?: number, gateSlotHeld?: boolean, gateLease?: object, mutate?: (directory: string) => string }} [options] - Queue wait before the private check started;+ * @param {{ waitMs?: number, gateSlotHeld?: boolean, gateLease?: object, mutate?: (directory: string) => string, guard?: object }} [options] - Queue wait before the private check started;* mutate changes the scratch tree after checkout (a guard revert) and returns a reason when it cannot [C7,V4].*/-export function checkAtCommit(root, item, { waitMs = 0, gateSlotHeld = false, gateLease, mutate } = {}) {+export function checkAtCommit(root, item, { waitMs = 0, gateSlotHeld = false, gateLease, mutate, guard } = {}) {const command = frozenCheck(item);if (!command) return { state: 'pass', green: true, checked: false, report: '' };+ let policy;let config;- try { config = itemPolicy(root, item).config; }+ try { policy = itemPolicy(root, item); config = policy.config; }catch { return checkResult('unverified', 'policy', '', '', { root, item }); }+ if (gateLease?.runner) {+ if (mutate && !guard) return checkResult('unverified', 'a remote mutation requires a frozen declarative guard', '', '', { root, item });+ return runnerPrivateCheck(root, item, command, policy, gateLease, guard, waitMs, checkResult);+ }const install = config.check.install;const timeout = config.check.timeoutMs;// Retain the physical root before cleanup; Node TAP resolves symlinks in test locations.