Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: confine autofixer repairs and verify runs on crash-log input (#12487)
[._.]/ Adam Eivy7d5b06433117
diff --git a/autofixer/sandbox.js b/autofixer/sandbox.jsindex 625ddef3a8..8495980b7c 100644--- a/autofixer/sandbox.js+++ b/autofixer/sandbox.js@@ -12,22 +12,36 @@* - `buildFixPrompt` — wrap logs in a per-session, forge-resistant* UNTRUSTED-EVIDENCE fence with strong "data, not* instructions" framing.- * - `restrictedToolArgs` — deny the shell/network toolset for claude-code so- * the agent can only Read/Edit files.+ * - `pickRepairProvider` — run a repair only on a CLI with an enforced+ * restricted mode (claude without shell/network+ * tools, or codex's network-denied workspace-write+ * sandbox); every other CLI is refused.* - `validateProposedDiff` — bound size + reject escapes/sensitive paths.* - git worktree helpers — run the agent against a disposable, detached* worktree; only a validated diff is ever promoted* back to the live checkout.+ * - `runVerifyCommand` — run the verify command over the agent-edited+ * worktree under OS containment, never on the host.*- * Node builtins only (child_process/fs/path/crypto/os) so the standalone+ * Node builtins plus dependency-light `server/lib` modules, so the standalone* autofixer package — which installs only `express` — can import it.*/import { spawn } from 'child_process';import { waitForChild, COMMAND_TIMEOUT_MS } from './childProcess.js';-import { writeFile, rm, mkdir, readdir } from 'fs/promises';+import { writeFile, rm, mkdir, mkdtemp, readdir, realpath, stat, access } from 'fs/promises';+import { constants as fsConstants } from 'fs';import { join, isAbsolute, normalize, resolve, dirname } from 'path';+import { homedir, tmpdir } from 'os';import { randomBytes } from 'crypto';+import { pickCliProvider } from '../server/lib/cliProviderRun.js';+import { restrictedRepairArgs } from '../server/lib/providerVendors.js';+import {+ CODE_ANIMATION_SEATBELT, CODE_ANIMATION_BUBBLEWRAP, codeAnimationContainmentMechanism,+} from '../server/lib/codeAnimationContainment.js';+import {+ autofixVerifyBubblewrapArgs, autofixVerifyEnv, autofixVerifyProtectedPaths, autofixVerifySeatbeltProfile,+} from '../server/lib/autofixVerifyContainment.js';// ---------------------------------------------------------------------------// Environment sanitization@@ -198,23 +212,33 @@ Fix the bug by editing files in the current working directory, then stop.`;}/**- * Extra CLI argv that constrain the agent's toolset. For claude-code we deny- * the shell + network tools so the agent — even if a log tricks it — cannot- * execute commands, read the environment, or exfiltrate over the network; it is- * left with file Read/Edit/Write/Grep/Glob only. Other CLIs have no portable- * equivalent flag, so they rely on the worktree + env + promotion isolation.+ * Resolve the repair provider, restricted. A worktree cwd does not confine a+ * shell, so only a CLI with an enforced restricted mode may run a repair:+ * claude with Bash/WebFetch/WebSearch denied (left with file tools, edits+ * auto-accepted inside the worktree only), or codex in its workspace-write+ * sandbox with network off (`restrictedRepairArgs`). A configured provider+ * without one is refused rather than swapped; with no configured provider the+ * pick is claude-code, else the first restrictable CLI — never an+ * unrestrictable `cli[0]`.*- * @param {object} provider resolved CLI provider ({ id, command })- * @returns {string[]}+ * @param {Array|Object} providers providers list or on-disk map+ * @param {{ providerId?: string, model?: string }} [config] settings.autofixer+ * @returns {{ provider: object, model: string|null, mode: string } | { error: string }}*/-export function restrictedToolArgs(provider) {- const id = provider?.id || '';- const command = provider?.command || '';- const isClaude = id === 'claude-code' || /(^|[\\/])claude(\.\w+)?$/.test(command);- if (isClaude) {- return ['--disallowedTools', 'Bash', 'WebFetch', 'WebSearch'];+export function pickRepairProvider(providers, config = {}) {+ const list = (Array.isArray(providers) ? providers : Object.values(providers || {})).filter((p) => p?.enabled !== false);+ const configured = config?.providerId && list.find((p) => p.id === config.providerId);+ if (configured && !restrictedRepairArgs(configured)) {+ return { error: `Provider ${configured.id} has no enforced restricted mode, so autonomous repair is skipped. Choose a Claude Code or Codex CLI provider for the autofixer.` };+ }+ const restrictable = list.filter((p) => restrictedRepairArgs(p));+ if (restrictable.length === 0) {+ return { error: 'No enabled Claude Code or Codex CLI provider, so autonomous repair is skipped: other CLIs cannot be restricted from running shell commands.' };}- return [];+ const picked = pickCliProvider(restrictable, config);+ if (picked.error) return picked;+ const { mode, args } = restrictedRepairArgs(picked.provider);+ return { provider: { ...picked.provider, args }, model: picked.model, mode };}// ---------------------------------------------------------------------------@@ -437,34 +461,113 @@ export async function sweepStaleWorktrees(parentDir) {return swept;}+const canExecute = (path) => access(path, fsConstants.X_OK).then(() => true, () => false);+/**- * Run the user-configured verification command (e.g. `npm test`) against the- * isolated worktree with the sanitized env, before any change reaches the live- * checkout. The command is user-supplied (trusted config), so it runs through a- * shell; the crash logs never influence it. Returns { ok, code, output }.- *- * @param {string} command user-configured shell command- * @param {string} cwd worktree path- * @param {Record<string,string>} env sanitized environment- * @param {number} [timeoutMs=300000]+ * The enforced mechanism available for the verify command: Seatbelt on macOS,+ * bubblewrap on Linux when it can create namespaces, otherwise a refusal.*/-export function runVerifyCommand(command, cwd, env, timeoutMs = 300000) {+export async function probeVerifyContainment() {+ if (process.platform === 'darwin') {+ return codeAnimationContainmentMechanism('darwin', await canExecute(CODE_ANIMATION_SEATBELT));+ }+ if (process.platform !== 'linux') return codeAnimationContainmentMechanism(process.platform, false);+ if (!(await canExecute(CODE_ANIMATION_BUBBLEWRAP))) {+ return codeAnimationContainmentMechanism('linux', false, { reason: 'install bubblewrap (/usr/bin/bwrap) to verify autofixes' });+ }+ const child = spawn(CODE_ANIMATION_BUBBLEWRAP, ['--unshare-all', '--die-with-parent', '--ro-bind', '/', '/', '--', '/bin/true'], {+ cwd: '/', env: {}, stdio: ['ignore', 'ignore', 'ignore'],+ });+ const { code } = await waitForChild(child, { timeoutMs: 5000, capture: false });+ return codeAnimationContainmentMechanism('linux', false, {+ supported: code === 0,+ reason: 'bubblewrap could not create namespaces; check unprivileged user namespaces and the host AppArmor policy',+ });+}++// Run a contained command as its own process group so a timeout reaches every+// process the test runner started, not just the sandbox launcher.+function runGroup(file, args, { cwd, env, timeoutMs }) {return new Promise((resolve) => {- const child = spawn(command, { cwd, env, shell: true, windowsHide: true });let output = '';let settled = false;+ let child;+ try {+ child = spawn(file, args, { cwd, env, detached: true, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });+ } catch (err) {+ resolve({ ok: false, code: -1, output: `[verify] ${err.message}` });+ return;+ }+ const killGroup = () => {+ try { process.kill(-child.pid, 'SIGKILL'); } catch { /* already gone */ }+ };const done = (result) => { if (settled) return; settled = true; clearTimeout(timer); resolve(result); };const timer = setTimeout(() => {- if (!child.killed) child.kill('SIGTERM');+ killGroup();done({ ok: false, code: -1, output: `${output}\n[verify] timed out after ${timeoutMs}ms` });}, timeoutMs);child.stdout?.on('data', (d) => { output += d.toString(); });child.stderr?.on('data', (d) => { output += d.toString(); });child.on('error', (err) => done({ ok: false, code: -1, output: `${output}\n[verify] ${err.message}` }));- child.on('close', (code) => done({ ok: code === 0, code, output }));+ child.on('close', (code) => { killGroup(); done({ ok: code === 0, code, output }); });});}+/**+ * Run the user-configured verification command (e.g. `npm test`) against the+ * agent-edited worktree before any change reaches the live checkout. The+ * command string is trusted config, but the files it executes (tests, npm+ * lifecycle scripts) were just written by an agent driven by untrusted logs,+ * so it runs only under OS containment (`autofixVerifyContainment.js`): no+ * network, writes confined to the worktree and a private scratch dir, no reads+ * of the PortOS data directory or host credential stores, and an environment+ * built from nothing — no provider key or PortOS token. Without an enforced+ * mechanism the verify is refused, which blocks promotion.+ *+ * @param {string} command user-configured shell command+ * @param {string} cwd worktree path+ * @param {object} [opts]+ * @param {string} [opts.dataDir] PortOS data directory to hide from the command+ * @param {number} [opts.timeoutMs=300000]+ * @param {() => Promise<{ id: string|null, supported: boolean, reason: string|null }>} [opts.probe]+ * @returns {Promise<{ ok: boolean, code: number, output: string, contained: boolean, mechanism?: string }>}+ */+export async function runVerifyCommand(command, cwd, { dataDir = null, timeoutMs = 300000, probe = probeVerifyContainment } = {}) {+ const mechanism = await probe();+ if (!mechanism.supported) {+ return { ok: false, code: -1, contained: false, output: `[verify] refused: no enforced containment for the verify command — ${mechanism.reason}` };+ }+ const scratchDir = await mkdtemp(join(tmpdir(), 'portos-autofix-verify-'));+ try {+ await Promise.all(['home', 'tmp'].map((name) => mkdir(join(scratchDir, name))));+ const worktree = await realpath(cwd);+ const scratch = await realpath(scratchDir);+ const realOrSelf = (path) => realpath(path).catch(() => path);+ const protectedPaths = autofixVerifyProtectedPaths({+ dataDir: dataDir ? await realOrSelf(dataDir) : null,+ realHome: await realOrSelf(homedir()),+ });+ const env = autofixVerifyEnv({ scratch, path: process.env.PATH });+ const shell = ['/bin/sh', '-c', command];+ let launch;+ if (mechanism.id === 'macos-seatbelt') {+ launch = [CODE_ANIMATION_SEATBELT, ['-p', autofixVerifySeatbeltProfile({ worktree, scratch, protectedPaths }), ...shell]];+ } else {+ const present = await Promise.all(protectedPaths.map(async (path) => [path, await stat(path).catch(() => null)]));+ const bwrapArgs = autofixVerifyBubblewrapArgs({+ worktree, scratch, env,+ protectedDirs: present.filter(([, info]) => info?.isDirectory()).map(([path]) => path),+ protectedFiles: present.filter(([, info]) => info && !info.isDirectory()).map(([path]) => path),+ });+ launch = [CODE_ANIMATION_BUBBLEWRAP, [...bwrapArgs, ...shell]];+ }+ const result = await runGroup(launch[0], launch[1], { cwd: worktree, env, timeoutMs });+ return { ...result, contained: true, mechanism: mechanism.id };+ } finally {+ await rm(scratchDir, { recursive: true, force: true }).catch(() => {});+ }+}+/*** Apply a validated diff to the live checkout. `git apply --check` first so a* non-applying patch never half-lands. Returns { ok } or { error }.diff --git a/autofixer/sandbox.test.js b/autofixer/sandbox.test.jsindex 2f8335292b..61620a68f6 100644--- a/autofixer/sandbox.test.js+++ b/autofixer/sandbox.test.js@@ -1,5 +1,9 @@import { describe, it, expect, vi, afterEach } from 'vitest';import { EventEmitter } from 'node:events';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { buildCliArgs } from '../server/lib/cliProviderArgs.js';const spawnMock = vi.hoisted(() => vi.fn());vi.mock('child_process', () => ({ spawn: spawnMock }));import {@@ -8,7 +12,8 @@ import {collectSecretEnvValues,buildFixPrompt,defuseSentinel,- restrictedToolArgs,+ pickRepairProvider,+ runVerifyCommand,validateProposedDiff,scanDiffForSecrets,extractDiffPaths,@@ -163,14 +168,93 @@ describe('buildFixPrompt — untrusted log fencing', () => {});});-describe('restrictedToolArgs — shell/network denial for claude', () => {- it('denies Bash/WebFetch/WebSearch for claude-code', () => {- expect(restrictedToolArgs({ id: 'claude-code' })).toEqual(['--disallowedTools', 'Bash', 'WebFetch', 'WebSearch']);- expect(restrictedToolArgs({ command: '/usr/local/bin/claude' })).toContain('Bash');+describe('pickRepairProvider — only an enforced restricted mode runs a repair', () => {+ const claude = { id: 'claude-code', type: 'cli', command: 'claude', args: ['--print', '--dangerously-skip-permissions', '--allowedTools', 'Bash'] };+ const codex = { id: 'codex', type: 'cli', command: 'codex', args: ['--dangerously-bypass-approvals-and-sandbox', '--sandbox', 'danger-full-access'] };+ const gemini = { id: 'gemini-cli', type: 'cli', command: 'gemini', args: ['--yolo'] };+ const agy = { id: 'antigravity-cli', type: 'cli', command: 'agy', args: ['--print', '--dangerously-skip-permissions'] };+ // The argv the runner actually spawns: buildCliArgs over the restricted clone.+ const spawnedArgv = (picked) => buildCliArgs(picked.provider);++ it('refuses when only non-restrictable CLIs are enabled instead of falling back to cli[0]', () => {+ const picked = pickRepairProvider([gemini, agy], {});+ expect(picked.provider).toBeUndefined();+ expect(picked.error).toMatch(/No enabled Claude Code or Codex CLI provider/);+ });++ it('refuses a configured non-restrictable provider rather than swapping it', () => {+ const picked = pickRepairProvider([gemini, claude], { providerId: 'gemini-cli' });+ expect(picked.error).toMatch(/gemini-cli has no enforced restricted mode/);+ });++ it('runs claude with shell/web tools denied, edits confined to the cwd, and saved bypasses stripped', () => {+ const picked = pickRepairProvider([gemini, claude], {});+ expect(picked).toMatchObject({ mode: 'claude-disallowed-tools', provider: { id: 'claude-code' } });+ const argv = spawnedArgv(picked);+ expect(argv).not.toContain('--dangerously-skip-permissions');+ expect(argv).not.toContain('--allowedTools');+ expect(argv.join(' ')).toContain('--permission-mode acceptEdits');+ expect(argv.join(' ')).toContain('--setting-sources user');+ expect(argv.join(' ')).toContain('--disallowedTools Bash WebFetch WebSearch');+ expect(argv.slice(-2)).toEqual(['-p', '-']);+ });++ it('runs codex in its network-denied workspace-write sandbox with the bypass stripped', () => {+ const picked = pickRepairProvider({ gemini, codex }, { providerId: 'codex' });+ expect(picked.mode).toBe('codex-workspace-write');+ const argv = spawnedArgv(picked);+ expect(argv[0]).toBe('exec');+ expect(argv).not.toContain('--dangerously-bypass-approvals-and-sandbox');+ expect(argv).not.toContain('danger-full-access');+ expect(argv.join(' ')).toContain('--sandbox workspace-write -c sandbox_workspace_write.network_access=false');+ expect(argv.at(-1)).toBe('-');});- it('returns no extra args for non-claude providers', () => {- expect(restrictedToolArgs({ id: 'codex' })).toEqual([]);- expect(restrictedToolArgs({ id: 'gemini-cli' })).toEqual([]);+});++describe('runVerifyCommand — contained, credential-free verify', () => {+ afterEach(() => spawnMock.mockReset());++ it('refuses without spawning when no enforced containment exists', async () => {+ const result = await runVerifyCommand('npm test', '/example/worktree', {+ probe: async () => ({ id: null, supported: false, reason: 'No enforced worker containment is implemented for win32.' }),+ });+ expect(result).toMatchObject({ ok: false, contained: false });+ expect(result.output).toContain('refused');+ expect(spawnMock).not.toHaveBeenCalled();+ });++ it('launches under Seatbelt with an environment built from nothing', async () => {+ const worktree = await mkdtemp(join(tmpdir(), 'autofix-verify-test-'));+ vi.stubEnv('ANTHROPIC_API_KEY', 'sk-ant-example-secret');+ vi.stubEnv('PORTOS_API_TOKEN', 'example-portos-token');+ spawnMock.mockImplementation(() => {+ const child = new EventEmitter();+ Object.assign(child, { pid: 4242, stdout: new EventEmitter(), stderr: new EventEmitter() });+ queueMicrotask(() => { child.stdout.emit('data', 'ok'); child.emit('close', 0); });+ return child;+ });+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);+ try {+ const result = await runVerifyCommand('npm test', worktree, {+ dataDir: '/example/data', probe: async () => ({ id: 'macos-seatbelt', supported: true, reason: null }),+ });+ expect(result).toMatchObject({ ok: true, contained: true, mechanism: 'macos-seatbelt', output: 'ok' });+ const [file, args, options] = spawnMock.mock.calls[0];+ expect(file).toBe('/usr/bin/sandbox-exec');+ expect(args.slice(-3)).toEqual(['/bin/sh', '-c', 'npm test']);+ expect(args[1]).toContain('(deny network*)');+ expect(args[1]).toContain('(deny file-read* (subpath "/example/data")');+ expect(options.detached).toBe(true);+ expect(Object.keys(options.env).sort()).toEqual([+ 'CI', 'HOME', 'LANG', 'LC_ALL', 'LOGNAME', 'PATH', 'TEMP', 'TMP', 'TMPDIR', 'USER',+ 'XDG_CACHE_HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME',+ ]);+ expect(options.env.HOME).not.toBe(process.env.HOME);+ expect(kill).toHaveBeenCalledWith(-4242, 'SIGKILL');+ } finally {+ vi.unstubAllEnvs();+ await rm(worktree, { recursive: true, force: true });+ }});});diff --git a/autofixer/sandbox.verify.test.js b/autofixer/sandbox.verify.test.jsnew file mode 100644index 0000000000..7332c0855d--- /dev/null+++ b/autofixer/sandbox.verify.test.js@@ -0,0 +1,69 @@+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';+import { mkdtemp, mkdir, rm, writeFile, readFile, access } from 'node:fs/promises';+import { createServer } from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { probeVerifyContainment, runVerifyCommand } from './sandbox.js';++// The real OS boundary an agent-written test file or npm lifecycle script meets.+const mechanism = await probeVerifyContainment();++describe.skipIf(!mechanism.supported)(`runVerifyCommand under ${mechanism.id || 'no containment'}`, () => {+ let root;+ let worktree;+ let dataDir;+ let outside;+ let server;+ let port;++ beforeAll(async () => {+ root = await mkdtemp(join(tmpdir(), 'autofix-verify-real-'));+ dataDir = join(root, 'data');+ worktree = join(dataDir, 'autofixer', 'worktrees', 'example');+ outside = join(root, 'outside');+ await mkdir(worktree, { recursive: true });+ await mkdir(outside);+ await writeFile(join(dataDir, 'providers.json'), '{"apiKey":"example-provider-key"}');+ server = createServer((socket) => socket.end('reached'));+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ port = server.address().port;+ });++ afterAll(async () => {+ vi.unstubAllEnvs();+ await new Promise((resolve) => server.close(resolve));+ await rm(root, { recursive: true, force: true });+ });++ const verify = (command) => runVerifyCommand(command, worktree, { dataDir, timeoutMs: 30000 });++ it('runs a forking test command that writes inside the worktree', async () => {+ const result = await verify('echo built > out.txt && (cat out.txt) && sh -c "exit 0"');+ expect(result).toMatchObject({ ok: true, contained: true, mechanism: mechanism.id });+ expect(await readFile(join(worktree, 'out.txt'), 'utf8')).toBe('built\n');+ });++ it('carries no provider key or PortOS token and a private HOME', async () => {+ vi.stubEnv('ANTHROPIC_API_KEY', 'sk-ant-example-verify-secret');+ vi.stubEnv('PORTOS_API_TOKEN', 'example-portos-token');+ const result = await verify('env');+ expect(result.ok).toBe(true);+ expect(result.output).not.toContain('sk-ant-example-verify-secret');+ expect(result.output).not.toContain('PORTOS_API_TOKEN');+ expect(result.output).not.toMatch(new RegExp(`^HOME=${process.env.HOME}$`, 'm'));+ });++ it('cannot write outside the worktree, read the PortOS data directory, or reach loopback', async () => {+ const write = await verify(`echo x > ${JSON.stringify(join(outside, 'escaped'))}`);+ expect(write.ok).toBe(false);+ await expect(access(join(outside, 'escaped'))).rejects.toThrow();++ const read = await verify(`cat ${JSON.stringify(join(dataDir, 'providers.json'))}`);+ expect(read.ok).toBe(false);+ expect(read.output).not.toContain('example-provider-key');++ const net = await verify(`${JSON.stringify(process.execPath)} -e "require('net').connect(${port}, '127.0.0.1').on('data', (d) => { console.log(String(d)); process.exit(0); }).on('error', () => process.exit(3))"`);+ expect(net.ok).toBe(false);+ expect(net.output).not.toContain('reached');+ });+});diff --git a/autofixer/server.js b/autofixer/server.jsindex 4988568ecb..12699b5ff8 100644--- a/autofixer/server.js+++ b/autofixer/server.js@@ -4,14 +4,14 @@ import { join } from 'path';// importing it from this standalone process doesn't pull in the AI toolkit.// Lets the autofixer honor the user's configured CLI provider/model instead// of hardcoding `claude -p`.-import { pickCliProvider, runCliProviderPrompt } from '../server/lib/cliProviderRun.js';+import { runCliProviderPrompt } from '../server/lib/cliProviderRun.js';import { signalDetachedGroups } from '../server/lib/credentialBootstrap.js';import { agentGuardEnv } from '../server/lib/agentGuard/index.js';import {sanitizeChildEnv,collectSecretEnvValues,buildFixPrompt,- restrictedToolArgs,+ pickRepairProvider,validateProposedDiff,isGitRepo,createDisposableWorktree,@@ -25,9 +25,8 @@ import {import { execPm2, listProcessesStrict, DATA_DIR, AUTOFIXER_DIR, INDEX_FILE, loadApps } from './shared.js';// Prepend the guarded pm2 shim to this process's PATH as defense-in-depth. The-// fix agent runs in an isolated worktree with a sanitized env and (for claude)-// no Bash tool, so it should never invoke pm2 at all — but the shim keeps a-// `pm2 kill` from a non-claude provider from downing the shared daemon. Our own+// fix agent runs restricted (claude without Bash, or codex's sandbox) in an+// isolated worktree with a sanitized env, so it should never invoke pm2 at all. Our own// execPm2 calls use an absolute PM2_BIN, so they bypass the shim. sanitizeChildEnv// preserves this guarded PATH into the agent's env.Object.assign(process.env, agentGuardEnv());@@ -218,10 +217,10 @@ function markAsFixed(processName) {// touch the live repository or inherit host credentials. The flow:// 1. Require a git checkout and cut a disposable, detached worktree at HEAD.// 2. Sanitize the child env down to system + AI-provider auth only.-// 3. Run the agent against the worktree with a fenced, untrusted-log prompt-// and (for claude) the shell/network toolset denied.+// 3. Run the agent against the worktree with a fenced, untrusted-log prompt,+// only on a provider with an enforced restricted mode (pickRepairProvider).// 4. Collect + validate the resulting diff (size/scope/forbidden paths).-// 5. Optionally verify it against a user-configured test command.+// 5. Optionally verify it against a user-configured test command, contained.// 6. Promotion gate: only when the user opted into `autoPromote` do we apply// the diff to the live checkout and restart the process; otherwise the// validated patch is staged beside the session for manual review.@@ -237,14 +236,12 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {const outputBuffer = [];// Resolve the configured CLI provider/model (settings.autofixer), falling- // back to claude-code — the historical default — when unset. The autofixer- // edits files, so it needs an agentic CLI provider; pickCliProvider restricts- // to type 'cli' (API chat providers can't do file edits). `autoPromote` and- // `verifyCommand` come from the same settings slice.+ // back to claude-code when unset, restricted to CLIs with an enforced+ // restricted mode. `autoPromote` and `verifyCommand` come from the same slice.const providers = await loadProviders();const settings = await loadSettings();const autofixerCfg = settings.autofixer || {};- const picked = pickCliProvider(providers, autofixerCfg);+ const picked = pickRepairProvider(providers, autofixerCfg);const autoPromote = autofixerCfg.autoPromote === true; // default OFF — stage onlyconst verifyCommand = typeof autofixerCfg.verifyCommand === 'string' ? autofixerCfg.verifyCommand.trim() : '';@@ -273,6 +270,7 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {autoPromote,provider: picked.provider?.id || null,model: picked.model || null,+ restriction: picked.mode || null,...extra,...(error ? { error } : {}),};@@ -290,7 +288,7 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {if (picked.error) {outputBuffer.push(`[ERROR] ${picked.error}`);- console.error(`❌ [Autofixer] ${picked.error}`);+ console.warn(`🛑 [Autofixer] Not repairing ${processName}: ${picked.error}`);return finalize({ success: false, exitCode: -1, error: picked.error });}@@ -313,7 +311,7 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {// system + AI-provider auth. provider.envVars still overlays inside the runner.const childEnv = sanitizeChildEnv(process.env);- console.log(`🤖 [Autofixer] Repairing ${processName} in isolated worktree via ${picked.provider.id}${picked.model ? ` (${picked.model})` : ''}`);+ console.log(`🤖 [Autofixer] Repairing ${processName} in isolated worktree via ${picked.provider.id}${picked.model ? ` (${picked.model})` : ''} [${picked.mode}]`);const result = await runCliProviderPrompt({provider: picked.provider,@@ -321,7 +319,6 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {prompt,cwd: worktreePath,baseEnv: childEnv,- extraArgs: restrictedToolArgs(picked.provider),timeoutMs: 600000, // 10 min — a fix may need several read/edit cyclesonData: (chunk, stream) => {if (stream === 'stderr') {@@ -347,12 +344,13 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {? validateProposedDiff(diff, { maxBytes: MAX_DIFF_BYTES, secretValues }): { ok: false, reason: `agent did not complete: ${result.error}`, files: [] };- // Optional verification against the user-configured test command, run in the- // isolated worktree with the sanitized env — before anything reaches live.+ // Optional verification against the user-configured test command, contained+ // over the isolated worktree — before anything reaches live.let verify = null;if (validation.ok && verifyCommand) {console.log(`🧪 [Autofixer] Verifying ${processName} fix: ${verifyCommand}`);- verify = await runVerifyCommand(verifyCommand, worktreePath, childEnv);+ verify = await runVerifyCommand(verifyCommand, worktreePath, { dataDir: DATA_DIR });+ if (!verify.contained) console.warn(`🛑 [Autofixer] ${verify.output}`);outputBuffer.push(`\n[VERIFY exit ${verify.code}]\n${verify.output}`);}const verifyOk = !verifyCommand || (verify && verify.ok);@@ -408,7 +406,7 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {changedFiles: validation.files,diffValid: validation.ok,...(validation.ok ? {} : { diffRejectedReason: validation.reason }),- ...(verify ? { verify: { ran: true, ok: verify.ok, exitCode: verify.code } } : { verify: { ran: false } }),+ ...(verify ? { verify: { ran: true, ok: verify.ok, exitCode: verify.code, contained: verify.contained } } : { verify: { ran: false } }),},});}diff --git a/autofixer/server.test.js b/autofixer/server.test.jsindex bf0913224f..562ea06824 100644--- a/autofixer/server.test.js+++ b/autofixer/server.test.js@@ -15,13 +15,12 @@ vi.mock('fs/promises', () => ({}));vi.mock('../server/lib/agentGuard/index.js', () => ({ agentGuardEnv: () => ({}) }));vi.mock('../server/lib/cliProviderRun.js', () => ({- pickCliProvider: () => ({ provider: { id: 'example-cli' } }),runCliProviderPrompt: harness.provider,}));vi.mock('./sandbox.js', () => ({sanitizeChildEnv: () => ({}), collectSecretEnvValues: () => [],buildFixPrompt: ({ errorLogs, outputLogs }) => JSON.stringify({ errorLogs, outputLogs }),- restrictedToolArgs: () => [], isGitRepo: async () => true,+ pickRepairProvider: () => ({ provider: { id: 'example-cli' }, mode: 'claude-disallowed-tools' }), isGitRepo: async () => true,createDisposableWorktree: async () => ({ path: '/example/worktree' }),collectWorktreeDiff: async () => '', removeWorktree: vi.fn(),sweepStaleWorktrees: harness.sweep,diff --git a/client/src/components/settings/AutofixerTab.jsx b/client/src/components/settings/AutofixerTab.jsxindex 35500c04a4..6ee451a92e 100644--- a/client/src/components/settings/AutofixerTab.jsx+++ b/client/src/components/settings/AutofixerTab.jsx@@ -42,8 +42,8 @@ export function AutofixerTab() {When a monitored process crashes, the Autofixer runs this AI provider to read the logs,propose a fix in an isolated checkout. Fixes are staged for review by default; apply or discardthem in the Autofixer History tab. Automatic application and restart require the toggle below.- Only agentic CLI providers are listed —- the fixer needs file-edit and shell access, which API chat providers can't do.+ Repairs run only on a Claude Code or Codex CLI provider, which can be restricted to editing+ files in that checkout with no shell or network access. Other CLI providers are skipped.</p><FeatureProviderPickerfeatureKey="autofixer"@@ -62,7 +62,7 @@ export function AutofixerTab() {value={verifyCommand} maxLength={500} disabled={!loaded || saving}onChange={event => setVerifyCommand(event.target.value)} placeholder="npm test" /></label>- <p className="text-xs text-gray-400">Optional command run in the isolated checkout before staging or automatic application.</p>+ <p className="text-xs text-gray-400">Optional command run in the isolated checkout before staging or automatic application. It runs contained (macOS Seatbelt or Linux bubblewrap): no network, no provider credentials, and writes only inside the checkout. Where containment is unavailable the check fails and the fix is not applied.</p><button className="px-3 py-2 bg-port-accent rounded text-white" disabled={!loaded || saving} onClick={save}>{saving ? 'Saving…' : 'Save promotion settings'}</button>diff --git a/server/lib/README.md b/server/lib/README.mdindex 72b7268a28..fa9132afcf 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -35,6 +35,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `credentialEnvVars.js` | `isCredentialEnvVarName(name)` / `isNonCredentialEnvVarName(name)` / `isMaskedEnvVar(name, secretEnvVars)`: name-convention classifier for credential env vars (API_KEY, TOKEN, SECRET…), shared by provider response masking and the client readiness check. Pure. || `codeAnimationAcceptance.js` | Code Animation production acceptance: splits run evidence into technical/visual/temporal/sound (unmeasured stays unverified), decides promotability, freezes source/audio/render hashes and detects stale acceptance. Pure. || `codeAnimationContainment.js` | Code Animation production worker containment contract: per-platform enforced mechanism (macOS Seatbelt or Linux bubblewrap, otherwise refusal), deny-by-default profiles and a process-denying Linux seccomp filter, from-scratch worker environment, operator tool-root rules, tool configuration and worker limit schemas. Pure; the runner is `services/codeAnimation/containedWorker.js`. |+| `autofixVerifyContainment.js` | Containment contract for the autofixer verify command (#12487): a Seatbelt profile / bubblewrap argv that permits a forking test runner but denies network, writes outside the worktree and scratch, reads of the PortOS data directory and host credential stores, and (macOS) Mach services and outside signals; plus the from-scratch verify environment. Pure; the runner is `autofixer/sandbox.js#runVerifyCommand`. || `generatedPreviewSandbox.js` | OS network-isolation plan for generated preview browsers: macOS Seatbelt or Linux bubblewrap, otherwise refusal. The jail denies IP and the host DNS resolver; Chrome flags are defense in depth. Pure; the launcher is `services/htmlComposition/ownedBrowser.js`. || `generatedPreviewPlaybackSchema.js` | Strict optional generated-preview clock, preparation, playback-anchor and pause message contracts, plus authored-producer reply contracts and private bridge constants; legacy open and seek payloads remain unchanged. || `codeAnimationPackage.js` | Versioned data-only Code Animation package schema, byte/path/reference integrity limits, SHA-256 revision binding, `createCodeAnimationPackage` and `summarizeCodeAnimationPackage`; validation never executes or stages code. |@@ -268,7 +269,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path, and `videoTextEncoderRuntimes()` enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written. || `pi.js` | Pi command identity, headless/TUI arguments, and positional prompt delivery. || `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, `localRuntimeNamespace(provider)` — the OpenCode namespace only when it names a LOCAL daemon, i.e. the composed "namespace and not a hosted gateway" test that `cliChildEnv.js`, `localProviderRuntime.js` and `providerVendors.js` all key on, `CODEX_OSS_LOCAL_PROVIDERS` / `CODEX_OSS_MIN_VERSION` / `codexOssLocalProvider` / `codexUnsupportedLocalRuntime` — the codex half of that same axis: which local runtimes Codex's `--local-provider` can serve, and which marked runtime it cannot, kept here beside the namespace they wrap so `providerPrerequisites.js` classifies a codex record without importing `codex.js` (the argv emitter, `buildCodexOssArgs`, stays there), `OPENCODE_PUBLIC_REVIEW_AGENT` — the read-only OpenCode agent a no-tool public-review stage runs as, kept in this leaf because `providerVendors.js` must not import `opencodeConfig.js`, `parseOpencodeConfigContent` — the shared "is this stored OPENCODE_CONFIG_CONTENT usable?" read — plus `opencodeConfigIsLocalOnly` / `opencodeProviderIsLocalOnly`, the ONE locality rule `providerVendors.js` (gate eligibility) and `cliChildEnv.js` (public-review env allowlist) must not disagree about: if eligibility says yes where the allowlist strips the config, the stage spawns against the user's own ~/.config/opencode with tools intact while still reporting an enforced tool-free gate, `normalizeClaudeModelId` / `resolveClaudeCliModel` — the Claude-argv chokepoint that rewrites a dotted first-party version (`claude-fable-5.1`) to the dashed id Claude Code actually serves before the Bedrock mapping runs, model-flag scan helpers incl. `stripBrokenModelFlags` and `stripProviderPinArgs` (explicit per-run selections override baked CLI pins), `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus the agy catalog family, which reads an `agy models` list as base ids paired with effort tiers (`splitAntigravityModel`, `antigravityBaseModels`, `antigravityModelEffortLevels`, `antigravityCatalogListsModel` — is a stored pin still served? — and `pickAntigravityRelayModel` — the cheapest tier to relay one tool call on when a vendor retires the pin PortOS shipped) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `clampEffortToLadder` (that clamp over an explicit ladder; the client's own `resolveCliEffort` runs its published-field ladder through it), `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file.; `isOpencodeLocalProvider` (the OpenCode-on-a-local-backend-or-gateway gate behind the OpenCode effort ladder) and `isCodexSubscriptionProvider` (the ChatGPT-subscription readiness key, housed here so the browser re-export skips `codexAccount.js`'s protocol tables) |-| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Also `toolFreeOneShotArgs` / `isToolFreeOneShotProvider` / `toolFreeOneShotRefusal` (#9008): the one-shot-over-caller-text posture Ask and AI app detection run — every approval-bypass flag stripped, the vendor tool-disable switch applied where one exists (claude, grok, pi), and host control required for every other CLI. Dependency-light on purpose, mirroring those files. |+| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Also `toolFreeOneShotArgs` / `isToolFreeOneShotProvider` / `toolFreeOneShotRefusal` (#9008): the one-shot-over-caller-text posture Ask and AI app detection run — every approval-bypass flag stripped, the vendor tool-disable switch applied where one exists (claude, grok, pi), and host control required for every other CLI. `restrictedRepairArgs` (#12487) is the autofixer repair posture: claude with Bash/web tools denied and edits auto-accepted only in the cwd, or codex in its network-denied workspace-write sandbox, with every saved bypass stripped; null for any other CLI. Dependency-light on purpose, mirroring those files. || `publicReviewSpawnGate.js` | The ordered spawn-time preconditions a public-content review stage must clear before `runAgentSpawn` starts an agent for it — `checkPublicReviewSpawnPreconditions` returns the FIRST failing gate as `{ reason, category, emit }` (or null), running them in the order that is the contract: `publicReviewScanBlock` (the model-abuse scan cleared at least one PR), `publicReviewEligibilityBlock` (a complete eligibility verdict COVERING every PR the issue watcher saw — a partial gate is not a pass), `publicReviewProviderBlock` from `providerVendors.js` (the vendor row declares a maintained recipe for the requested posture; it owns the ordinary-task `null` posture, the re-derivation #5866 got wrong), then the model itself. `emit` tells the caller how to announce it: `warn-log` for the two fail-closed CONTENT gates, whose block must not raise an investigator that could retry the same unvalidated input, `agent:error` for a provider/model misconfiguration that should. `validateModel` is injected rather than imported — it is the one gate that probes a live runtime, so taking it as a parameter keeps this leaf out of the local-LLM graph and makes the gate ORDER testable with a stub. || `modelCapabilityTests.js` | Catalog + scoring for the CAPABILITY tests on `/models/performance` (run by `services/modelCapabilityTests.js`): `CAPABILITY_TESTS` (sandbox repair / image analysis / story outline / fiction scene / rhetoric evaluator, each gated on the capability badges the install catalog already shows), `applicabilityFor` + `applicableTests` (`applicable` / `not-applicable` / `unknown` — an UNCLAIMED capability is never a failure, and `null` capabilities mean the runtime reported none, which is distinct from `[]`), `scoreKeywords` + `VISION_FIXTURE_KEYWORDS` (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), `scoreStoryBeats` + `HEROS_JOURNEY_BEATS` (coverage AND ordering, judged only over the beats present), `scoreSandboxRepair` (verdict from observed disk facts — editing the test instead of the module fails outright), `formatAgentEvent` (one agent stream frame → a transcript line), `rollUpVerdict`, and the verbatim `CAPABILITY_TEST_PROMPTS` / `SANDBOX_TASK_PROMPT` the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call. || `modelPinMembership.js` | THE model-pin membership rule, and the local-daemon classification it rests on — `modelPinIsOffered(provider, model)` (may this provider be handed this model? a configured-default sentinel, an empty catalog and a local daemon's cached snapshot are all pass-throughs, so a freshly pulled Ollama model is never rejected as "not offered"; beyond those the match is exact, with two same-model-spelled-differently tolerances: agy compares on BASE ids, since `--effort` carries the tier and the spawner splits a suffixed pin into exactly that, and OpenCode's `namespace/model` form matches a bare pin, since pins are stored bare and namespaced at spawn), plus `localRuntimeKind(provider)` (the `*Backed` markers first, then the endpoint/name classifier; `orcarouter` excluded as a remote API) and `localBackendForProvider`. Split out of `localProviderRuntime.js` — which re-exports all three, so existing importers are untouched — because the browser needs this rule for a picker and must not pull that module's endpoint graph (`opencodeConfig.js` → `zod`, not a client dependency) to get it. Carries `LOCAL_RUNTIME_MANAGE_URLS` for the same reason (#7414): the route that manages each local runtime — Models → Runtimes for the servers, Models → LLMs for the weights catalog, `null` for the operator-owned compose projects — read by `LOCAL_RUNTIMES[*].manageUrl` and by the client surfaces that must name the same page. Consumed by `cliProviderRun.js`, `routes/brainSettings.js`, `services/agentProviderResolution.js`, `modelPinReconcile.js` and `client/src/utils/providerModels.js` — one answer for all five (#7327). |diff --git a/server/lib/autofixVerifyContainment.js b/server/lib/autofixVerifyContainment.jsnew file mode 100644index 0000000000..f58ae3df68--- /dev/null+++ b/server/lib/autofixVerifyContainment.js@@ -0,0 +1,90 @@+/**+ * Containment contract for the autofixer's verify command (#12487).+ *+ * The verify command (`npm test`, …) runs over a worktree a crash-log-driven+ * agent just edited, so a test file or `pretest` script it wrote executes+ * here. A test runner forks, so the single-process Code Animation profile+ * (`codeAnimationContainment.js`) cannot host it; this profile keeps the same+ * mechanisms (macOS Seatbelt, Linux bubblewrap, refusal elsewhere) with these+ * bounds instead:+ * - no network, including loopback and Unix sockets (PortOS's API);+ * - writes only to the worktree and a private scratch home/tmp;+ * - no reads of the PortOS data directory (providers, settings, keys) or the+ * host user's credential stores; the rest of the host stays readable so+ * toolchains resolve;+ * - macOS: no Mach services beyond user/log lookups (no LaunchServices,+ * keychain or pasteboard) and no signals outside the sandbox;+ * - an environment built from nothing — no provider key or PortOS token.+ *+ * Pure: no filesystem, process or settings access. Paths must be realpaths.+ */+import { join, posix } from 'node:path';+import { seatbeltPathLiteral } from './codeAnimationContainment.js';++/** Host-user credential stores, relative to the real home directory. */+export const AUTOFIX_VERIFY_PROTECTED_HOME_PATHS = Object.freeze([+ '.ssh', '.aws', '.gnupg', '.docker', '.kube', '.azure', '.portos', '.claude', '.claude.json', '.codex',+ '.netrc', '.npmrc', '.git-credentials', '.config/gh', '.config/gcloud', '.config/git/credentials',+ 'Library/Keychains',+]);++// Mach services a test runner needs for user/group lookups and logging.+const SEATBELT_MACH_ALLOW = [+ 'com.apple.system.opendirectoryd.libinfo', 'com.apple.system.notification_center',+ 'com.apple.system.logger', 'com.apple.logd', 'com.apple.diagnosticd', 'com.apple.FSEvents',+];++/**+ * Read-protected paths for one run: the PortOS data directory plus the host+ * user's credential stores. The worktree is re-allowed by each profile even+ * when it sits under the data directory.+ */+export function autofixVerifyProtectedPaths({ dataDir, realHome }) {+ return [dataDir, ...AUTOFIX_VERIFY_PROTECTED_HOME_PATHS.map((rel) => join(realHome, rel))].filter(Boolean);+}++/** The verify command's complete environment; `path` is the host PATH. */+export function autofixVerifyEnv({ scratch, path }) {+ const home = posix.join(scratch, 'home');+ const tmp = posix.join(scratch, 'tmp');+ return {+ PATH: path || '/usr/bin:/bin', HOME: home, TMPDIR: tmp, TMP: tmp, TEMP: tmp,+ LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8', USER: 'worker', LOGNAME: 'worker',+ XDG_CONFIG_HOME: posix.join(home, 'config'), XDG_CACHE_HOME: posix.join(home, 'cache'), XDG_DATA_HOME: posix.join(home, 'data'),+ CI: '1',+ };+}++/** Seatbelt profile; later rules win, so the worktree re-allow follows the denials. */+export function autofixVerifySeatbeltProfile({ worktree, scratch, protectedPaths = [] }) {+ const lit = seatbeltPathLiteral;+ const denied = protectedPaths.map((path) => `(subpath ${lit(path)})`).join(' ');+ return `(version 1)+(allow default)+(deny network*)+(deny mach-lookup)+(allow mach-lookup ${SEATBELT_MACH_ALLOW.map((name) => `(global-name ${JSON.stringify(name)})`).join(' ')})+(deny signal)+(allow signal (target same-sandbox))+(deny file-write*)+(allow file-write* (literal "/dev/null") (subpath ${lit(worktree)}) (subpath ${lit(scratch)}))+${denied ? `(deny file-read* ${denied})\n` : ''}(allow file-read* (subpath ${lit(worktree)}) (subpath ${lit(scratch)}))`;+}++/**+ * bubblewrap argv up to the command. `protectedDirs` / `protectedFiles` must+ * exist (bwrap mounts over them): directories become empty tmpfs, files+ * become /dev/null. The worktree and scratch are bound writable last.+ */+export function autofixVerifyBubblewrapArgs({ worktree, scratch, env, protectedDirs = [], protectedFiles = [] }) {+ const args = [+ '--unshare-all', '--die-with-parent', '--new-session', '--cap-drop', 'ALL', '--clearenv',+ '--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--tmpfs', '/tmp',+ ];+ for (const dir of protectedDirs) args.push('--tmpfs', dir);+ for (const file of protectedFiles) args.push('--ro-bind', '/dev/null', file);+ args.push('--bind', scratch, scratch, '--bind', worktree, worktree);+ for (const [key, value] of Object.entries(env)) args.push('--setenv', key, value);+ args.push('--chdir', worktree, '--');+ return args;+}diff --git a/server/lib/codeAnimationContainment.js b/server/lib/codeAnimationContainment.jsindex 551bca4bac..ede98a4b52 100644--- a/server/lib/codeAnimationContainment.js+++ b/server/lib/codeAnimationContainment.js@@ -62,8 +62,8 @@ export function codeAnimationContainmentMechanism(platform, seatbeltAvailable, b};}-// SBPL string literals: refuse anything that could close the literal or the form.-const sbplPath = (path) => {+/** SBPL string literal for a path; refuses anything that could close the literal or the form. */+export const seatbeltPathLiteral = (path) => {if (typeof path !== 'string' || !isAbsolute(path) || normalize(path) !== path || /["\\()\0\r\n]/.test(path)) {throw new Error('Containment paths must be normalized absolute paths without quote, backslash or parenthesis characters');}@@ -120,12 +120,12 @@ export function codeAnimationSeatbeltProfile({ executable, toolRoots, workspaceconst metadata = [...new Set([...readRoots, executable].flatMap(ancestors))];return `(version 1)(deny default)-(allow process-exec (literal ${sbplPath(executable)}))+(allow process-exec (literal ${seatbeltPathLiteral(executable)}))(allow sysctl-read)-(allow file-read-metadata (literal "/") ${metadata.map((path) => `(literal ${sbplPath(path)})`).join(' ')})+(allow file-read-metadata (literal "/") ${metadata.map((path) => `(literal ${seatbeltPathLiteral(path)})`).join(' ')})(allow file-read* (literal "/") (literal "/dev/null") (literal "/dev/zero") (literal "/dev/random") (literal "/dev/urandom")- ${readRoots.map((path) => `(subpath ${sbplPath(path)})`).join(' ')})-(allow file-write* (literal "/dev/null") ${writable.map((path) => `(subpath ${sbplPath(path)})`).join(' ')})`;+ ${readRoots.map((path) => `(subpath ${seatbeltPathLiteral(path)})`).join(' ')})+(allow file-write* (literal "/dev/null") ${writable.map((path) => `(subpath ${seatbeltPathLiteral(path)})`).join(' ')})`;}/**diff --git a/server/lib/index.js b/server/lib/index.jsindex 2ef5b7a4c5..caccc7d10e 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -22,6 +22,7 @@ export * from './apiContractSchemas.js';export * from './codeAnimationPackage.js';export * from './codeAnimationAcceptance.js';export * from './codeAnimationContainment.js';+export * from './autofixVerifyContainment.js';export * from './generatedPreviewSandbox.js';export * from './generatedPreviewPlaybackSchema.js';export * from './autonomousJobTask.js';diff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex 177a5c8af1..cc4da40712 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -727,6 +727,9 @@ export function buildEffortArgs(effort, provider, existingArgs = [], model = nul// edit rather than a four-builder grep.export const CODEX_UPDATE_CHECK_KEY = 'check_for_update_on_startup';export const CODEX_AGENT_THREADS_KEY = 'agents.max_concurrent_threads_per_session';+// Forced off for autofixer repairs (#12487) so a user config cannot open the+// workspace-write sandbox to the network.+export const CODEX_WORKSPACE_NETWORK_KEY = 'sandbox_workspace_write.network_access';/*** Give a Codex swarm enough session threads for its root orchestrator plus@@ -806,6 +809,7 @@ export const PORTOS_CLI_CONFIG_KEYS = Object.freeze([CODEX_AGENT_THREADS_KEY,CODEX_EFFORT_KEY,CODEX_UPDATE_CHECK_KEY,+ CODEX_WORKSPACE_NETWORK_KEY,]);/**diff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.jsindex 878bab4b9b..278dd7d1fc 100644--- a/server/lib/providerModels.test.js+++ b/server/lib/providerModels.test.js@@ -42,6 +42,7 @@ import {CODEX_UPDATE_CHECK_KEY,PORTOS_CLI_CONFIG_KEYS,CODEX_AGENT_THREADS_KEY,+ CODEX_WORKSPACE_NETWORK_KEY,isPortosSuppliedConfigKey,hasCodexUpdateCheckConfig,buildCodexStartupArgs,@@ -748,6 +749,7 @@ describe('providerModels', () => {CODEX_AGENT_THREADS_KEY,CODEX_EFFORT_KEY,CODEX_UPDATE_CHECK_KEY,+ CODEX_WORKSPACE_NETWORK_KEY,].sort());// Guard against a third emitter appearing without a row: both builders// that produce `-c` are asserted to use a listed key.diff --git a/server/lib/providerVendors.js b/server/lib/providerVendors.jsindex 13dffecb84..4e3e411784 100644--- a/server/lib/providerVendors.js+++ b/server/lib/providerVendors.js@@ -79,6 +79,7 @@ import {OPENCODE_PUBLIC_REVIEW_AGENT,OPENCODE_BUILD_AGENT,applyLeanClaudeArgs,+ CODEX_WORKSPACE_NETWORK_KEY,} from './providerModels.js';import {isCodexCommand,@@ -1142,6 +1143,49 @@ export function toolFreeOneShotArgs(provider, args = []) {return { args: removed && spec?.afterStrip ? spec.afterStrip(stripped) : stripped, toolFree: false };}+// Autofixer repair posture (#12487). Claude keeps file Read/Edit/Write only:+// acceptEdits auto-approves edits inside the working directory and nothing+// else, and neither project MCP servers nor project settings (hooks) load.+const CLAUDE_REPAIR_ARGS = [+ '--permission-mode', 'acceptEdits',+ '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}',+ '--setting-sources', 'user',+ '--disallowedTools', 'Bash', 'WebFetch', 'WebSearch',+];+// Codex's OS sandbox: writes confined to the working directory, network off+// even when the user's config.toml enables it for workspace-write.+const CODEX_REPAIR_ARGS = ['--sandbox', 'workspace-write', '-c', `${CODEX_WORKSPACE_NETWORK_KEY}=false`];++/**+ * Saved provider argv for a file-editing repair driven by untrusted input+ * (autofixer crash logs), or null when the vendor has no enforced restricted+ * mode. Every approval bypass is removed and the vendor's own posture options+ * are replaced, so a saved bypass or wider grant cannot override the recipe.+ * The result replaces `provider.args`; the vendor builder adds `-p -` / `-`.+ *+ * @param {object} provider - provider record (command, args)+ * @returns {{ mode: 'claude-disallowed-tools'|'codex-workspace-write', args: string[] } | null}+ */+export function restrictedRepairArgs(provider) {+ const command = provider?.command;+ if (!command) return null;+ const saved = stripApprovalBypassArgs(Array.isArray(provider.args) ? provider.args : []).args;+ if (isClaudeCommand(command)) {+ const cleared = dropOptions(+ dropOptions(saved, ['--allowedTools', '--allowed-tools', '--disallowedTools', '--disallowed-tools', '--mcp-config'], { variadic: true }),+ ['--permission-mode', '--setting-sources'],+ ).filter((arg) => arg !== '--strict-mcp-config');+ return { mode: 'claude-disallowed-tools', args: [...cleared, ...CLAUDE_REPAIR_ARGS] };+ }+ if (isCodexCommand(command)) {+ const cleared = dropOptions(saved, ['--sandbox', '-s']);+ // Options must follow the subcommand; the builder appends `exec` only when absent.+ const withExec = cleared.includes('exec') ? cleared : ['exec', ...cleared];+ return { mode: 'codex-workspace-write', args: [...withExec, ...CODEX_REPAIR_ARGS] };+ }+ return null;+}+/*** Whether a one-shot call on `provider` can run without host authority: an API* provider, or a headless CLI whose vendor has a tool-disable switch. A TUI