Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(core): name sandbox-blocked checks [I1,C7]
Corey Olsoncf53683b11f4
diff --git a/src/cli.js b/src/cli.jsindex 9ccc8f9c..32e725a7 100644--- a/src/cli.js+++ b/src/cli.js@@ -17,7 +17,7 @@ import { doctrineHistory, loadDoctrine } from './doctrine.js';import { agentSessionDigest, requirePersonChannel } from './person.js';import { bindLocalSession, localSessionMatches } from './agent-session.js';import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';-import { digestOf, gateReport, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';+import { digestOf, gateReport, refuseSandboxBlocked, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';import { checkNeedsBrowser } from './browser-admission.js';import { bareWorktreeFinding, codeIsFromMain, contains, differFromHead, git, gitChildEnv, headCommit, headTree, invalidateGitFacts, isClean, mainCheckout, patchId, repoInfo, resolveCommit, tryGit, untracked, withGitFacts } from './git.js';import {@@ -2231,6 +2231,7 @@ async function verifyHere(ctx, id, { second, values }) {refuseUnverifiedStack(root, board, item, commit, trunk);const browser = !browserFreeChecksEnabled() || await checkNeedsBrowser(root, frozenCheck(item), { commit, onFallback: browserAdmissionReporter(ctx.io, ctx.io.relayJson) });check = await withGateSlot(root, (lease) => checkAtCommit(root, item, { waitMs: lease.waitMs, gateLease: lease }), { browser, agent: me.id, item: String(id), kind: 'review', itemCheck: true, onWait: gateWaitReporter(ctx.io) });+ refuseSandboxBlocked(check);verificationProfile = check.profile ?? null;const evidence = check.checked? `\nlast output lines (up to 40):\n${(check.outputTail ?? '(no output)').split('\n').map((line) => ` ${line}`).join('\n')}\nfull output file: ${check.outputPath ?? `(unavailable${check.outputError ? `: ${check.outputError}` : ''})`}`@@ -2635,6 +2636,7 @@ function workCommands(io, args) {}const browser = !browserFreeChecksEnabled() || await checkNeedsBrowser(ctx.info.root, check, { onFallback: browserAdmissionReporter(io, values.json) });const run = await withGateSlot(ctx.info.root, (lease) => runProfiledShell(ctx.info.root, check, { waitMs: lease.waitMs, artifactPrefix: `pullboard-check-${item.item_id}`, persistLog: true, gateLease: lease }), { browser, agent: caller, item: String(item.item_id), kind: 'check', itemCheck: true, onWait: gateWaitReporter(io) });+ refuseSandboxBlocked(run);io.result?.({ id: item.item_id, green: run.isGreen, seconds: run.seconds, check, by, report: run.isGreen ? '' : digestOf(run.output) });const timings = timingDigest(run.profile);const compact = timings && !run.profile.files.lengthdiff --git a/src/gate.js b/src/gate.jsindex f2154b49..3a0a9b9e 100644--- a/src/gate.js+++ b/src/gate.js@@ -6,8 +6,8 @@*/import { spawn, spawnSync } from 'node:child_process';import { randomUUID } from 'node:crypto';-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';-import { dirname, join } from 'node:path';+import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';+import { dirname, isAbsolute, join, relative, resolve } from 'node:path';import { availableParallelism } from 'node:os';import { gitChildEnv, gitPath, headTree, invalidateGitFacts, isClean, untracked } from './git.js';import { secretsIn } from './hooks.js';@@ -147,7 +147,50 @@ export function runShell(root, command, { pipefail = false, env = {} } = {}) {// Newlines, not spaces, around the command, so a trailing comment in it cannot swallow the `)`.const result = spawnSync(`${prefix}(\n${command}\n) 2>&1`, options);invalidateGitFacts();- return { isGreen: result.status === 0, output: `${result.stdout ?? ''}${result.stderr ?? ''}`, seconds: Math.round((Date.now() - started) / 1000) };+ const output = `${result.stdout ?? ''}${result.stderr ?? ''}`;+ return { isGreen: result.status === 0, output, seconds: Math.round((Date.now() - started) / 1000),+ sandboxBlocked: result.status === 0 ? null : sandboxBlockedOperation(root, output) };+}++/** Resolve existing path prefixes so a symlink cannot hide an outside-worktree operation. */+function diagnosticPath(path) {+ let current = resolve(path);+ const missing = [];+ for (;;) {+ try { return resolve(realpathSync(current), ...missing); }+ catch (error) {+ if (!['ENOENT', 'ENOTDIR'].includes(error.code)) return null;+ const parent = dirname(current);+ if (parent === current) return null;+ missing.unshift(relative(parent, current));+ current = parent;+ }+ }+}++/** Recognize concrete OS permission diagnostics, keeping ordinary assertion failures ordinary. */+export function sandboxBlockedOperation(root, output) {+ for (const raw of output.split('\n')) {+ const line = raw.trim().replace(/^#\s*/u, '');+ const network = /^Error: (listen|bind) (EPERM|EACCES)\b/u.exec(line);+ if (network) return `${network[1]} (${network[2]})`;+ const file = /^Error: (EPERM|EACCES): [^\n]*?, (open|mkdir|read|write|rename|unlink|scandir|access) ['"]([^'"\n]+)['"]/u.exec(line);+ const python = /^PermissionError: \[Errno (?:1|13)\] [^\n]*?: ['"]([^'"\n]+)['"]/u.exec(line);+ if (!file && !python) continue;+ const path = diagnosticPath(resolve(root, file ? file[3] : python[1]));+ const tree = diagnosticPath(root);+ if (!path || !tree) continue;+ const within = relative(tree, path);+ if (within !== '..' && !within.startsWith('../') && !isAbsolute(within)) continue;+ return `${file ? file[2] : 'file access'} ${JSON.stringify(path)} (${file ? file[1] : 'EACCES'})`;+ }+ return null;+}++/** Refuse an environment-blocked proof after its ordinary raw logs and timings are persisted. */+export function refuseSandboxBlocked(run) {+ if (run.sandboxBlocked) throw new Refused('SANDBOX_BLOCKED',+ `The environment refused ${run.sandboxBlocked}. Ask the person to allow this operation, or run the gate outside the sandbox; keep the tests unchanged.`);}/** Replace a possible secret-bearing line before persisting a direct item-check log. */@@ -219,7 +262,7 @@ export async function runProfiledShellAsync(root, command, { waitMs = 0, gateSloconst profilePath = join(dirname(gitPath(root, LOG)), `pullboard-gate-${randomUUID()}.profile.json`);const profile = writeTimingProfile(profilePath, { ...timingFromOutput(output, timingRunner(command)),waitMs: Math.max(0, Math.round(waitMs)), wallMs });- return { isGreen: status === 0 && !overflow && !failure, output, seconds: Math.round(wallMs / 1000), profile, profilePath, logPath: null };+ return { isGreen: status === 0 && !overflow && !failure, sandboxBlocked: status === 0 ? null : sandboxBlockedOperation(root, output), output, seconds: Math.round(wallMs / 1000), profile, profilePath, logPath: null };}/** Persist one sanitized timing profile as a private artifact.@@ -335,8 +378,10 @@ export async function runGate(root, config, { trustStamp = true, onWait, landingfunction fullGateRun(root, config, trustStamp = false, { waitMs = 0, log = gitPath(root, LOG), gateLease, landing = false } = {}) {if (trustStamp && isStampedGreen(root)) return { isGreen: true, isCached: true, output: '', seconds: 0, log: '' };const before = committedTree(root);- const { isGreen, output, seconds, profile, profilePath } = runProfiledShell(root, config.gate, { waitMs, pipefail: true, profileFile: `${log}.profile.json`, gateLease, landing });+ const run = runProfiledShell(root, config.gate, { waitMs, pipefail: true, profileFile: `${log}.profile.json`, gateLease, landing });+ const { isGreen, output, seconds, profile, profilePath } = run;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 };}@@ -388,12 +433,13 @@ export async function runSubmitGate(root, config, { base, trunk, changed, check,format: [...new Set(profiles.map(value => value.format))].join('+'),unavailable: profiles.some(value => value.unavailable) ? 'per-test timing unavailable: output was not TAP or JUnit (one or more phases)' : null,});+ refuseSandboxBlocked(proof);return { ...proof, log, seconds: criterion.seconds + proof.seconds, ...selection, deferred, deferFullFallback, check: receipt,profile, profilePath, proofProfilePath: proof.profilePath, proofLog: proof.log };};if (!criterion.isGreen) {writeFileSync(log, criterion.output);- return finish({ isGreen: false, isCached: false, output: criterion.output, seconds: 0, log: '' });+ return finish({ isGreen: false, sandboxBlocked: criterion.sandboxBlocked, isCached: false, output: criterion.output, seconds: 0, log: '' });}// The proof already owns this lease: its phase profile has no additional queue wait.const proofWait = check ? 0 : lease.waitMs;diff --git a/src/run.js b/src/run.jsindex e8b87370..cf450722 100644--- a/src/run.js+++ b/src/run.js@@ -16,7 +16,7 @@ import * as store from './board.js';import { briefFiles } from './brief.js';import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';import { doctrineText, loadDoctrine } from './doctrine.js';-import { digestOf, runGate } from './gate.js';+import { digestOf, refuseSandboxBlocked, sandboxBlockedOperation, runGate } from './gate.js';import { contains, git, headCommit, invalidateGitFacts, isClean, tryGit, untracked } from './git.js';import { laneNames, outOfLane } from './lanes.js';import { Refused } from './refused.js';@@ -315,6 +315,7 @@ async function tryItem(ctx, item, { command, attempts, minutes, deps, me, start,const late = built.timedOut ? `The agent ran out of time after ${minutes} minutes.\n` : '';const checked = await runCommand(item.item_check, { cwd: root, timeoutMs: minutes * 60_000 });seconds += built.seconds + checked.seconds;+ if (checked.status !== 0) refuseSandboxBlocked({ sandboxBlocked: sandboxBlockedOperation(root, checked.output) });let result = 'green';if (checked.status !== 0) {result = 'red';diff --git a/src/trusted-policy.js b/src/trusted-policy.jsindex 76f2c7b4..99602b48 100644--- a/src/trusted-policy.js+++ b/src/trusted-policy.js@@ -1,7 +1,7 @@/** Coordinator policy and immutable submission checks cannot come from a builder's candidate [V4,V16,L3,M3]. */import { randomUUID } from 'node:crypto';import { spawnSync } from 'node:child_process';-import { digestOf, writeTimingProfile } from './gate.js';+import { digestOf, sandboxBlockedOperation, writeTimingProfile } from './gate.js';import { timingFromOutput, timingFromLog, timingRunner } from './timing.js';import { closeSync, existsSync, mkdtempSync, mkdirSync, openSync, readFileSync, readSync, rmSync, writeSync } from 'node:fs';import { tmpdir } from 'node:os';@@ -177,7 +177,7 @@ export function checkAtCommit(root, item, { waitMs = 0, gateSlotHeld = false, gaconst runner = timingRunner(command);const events = checkLogPath && existsSync(checkLogPath) ? timingFromLog(checkLogPath, runner) : timingFromOutput(checkOutput, runner);timingProfile = { ...events, wallMs: Math.max(0, Date.now() - checkStartedAt) };- return checkResult(state, stage, installOutput, checkOutput, { root, item, installLogPath, checkLogPath, timingProfile, waitMs });+ return checkResult(state, stage, installOutput, checkOutput, { root, item, commandRoot: copy, installLogPath, checkLogPath, timingProfile, waitMs });};try {const common = policyGit(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']).trim();@@ -271,7 +271,7 @@ function secretScanned(output, path) {}/** Stream one worker log into a private artifact while retaining only its bounded sanitized tail. */-function streamSanitizedLog(path, fallback, label, writeArtifact) {+function streamSanitizedLog(path, fallback, label, writeArtifact, onLine = () => {}) {const decoder = new StringDecoder('utf8');const tail = [];let line = '';@@ -298,6 +298,7 @@ function streamSanitizedLog(path, fallback, label, writeArtifact) {/** Retain one bounded tail line and append its scanned form to the artifact buffer. */function emitLine(newline) {const sanitized = oversized ? CHECK_OVERSIZED_LINE : scanOutputLine(line, label, lineNumber);+ onLine(sanitized);const bounded = sanitized.length > 2000? `${sanitized.slice(0, 1000)}…[line truncated]…${sanitized.slice(-1000)}` : sanitized;tail.push(bounded);@@ -365,12 +366,13 @@ function streamSanitizedLog(path, fallback, label, writeArtifact) {}/** Persist a sanitized full diagnostic outside the temporary checkout so a refusal can name it. */-function checkResult(state, stage, installCapture, checkCapture, { root = '', item = {}, installLogPath = '', checkLogPath = '', timingProfile = null, waitMs = 0 } = {}) {+function checkResult(state, stage, installCapture, checkCapture, { root = '', item = {}, commandRoot = root, installLogPath = '', checkLogPath = '', timingProfile = null, waitMs = 0 } = {}) {const boundedInstall = secretScanned(installCapture, 'check install capture');const boundedCheck = secretScanned(checkCapture, 'frozen check capture');const install = digestOf(boundedInstall) || '(no output)';const check = digestOf(boundedCheck) || '(not run or no output)';const report = `install output:\n${install}\ncheck output:\n${check}`;+ let sandboxBlocked = null;let outputPath = null;let outputError = null;let artifactFd = null;@@ -404,7 +406,7 @@ function checkResult(state, stage, installCapture, checkCapture, { root = '', itconst written = writeSync(artifactFd, buffer, offset, buffer.length - offset);if (written <= 0) throw new Error('diagnostic artifact write made no progress');return written;- });+ }, line => { if (state !== 'pass' && title === (stage.startsWith('install') ? 'install' : 'check')) sandboxBlocked ??= sandboxBlockedOperation(commandRoot, line); });if (!result.sawOutput) appendArtifact(`${absentText}\n`);return result;};@@ -438,5 +440,5 @@ function checkResult(state, stage, installCapture, checkCapture, { root = '', itconst failure = state === 'red' ? 'failed' : /timed out/u.test(stage) ? 'timed out': /could not start/u.test(stage) ? "couldn't start" : state === 'unverified' ? 'could not be verified' : 'passed';const output = `install output:\n${boundedInstall || '(no output)'}\ncheck output:\n${boundedCheck || '(not run or no output)'}`;- return { state, green: state === 'pass', checked: true, stage, failure, report, output, outputTail, outputPath, outputError, profilePath, profile: timingProfile ? { ...timingProfile, profilePath } : null };+ return { sandboxBlocked, state, green: state === 'pass', checked: true, stage, failure, report, output, outputTail, outputPath, outputError, profilePath, profile: timingProfile ? { ...timingProfile, profilePath } : null };}diff --git a/test/machine.test.js b/test/machine.test.jsindex 34cf542e..c1a3cce3 100644--- a/test/machine.test.js+++ b/test/machine.test.js@@ -27,6 +27,7 @@ const NOT_MOVES = {ALREADY_JOINED: 'registering who is asking, before any move',BAD_ROUTE: 'registering who is asking, before any move',ONE_COORDINATOR: 'registering who is asking, before any move',+ SANDBOX_BLOCKED: 'the command environment must allow the gate or check operation',BAD_MACHINE_SETTINGS: 'machine-wide settings checked before a command runs',BAD_GATE_SLOTS: 'machine-wide gate capacity checked before a command runs',BAD_BROWSER_SLOTS: 'machine-wide browser capacity checked before a command runs',diff --git a/test/submit-gate.test.js b/test/submit-gate.test.jsindex 2d50e072..7e66a210 100644--- a/test/submit-gate.test.js+++ b/test/submit-gate.test.js@@ -12,6 +12,8 @@ import { dirname, join, resolve } from 'node:path';import { after, test } from 'node:test';import { selectAffectedTests } from '../src/affected-tests.js';import { configFromSource } from '../src/config.js';+import { checkAtCommit } from '../src/trusted-policy.js';+import { refuseSandboxBlocked } from '../src/gate.js';const BIN = resolveBin();const dirs = [];@@ -748,3 +750,102 @@ for (const mode of ['deleted source', 'topic parent', 'merge commit']) {if (mode !== 'deleted source') assert.equal(readFileSync(marker, 'utf8'), 'ran\nran\n', 'submit executes the unchanged transitive importer against the candidate and exact main');});}++test('a sandbox-blocked gate asks the person [I1,C7]', async (t) => {+ const command = 'node -e "console.error(process.env.BLOCKED_DIAGNOSTIC); process.exit(Number(process.env.BLOCKED_EXIT || 1))"';+ /** Assert the actual CLI names the refused operation and directs the person to restore access. */+ function blocked(result, operation) {+ assert.equal(result.code, 1, result.out + result.err);+ assert.match(result.err, /SANDBOX_BLOCKED/u);+ assert.ok(result.err.includes(operation), result.err);+ assert.match(result.err, /Ask the person to allow this operation/u);+ assert.match(result.err, /run the gate outside the sandbox/u);+ assert.match(result.err, /keep the tests unchanged/u);+ }+ await t.test('full gates distinguish listener denial from ordinary failures [I1,C7]', () => {+ const box = privateRepo(t);+ put(box.root, 'pullboard.json', JSON.stringify({ gate: command }));+ seedGraph(box);+ box.env.BLOCKED_DIAGNOSTIC = 'Error: listen EPERM: operation not permitted 127.0.0.1:0';+ blocked(box.run('gate'), 'listen');+ const log = resolve(box.root, box.git('rev-parse', '--git-path', 'pullboard-gate.log'));+ assert.match(readFileSync(log, 'utf8'), /Error: listen EPERM/u, 'the original diagnostic is retained');+ assert.ok(existsSync(log + '.profile.json'), 'ordinary timings are retained');+ box.env.BLOCKED_DIAGNOSTIC = 'Error: bind EACCES: permission denied 127.0.0.1:0';+ blocked(box.run('gate'), 'bind');+ for (const diagnostic of [+ 'AssertionError [ERR_ASSERTION]: expected EPERM when listen was called',+ 'Error: listen EADDRINUSE: address already in use',+ `Error: EACCES: permission denied, open '${join(box.root, 'inside.txt')}'`,+ ]) {+ box.env.BLOCKED_DIAGNOSTIC = diagnostic;+ const ordinary = box.run('gate');+ assert.equal(ordinary.code, 1, ordinary.out + ordinary.err);+ assert.doesNotMatch(ordinary.out + ordinary.err, /SANDBOX_BLOCKED/u);+ assert.match(ordinary.out, /gate red/u);+ }+ put(box.root, 'pullboard.json', JSON.stringify({ gate: 'node -e "require(\'node:assert/strict\').fail(\'ordinary assertion\')"' }));+ commitAll(box);+ const assertion = box.run('gate');+ assert.equal(assertion.code, 1);+ assert.match(assertion.out, /AssertionError/u);+ assert.doesNotMatch(assertion.out + assertion.err, /SANDBOX_BLOCKED/u);+ put(box.root, 'pullboard.json', JSON.stringify({ gate: command }));+ commitAll(box);+ box.env.BLOCKED_DIAGNOSTIC = 'Error: listen EPERM: operation not permitted';+ box.env.BLOCKED_EXIT = '0';+ const green = box.run('gate');+ assert.equal(green.code, 0, green.err);+ assert.doesNotMatch(green.out + green.err, /SANDBOX_BLOCKED/u, 'a successful diagnostic is not a refusal');+ });+ await t.test('frozen checks retain outside-file refusal before submit proof [I1,C7]', () => {+ let box = privateRepo(t);+ put(box.root, 'pullboard.json', JSON.stringify({ gate: 'node --test', affectedTests: 'node --test' }));+ seedGraph(box);+ box = builderRepo(box);+ const added = box.coordinator('add', 'build', 'Sandbox check', '--check', command);+ assert.equal(added.code, 0, added.err);+ assert.equal(box.run('claim', '1').code, 0);+ put(box.root, 'src/a.js', 'export const value = 2;\n');+ commitAll(box, 'feat(core): update selected source [G1]');+ const outside = join(box.dir, 'outside.txt');+ box.env.BLOCKED_DIAGNOSTIC = `Error: EACCES: permission denied, open '${outside}'`;+ blocked(box.run('check', '1', '--yes'), 'open');+ blocked(box.run('submit', '1'), 'open');+ const log = resolve(box.root, box.git('rev-parse', '--git-path', 'pullboard-submit.log.check.log'));+ assert.ok(readFileSync(log, 'utf8').includes(outside), 'the exact refused path remains in the raw log');+ box.env.BLOCKED_DIAGNOSTIC = 'AssertionError [ERR_ASSERTION]: ordinary assertion';+ const ordinary = box.run('submit', '1');+ assert.equal(ordinary.code, 1);+ assert.match(ordinary.err, /GATE_RED/u);+ assert.doesNotMatch(ordinary.err, /SANDBOX_BLOCKED/u);+ box.env.BLOCKED_EXIT = '0';+ assert.equal(box.run('submit', '1').code, 0, 'the unchanged check can pass when the operation is allowed');+ const item = JSON.parse(box.coordinator('show', '1', '--json').out);+ /** Run the actual private checker with only these fixture diagnostics in its child environment. */+ function privateCheck(diagnostic) {+ const savedDiagnostic = process.env.BLOCKED_DIAGNOSTIC;+ const savedExit = process.env.BLOCKED_EXIT;+ process.env.BLOCKED_DIAGNOSTIC = diagnostic;+ process.env.BLOCKED_EXIT = '1';+ try { return checkAtCommit(box.root, item); }+ finally {+ if (savedDiagnostic === undefined) delete process.env.BLOCKED_DIAGNOSTIC;+ else process.env.BLOCKED_DIAGNOSTIC = savedDiagnostic;+ if (savedExit === undefined) delete process.env.BLOCKED_EXIT;+ else process.env.BLOCKED_EXIT = savedExit;+ }+ }+ const privateResult = privateCheck('Error: listen EPERM: operation not permitted\n' + 'ordinary trailing output\n'.repeat(80));+ assert.equal(privateResult.state, 'red');+ assert.equal(privateResult.sandboxBlocked, 'listen (EPERM)', 'classification scans before the bounded tail');+ assert.doesNotMatch(privateResult.outputTail, /EPERM/u);+ assert.throws(() => refuseSandboxBlocked(privateResult), { code: 'SANDBOX_BLOCKED' });+ assert.match(readFileSync(privateResult.outputPath, 'utf8'), /Error: listen EPERM/u);+ assert.ok(existsSync(privateResult.profilePath));+ const inside = privateCheck("Error: EACCES: permission denied, open './inside.txt'");+ assert.equal(inside.state, 'red');+ assert.equal(inside.sandboxBlocked, null, 'a private-clone file stays inside that check worktree');+ assert.equal(JSON.parse(box.coordinator('show', '1', '--json').out).item_status, 'submitted', 'checks alone record no verdict');+ });+});