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(autofixer): close repair configuration and verifier escape paths
[._.]/ Adam Eivy1c096782c22e
diff --git a/autofixer/sandbox.js b/autofixer/sandbox.jsindex 72f4eef60e..10dde25f5d 100644--- a/autofixer/sandbox.js+++ b/autofixer/sandbox.js@@ -27,20 +27,20 @@* autofixer package — which installs only `express` — can import it.*/-import { spawn } from 'child_process';+import { spawn } from 'node:child_process';import { waitForChild, COMMAND_TIMEOUT_MS } from './childProcess.js';-import { writeFile, rm, mkdir, mkdtemp, readdir, realpath, lstat, 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 { writeFile, rm, mkdir, mkdtemp, readdir, realpath, lstat, access } from 'node:fs/promises';+import { constants as fsConstants } from 'node:fs';+import { join, isAbsolute, normalize, resolve, dirname } from 'node:path';+import { homedir, tmpdir } from 'node:os';+import { randomBytes } from 'node:crypto';import { pickCliProvider } from '../server/lib/cliProviderRun.js';import { restrictedRepairArgs } from '../server/lib/providerVendors.js';import {- CODE_ANIMATION_SEATBELT, CODE_ANIMATION_BUBBLEWRAP, codeAnimationContainmentMechanism,+ CODE_ANIMATION_BUBBLEWRAP, codeAnimationContainmentMechanism,} from '../server/lib/codeAnimationContainment.js';import {- autofixVerifyBubblewrapArgs, autofixVerifyEnv, autofixVerifyProtectedPaths, autofixVerifySeatbeltProfile,+ autofixVerifyBubblewrapArgs, autofixVerifyEnv, autofixVerifyProtectedPaths,autofixVerifySeccompFilter,} from '../server/lib/autofixVerifyContainment.js';@@ -242,6 +242,25 @@ export function pickRepairProvider(providers, config = {}) {return { provider: { ...picked.provider, args }, model: picked.model, mode };}+/** User-config suppression does not establish project-layer trust behavior.+ * Both the source checkout and disposable linked checkout are project roots;+ * refuse executable Codex configuration there before exposing crash-log input.+ */+export async function repairWorkspaceHold(mode, sourceWorkspace, worktreePath) {+ if (mode !== 'codex-workspace-write') return null;+ for (const root of new Set([sourceWorkspace, worktreePath])) {+ for (const file of ['config.toml', 'hooks.json']) {+ try {+ await lstat(join(root, '.codex', file));+ return 'Codex repair refused: project configuration or hooks could restore tools outside the repair sandbox';+ } catch (error) {+ if (error.code !== 'ENOENT') return 'Codex repair refused: project configuration could not be safely inspected';+ }+ }+ }+ return null;+}+// ---------------------------------------------------------------------------// Diff validation (promotion gate)// ---------------------------------------------------------------------------@@ -260,6 +279,8 @@ const FORBIDDEN_PATH_PATTERNS = [/\.pem$/,/(^|[\\/])\.github([\\/]|$)/,/(^|[\\/])\.claude([\\/]|$)/,+ /(^|[\\/])\.(codex|agents)([\\/]|$)/,+ /(^|[\\/])\.mcp\.json$/,];/**@@ -465,12 +486,13 @@ export async function sweepStaleWorktrees(parentDir) {const canExecute = (path) => access(path, fsConstants.X_OK).then(() => true, () => false);/**- * The enforced mechanism available for the verify command: Seatbelt on macOS,- * bubblewrap on Linux when it can create namespaces, otherwise a refusal.+ * Verification needs filesystem/network AND descendant lifecycle containment.+ * Linux bubblewrap supplies a PID namespace; a process-group kill on macOS+ * cannot contain a verifier that creates a new session with setsid.*/export async function probeVerifyContainment() {if (process.platform === 'darwin') {- return codeAnimationContainmentMechanism('darwin', await canExecute(CODE_ANIMATION_SEATBELT));+ return { id: null, supported: false, reason: 'macOS verification is unavailable: Seatbelt cannot prevent detached verifier descendants from surviving completion or timeout' };}if (process.platform !== 'linux') return codeAnimationContainmentMechanism(process.platform, false);if (!['x64', 'arm64'].includes(process.arch)) {@@ -547,7 +569,7 @@ function runGroup(file, args, { cwd, env, timeoutMs, seccomp = null }) {*/export async function runVerifyCommand(command, cwd, { dataDir = null, homeDir = homedir(), timeoutMs = 300000, probe = probeVerifyContainment } = {}) {const mechanism = await probe();- if (!mechanism.supported) {+ if (!mechanism.supported || mechanism.id !== 'linux-bubblewrap') {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-'));@@ -560,29 +582,21 @@ export async function runVerifyCommand(command, cwd, { dataDir = null, homeDir =dataDir: dataDir ? await realOrSelf(dataDir) : null,realHome: await realOrSelf(homeDir),});- // Seatbelt matches resolved paths: a symlinked store (~/.ssh → elsewhere)- // is protected only through its target, so list both.+ // Protect a symlinked store (~/.ssh → elsewhere) through its target too.const protectedPaths = [...new Set([...listed, ...await Promise.all(listed.map(realOrSelf))])];const env = autofixVerifyEnv({ scratch, path: process.env.PATH });const shell = ['/bin/sh', '-c', command];- let launch;- let seccomp = null;- if (mechanism.id === 'macos-seatbelt') {- launch = [CODE_ANIMATION_SEATBELT, ['-p', autofixVerifySeatbeltProfile({ worktree, scratch, protectedPaths }), ...shell]];- } else {- seccomp = autofixVerifySeccompFilter(process.arch);- // bwrap mounts over each path, so a symlink is skipped: its resolved- // target is already listed and is what the mount must cover.- const present = (await Promise.all(protectedPaths.map(async (path) => [path, await lstat(path).catch(() => null)])))- .filter(([, info]) => info && !info.isSymbolicLink());- const bwrapArgs = autofixVerifyBubblewrapArgs({- worktree, scratch, env,- protectedDirs: present.filter(([, info]) => info?.isDirectory()).map(([path]) => path),- protectedFiles: present.filter(([, info]) => !info.isDirectory()).map(([path]) => path),- });- launch = [CODE_ANIMATION_BUBBLEWRAP, [...bwrapArgs, ...shell]];- }- const result = await runGroup(launch[0], launch[1], { cwd: worktree, env, timeoutMs, seccomp });+ const seccomp = autofixVerifySeccompFilter(process.arch);+ // bwrap mounts over each path, so a symlink is skipped: its resolved+ // target is already listed and is what the mount must cover.+ const present = (await Promise.all(protectedPaths.map(async (path) => [path, await lstat(path).catch(() => null)])))+ .filter(([, info]) => info && !info.isSymbolicLink());+ const bwrapArgs = autofixVerifyBubblewrapArgs({+ worktree, scratch, env,+ protectedDirs: present.filter(([, info]) => info?.isDirectory()).map(([path]) => path),+ protectedFiles: present.filter(([, info]) => !info.isDirectory()).map(([path]) => path),+ });+ const result = await runGroup(CODE_ANIMATION_BUBBLEWRAP, [...bwrapArgs, ...shell], { cwd: worktree, env, timeoutMs, seccomp });return { ...result, contained: true, mechanism: mechanism.id };} finally {await rm(scratchDir, { recursive: true, force: true }).catch(() => {});diff --git a/autofixer/sandbox.test.js b/autofixer/sandbox.test.jsindex f03bdc8e66..a0b46ab41c 100644--- a/autofixer/sandbox.test.js+++ b/autofixer/sandbox.test.js@@ -1,11 +1,11 @@import { describe, it, expect, vi, afterEach } from 'vitest';import { EventEmitter } from 'node:events';-import { mkdtemp, rm } from 'node:fs/promises';+import { mkdtemp, mkdir, rm, writeFile, symlink } 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 }));+vi.mock('node:child_process', () => ({ spawn: spawnMock }));import {execGit,sanitizeChildEnv,@@ -13,6 +13,8 @@ import {buildFixPrompt,defuseSentinel,pickRepairProvider,+ probeVerifyContainment,+ repairWorkspaceHold,runVerifyCommand,validateProposedDiff,scanDiffForSecrets,@@ -195,7 +197,8 @@ describe('pickRepairProvider — only an enforced restricted mode runs a repair'expect(argv).not.toContain('--allowedTools');expect(argv).not.toContain('/example/live');expect(argv.join(' ')).toContain('--permission-mode acceptEdits');- expect(argv.join(' ')).toContain('--setting-sources user');+ expect(argv).toContain('--restricted');+ expect(argv).toContain('--safe-mode');expect(argv.join(' ')).toContain('--disallowedTools Bash WebFetch WebSearch');expect(argv.slice(-2)).toEqual(['-p', '-']);});@@ -209,13 +212,43 @@ describe('pickRepairProvider — only an enforced restricted mode runs a repair'expect(argv).not.toContain('danger-full-access');expect(argv).not.toContain('/example/live');expect(argv.join(' ')).toContain([- '--sandbox workspace-write --ignore-user-config',+ '--sandbox workspace-write --ignore-user-config --ignore-rules','-c sandbox_workspace_write.network_access=false -c sandbox_workspace_write.writable_roots=[]','-c features.plugins=false -c features.apps=false',+ '-c features.hooks=false',].join(' '));expect(argv.filter((arg) => arg === '--ignore-user-config')).toHaveLength(1);expect(argv.at(-1)).toBe('-');});++ it('cannot restore host tools through saved config or plugin options while preserving declared model pins', () => {+ for (const provider of [+ { ...codex, args: ['exec', '-c', 'mcp_servers.example.command="unsafe-tool"', '--enable', 'plugins'] },+ { ...claude, args: ['--settings', '/example/hooks.json', '--plugin-dir', '/example/plugins', '--tools', 'Agent,Bash'] },+ ]) {+ const argv = spawnedArgv(pickRepairProvider([{ ...provider, defaultModel: 'example-model' }]));+ expect(argv.join(' ')).not.toMatch(/unsafe-tool|mcp_servers|example\/hooks|example\/plugins|Agent,Bash|--enable/);+ expect(argv).toContain('example-model');+ if (provider.command === 'claude') expect(argv.join(' ')).toContain('--tools Read,Edit,Write,Grep,Glob');+ }+ });+});++describe('Codex project configuration repair boundary', () => {+ it('refuses executable project configuration in either linked checkout, including dangling links', async () => {+ const root = await mkdtemp(join(tmpdir(), 'autofix-project-config-'));+ const source = join(root, 'source');+ const worktree = join(root, 'worktree');+ await Promise.all([source, worktree].map(path => mkdir(join(path, '.codex'), { recursive: true })));+ try {+ expect(await repairWorkspaceHold('codex-workspace-write', source, worktree)).toBeNull();+ await writeFile(join(source, '.codex', 'config.toml'), '[mcp_servers.example]\ncommand="example"');+ expect(await repairWorkspaceHold('codex-workspace-write', source, worktree)).toContain('project configuration');+ await rm(join(source, '.codex', 'config.toml'));+ await symlink(join(root, 'missing'), join(worktree, '.codex', 'hooks.json'));+ expect(await repairWorkspaceHold('codex-workspace-write', source, worktree)).toContain('project configuration');+ } finally { await rm(root, { recursive: true, force: true }); }+ });});describe('runVerifyCommand — contained, credential-free verify', () => {@@ -230,27 +263,34 @@ describe('runVerifyCommand — contained, credential-free verify', () => {expect(spawnMock).not.toHaveBeenCalled();});- it('launches under Seatbelt with an environment built from nothing', async () => {+ it.skipIf(process.platform !== 'darwin')('refuses macOS verification when detached descendants cannot be contained', async () => {+ expect(await probeVerifyContainment()).toMatchObject({ supported: false, reason: expect.stringContaining('detached verifier descendants') });+ expect(await runVerifyCommand('npm test', '/example/worktree')).toMatchObject({ ok: false, contained: false });+ expect(spawnMock).not.toHaveBeenCalled();+ });++ it('launches under bubblewrap 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() });+ Object.assign(child, { pid: 4242, stdout: new EventEmitter(), stderr: new EventEmitter(),+ stdio: [null, null, null, { on: vi.fn(), end: vi.fn() }] });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 }),+ dataDir: '/example/data', probe: async () => ({ id: 'linux-bubblewrap', supported: true, reason: null }),});- expect(result).toMatchObject({ ok: true, contained: true, mechanism: 'macos-seatbelt', output: 'ok' });+ expect(result).toMatchObject({ ok: true, contained: true, mechanism: 'linux-bubblewrap', output: 'ok' });const [file, args, options] = spawnMock.mock.calls[0];- expect(file).toBe('/usr/bin/sandbox-exec');+ expect(file).toBe('/usr/bin/bwrap');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(args).toContain('--unshare-all');+ expect(args).toContain('--seccomp');expect(options.detached).toBe(true);expect(Object.keys(options.env).sort()).toEqual(['CI', 'HOME', 'LANG', 'LC_ALL', 'LOGNAME', 'PATH', 'TEMP', 'TMP', 'TMPDIR', 'USER',@@ -303,6 +343,10 @@ index 111..222 100644expect(validateProposedDiff(goodDiff.replace(/src\/index\.js/g, '.github/workflows/ci.yml')).ok).toBe(false);});+ it.each(['.codex/config.toml', '.agents/skills/example/SKILL.md', '.mcp.json'])('rejects promotion of agent/tool configuration %s', path => {+ expect(validateProposedDiff(goodDiff.replace(/src\/index\.js/g, path)).ok).toBe(false);+ });+it('rejects a path that escapes the repo (adversarial traversal)', () => {const diff = goodDiff.replace(/src\/index\.js/g, '../../etc/cron.d/pwn');expect(validateProposedDiff(diff).ok).toBe(false);diff --git a/autofixer/sandbox.verify.test.js b/autofixer/sandbox.verify.test.jsindex d807b457e1..8609d2d76e 100644--- a/autofixer/sandbox.verify.test.js+++ b/autofixer/sandbox.verify.test.js@@ -103,4 +103,47 @@ describe.skipIf(!mechanism.supported)(`runVerifyCommand under ${mechanism.id ||expect(unix.ok).toBe(false);expect(unix.output).not.toContain('reached');});++ it.skipIf(process.platform !== 'linux')('cannot create an io_uring that bypasses socket syscall restrictions', async () => {+ await writeFile(join(worktree, 'uring-probe.py'), [+ 'import ctypes, errno',+ 'libc = ctypes.CDLL(None, use_errno=True)',+ 'params = ctypes.create_string_buffer(256)',+ 'result = libc.syscall(425, 1, ctypes.byref(params))',+ 'assert result == -1 and ctypes.get_errno() == errno.EPERM',+ ].join('\n'));+ expect(await verify('python3 uring-probe.py')).toMatchObject({ ok: true, contained: true });+ });++ it('refuses datagram socketpairs that can reconnect to host pathname sockets', async () => {+ await writeFile(join(worktree, 'socketpair-probe.py'), [+ 'import socket, errno',+ 'a, b = socket.socketpair(type=socket.SOCK_STREAM)',+ 'a.close(); b.close()',+ 'try:',+ ' socket.socketpair(type=socket.SOCK_DGRAM)',+ 'except OSError as error:',+ ' assert error.errno == errno.EPERM',+ 'else:',+ ' raise AssertionError("datagram socketpair escaped")',+ ].join('\n'));+ expect(await verify('python3 socketpair-probe.py')).toMatchObject({ ok: true, contained: true });+ });++ it.each([false, true])('terminates detached descendants after verification (timeout=%s)', async timeout => {+ const marker = timeout ? 'timeout-late.txt' : 'completed-late.txt';+ await writeFile(join(worktree, 'descendant-probe.cjs'), [+ "const { spawn } = require('node:child_process');",+ `const child = spawn(process.execPath, ['-e', ${JSON.stringify(`setTimeout(() => require('node:fs').writeFileSync('${marker}', 'late'), 1200)`)}], { detached: true, stdio: 'ignore' });`,+ "child.on('error', error => { console.error(error); process.exitCode = 1; });",+ "child.on('spawn', () => console.log('descendant-started')); child.unref();",+ ...(timeout ? ['setTimeout(() => {}, 2500);'] : []),+ ].join('\n'));+ const result = await runVerifyCommand(`${JSON.stringify(process.execPath)} descendant-probe.cjs`, worktree,+ { dataDir, homeDir: home, timeoutMs: timeout ? 600 : 30000 });+ expect(result.output).toContain('descendant-started');+ expect(result.ok).toBe(!timeout);+ await new Promise(resolve => setTimeout(resolve, 1500));+ await expect(access(join(worktree, marker))).rejects.toThrow();+ });});diff --git a/autofixer/server.js b/autofixer/server.jsindex 12699b5ff8..f9ba4d0c36 100644--- a/autofixer/server.js+++ b/autofixer/server.js@@ -1,5 +1,5 @@-import { readFile, writeFile, mkdir, access, rename } from 'fs/promises';-import { join } from 'path';+import { readFile, writeFile, mkdir, access, rename } from 'node:fs/promises';+import { join } from 'node:path';// Dependency-light shared module (node builtins + pure arg builder only), so// 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@@ -12,6 +12,7 @@ import {collectSecretEnvValues,buildFixPrompt,pickRepairProvider,+ repairWorkspaceHold,validateProposedDiff,isGitRepo,createDisposableWorktree,@@ -307,6 +308,12 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {}const worktreePath = wt.path;activeRepair = { sessionId, processName, app, startTime, prompt, outputBuffer, worktreePath };+ const workspaceHold = await repairWorkspaceHold(picked.mode, app.repoPath, worktreePath);+ if (workspaceHold) {+ console.warn(`🛑 [Autofixer] ${workspaceHold}`);+ await removeWorktree(app.repoPath, worktreePath);+ return finalize({ success: false, exitCode: -1, error: workspaceHold, extra: { isolated: true } });+ }// Strip host credentials the agent has no business seeing — it keeps only// system + AI-provider auth. provider.envVars still overlays inside the runner.const childEnv = sanitizeChildEnv(process.env);@@ -335,14 +342,14 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {// spawn failure / timeout can leave a partial edit — don't promote or stage// work from an agent that didn't finish cleanly.const diff = await collectWorktreeDiff(worktreePath);- const agentOk = !result.error;+ const agentOk = !result.error && result.partial === false && result.exitCode === 0;// The live env's provider-auth values (incl. runner-injected provider.envVars// keys) — reject any diff that tries to write one into the repo (agent// read-then-promote exfil backstop).const secretValues = collectSecretEnvValues(childEnv, picked.provider?.envVars);const validation = agentOk? validateProposedDiff(diff, { maxBytes: MAX_DIFF_BYTES, secretValues })- : { ok: false, reason: `agent did not complete: ${result.error}`, files: [] };+ : { ok: false, reason: `agent did not complete: ${result.error || 'repair process returned incomplete output or an unsuccessful exit'}`, files: [] };// Optional verification against the user-configured test command, contained// over the isolated worktree — before anything reaches live.@@ -353,7 +360,7 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {if (!verify.contained) console.warn(`🛑 [Autofixer] ${verify.output}`);outputBuffer.push(`\n[VERIFY exit ${verify.code}]\n${verify.output}`);}- const verifyOk = !verifyCommand || (verify && verify.ok);+ const verifyOk = !verifyCommand || verify?.ok;// Promotion gate — only a validated (and, if configured, verified) diff may// touch the live checkout, and only when the user explicitly opted in.diff --git a/autofixer/server.test.js b/autofixer/server.test.jsindex 562ea06824..596a4bd90a 100644--- a/autofixer/server.test.js+++ b/autofixer/server.test.js@@ -1,15 +1,16 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { writeFile, rename } from 'fs/promises';+import { writeFile, rename } from 'node:fs/promises';const harness = vi.hoisted(() => ({apps: vi.fn(), sweep: vi.fn(), validate: vi.fn(), pm2: vi.fn(), list: vi.fn(), provider: vi.fn(),+ settings: {}, verify: vi.fn(), apply: vi.fn(),}));vi.mock('./shared.js', () => ({DATA_DIR: '/example/data', AUTOFIXER_DIR: '/example/autofixer', INDEX_FILE: '/example/index.json',loadApps: harness.apps, execPm2: harness.pm2, listProcessesStrict: harness.list,}));-vi.mock('fs/promises', () => ({- readFile: vi.fn(async file => file.endsWith('index.json') ? '[]' : '{}'),+vi.mock('node:fs/promises', () => ({+ readFile: vi.fn(async file => file.endsWith('index.json') ? '[]' : file.endsWith('settings.json') ? JSON.stringify(harness.settings) : '{}'),writeFile: vi.fn(async () => {}), mkdir: vi.fn(async () => {}), access: vi.fn(async () => {}),rename: vi.fn(async () => {}),}));@@ -21,11 +22,12 @@ vi.mock('./sandbox.js', () => ({sanitizeChildEnv: () => ({}), collectSecretEnvValues: () => [],buildFixPrompt: ({ errorLogs, outputLogs }) => JSON.stringify({ errorLogs, outputLogs }),pickRepairProvider: () => ({ provider: { id: 'example-cli' }, mode: 'claude-disallowed-tools' }), isGitRepo: async () => true,+ repairWorkspaceHold: async () => null,createDisposableWorktree: async () => ({ path: '/example/worktree' }),collectWorktreeDiff: async () => '', removeWorktree: vi.fn(),sweepStaleWorktrees: harness.sweep,validateProposedDiff: harness.validate,- applyDiffToLive: vi.fn(), revertDiffFromLive: vi.fn(), runVerifyCommand: vi.fn(),+ applyDiffToLive: harness.apply, revertDiffFromLive: vi.fn(), runVerifyCommand: harness.verify,}));let errorLog;@@ -42,6 +44,9 @@ beforeEach(() => {harness.sweep.mockReset().mockResolvedValue([]);harness.pm2.mockReset().mockResolvedValue({ stdout: '' });harness.provider.mockReset().mockResolvedValue({ error: 'Example agent stopped', exitCode: 1 });+ harness.settings = {};+ harness.verify.mockReset();+ harness.apply.mockReset();});afterEach(() => {vi.clearAllTimers();@@ -106,8 +111,35 @@ describe('Autofixer daemon repair input boundary', () => {expect(rename).toHaveBeenCalledWith('/example/index.json.tmp', '/example/index.json');});+ it('refuses partial edits from a repair process that exited unsuccessfully', async () => {+ harness.provider.mockResolvedValue({ text: 'partially repaired', partial: true, exitCode: 1 });+ await start();+ expect(harness.validate).not.toHaveBeenCalled();+ const meta = writeFile.mock.calls.find(([f]) => String(f).endsWith('metadata.json'));+ expect(JSON.parse(meta[1])).toMatchObject({ success: false, diffValid: false, promoted: false, staged: false });+ });++ it('validates edits only after a complete successful repair process', async () => {+ harness.provider.mockResolvedValue({ text: 'repaired', partial: false, exitCode: 0 });+ await start();+ expect(harness.validate).toHaveBeenCalledOnce();+ });++ it('blocks staging and promotion when the configured verifier has no supported containment', async () => {+ harness.settings = { autofixer: { autoPromote: true, verifyCommand: 'npm test' } };+ harness.provider.mockResolvedValue({ text: 'repaired', partial: false, exitCode: 0 });+ harness.validate.mockReturnValue({ ok: true, files: ['a.js'] });+ harness.verify.mockResolvedValue({ ok: false, contained: false, code: -1, output: 'verification refused: no descendant containment' });+ await start();+ expect(harness.verify).toHaveBeenCalledOnce();+ expect(harness.apply).not.toHaveBeenCalled();+ const meta = writeFile.mock.calls.find(([f]) => String(f).endsWith('metadata.json'));+ expect(JSON.parse(meta[1])).toMatchObject({ success: false, promoted: false, staged: false,+ verify: { ok: false, contained: false, exitCode: -1 } });+ });+it('still cools the process down when persisting the session fails', async () => {- harness.provider.mockResolvedValue({ exitCode: 0 });+ harness.provider.mockResolvedValue({ exitCode: 0, partial: false });harness.validate.mockReturnValue({ ok: true, files: ['a.js'] });writeFile.mockImplementation(async (f) => { if (String(f).endsWith('prompt.txt')) throw new Error('disk full'); });await start();diff --git a/client/src/components/settings/AutofixerTab.jsx b/client/src/components/settings/AutofixerTab.jsxindex 6ee451a92e..814d30b14f 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.- 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.+ Repairs run only on a Claude Code or Codex CLI provider. Claude uses file-editing tools;+ Codex runs commands in a sandbox with network access disabled. 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. 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>+ <p className="text-xs text-gray-400">Optional command run in the isolated checkout before staging or automatic application. Verification requires Linux bubblewrap to contain files, network access, and child processes. On macOS and other unsupported systems, a configured check is refused 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 73a2b5898d..6c576760d0 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -35,7 +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`. |+| `autofixVerifyContainment.js` | Containment contract for the autofixer verify command (#12487): Linux bubblewrap argv and seccomp policy that contain a forking test runner, deny network and host sockets, restrict writes to the worktree/scratch and hide credential stores; unsupported platforms refuse verification. Includes 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. |@@ -269,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. `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 without user config, plugins or apps, with every saved bypass and extra writable directory stripped; null for any 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 without user config, plugins or apps, built from fixed arguments so saved options cannot restore host tools; 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.jsindex ac0f581d44..aeb5fb9d6d 100644--- a/server/lib/autofixVerifyContainment.js+++ b/server/lib/autofixVerifyContainment.js@@ -5,23 +5,21 @@* 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:+ * Linux bubblewrap mechanism, with refusal elsewhere, and these bounds:* - no network, including loopback and pathname Unix sockets (PortOS's API,- * a Docker or database socket): Seatbelt denies them, and on Linux a- * network namespace plus a seccomp filter refusing AF_UNIX sockets;+ * a Docker or database socket): a network namespace plus a seccomp filter+ * refusing AF_UNIX sockets and io_uring;* - 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;+ * - a PID namespace so detached descendants cannot survive their supervisor;* - 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 { encodeSeccompProgram, seatbeltPathLiteral } from './codeAnimationContainment.js';+import { encodeSeccompProgram } from './codeAnimationContainment.js';/** Host-user credential stores, relative to the real home directory. */export const AUTOFIX_VERIFY_PROTECTED_HOME_PATHS = Object.freeze([@@ -30,15 +28,9 @@ export const AUTOFIX_VERIFY_PROTECTED_HOME_PATHS = Object.freeze(['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+ * user's credential stores. The worktree is re-allowed by the profile even* when it sits under the data directory.*/export function autofixVerifyProtectedPaths({ dataDir, realHome }) {@@ -57,30 +49,16 @@ export function autofixVerifyEnv({ scratch, path }) {};}-/** 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)}))`;-}-/*** Linux seccomp program for the verify command: `socket(AF_UNIX, …)` fails* with EPERM, so a host pathname socket visible through the read-only root- * cannot be connected to. `socketpair` (child-process stdio) stays allowed.+ * cannot be connected to. io_uring is refused too: its socket operations bypass+ * the socket syscall. Only stream `socketpair` (child-process stdio) is allowed:+ * datagram endpoints can reconnect/send to a host pathname socket.* Unknown ABIs (including x32) are killed rather than bypassing the check.*/export function autofixVerifySeccompFilter(arch) {- const abi = { x64: { audit: 0xc000003e, socket: 41 }, arm64: { audit: 0xc00000b7, socket: 198 } }[arch];+ const abi = { x64: { audit: 0xc000003e, socket: 41, socketpair: 53 }, arm64: { audit: 0xc00000b7, socket: 198, socketpair: 199 } }[arch];if (!abi) throw new Error('Autofix verify seccomp supports only x64 and arm64.');const ALLOW = 0x7fff0000, KILL = 0x80000000, EPERM = 0x00050001, AF_UNIX = 1;return encodeSeccompProgram([@@ -90,6 +68,16 @@ export function autofixVerifySeccompFilter(arch) {[0x20, 0, 0, 0], // seccomp_data.nr[0x35, 0, 1, 0x40000000], // x32/invalid syscall range[0x06, 0, 0, KILL],+ ...[425, 426, 427].flatMap(nr => [ // io_uring_setup/enter/register, both ABIs+ [0x15, 0, 1, nr],+ [0x06, 0, 0, EPERM],+ ]),+ [0x15, 0, 5, abi.socketpair],+ [0x20, 0, 0, 24], // socketpair type, args[1] low word+ [0x54, 0, 0, 0xf], // strip SOCK_CLOEXEC/SOCK_NONBLOCK+ [0x15, 1, 0, 1], // SOCK_STREAM only+ [0x06, 0, 0, EPERM],+ [0x06, 0, 0, ALLOW],[0x15, 0, 3, abi.socket],[0x20, 0, 0, 16], // socket domain, args[0] low word[0x15, 0, 1, AF_UNIX],diff --git a/server/lib/codeAnimationContainment.js b/server/lib/codeAnimationContainment.jsindex 92d1c20d3e..71de584f6e 100644--- a/server/lib/codeAnimationContainment.js+++ b/server/lib/codeAnimationContainment.js@@ -63,7 +63,7 @@ export function codeAnimationContainmentMechanism(platform, seatbeltAvailable, b}/** SBPL string literal for a path; refuses anything that could close the literal or the form. */-export const seatbeltPathLiteral = (path) => {+const sbplPath = (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 ${seatbeltPathLiteral(executable)}))+(allow process-exec (literal ${sbplPath(executable)}))(allow sysctl-read)-(allow file-read-metadata (literal "/") ${metadata.map((path) => `(literal ${seatbeltPathLiteral(path)})`).join(' ')})+(allow file-read-metadata (literal "/") ${metadata.map((path) => `(literal ${sbplPath(path)})`).join(' ')})(allow file-read* (literal "/") (literal "/dev/null") (literal "/dev/zero") (literal "/dev/random") (literal "/dev/urandom")- ${readRoots.map((path) => `(subpath ${seatbeltPathLiteral(path)})`).join(' ')})-(allow file-write* (literal "/dev/null") ${writable.map((path) => `(subpath ${seatbeltPathLiteral(path)})`).join(' ')})`;+ ${readRoots.map((path) => `(subpath ${sbplPath(path)})`).join(' ')})+(allow file-write* (literal "/dev/null") ${writable.map((path) => `(subpath ${sbplPath(path)})`).join(' ')})`;}/**diff --git a/server/lib/codeAnimationContainment.test.js b/server/lib/codeAnimationContainment.test.jsindex ec9be6fd2c..6c260ad3b9 100644--- a/server/lib/codeAnimationContainment.test.js+++ b/server/lib/codeAnimationContainment.test.js@@ -1,16 +1,18 @@import { describe, expect, it } from 'vitest';import { codeAnimationBubblewrapArgs, codeAnimationSeccompFilter } from './codeAnimationContainment.js';+import { autofixVerifySeccompFilter } from './autofixVerifyContainment.js';// Interpret the small classic-BPF instruction set this security filter uses.// This catches ABI bypasses and jump/offset mistakes even on non-Linux hosts.-const verdict = (filter, { arch, nr, flags = 0 }) => {- const data = new Map([[0, nr], [4, arch], [16, flags]]);+const verdict = (filter, { arch, nr, flags = 0, type = 0 }) => {+ const data = new Map([[0, nr], [4, arch], [16, flags], [24, type]]);let accumulator = 0;for (let pc = 0; pc < filter.length / 8; pc += 1) {const offset = pc * 8;const code = filter.readUInt16LE(offset);const value = filter.readUInt32LE(offset + 4);if (code === 0x20) accumulator = data.get(value) ?? 0;+ else if (code === 0x54) accumulator &= value;else if (code === 0x06) return value;else {const match = code === 0x15 ? accumulator === value@@ -23,6 +25,22 @@ const verdict = (filter, { arch, nr, flags = 0 }) => {};describe('Linux worker containment policy', () => {+ it.each([+ ['x64', 0xc000003e, 41, 53],+ ['arm64', 0xc00000b7, 198, 199],+ ])('blocks direct and io_uring Unix sockets in autofix verification on %s', (name, arch, socket, socketpair) => {+ const filter = autofixVerifySeccompFilter(name);+ const run = (nr, flags = 0, type = 0) => verdict(filter, { arch, nr, flags, type });+ expect(run(socket, 1)).toBe(0x00050001);+ for (const nr of [425, 426, 427]) expect(run(nr)).toBe(0x00050001);+ expect(run(socketpair, 1, 1)).toBe(0x7fff0000);+ expect(run(socketpair, 1, 1 | 0x80000 | 0x800)).toBe(0x7fff0000);+ for (const type of [2, 5, 2 | 0x80000]) expect(run(socketpair, 1, type)).toBe(0x00050001);+ expect(run(1)).toBe(0x7fff0000);+ expect(run(0x40000000)).toBe(0x80000000);+ expect(verdict(filter, { arch: 0x40000003, nr: 102 })).toBe(0x80000000);+ });+it.each([['x64', 0xc000003e, 56, [57, 58, 41, 272, 308]],['arm64', 0xc00000b7, 220, [198, 97, 268]],diff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex 25b894d7f1..d2ce628903 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -733,6 +733,7 @@ export const CODEX_WORKSPACE_NETWORK_KEY = 'sandbox_workspace_write.network_acceexport const CODEX_WORKSPACE_WRITABLE_ROOTS_KEY = 'sandbox_workspace_write.writable_roots';export const CODEX_PLUGINS_FEATURE_KEY = 'features.plugins';export const CODEX_APPS_FEATURE_KEY = 'features.apps';+export const CODEX_HOOKS_FEATURE_KEY = 'features.hooks';/*** Give a Codex swarm enough session threads for its root orchestrator plus@@ -816,6 +817,7 @@ export const PORTOS_CLI_CONFIG_KEYS = Object.freeze([CODEX_WORKSPACE_WRITABLE_ROOTS_KEY,CODEX_PLUGINS_FEATURE_KEY,CODEX_APPS_FEATURE_KEY,+ CODEX_HOOKS_FEATURE_KEY,]);/**diff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.jsindex f0300bf70f..fa788541be 100644--- a/server/lib/providerModels.test.js+++ b/server/lib/providerModels.test.js@@ -46,6 +46,7 @@ import {CODEX_WORKSPACE_WRITABLE_ROOTS_KEY,CODEX_PLUGINS_FEATURE_KEY,CODEX_APPS_FEATURE_KEY,+ CODEX_HOOKS_FEATURE_KEY,isPortosSuppliedConfigKey,hasCodexUpdateCheckConfig,buildCodexStartupArgs,@@ -756,6 +757,7 @@ describe('providerModels', () => {CODEX_WORKSPACE_WRITABLE_ROOTS_KEY,CODEX_PLUGINS_FEATURE_KEY,CODEX_APPS_FEATURE_KEY,+ CODEX_HOOKS_FEATURE_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 cfc170eec0..caa7eef4e5 100644--- a/server/lib/providerVendors.js+++ b/server/lib/providerVendors.js@@ -83,6 +83,7 @@ import {CODEX_WORKSPACE_WRITABLE_ROOTS_KEY,CODEX_PLUGINS_FEATURE_KEY,CODEX_APPS_FEATURE_KEY,+ CODEX_HOOKS_FEATURE_KEY,} from './providerModels.js';import {isCodexCommand,@@ -1150,9 +1151,11 @@ export function toolFreeOneShotArgs(provider, args = []) {// 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 = [+ '--restricted', '--safe-mode','--permission-mode', 'acceptEdits',+ '--tools', 'Read,Edit,Write,Grep,Glob','--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}',- '--setting-sources', 'user',+ '--no-chrome', '--disable-slash-commands','--disallowedTools', 'Bash', 'WebFetch', 'WebSearch',];// Codex's OS sandbox confines its shell commands to the working directory@@ -1161,16 +1164,18 @@ const CLAUDE_REPAIR_ARGS = [// so the user's config.toml is not loaded at all (auth still is) and the// plugin/app surfaces are disabled.const CODEX_REPAIR_ARGS = [- '--sandbox', 'workspace-write', '--ignore-user-config',+ '--sandbox', 'workspace-write', '--ignore-user-config', '--ignore-rules','-c', `${CODEX_WORKSPACE_NETWORK_KEY}=false`, '-c', `${CODEX_WORKSPACE_WRITABLE_ROOTS_KEY}=[]`,'-c', `${CODEX_PLUGINS_FEATURE_KEY}=false`, '-c', `${CODEX_APPS_FEATURE_KEY}=false`,+ '-c', `${CODEX_HOOKS_FEATURE_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.+ * mode. Build from the fixed recipe: arbitrary saved options can restore MCP,+ * plugins, hooks or writable roots even after a sandbox flag is overridden.+ * Model and effort still come from the provider's fields in the vendor builder.* The result replaces `provider.args`; the vendor builder adds `-p -` / `-`.** @param {object} provider - provider record (command, args)@@ -1179,20 +1184,11 @@ const CODEX_REPAIR_ARGS = [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', '--add-dir'], { variadic: true }),- ['--permission-mode', '--setting-sources'],- ).filter((arg) => arg !== '--strict-mcp-config');- return { mode: 'claude-disallowed-tools', args: [...cleared, ...CLAUDE_REPAIR_ARGS] };+ return { mode: 'claude-disallowed-tools', args: [...CLAUDE_REPAIR_ARGS] };}if (isCodexCommand(command)) {- // --add-dir widens the writable roots; --cd moves the workspace root itself.- const cleared = dropOptions(saved, ['--sandbox', '-s', '--add-dir', '--cd', '-C']);- // 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 { mode: 'codex-workspace-write', args: ['exec', ...CODEX_REPAIR_ARGS] };}return null;}