Skip to content

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

fix: enforce security scanner execution and preserve observed outcomes (#11354)

[._.]/83684b4e1399
diff --git a/client/src/components/cos/AgentResultLine.jsx b/client/src/components/cos/AgentResultLine.jsx
index 05111b0c4d..66300f2a5d 100644
--- a/client/src/components/cos/AgentResultLine.jsx
+++ b/client/src/components/cos/AgentResultLine.jsx
@@ -43,16 +43,24 @@ export default function AgentResultLine({ agent, className = '' }) {
)}
</span>
{interruption && <div>Execution interrupted: {interruption.category === 'content-refusal' ? 'provider safety refusal; automatic retry stopped' : interruption.category}</div>}
- {scanner && <div className="mt-1 break-words">
- <div>Security scanner (agent reported): {scanner.status}</div>
- <div>Model: {scanner.model ?? 'unknown'} · Effort: {scanner.effort ?? 'unknown'} · Auth: {scanner.auth}</div>
- <div>Estimated cost: {scanner.estimatedCostUsd == null ? 'unknown' : formatUsd(scanner.estimatedCostUsd, { maximumFractionDigits: 4 })} · Budget: {scanner.maxCostUsd == null ? 'unknown' : formatUsd(scanner.maxCostUsd, { maximumFractionDigits: 4 })} (API-equivalent USD)</div>
- <div>Time limit: {scanner.timeLimitSeconds == null ? 'unknown' : `${formatCount(scanner.timeLimitSeconds)}s`} · Exit: {scanner.exitCode ?? 'unknown'}</div>
- <div>Artifacts — findings: {scanner.artifacts?.findings == null ? 'unknown' : scanner.artifacts.findings ? 'saved' : 'absent'}; coverage: {scanner.artifacts?.coverage == null ? 'unknown' : scanner.artifacts.coverage ? 'saved' : 'absent'}</div>
- </div>}
+ <SecurityScanEvidence scanner={scanner} control={agent.metadata?.securityScanControl} />
{!handoff && assessment && <div>{assessment.status === 'recorded' ? 'Assessment saved' : assessment.status === 'persistence-failed' ? 'Assessment could not be saved' : assessment.status === 'not-attempted' ? 'Assessment not attempted' : 'Assessment not verified as saved'}</div>}
{!handoff && validationFailed && <div>Delivery validation failed</div>}
{!handoff && publicationIncomplete && <div>{publication.status === 'running' ? 'Publication checks running' : 'Publication blocked; worktree preserved'}</div>}
</div>
);
}
+
+export function SecurityScanEvidence({ scanner, control }) {
+ if (!scanner) return null;
+ return (
+ <div className="mt-1 break-words">
+ <div>Security scanner ({scanner.source === 'runner' ? 'runner observed' : 'agent reported'}): {control?.status || scanner.status}{control && ' (runner connection lost)'}</div>
+ <div>Model: {scanner.model ?? 'unknown'} · Effort: {scanner.effort ?? 'unknown'} · Auth: {scanner.auth}</div>
+ <div>Estimated cost: {scanner.estimatedCostUsd == null ? 'unknown' : formatUsd(scanner.estimatedCostUsd, { maximumFractionDigits: 4 })} · Budget: {scanner.maxCostUsd == null ? 'unknown' : formatUsd(scanner.maxCostUsd, { maximumFractionDigits: 4 })} (API-equivalent USD)</div>
+ <div>Time limit: {scanner.timeLimitSeconds == null ? 'unknown' : `${formatCount(scanner.timeLimitSeconds)}s`} · Exit: {scanner.exitCode ?? 'unknown'}</div>
+ <div>Artifacts — findings: {scanner.artifacts?.findings == null ? 'unknown' : scanner.artifacts.findings ? 'saved' : 'absent'}; coverage: {scanner.artifacts?.coverage == null ? 'unknown' : scanner.artifacts.coverage ? 'saved' : 'absent'}</div>
+ {(control?.cleanup || scanner.cleanup) && <div>Process cleanup: {control?.cleanup || scanner.cleanup}</div>}
+ </div>
+ );
+}
diff --git a/client/src/components/cos/AgentResultLine.test.jsx b/client/src/components/cos/AgentResultLine.test.jsx
index 486baa3773..048bcb6848 100644
--- a/client/src/components/cos/AgentResultLine.test.jsx
+++ b/client/src/components/cos/AgentResultLine.test.jsx
@@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react';
import { expect, it } from 'vitest';
-import AgentResultLine from './AgentResultLine';
+import AgentResultLine, { SecurityScanEvidence } from './AgentResultLine';
it('separates clean execution, assessment persistence and delivery validation', () => {
const agent = { result: { success: true, validationPassed: false, auditAssessment: { status: 'persistence-failed' } } };
@@ -49,3 +49,16 @@ it('retains refusal and scanner interruption evidence alongside successful deliv
expect(screen.getByText(/Exit: unknown/)).toBeInTheDocument();
expect(screen.getByText(/findings: saved; coverage: unknown/)).toBeInTheDocument();
});
+
+it('shows runner observations during execution without requiring an agent completion summary', () => {
+ render(<SecurityScanEvidence scanner={{ source: 'runner', status: 'interrupted', cleanup: 'unconfirmed', model: 'example-model', effort: 'medium', auth: 'chatgpt' }} />);
+ expect(screen.getByText('Security scanner (runner observed): interrupted')).toBeInTheDocument();
+ expect(screen.getByText('Process cleanup: unconfirmed')).toBeInTheDocument();
+ expect(screen.queryByText('Completed successfully')).not.toBeInTheDocument();
+});
+
+it('distinguishes connection loss from the last trusted runner observation', () => {
+ render(<SecurityScanEvidence scanner={{ source: 'runner', status: 'running', auth: 'chatgpt' }} control={{ status: 'interrupted', cleanup: 'unconfirmed' }} />);
+ expect(screen.getByText(/interrupted \(runner connection lost\)/)).toBeInTheDocument();
+ expect(screen.getByText('Process cleanup: unconfirmed')).toBeInTheDocument();
+});
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index 574d3231b8..891249af66 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -32,7 +32,7 @@ import toast from '../../ui/Toast';
import { copyToClipboard } from '../../../lib/clipboard';
import { estimateCosDuration } from '../../../lib/cosDurationEstimate';
import { isAgentFeedbackUpdateTarget, isSystemAgent as isSystemAgentRecord } from '../../../lib/cosAgentFeedback';
-import AgentResultLine from '../AgentResultLine';
+import AgentResultLine, { SecurityScanEvidence } from '../AgentResultLine';
import AuditSourceEvidence from '../AuditSourceEvidence';
import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';
import { formatBytes, formatCount, formatDurationMs, formatDateTime, formatTimeOfDay, shortClaudeModelName } from '../../../utils/formatters';
@@ -1127,6 +1127,8 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
<AuditSourceEvidence evidence={agent.metadata?.auditSourceEvidence} />
+ {!agent.result && <SecurityScanEvidence scanner={agent.metadata?.securityScan} control={agent.metadata?.securityScanControl} />}
+
{agent.result && (
<div className="flex items-center gap-4 flex-wrap">
<AgentResultLine agent={agent} />
diff --git a/docs/README.md b/docs/README.md
index bba1b55a13..279175df6d 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -37,6 +37,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
| [features/music-renderer-benchmarks.md](./features/music-renderer-benchmarks.md) | Technical and full-length listening evidence for local music renderer profiles |
| [CONTRIBUTING.md](./CONTRIBUTING.md) | Dev setup (PostgreSQL required), code conventions |
| [CLI_REVIEW_OUTCOMES.md](./CLI_REVIEW_OUTCOMES.md) | Reviewer tiers, provider pins and bounded, authenticated CLI health reports |
+| [SECURITY_SCANNER_RUNTIME.md](./SECURITY_SCANNER_RUNTIME.md) | Runner-owned Codex security scans, pinned execution, process cleanup and observed evidence |
| [UX_DESIGN_GUIDE.md](./UX_DESIGN_GUIDE.md) | Admin workspace design specification: icon navigation, responsive layouts, disclosure, visual hierarchy, and redesign acceptance |
| [UX_DESIGN_AUDIT.md](./UX_DESIGN_AUDIT.md) | Representative UX audit and Jev/Performance pilot content maps |
| [GITHUB_ACTIONS.md](./GITHUB_ACTIONS.md) | CI and release workflows |
diff --git a/docs/SECURITY_SCANNER_RUNTIME.md b/docs/SECURITY_SCANNER_RUNTIME.md
new file mode 100644
index 0000000000..be39172f98
--- /dev/null
+++ b/docs/SECURITY_SCANNER_RUNTIME.md
@@ -0,0 +1,44 @@
+# Codex security scanner runtime
+
+Codex security audits request one scanner attempt through the authenticated
+`POST /api/cos/agents/:id/security-scan` host-control endpoint. The request contains
+the actual audit prompt, workspace-relative source paths, and optional knowledge
+base paths. The runner resolves paths inside the assigned workspace and launches
+an already installed `@openai/codex-security` CLI. It never installs a package or
+selects another provider after a failure.
+
+The immutable dispatch grant uses the effective outer Codex command's model and
+effort, including saved flags and supported-effort clamping. Missing or conflicting
+pins make the scanner unavailable. The bounded workflow retains explicit ChatGPT
+authentication, a $2 API-equivalent estimated-cost ceiling, and a 180-second scan
+deadline. API-key environment variables are not passed to this subprocess. These
+estimates do not establish billing charges. A cybersecurity-policy refusal stops
+the scanner and outer request without automatic continuation, retry or fallback.
+
+The runner owns a separate POSIX process group. A small IPC supervisor waits until
+its ownership receipt is durable before launching the scanner. Losing the runner
+connection kills that group. Outer completion, termination, pause and shutdown
+settle the scanner first; cleanup escalates independently of the outer agent map.
+After restart, recovery verifies the group's start identity or each surviving
+worker's inherited ownership marker before signaling it. Ambiguous ownership is
+left untouched and shown as cleanup unconfirmed. Windows reports this scanner
+runtime unavailable until equivalent process ownership is supported.
+
+Runner observations are emitted while the audit is running and saved in ordinary
+agent metadata, independently of the completion sentinel or quality assessment.
+The UI labels them **runner observed**; older `SCANNER_STATUS_JSON` records remain
+**agent reported**. Ordered runner receipts cannot be replaced by older socket
+snapshots or agent claims. A lost runner connection is recorded separately from
+the last runner revision, so a later observed refusal or exit can still arrive.
+A successful assessment/delivery never changes an
+interrupted scan into a completed one. Artifact presence describes saved files,
+not a guarantee of findings quality or full coverage.
+
+Two additive per-run files, `security-scan.json` and `security-scan-process.json`,
+live in the existing agent directory and move with its archive. The first is a
+bounded recovery receipt, the second a private process ownership journal. Old
+agent records need no transformation and remain readable. Prompts, scanner state,
+full logs and result files stay in a private temporary directory; the HTTP response
+gives that directory to the owning audit. These files are machine-local runtime
+evidence and are not added to federation payloads. No live scan is necessary for
+the synthetic process, dispatch, authorization and completion regression suites.
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 0918fb7d41..d941eed1c8 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -1,5 +1,7 @@
import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { persistRunnerCompletion } from './completion.js';
+import { createSecurityScanManager } from './securityScan.js';
+import { securityScanRequestSchema } from '../lib/securityScanEvidence.js';
import { maintenance } from '../lib/maintenanceAdmission.js';
import '../services/databaseBootFence.js';
/**
@@ -132,6 +134,35 @@ io.use((socket, next) => next(lifecycle.isStopping() ? new Error('Runner is shut
const persistCompletion = (agentId, output, metadata) => persistRunnerCompletion(AGENTS_DIR, agentId, output, metadata);
+const securityScans = createSecurityScanManager({
+ agentsDir: AGENTS_DIR,
+ getAgent: id => activeAgents.get(id),
+ trackWork: work => lifecycle.trackWork(work),
+ emitEvidence: async (agentId, evidence) => {
+ const agent = activeAgents.get(agentId);
+ if (agent) agent.securityScan = evidence;
+ emitToServer('agent:security-scan', { agentId, evidence });
+ },
+});
+
+app.post('/agents/:agentId/security-scan', async (req, res) => {
+ const parsed = securityScanRequestSchema.safeParse(req.body ?? {});
+ if (!parsed.success) return res.status(400).json({ error: bodyErrorMessage(parsed.error) });
+ if (lifecycle.rejectSpawn(res)) return;
+ try {
+ assertDatabaseAdmission();
+ res.json(await securityScans.start(req.params.agentId, parsed.data));
+ } catch (err) { res.status(err.status || 500).json({ error: err.message }); }
+});
+app.post('/agents/:agentId/security-scan/stop', async (req, res) => {
+ try { res.json({ evidence: await securityScans.stop(req.params.agentId) }); }
+ catch (err) { res.status(err.status || 500).json({ error: err.message }); }
+});
+app.get('/agents/:agentId/security-scan', async (req, res) => {
+ try { res.json({ evidence: await securityScans.read(req.params.agentId) }); }
+ catch (err) { res.status(err.status || 500).json({ error: err.message }); }
+});
+
/**
* Emit event to connected portos-server instances
*/
@@ -183,6 +214,7 @@ app.get('/agents', async (req, res) => {
sessionId: agent.sessionId || null,
command: agent.command || null,
workspacePath: agent.workspacePath || null,
+ securityScan: agent.securityScan || null,
});
}
res.json(agents);
@@ -272,6 +304,7 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {
// Use the same safe wrapper for the actual PTY launch. In particular, this
// preserves the shared escaping contract for paths/args passed to cmd.exe.
const { command: ptyCommand, args: ptyArgs } = prepareCliSpawn(executable, args, childEnv);
+ await securityScans.register(agentId, body.data.securityScanGrant);
// Both checks above cleared the executable, so a throw here is about the PTY
// layer or the workspace — not the command. node-pty collapses those into one
// opaque `posix_spawn failed: No such file or directory`, which read as a
@@ -316,6 +349,8 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {
// node-pty reports pid 0 for ConPTY on Windows, so a pid probe is not a
// liveness signal. onExit is the runner's authority; GET /agents reads this.
exited: false,
+ securityScan: await securityScans.read(agentId),
+ stopSecurityScan: () => securityScans.stop(agentId).catch(err => lifecycle.reportFailure(err)),
};
activeAgents.set(agentId, agent);
const sentinelAccess = createAgentSentinelAccess({
@@ -403,6 +438,7 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {
sessionId,
workspacePath: cwd,
doneSentinelPath,
+ securityScanGrant: body.data.securityScanGrant,
};
state.stats.spawned++;
});
@@ -528,6 +564,7 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
}
// Spawn the CLI process
+ await securityScans.register(agentId, body.data.securityScanGrant);
const claudeProcess = spawn(spawnCommand, finalSpawnArgs, {
cwd,
shell: false,
@@ -558,7 +595,9 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
// A stream-json stdout is NDJSON with no raw ESC byte, so it skips the scan.
stripStdoutAnsi: isStreamJson ? (text) => text : createStreamingAnsiStripper(),
stripStderrAnsi: createStreamingAnsiStripper(),
- workspacePath: cwd
+ workspacePath: cwd,
+ securityScan: await securityScans.read(agentId),
+ stopSecurityScan: () => securityScans.stop(agentId).catch(err => lifecycle.reportFailure(err)),
};
activeAgents.set(agentId, agent);
@@ -634,6 +673,7 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
cleanupPromptFile();
try {
agent.exited = true;
+ await agent.stopSecurityScan?.();
// Cancel any pending SIGKILL timer — process already exited.
if (agent?.killTimer) {
clearTimeout(agent.killTimer);
@@ -680,6 +720,7 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
exitCode: code,
success: code === 0,
duration,
+ securityScan: agent.securityScan,
});
if (paused) {
activeAgents.delete(agentId);
@@ -693,7 +734,8 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
exitCode: code,
success: code === 0,
duration,
- outputLength: output.length
+ outputLength: output.length,
+ securityScan: agent.securityScan,
});
// Update state — serialize with the spawn write path via withState.
@@ -717,6 +759,7 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
await withState((state) => {
state.agents[agentId] = {
pid: claudeProcess.pid,
+ securityScanGrant: body.data.securityScanGrant,
taskId,
startedAt: Date.now()
};
@@ -733,7 +776,7 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
/**
* Terminate an agent (graceful with SIGTERM, then SIGKILL after timeout)
*/
-app.post('/terminate/:agentId', (req, res) => {
+app.post('/terminate/:agentId', async (req, res) => {
const { agentId } = req.params;
const agent = activeAgents.get(agentId);
@@ -742,7 +785,7 @@ app.post('/terminate/:agentId', (req, res) => {
}
console.log(`🔪 Terminating agent ${agentId}`);
-
+ await agent.stopSecurityScan?.();
killProcessTree(agent.process, 'SIGTERM');
armForceKill(agentId, agent);
@@ -761,7 +804,7 @@ app.post('/kill/:agentId', async (req, res) => {
}
console.log(`💀 Force killing agent ${agentId} (PID: ${agent.pid})`);
-
+ await agent.stopSecurityScan?.();
killProcessTree(agent.process, 'SIGKILL');
// Clean up immediately
@@ -797,7 +840,7 @@ app.post('/pause/:agentId', async (req, res) => {
agent.paused = true;
agent.pausedAt = pausedAt;
agent.pauseReason = reason;
-
+ await agent.stopSecurityScan?.();
killProcessTree(agent.process, 'SIGTERM');
// NOT armForceKill: a pause keeps its map entry (the agent is meant to be
// resumable) and only escalates while the pause is still in force.
@@ -823,6 +866,7 @@ app.post('/terminate-all', async (req, res) => {
for (const agentId of agentIds) {
const agent = activeAgents.get(agentId);
if (agent) {
+ await agent.stopSecurityScan?.();
killProcessTree(agent.process, 'SIGTERM');
armForceKill(agentId, agent);
}
@@ -915,13 +959,14 @@ io.on('connection', (socket) => {
}
});
- socket.on('tui:kill', ({ sessionId, signal = 'SIGTERM' }) => {
+ socket.on('tui:kill', async ({ sessionId, signal = 'SIGTERM' }) => {
try {
if (!TUI_SIGNALS.has(signal)) return;
const entry = [...activeAgents.entries()].find(([, candidate]) => candidate.sessionId === sessionId);
if (!entry) return;
const [agentId, agent] = entry;
if (agent.kind !== 'tui') return;
+ await agent.stopSecurityScan?.();
killProcessTree(agent.process, signal);
// `dropState` only for an agent the server has already FINALIZED. A pause
// also relays a kill (the server stops a TUI session through this socket),
@@ -949,6 +994,7 @@ async function cleanupOrphanedAgents() {
// write in the same queue so an old snapshot cannot resurrect completed runs.
await withState(async (state) => {
for (const [agentId, agentInfo] of Object.entries(state.agents)) {
+ if (agentInfo.securityScanGrant) await securityScans.recover(agentId);
const isRunning = await checkProcessRunning(agentInfo.pid);
if (!isRunning) {
orphaned.push({ agentId, taskId: agentInfo.taskId });
diff --git a/server/cos-runner/requestSchemas.js b/server/cos-runner/requestSchemas.js
index 46ca4411b2..a0592f8b9f 100644
--- a/server/cos-runner/requestSchemas.js
+++ b/server/cos-runner/requestSchemas.js
@@ -15,6 +15,7 @@
*/
import { z } from 'zod';
+import { securityScanGrantSchema } from '../lib/securityScanEvidence.js';
const optionalString = z.string().nullish();
// Free-form maps composed server-side (provider env, auth descriptor); the
@@ -23,6 +24,7 @@ const optionalString = z.string().nullish();
const looseRecord = z.record(z.string(), z.unknown()).nullish();
export const spawnTuiBodySchema = z.object({
+ securityScanGrant: securityScanGrantSchema.nullish(),
agentId: optionalString,
maintenanceParentId: z.string().uuid().nullish(),
taskId: optionalString,
@@ -38,6 +40,7 @@ export const spawnTuiBodySchema = z.object({
});
export const spawnBodySchema = z.object({
+ securityScanGrant: securityScanGrantSchema.nullish(),
agentId: optionalString,
maintenanceParentId: z.string().uuid().nullish(),
taskId: optionalString,
diff --git a/server/cos-runner/securityScan.js b/server/cos-runner/securityScan.js
new file mode 100644
index 0000000000..b5dc5b1e37
--- /dev/null
+++ b/server/cos-runner/securityScan.js
@@ -0,0 +1,276 @@
+import { mkdtemp, readFile, readdir, realpath, stat, chmod } from 'fs/promises';
+import { join, relative, isAbsolute, resolve } from 'path';
+import { homedir, tmpdir } from 'os';
+import { randomUUID } from 'crypto';
+import { fileURLToPath } from 'url';
+import { spawn } from '../lib/childProcess.js';
+import { atomicWrite, ensureDir, writeFileGuarded } from '../lib/fileCore.js';
+import { killProcessTree } from '../lib/bufferedSpawn.js';
+import { createContentRefusalDetector, isContentRefusalError } from '../lib/aiToolkit/errorDetection.js';
+import { initialSecurityScanEvidence, securityScanGrantSchema, securityScanRequestSchema } from '../lib/securityScanEvidence.js';
+import { armForceKill } from './forceKill.js';
+import { cleanupSecurityScanGroup } from './securityScanRecovery.js';
+
+const CHILD = fileURLToPath(new URL('./securityScanChild.js', import.meta.url));
+const AGENT_ID = /^[a-zA-Z0-9_-]{1,200}$/;
+const ENV_KEYS = new Set(['PATH', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'TMPDIR', 'LANG', 'LC_ALL', 'CODEX_HOME']);
+const failure = (message, status = 409) => Object.assign(new Error(message), { status });
+
+// Read installed package metadata only. Never run npx, download a package, or
+// consult the registry while deciding whether a scan can be started.
+async function resolveInstalledSecurityScanner({ home = homedir(), root = process.cwd() } = {}) {
+ const candidates = [join(root, 'node_modules/@openai/codex-security')];
+ const cache = join(home, '.npm/_npx');
+ for (const name of (await readdir(cache).catch(() => [])).sort()) {
+ if (/^[a-f0-9]+$/.test(name)) candidates.push(join(cache, name, 'node_modules/@openai/codex-security'));
+ }
+ for (const directory of candidates) {
+ const pkg = await readFile(join(directory, 'package.json'), 'utf8').then(JSON.parse).catch(() => null);
+ const bin = pkg?.bin?.['codex-security'];
+ if (pkg?.name !== '@openai/codex-security' || typeof bin !== 'string') continue;
+ const path = resolve(directory, bin);
+ if (relative(directory, path).startsWith('..') || !(await stat(path).catch(() => null))?.isFile()) continue;
+ return { command: process.execPath, args: [path], version: pkg.version };
+ }
+ return null;
+}
+
+async function scopePaths(cwd, values) {
+ const root = await realpath(cwd);
+ return Promise.all(values.map(async value => {
+ const path = await realpath(resolve(root, value));
+ const rel = relative(root, path);
+ if (rel === '..' || rel.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) || isAbsolute(rel)) {
+ throw failure('Scanner context must stay inside the agent workspace', 400);
+ }
+ return path;
+ }));
+}
+
+/** One scanner attempt, owned by the runner rather than by an agent shell. */
+export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, trackWork = fn => fn(),
+ resolveCli = resolveInstalledSecurityScanner, spawnProcess = spawn, kill = killProcessTree,
+ environment = process.env, tempRoot = tmpdir(), graceMs = 5000, cleanupGroup = cleanupSecurityScanGroup } = {}) {
+ const entries = new Map();
+ const terminateRefusedOuter = id => {
+ const agent = getAgent(id);
+ if (!agent || agent.exited || agent.scannerRefused) return;
+ agent.scannerRefused = true;
+ // Independent ownership survives removal from the public outer-agent map.
+ const owned = new Map([[id, agent]]);
+ armForceKill(owned, id, agent, { graceMs });
+ kill(agent.process, 'SIGTERM');
+ };
+ const evidencePath = id => {
+ if (!AGENT_ID.test(id)) throw failure('Invalid agent id', 400);
+ return join(agentsDir, id, 'security-scan.json');
+ };
+ const persist = async (id, entry) => {
+ // Queue snapshots, not mutable references. The running snapshot must be
+ // durable before spawn; the final one must precede outer completion.
+ entry.evidence.sequence = (entry.evidence.sequence || 0) + 1;
+ const snapshot = structuredClone(entry.evidence);
+ entry.writes = (entry.writes || Promise.resolve()).then(async () => {
+ // Live observations remain available even if the local receipt write fails.
+ await emitEvidence?.(id, snapshot);
+ await atomicWrite(evidencePath(id), snapshot);
+ });
+ return entry.writes;
+ };
+ const read = async id => {
+ if (entries.has(id)) return entries.get(id).evidence;
+ const saved = await readFile(evidencePath(id), 'utf8').then(JSON.parse).catch(err => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ // A prior runner's in-flight attempt cannot be resumed or inferred complete.
+ return saved;
+ };
+ const register = async (id, grant) => {
+ if (!grant) return;
+ const parsed = securityScanGrantSchema.parse(grant);
+ if (await read(id)) throw failure('Scanner grant already exists for this agent');
+ const entry = { grant: Object.freeze(parsed), evidence: initialSecurityScanEvidence(parsed), attempted: false };
+ entries.set(id, entry);
+ await persist(id, entry);
+ };
+ const stop = async (id, reason = 'interrupted') => {
+ const entry = entries.get(id);
+ if (!entry) {
+ const evidence = await read(id);
+ if (evidence?.status !== 'running') return evidence;
+ const owner = await readFile(join(agentsDir, id, 'security-scan-process.json'), 'utf8').then(JSON.parse).catch(() => null);
+ const confirmed = await cleanupGroup(owner).catch(() => false);
+ const recovered = { evidence: { ...evidence, status: 'interrupted', exitCode: null, cleanup: confirmed ? 'confirmed' : 'unconfirmed' } };
+ await persist(id, recovered);
+ return recovered.evidence;
+ }
+ // Latch even during async scope/installation checks: a Stop must win over
+ // the subsequent spawn, and must never turn an already completed scan red.
+ if (!entry.terminal) entry.stopReason ||= reason;
+ entry.cancel?.();
+ await entry.promise;
+ return entry.evidence;
+ };
+ const start = (id, input) => {
+ const request = securityScanRequestSchema.parse(input);
+ const agent = getAgent(id);
+ const entry = entries.get(id);
+ if (!agent || agent.exited || agent.paused || !entry) throw failure('No active runner-owned security scan grant');
+ // Synchronous reservation before any I/O. Replays share the same promise;
+ // request loss and duplicate POSTs never authorize another provider call.
+ if (entry.attempted) return entry.promise;
+ if (entry.stopReason) throw failure('The scanner grant has been stopped');
+ entry.attempted = true;
+ entry.promise = trackWork(async () => {
+ let directory;
+ let forceTimer;
+ let deadline;
+ let drainTimer;
+ try {
+ const [paths, knowledgeBase, cli] = await Promise.all([
+ scopePaths(agent.workspacePath, request.paths), scopePaths(agent.workspacePath, request.knowledgeBase), resolveCli(),
+ ]);
+ if (entry.stopReason) { entry.evidence.status = entry.stopReason; return { evidence: entry.evidence, artifactDirectory: null }; }
+ if (!cli || !entry.grant.model || !entry.grant.effort || process.platform === 'win32') { entry.evidence.status = 'unavailable'; return { evidence: entry.evidence, artifactDirectory: null }; }
+ directory = await mkdtemp(join(tempRoot, 'portos-security-'));
+ await chmod(directory, 0o700);
+ const outputDir = join(directory, 'results');
+ const promptFile = join(directory, 'prompt.md');
+ await writeFileGuarded(promptFile, request.prompt, { mode: 0o600 });
+ await ensureDir(outputDir);
+ const args = [...cli.args, 'scan', agent.workspacePath, '--mode', 'standard', '--auth', 'chatgpt', '--headless', '--json',
+ '--model', entry.grant.model, '--effort', entry.grant.effort, '--max-cost', String(entry.grant.maxCostUsd),
+ '--output-dir', outputDir, '--scan-prompt-file', promptFile,
+ ...paths.flatMap(path => ['--path', path]), ...knowledgeBase.flatMap(path => ['--knowledge-base', path])];
+ const env = Object.fromEntries(Object.entries(environment).filter(([key]) => ENV_KEYS.has(key)));
+ env.CODEX_SECURITY_STATE_DIR = join(directory, 'state');
+ env.PORTOS_SECURITY_SCAN_OWNER = randomUUID();
+ entry.evidence.status = 'running';
+ entry.evidence.cleanup = 'unconfirmed';
+ await persist(id, entry);
+ if (entry.stopReason) { entry.evidence.status = entry.stopReason; return { evidence: entry.evidence, artifactDirectory: directory }; }
+ const detectRefusal = createContentRefusalDetector();
+ let logTail = '';
+ let logWrites = Promise.resolve();
+ let logError;
+ const logPath = join(directory, 'scan.log');
+ const child = spawnProcess(process.execPath, [CHILD, outputDir], {
+ cwd: agent.workspacePath, env, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
+ });
+ entry.child = child;
+ entry.owner = { pid: child.pid, startedAt: Date.now(), marker: env.PORTOS_SECURITY_SCAN_OWNER, outputDir };
+ // Private ownership receipt allows restart cleanup to verify identity,
+ // including descendants whose group leader exited. Never signal by a
+ // persisted PID alone.
+ let resolveExit;
+ let exitCleanup;
+ const signal = signalName => kill(child, signalName, { processGroup: true });
+ const cancel = () => {
+ if (entry.cancelling) return;
+ entry.cancelling = true;
+ // Independent of the outer agent map and of child.killed. A wrapper
+ // may exit before descendants; the process-group escalation survives.
+ forceTimer = setTimeout(() => {
+ exitCleanup = cleanupGroup(entry.owner).catch(() => false);
+ // Do not wait forever for inherited pipes or a missing close event.
+ exitCleanup.then(() => resolveExit({ code: null, failed: true }));
+ }, graceMs);
+ signal('SIGTERM');
+ };
+ entry.cancel = cancel;
+ const consume = chunk => {
+ const text = String(chunk);
+ logTail = (logTail + text).slice(-65536);
+ // The complete private log is an artifact; only bounded typed fields
+ // are sent to PortOS or kept in the agent card.
+ logWrites = logWrites.then(async () => {
+ const { appendFileGuarded } = await import('../lib/fileCore.js');
+ await appendFileGuarded(logPath, text, { mode: 0o600 });
+ }).catch(err => { logError = err; entry.stopReason ||= 'interrupted'; cancel(); });
+ const envelopes = [...logTail.split('\n'), logTail.slice(Math.max(0, logTail.lastIndexOf('\n{') + 1))];
+ const structuredRefusal = envelopes.some(line => {
+ let event; try { event = JSON.parse(line); } catch { return false; }
+ const error = event.error || (event.type === 'event_msg' && event.payload?.type === 'task_complete' ? event.payload.error : null)
+ || (event.method === 'turn/completed' ? event.params?.turn?.error : null);
+ return error && isContentRefusalError({ message: typeof error === 'string' ? error : JSON.stringify(error) });
+ });
+ if ((detectRefusal(text) || structuredRefusal) && entry.stopReason !== 'refused') {
+ entry.stopReason = 'refused';
+ entry.evidence.status = 'refused';
+ void persist(id, entry).catch(() => console.error(`❌ Scanner refusal receipt could not be saved for ${id}`));
+ terminateRefusedOuter(id);
+ cancel();
+ }
+ };
+ child.stdout.on('data', consume);
+ child.stderr.on('data', consume);
+ const streamsEnded = Promise.all([child.stdout, child.stderr].map(stream =>
+ new Promise(resolve => { stream.once('end', resolve); stream.once('close', resolve); })));
+ const exitPromise = new Promise(resolve => {
+ resolveExit = resolve;
+ child.once('error', () => resolveExit({ code: null, failed: true }));
+ child.once('exit', (code, signal) => {
+ clearTimeout(deadline);
+ exitCleanup = cleanupGroup(entry.owner).catch(() => false);
+ // Exit can precede the last stderr refusal. Drain both streams,
+ // bounded for a descendant holding inherited pipes open.
+ drainTimer = setTimeout(() => resolveExit({ code, signal }), graceMs);
+ Promise.all([streamsEnded, exitCleanup]).then(() => resolveExit({ code, signal }));
+ });
+ child.once('close', (code, signalName) => resolveExit({ code, signal: signalName }));
+ deadline = setTimeout(() => { entry.stopReason ||= 'time-limit'; cancel(); }, entry.grant.timeLimitSeconds * 1000);
+ if (entry.stopReason) cancel();
+ });
+ await atomicWrite(join(agentsDir, id, 'security-scan-process.json'), entry.owner);
+ if (!entry.stopReason) {
+ await new Promise((resolve, reject) => child.send({ command: cli.command, args }, err => err ? reject(err) : resolve()));
+ }
+ const exit = await exitPromise;
+ clearTimeout(deadline);
+ // Retire a still-owned group even on normal wrapper exit. Never leave
+ // a scanner worker consuming quota after its CLI's completion.
+ entry.evidence.cleanup = await (exitCleanup || cleanupGroup(entry.owner).catch(() => false)) ? 'confirmed' : 'unconfirmed';
+ clearTimeout(forceTimer);
+ entry.evidence.exitCode = exit.code ?? (exit.signal === 'SIGTERM' ? 143 : exit.signal === 'SIGKILL' ? 137 : null);
+ entry.evidence.status = entry.stopReason || (exit.code === 0 && !exit.failed && entry.evidence.cleanup === 'confirmed' ? 'completed' : 'failed');
+ const costs = [...logTail.matchAll(/short-context budget baseline:\s*\$([\d.]+)/g)];
+ if (costs.length) entry.evidence.estimatedCostUsd = Number(costs.at(-1)[1]);
+ if (!entry.stopReason && /(?:exceeds?|exceeded).*?(?:max.cost|budget)|budget.*?(?:exceeded|limit reached)/i.test(logTail)) entry.evidence.status = 'budget-limit';
+ const files = await readdir(outputDir).catch(() => null);
+ entry.evidence.artifacts = { findings: files?.includes('findings.json') ?? null, coverage: files?.includes('coverage.json') ?? null };
+ await logWrites;
+ if (logError) throw logError;
+ } catch (err) {
+ if (entry.child) {
+ const confirmed = await cleanupGroup(entry.owner).catch(() => false);
+ entry.evidence.cleanup = confirmed ? 'confirmed' : 'unconfirmed';
+ }
+ entry.evidence.status = entry.stopReason || 'unavailable';
+ // No provider text, paths or credentials in shared logs.
+ console.warn(`⚠️ Security scanner ${id} could not complete (${err.code || 'runtime-error'})`);
+ } finally {
+ clearTimeout(forceTimer);
+ clearTimeout(deadline);
+ clearTimeout(drainTimer);
+ // Output may arrive during artifact/log persistence after process exit.
+ if (entry.stopReason) entry.evidence.status = entry.stopReason;
+ entry.child?.stdout.destroy();
+ entry.child?.stderr.destroy();
+ entry.child?.unref?.();
+ entry.terminal = true;
+ entry.cancel = null;
+ try { await persist(id, entry); }
+ finally {
+ // A disk failure must never prevent stopping a refused outer request.
+ if (entry.evidence.status === 'refused') terminateRefusedOuter(id);
+ }
+ }
+ return { evidence: entry.evidence, artifactDirectory: directory || null };
+ });
+ return entry.promise;
+ };
+ // The delayed boot sweep must not stop a grant launched by this runner.
+ const recover = id => getAgent(id) ? read(id) : stop(id);
+ return { register, start, stop, read, recover };
+}
diff --git a/server/cos-runner/securityScan.process.test.js b/server/cos-runner/securityScan.process.test.js
new file mode 100644
index 0000000000..633992d9f3
--- /dev/null
+++ b/server/cos-runner/securityScan.process.test.js
@@ -0,0 +1,56 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { mkdtemp, mkdir, readFile, writeFile, rm } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { fileURLToPath } from 'url';
+import { randomUUID } from 'crypto';
+import { spawn } from '../lib/childProcess.js';
+import { createSecurityScanManager } from './securityScan.js';
+import { cleanupSecurityScanGroup } from './securityScanRecovery.js';
+
+let root;
+const owners = [];
+beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'scanner-process-test-')); await mkdir(join(root, 'repo')); });
+afterEach(async () => {
+ for (const owner of owners.splice(0)) await cleanupSecurityScanGroup(owner);
+ await rm(root, { recursive: true, force: true });
+});
+const gone = pid => { try { process.kill(pid, 0); return false; } catch (err) { return err.code === 'ESRCH'; } };
+
+it.skipIf(process.platform === 'win32')('reaps a real inherited worker after the scanner exits without waiting for its pipes', async () => {
+ // This fixture is a local Node process only. It has no provider/network code.
+ const fixture = join(root, 'fixture.cjs');
+ await writeFile(fixture, `const {spawn}=require('node:child_process'); const fs=require('node:fs');
+ const out=process.argv[process.argv.indexOf('--output-dir')+1];
+ const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'inherit'});
+ fs.writeFileSync(out+'/worker.pid',String(child.pid)); child.unref(); process.exit(0);`);
+ const manager = createSecurityScanManager({ agentsDir: join(root, 'agents'), tempRoot: root,
+ getAgent: () => ({ workspacePath: join(root, 'repo') }),
+ resolveCli: async () => ({ command: process.execPath, args: [fixture] }),
+ });
+ await manager.register('agent-example', { model: 'example-model', effort: 'medium', auth: 'chatgpt', maxCostUsd: 2, timeLimitSeconds: 180 });
+ const result = await manager.start('agent-example', { prompt: 'Synthetic lifecycle fixture', paths: ['.'] });
+ owners.push(JSON.parse(await readFile(join(root, 'agents/agent-example/security-scan-process.json'), 'utf8')));
+ const workerPid = Number(await readFile(join(result.artifactDirectory, 'results/worker.pid'), 'utf8'));
+ expect(result.evidence).toMatchObject({ status: 'completed', exitCode: 0, cleanup: 'confirmed' });
+ await vi.waitFor(() => expect(gone(workerPid)).toBe(true));
+});
+
+it.skipIf(process.platform === 'win32')('waits for the durable-receipt handshake and kills its group on runner IPC loss', async () => {
+ const marker = randomUUID();
+ const supervisor = fileURLToPath(new URL('./securityScanChild.js', import.meta.url));
+ const child = spawn(process.execPath, [supervisor, root], { detached: true, stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
+ env: { PATH: process.env.PATH, PORTOS_SECURITY_SCAN_OWNER: marker } });
+ const owner = { pid: child.pid, startedAt: Date.now(), marker, outputDir: root };
+ owners.push(owner);
+ const exit = new Promise(resolve => child.once('exit', resolve));
+ const markerFile = join(root, 'launched');
+ expect(await readFile(markerFile).catch(() => null)).toBeNull();
+ child.send({ command: process.execPath, args: ['-e', `require('node:fs').writeFileSync(${JSON.stringify(markerFile)},String(process.pid));setInterval(()=>{},1000)`] });
+ let workerPid;
+ await vi.waitFor(async () => { workerPid = Number(await readFile(markerFile, 'utf8')); expect(workerPid).toBeGreaterThan(1); });
+ child.disconnect();
+ await exit;
+ await vi.waitFor(() => expect(gone(workerPid)).toBe(true));
+ expect(await cleanupSecurityScanGroup(owner)).toBe(true);
+});
diff --git a/server/cos-runner/securityScan.test.js b/server/cos-runner/securityScan.test.js
new file mode 100644
index 0000000000..79edca43fe
--- /dev/null
+++ b/server/cos-runner/securityScan.test.js
@@ -0,0 +1,225 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { EventEmitter } from 'events';
+import { PassThrough } from 'stream';
+import { mkdtemp, mkdir, readFile, writeFile, rm } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { createSecurityScanManager } from './securityScan.js';
+
+const grant = { model: 'example-model', effort: 'medium', auth: 'chatgpt', maxCostUsd: 2, timeLimitSeconds: 180 };
+let root;
+const outerAgents = [];
+beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'scanner-runtime-test-')); await mkdir(join(root, 'repo')); });
+afterEach(async () => { for (const agent of outerAgents.splice(0)) clearTimeout(agent.killTimer); vi.useRealTimers(); await rm(root, { recursive: true, force: true }); });
+
+function setup({ finish, ...overrides } = {}) {
+ let child;
+ let onSpawn;
+ const spawned = new Promise(resolve => { onSpawn = resolve; });
+ const agent = { workspacePath: join(root, 'repo'), process: { kill: vi.fn() } };
+ outerAgents.push(agent);
+ const evidence = [];
+ const spawnProcess = vi.fn((command, args, options) => {
+ child = Object.assign(new EventEmitter(), { pid: 99999999, stdout: new PassThrough(), stderr: new PassThrough() });
+ child.send = ({ command: scannerCommand, args: scannerArgs }, done) => {
+ onSpawn({ child, command: scannerCommand, args: scannerArgs, options });
+ done();
+ if (finish) setImmediate(() => finish(child, scannerArgs));
+ };
+ return child;
+ });
+ const kill = vi.fn((_child, signal) => {
+ if (_child === agent.process) agent.process.kill(signal);
+ else setImmediate(() => child.emit('close', null, signal));
+ });
+ const manager = createSecurityScanManager({ agentsDir: join(root, 'agents'), getAgent: () => agent,
+ emitEvidence: async (_id, value) => { evidence.push(value); },
+ resolveCli: async () => ({ command: 'installed-scanner', args: [] }), spawnProcess, kill,
+ cleanupGroup: async () => true, tempRoot: root,
+ environment: { PATH: '/example/bin', HOME: root, OPENAI_API_KEY: 'example-not-a-key', PORTOS_API_TOKEN: 'example-not-a-token' },
+ ...overrides });
+ return { manager, agent, spawnProcess, kill, spawned, evidence };
+}
+
+const input = { prompt: 'Report-only source audit of the selected boundary.', paths: ['.'], knowledgeBase: [] };
+
+describe.skipIf(process.platform === 'win32')('runner-owned scanner lifecycle', () => {
+ it('pins the launch grant, strips API credentials and records successful evidence without an agent sentinel', async () => {
+ const h = setup();
+ await h.manager.register('agent-example', grant);
+ const run = h.manager.start('agent-example', input);
+ const { child, args, options } = await h.spawned;
+ expect(args).toContain('--auth');
+ expect(args.slice(args.indexOf('--auth'), args.indexOf('--auth') + 2)).toEqual(['--auth', 'chatgpt']);
+ expect(args.slice(args.indexOf('--model'), args.indexOf('--model') + 4)).toEqual(['--model', 'example-model', '--effort', 'medium']);
+ expect(options.env).not.toHaveProperty('OPENAI_API_KEY');
+ expect(options.env).not.toHaveProperty('PORTOS_API_TOKEN');
+ expect(options.stdio[0]).toBe('ignore');
+ const output = args[args.indexOf('--output-dir') + 1];
+ await writeFile(join(output, 'findings.json'), '[]');
+ await writeFile(join(output, 'coverage.json'), '{}');
+ child.stdout.write('short-context budget baseline: $0.25 of $2.00 limit\n');
+ child.emit('close', 0, null);
+ const result = await run;
+ expect(result.evidence).toMatchObject({ source: 'runner', status: 'completed', model: 'example-model', effort: 'medium',
+ maxCostUsd: 2, timeLimitSeconds: 180, estimatedCostUsd: 0.25, exitCode: 0, artifacts: { findings: true, coverage: true } });
+ expect(JSON.parse(await readFile(join(root, 'agents/agent-example/security-scan.json'), 'utf8'))).toEqual(result.evidence);
+ expect(h.evidence.map(e => e.status)).toEqual(['not-run', 'running', 'completed']);
+ });
+
+ it('rejects request overrides and shares a single attempt across duplicate or lost-response requests', async () => {
+ const h = setup();
+ await h.manager.register('agent-example', grant);
+ expect(() => h.manager.start('agent-example', { ...input, model: 'more-expensive-model' })).toThrow();
+ const first = h.manager.start('agent-example', input);
+ const replay = h.manager.start('agent-example', input);
+ expect(first).toBe(replay);
+ const { child } = await h.spawned;
+ child.emit('close', 0, null);
+ await first;
+ expect(await h.manager.start('agent-example', input)).toEqual(await first);
+ expect(h.spawnProcess).toHaveBeenCalledTimes(1);
+ });
+
+ it('latches a structured refusal, ignores exit zero and stops the outer request without retry', async () => {
+ const h = setup();
+ await h.manager.register('agent-example', grant);
+ const run = h.manager.start('agent-example', input);
+ const { child } = await h.spawned;
+ child.stderr.write('{"type":"turn.failed","error":{"codex_error_info":"cyber_');
+ child.stderr.write('policy"}}\n');
+ child.emit('close', 0, null);
+ expect((await run).evidence.status).toBe('refused');
+ expect(h.agent.process.kill).toHaveBeenCalledOnce();
+ await h.manager.start('agent-example', input);
+ expect(h.spawnProcess).toHaveBeenCalledOnce();
+ });
+
+ it('preserves interruption and artifact absence when the outer agent exits without completion', async () => {
+ const h = setup();
+ await h.manager.register('agent-example', grant);
+ const run = h.manager.start('agent-example', input);
+ await h.spawned;
+ const stopped = await h.manager.stop('agent-example');
+ await run;
+ expect(stopped).toMatchObject({ status: 'interrupted', exitCode: 143, cleanup: 'confirmed', artifacts: { findings: false, coverage: false } });
+ expect(h.kill).toHaveBeenCalledWith(expect.anything(), 'SIGTERM', { processGroup: true });
+ });
+
+ it('keeps a buffered refusal terminal when cancellation has already started', async () => {
+ const h = setup();
+ await h.manager.register('agent-example', grant);
+ const run = h.manager.start('agent-example', input);
+ const { child } = await h.spawned;
+ const stopped = h.manager.stop('agent-example');
+ child.stderr.write('{"type":"turn.failed","error":{"codex_error_info":"cyber_policy"}}\n');
+ child.emit('close', 0, null);
+ expect((await run).evidence.status).toBe('refused');
+ expect((await stopped).status).toBe('refused');
+ expect(h.kill).toHaveBeenCalledWith(h.agent.process, 'SIGTERM');
+ await h.manager.start('agent-example', input);
+ expect(h.spawnProcess).toHaveBeenCalledOnce();
+ });
+
+ it('lets cancellation during installation discovery prevent any child launch', async () => {
+ let release;
+ const h = setup({ resolveCli: () => new Promise(resolve => { release = resolve; }) });
+ await h.manager.register('agent-example', grant);
+ const run = h.manager.start('agent-example', input);
+ const stopped = h.manager.stop('agent-example');
+ release({ command: 'installed-scanner', args: [] });
+ await Promise.all([run, stopped]);
+ expect(h.spawnProcess).not.toHaveBeenCalled();
+ expect((await h.manager.read('agent-example')).status).toBe('interrupted');
+ });
+
+ it('reports missing installation without npx, scanner defaults or fallback', async () => {
+ const h = setup({ resolveCli: async () => null });
+ await h.manager.register('agent-example', grant);
+ expect((await h.manager.start('agent-example', input)).evidence.status).toBe('unavailable');
+ expect(h.spawnProcess).not.toHaveBeenCalled();
+ });
+
+ it('recovers a missing completion from durable evidence without relaunching or trusting a bare PID', async () => {
+ const h = setup();
+ await h.manager.register('agent-example', grant);
+ const run = h.manager.start('agent-example', input);
+ await h.spawned;
+ await vi.waitFor(async () => expect(JSON.parse(await readFile(join(root, 'agents/agent-example/security-scan-process.json'), 'utf8'))).toHaveProperty('marker'));
+ const cleanupGroup = vi.fn(async () => false);
+ const recovered = setup({ cleanupGroup });
+ expect((await recovered.manager.stop('agent-example'))).toMatchObject({ status: 'interrupted', exitCode: null, cleanup: 'unconfirmed' });
+ expect(recovered.spawnProcess).not.toHaveBeenCalled();
+ await expect(recovered.manager.register('agent-example', grant)).rejects.toThrow('already exists');
+ await h.manager.stop('agent-example');
+ await run;
+ });
+ it('bounds a stuck child with the existing deadline and records unconfirmed cleanup without claiming success', async () => {
+ const h = setup({ kill: vi.fn(), cleanupGroup: async () => false });
+ await h.manager.register('agent-example', grant);
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ const run = h.manager.start('agent-example', input);
+ await h.spawned;
+ await vi.advanceTimersByTimeAsync(185000);
+ expect((await run).evidence).toMatchObject({ status: 'time-limit', exitCode: null, cleanup: 'unconfirmed' });
+ });
+
+ it('does not treat quoted policy findings as a provider refusal', async () => {
+ const h = setup();
+ await h.manager.register('agent-example', grant);
+ const run = h.manager.start('agent-example', input);
+ const { child } = await h.spawned;
+ child.stdout.write(JSON.stringify({ findings: [{ title: 'cyber_policy', description: 'A quoted policy field in source code.' }] }) + '\n');
+ child.emit('close', 0, null);
+ expect((await run).evidence.status).toBe('completed');
+ expect(h.agent.process.kill).not.toHaveBeenCalled();
+ });
+
+ it('never launches with missing resolved effort or paths outside the workspace', async () => {
+ const h = setup();
+ await h.manager.register('agent-example', { ...grant, effort: null });
+ expect((await h.manager.start('agent-example', input)).evidence.status).toBe('unavailable');
+ await h.manager.register('agent-other', grant);
+ expect((await h.manager.start('agent-other', { ...input, paths: ['..'] })).evidence.status).toBe('unavailable');
+ expect(h.spawnProcess).not.toHaveBeenCalled();
+ });
+
+ it('still stops a refused outer request when publishing the final receipt fails', async () => {
+ const h = setup({ emitEvidence: async (_id, value) => { if (value.status === 'refused') throw new Error('synthetic persistence outage'); } });
+ await h.manager.register('agent-example', grant);
+ const run = h.manager.start('agent-example', input);
+ const { child } = await h.spawned;
+ child.stderr.write('{"type":"turn.failed","error":{"codex_error_info":"cyber_policy"}}\n');
+ await expect(run).rejects.toThrow('synthetic persistence outage');
+ expect(h.agent.process.kill).toHaveBeenCalledOnce();
+ });
+
+ it('a refusal in final stderr wins over exit zero and forces an outer process that ignores TERM', async () => {
+ const h = setup();
+ await h.manager.register('agent-example', grant);
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ const run = h.manager.start('agent-example', input);
+ const { child } = await h.spawned;
+ child.emit('exit', 0, null);
+ child.stderr.write('{"type":"turn.failed","error":{"codex_error_info":"cyber_policy"}}\n');
+ child.emit('close', 0, null);
+ expect((await run).evidence.status).toBe('refused');
+ expect(h.agent.process.kill).toHaveBeenCalledWith('SIGTERM');
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(h.agent.process.kill).toHaveBeenCalledWith('SIGKILL');
+ });
+
+ it('boot recovery leaves a newly launched TUI grant usable while settling a prior runner receipt', async () => {
+ const h = setup({ getAgent: id => id === 'agent-new' ? { workspacePath: join(root, 'repo') } : null });
+ await h.manager.register('agent-new', grant);
+ await h.manager.recover('agent-new');
+ await mkdir(join(root, 'agents/agent-old'), { recursive: true });
+ await writeFile(join(root, 'agents/agent-old/security-scan.json'), JSON.stringify({ ...(await h.manager.read('agent-new')), status: 'running' }));
+ expect((await h.manager.recover('agent-old')).status).toBe('interrupted');
+ const run = h.manager.start('agent-new', input);
+ const { child } = await h.spawned;
+ child.emit('close', 0, null);
+ expect((await run).evidence.status).toBe('completed');
+ });
+
+});
diff --git a/server/cos-runner/securityScanChild.js b/server/cos-runner/securityScanChild.js
new file mode 100644
index 0000000000..c6d431c034
--- /dev/null
+++ b/server/cos-runner/securityScanChild.js
@@ -0,0 +1,18 @@
+import { spawn } from '../lib/childProcess.js';
+
+// The runner first persists this supervisor's identity, then releases exactly
+// one launch over its private IPC channel. A crash before that cannot start a
+// provider call. A crash afterwards closes IPC and kills our own process group.
+// The scanner receives ordinary inherited stdio, never the control channel.
+const killOwnedGroup = () => {
+ try { process.kill(-process.pid, 'SIGKILL'); }
+ catch { process.exit(1); }
+};
+process.once('disconnect', killOwnedGroup);
+process.once('message', ({ command, args }) => {
+ const child = spawn(command, args, { stdio: ['ignore', 'inherit', 'inherit'] });
+ child.once('error', () => process.exit(1));
+ child.once('exit', (code, signal) => {
+ process.exit(code ?? (signal === 'SIGTERM' ? 143 : signal === 'SIGKILL' ? 137 : 1));
+ });
+});
diff --git a/server/cos-runner/securityScanRecovery.js b/server/cos-runner/securityScanRecovery.js
new file mode 100644
index 0000000000..00f6858c8c
--- /dev/null
+++ b/server/cos-runner/securityScanRecovery.js
@@ -0,0 +1,44 @@
+import { promisify } from 'util';
+import { execFile } from '../lib/childProcess.js';
+
+const exec = promisify(execFile);
+
+async function snapshot() {
+ const { stdout } = await exec('/bin/ps', ['-axo', 'pid=,pgid=,stat=,lstart=,command='], { timeout: 1000, maxBuffer: 8 * 1024 * 1024 });
+ return stdout.split('\n').flatMap(line => {
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)\s+(\w+\s+\w+\s+\d+\s+\d+:\d+:\d+\s+\d+)\s+(.*)$/);
+ return match ? [{ pid: Number(match[1]), pgid: Number(match[2]), state: match[3], startedAt: Date.parse(match[4]), command: match[5] }] : [];
+ });
+}
+
+async function hasMarker(pid, marker) {
+ // Read only the already selected group member; never return or log its env.
+ const { stdout } = await exec('/bin/ps', ['eww', '-p', String(pid), '-o', 'command='], { timeout: 1000, maxBuffer: 1024 * 1024 });
+ return stdout.split(/\s+/).includes(`PORTOS_SECURITY_SCAN_OWNER=${marker}`);
+}
+
+/** Revalidate ownership before EACH recovery signal; never trust a stale PID. */
+export async function cleanupSecurityScanGroup(owner, { processes = snapshot, marked = hasMarker,
+ signal = (pid, value) => process.kill(-pid, value), signalName = 'SIGKILL' } = {}) {
+ if (!owner || !Number.isInteger(owner.pid) || owner.pid <= 1 || !/^[a-f0-9-]{36}$/.test(owner.marker || '')) return false;
+ if (process.platform === 'win32') return false;
+ const members = (await processes()).filter(p => p.pgid === owner.pid && !p.state.startsWith('Z'));
+ if (!members.length) return true;
+ const leader = members.find(p => p.pid === owner.pid);
+ const timeMatches = leader && leader.startedAt >= owner.startedAt - 2000 && leader.startedAt <= owner.startedAt + 2000;
+ // The leader's private output directory is a per-attempt nonce. If it has
+ // exited, descendants must still carry the inherited launch marker. A reused
+ // group or an ambiguous observation is left untouched and shown unconfirmed.
+ const proven = leader ? timeMatches && leader.command.includes(owner.outputDir)
+ : (await Promise.all(members.map(p => marked(p.pid, owner.marker).catch(() => false)))).every(Boolean);
+ if (!proven) return false;
+ try { signal(owner.pid, signalName); } catch (err) { if (err.code !== 'ESRCH') throw err; }
+ // A sent signal is not evidence of cleanup. Confirm quiescence separately.
+ const deadline = Date.now() + 1000;
+ do {
+ const remaining = (await processes()).filter(p => p.pgid === owner.pid && !p.state.startsWith('Z'));
+ if (!remaining.length) return true;
+ await new Promise(resolve => setTimeout(resolve, 25));
+ } while (Date.now() < deadline);
+ return false;
+}
diff --git a/server/cos-runner/securityScanRecovery.test.js b/server/cos-runner/securityScanRecovery.test.js
new file mode 100644
index 0000000000..73bcb182b1
--- /dev/null
+++ b/server/cos-runner/securityScanRecovery.test.js
@@ -0,0 +1,17 @@
+import { expect, it, vi } from 'vitest';
+import { cleanupSecurityScanGroup } from './securityScanRecovery.js';
+
+const owner = { pid: 1234, startedAt: 10000, marker: '00000000-0000-4000-8000-000000000001', outputDir: '/example/private/scan-one' };
+it.skipIf(process.platform === 'win32')('reaps proven detached descendants after their scanner leader exits', async () => {
+ const signal = vi.fn();
+ const processes = async () => signal.mock.calls.length ? [] : [{ pid: 1235, pgid: 1234, startedAt: 11000, state: 'S', command: 'worker' }];
+ expect(await cleanupSecurityScanGroup(owner, { processes, marked: async () => true, signal })).toBe(true);
+ expect(signal).toHaveBeenCalledWith(1234, 'SIGKILL');
+});
+it.skipIf(process.platform === 'win32')('never signals a reused group leader or an unverified descendant', async () => {
+ const signal = vi.fn();
+ const processes = async () => [{ pid: 1234, pgid: 1234, startedAt: 90000, state: 'S', command: owner.outputDir }];
+ expect(await cleanupSecurityScanGroup(owner, { processes, marked: async () => true, signal })).toBe(false);
+ expect(await cleanupSecurityScanGroup(owner, { processes: async () => [{ pid: 1235, pgid: 1234, state: 'S' }], marked: async () => false, signal })).toBe(false);
+ expect(signal).not.toHaveBeenCalled();
+});
diff --git a/server/cos-runner/shutdown.js b/server/cos-runner/shutdown.js
index 22600635a3..56cc7117d9 100644
--- a/server/cos-runner/shutdown.js
+++ b/server/cos-runner/shutdown.js
@@ -101,6 +101,7 @@ export function createRunnerShutdown({
// Arm first so a synchronous exit from a process double can cancel it.
armForceKill(new Map([[agentId, agent]]), agentId, agent, { graceMs });
try {
+ if (agent.stopSecurityScan) trackWork(() => agent.stopSecurityScan());
killProcessTree(agent.process, 'SIGTERM');
} catch (err) {
reportFailure(err);
diff --git a/server/cos-runner/shutdown.test.js b/server/cos-runner/shutdown.test.js
index bf97536b0b..2109574d4d 100644
--- a/server/cos-runner/shutdown.test.js
+++ b/server/cos-runner/shutdown.test.js
@@ -39,6 +39,8 @@ vi.mock('../lib/bufferedSpawn.js', () => ({
}));
import { killProcessTree } from '../lib/bufferedSpawn.js';
import { createRunnerShutdown, registerRunnerShutdownSignals } from './shutdown.js';
+import { createSecurityScanManager } from './securityScan.js';
+import { securityScanRequestSchema } from '../lib/securityScanEvidence.js';
import { createTuiExitHandler } from './tuiExit.js';
import { armForceKill } from './forceKill.js';
import * as requestSchemas from './requestSchemas.js';
@@ -111,6 +113,7 @@ function runner(assertDatabaseAdmission = vi.fn()) {
withState, drainState,
...requestSchemas,
createRunnerShutdown, registerRunnerShutdownSignals, createTuiExitHandler, createHttpDrain,
+ createSecurityScanManager, securityScanRequestSchema,
armForceKillShared: armForceKill, killProcessTree, spawn, pty,
createAgentSentinelAccess,
buildCliChildEnv: () => ({}), prepareCliSpawn: (command, args) => ({ command, args }),
diff --git a/server/cos-runner/tuiExit.js b/server/cos-runner/tuiExit.js
index 080d348e42..01f3208ea3 100644
--- a/server/cos-runner/tuiExit.js
+++ b/server/cos-runner/tuiExit.js
@@ -30,6 +30,10 @@ export function createTuiExitHandler({ agentId, taskId, sessionId, agent, active
const current = agent;
if (current.exited) return;
current.exited = true;
+ await current.stopSecurityScan?.().catch(err => {
+ console.error(`❌ Scanner settlement failed during TUI exit: ${err.message}`);
+ onError?.(err);
+ });
// Drop the handle before the awaited state write so GET /agents cannot
// publish processActive:false for a TUI whose completion event is still
// in flight (completeAgent keeps the first terminal verdict).
@@ -55,6 +59,7 @@ export function createTuiExitHandler({ agentId, taskId, sessionId, agent, active
taskId, completedAt: new Date().toISOString(), exitCode: effectiveExitCode,
signal: effectiveSignal, success: !!success, duration,
completionReason: success ? 'agent-signaled-done' : 'tui-exit',
+ securityScan: current.securityScan,
});
io.emit('tui:exit', {
sessionId,
@@ -75,6 +80,7 @@ export function createTuiExitHandler({ agentId, taskId, sessionId, agent, active
duration,
outputLength: completionOutput.length,
completionReason: current.completedBySentinel ? 'agent-signaled-done' : 'tui-exit',
+ securityScan: current.securityScan,
});
await withState((state) => {
state.stats.completed++;
diff --git a/server/cos-runner/tuiExit.test.js b/server/cos-runner/tuiExit.test.js
index 4df4aaa3ee..433938dd25 100644
--- a/server/cos-runner/tuiExit.test.js
+++ b/server/cos-runner/tuiExit.test.js
@@ -90,4 +90,11 @@ describe('runner TUI exit handoff', () => {
await failed.onExit({ exitCode: 1, signal: 0 });
expect(failed.persistCompletion.mock.calls[0][1]).toBe('Usage limit reached');
});
+ it('publishes transport completion even when scanner evidence settlement fails', async () => {
+ const run = setup({ stopSecurityScan: vi.fn().mockRejectedValue(new Error('synthetic disk outage')) });
+ await run.onExit({ exitCode: 143, signal: 15 });
+ expect(run.io.emit).toHaveBeenCalledWith('tui:exit', expect.objectContaining({ exitCode: 143 }));
+ expect(run.emitToServer).toHaveBeenCalledWith('agent:completed', expect.objectContaining({ success: false }));
+ });
+
});
diff --git a/server/lib/README.md b/server/lib/README.md
index 71934b7bbe..8ea4680ffe 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -372,7 +372,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `pm2Jlist.js` | Sole owner of the strict `pm2 jlist` stdout parser: `parsePm2JlistStdout(stdout)` returns the parsed process array (incl. `[]` for a genuine empty read) or `null` when the read effectively failed (empty/garbage/non-array stdout) — the absent-vs-empty contract from issue #968, consolidated by #8164. Zero imports so `autofixer/shared.js` can use it without the server dependency graph. `services/pm2.js` re-exports it as `parseJlistStdout` for compatibility; `services/pm2.js#listProcessesStrict` and `autofixer/shared.js` are the only non-test callers permitted to execute raw `pm2 jlist`. |
| `secretText.js` | `scrubSecretTokens(text)` — replace credential-SHAPED substrings (prefixed API keys, GitHub/Slack tokens, JWTs, AWS key ids, pasted Bearer headers, 48+-char hex) with `[REDACTED]` in free text bound for an LLM provider or a world-readable artifact; `scrubSecretTokensDeep(value)` walks arrays/plain objects and scrubs every string value. Value-side counterpart to the operator-action ledger's key-based `redactPayload` and `commandSecurity.js#redactOutput`'s JSON patterns; conservative so prose, 40-hex git SHAs, and short ids survive. |
| `securityAuditLog.js` | `logSecurityEvent(event, { refused, ...fields })` — one-line `🔐`/`⛔ Security [event] key=value` audit trail for sign-ins, password/session/agent-key changes and refused host-control or browser-relay requests. Flattens control characters and truncates values so a caller-controlled path/Host can't forge a log line; refusals use `console.warn`. |
-| `securityScanEvidence.js` | Strict, bounded scanner diagnostics parser; preserves unknown budget, exit and artifact evidence separately from assessment/delivery outcomes. |
+| `securityScanEvidence.js` | Strict scanner evidence/request/grant schemas; `securityScanGrantFromArgs` resolves actual Codex launch pins, `parseRunnerSecurityScanEvidence` preserves ordered runner observations, and `parseSecurityScanEvidence` retains legacy agent reports. |
| `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). |
| `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore` — a TTL-cached mutable JSON document with serialized `save`/`mutate`; its `load()` is strict (#4115) so a corrupt file rejects instead of being overwritten by the next `mutate`. |
| `settingsStore.js` | `createSettingsStore(filePath | () => filePath, defaults, { normalize? })` → `{ get, update, path }` — the one owner of a flat per-feature settings document with shipped defaults (`journal-settings.json`, `activity-digest-settings.json`, `goal-scorecard-settings.json`, …). `get()` reads strict (#4115: a corrupt file rejects rather than reading as the defaults, because `update` writes it back), merges the file over `defaults`, then runs `normalize`; `update(patch)` is a serialized `get → apply → atomicWrite` that skips `undefined` values and writes `null` as an explicit clear. Filter client-settable keys BEFORE calling `update`. Reach for `createCachedStore` for an in-place-edited document and `createCollectionStore` for per-record collections. |
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 58cf8a0f0c..51ac286032 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -315,6 +315,7 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
'POST /api/cos/agents/:id/resume',
'POST /api/cos/agents/:id/relaunch',
'POST /api/cos/agents/:id/btw',
+ 'POST /api/cos/agents/:id/security-scan',
'POST /api/cos/jobs',
'PUT /api/cos/jobs/:id',
// Toggle arms an existing job, shell jobs included, for its next run.
diff --git a/server/lib/securityScanEvidence.js b/server/lib/securityScanEvidence.js
index f3f700647e..4afc0b387d 100644
--- a/server/lib/securityScanEvidence.js
+++ b/server/lib/securityScanEvidence.js
@@ -3,11 +3,11 @@ import { z } from 'zod';
const PREFIX = 'SCANNER_STATUS_JSON:';
const nullableCost = z.number().finite().nonnegative().nullable();
-// Bounded, agent-reported diagnostics. No paths, prompts, findings, credentials,
+// Bounded diagnostics with explicit provenance at the ingestion boundary. No paths, prompts, findings, credentials,
// or billing claims cross this boundary; null means not established.
export const securityScanEvidenceSchema = z.object({
version: z.literal(1),
- status: z.enum(['not-run', 'unavailable', 'completed', 'failed', 'time-limit', 'budget-limit', 'refused']),
+ status: z.enum(['not-run', 'running', 'unavailable', 'completed', 'failed', 'interrupted', 'time-limit', 'budget-limit', 'refused']),
model: z.string().regex(/^[a-zA-Z0-9_.:-]{1,100}$/).nullable(),
effort: z.enum(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']).nullable(),
auth: z.enum(['chatgpt', 'api-key', 'unknown']),
@@ -16,8 +16,38 @@ export const securityScanEvidenceSchema = z.object({
timeLimitSeconds: z.number().int().nonnegative().nullable(),
exitCode: z.number().int().nullable(),
artifacts: z.object({ findings: z.boolean().nullable(), coverage: z.boolean().nullable() }).strict(),
+ cleanup: z.enum(['not-needed', 'confirmed', 'unconfirmed']).optional(),
}).strict().refine(value => value.status !== 'completed' || value.exitCode === 0);
+// This grant is set once at agent dispatch, never accepted from the model's
+// scan request. These ceilings preserve the bounded existing scanner workflow.
+export const securityScanGrantSchema = z.object({
+ model: z.string().regex(/^[a-zA-Z0-9_.:-]{1,100}$/).nullable(),
+ effort: z.enum(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']).nullable(),
+ auth: z.literal('chatgpt'),
+ maxCostUsd: z.literal(2),
+ timeLimitSeconds: z.literal(180),
+}).strict();
+
+export const securityScanRequestSchema = z.object({
+ prompt: z.string().min(1).max(32000),
+ paths: z.array(z.string().min(1).max(4096)).min(1).max(100),
+ knowledgeBase: z.array(z.string().min(1).max(4096)).max(20).default([]),
+}).strict();
+
+export function initialSecurityScanEvidence(grant) {
+ return { version: 1, status: 'not-run', ...grant, estimatedCostUsd: null,
+ exitCode: null, artifacts: { findings: null, coverage: null }, cleanup: 'not-needed', source: 'runner' };
+}
+
+export function parseRunnerSecurityScanEvidence(value) {
+ if (value?.source !== 'runner') return null;
+ const { source, sequence, ...data } = value;
+ if (!Number.isSafeInteger(sequence) || sequence < 1) return null;
+ const parsed = securityScanEvidenceSchema.safeParse(data);
+ return parsed.success ? { ...parsed.data, source, sequence } : null;
+}
+
/** Invalid/absent evidence stays unreported; delivery success cannot fill it in. */
export function parseSecurityScanEvidence(summary) {
if (typeof summary !== 'string') return null;
@@ -28,3 +58,28 @@ export function parseSecurityScanEvidence(summary) {
const result = securityScanEvidenceSchema.safeParse(raw);
return result.success ? { ...result.data, source: 'agent-report' } : null;
}
+
+/** Pin to the effective Codex argv, including saved flags and effort clamping.
+ * Implicit defaults or conflicting pins are unavailable, never guessed. */
+export function securityScanGrantFromArgs(args = []) {
+ const models = new Set();
+ const efforts = new Set();
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--model' || arg === '-m') models.add(args[++i]);
+ else if (/^(?:--model|-m)=/.test(arg)) models.add(arg.slice(arg.indexOf('=') + 1));
+ else {
+ const config = arg === '-c' || arg === '--config' ? args[++i]
+ : arg.startsWith('--config=') ? arg.slice(9) : arg.startsWith('-c') ? arg.slice(2) : null;
+ const match = config?.match(/^(model|model_reasoning_effort)\s*=\s*(.*?)\s*$/);
+ if (match) {
+ const value = match[2].replace(/^(["'])(.*)\1$/, '$2');
+ (match[1] === 'model' ? models : efforts).add(value);
+ }
+ }
+ }
+ const model = models.size === 1 ? [...models][0] : null;
+ const effort = efforts.size === 1 ? [...efforts][0] : null;
+ const parsed = securityScanGrantSchema.safeParse({ model, effort, auth: 'chatgpt', maxCostUsd: 2, timeLimitSeconds: 180 });
+ return parsed.success ? parsed.data : { model: null, effort: null, auth: 'chatgpt', maxCostUsd: 2, timeLimitSeconds: 180 };
+}
diff --git a/server/lib/securityScanEvidence.test.js b/server/lib/securityScanEvidence.test.js
index 8b81110449..5c88994c3b 100644
--- a/server/lib/securityScanEvidence.test.js
+++ b/server/lib/securityScanEvidence.test.js
@@ -1,5 +1,5 @@
import { expect, it } from 'vitest';
-import { parseSecurityScanEvidence } from './securityScanEvidence.js';
+import { parseSecurityScanEvidence, securityScanGrantFromArgs } from './securityScanEvidence.js';
const report = {
version: 1, status: 'time-limit', model: 'example-model', effort: 'low', auth: 'chatgpt',
@@ -20,3 +20,9 @@ it('rejects fabricated completion, ambiguous reports and fields that could discl
expect(parseSecurityScanEvidence('Completed successfully')).toBeNull();
expect(parseSecurityScanEvidence(`SCANNER_STATUS_JSON: ${JSON.stringify(report)}\nSCANNER_STATUS_JSON: ${JSON.stringify(report)}`)).toBeNull();
});
+
+it('derives scanner pins from effective argv and refuses conflicting or implicit defaults', () => {
+ expect(securityScanGrantFromArgs(['--model', 'saved-model', '-c', 'model_reasoning_effort="high"'])).toMatchObject({ model: 'saved-model', effort: 'high' });
+ expect(securityScanGrantFromArgs(['--model=selected-model', '--config=model="another-model"', '-cmodel_reasoning_effort=low'])).toMatchObject({ model: null, effort: 'low' });
+ expect(securityScanGrantFromArgs([])).toMatchObject({ model: null, effort: null });
+});
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index 92a7fd16ca..547c7c7911 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -9,10 +9,17 @@ import * as cos from '../services/cos.js';
import * as agentOrchestrator from '../services/agentOrchestrator.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { toAgentListItems } from '../lib/cosAgentListProjection.js';
+import { securityScanRequestSchema } from '../lib/securityScanEvidence.js';
import { validateRequest, resumeCosAgentSchema, relaunchCosAgentSchema, cosAgentFeedbackBodySchema, cosAgentBtwBodySchema } from '../lib/validation.js';
const router = Router();
+router.post('/agents/:id/security-scan', asyncHandler(async (req, res) => {
+ const input = validateRequest(securityScanRequestSchema, req.body ?? {});
+ const { runAgentSecurityScan } = await import('../services/agentSecurityScan.js');
+ res.json(await runAgentSecurityScan(req.params.id, input));
+}));
+
const mergeAdmissionSchema = z.object({
agentId: z.string().min(1).max(200),
action: z.enum(['acquire', 'check', 'release']),
diff --git a/server/routes/securityScan.test.js b/server/routes/securityScan.test.js
new file mode 100644
index 0000000000..dece5b9461
--- /dev/null
+++ b/server/routes/securityScan.test.js
@@ -0,0 +1,47 @@
+import { beforeEach, expect, it, vi } from 'vitest';
+import express from 'express';
+import { EventEmitter } from 'events';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const auth = vi.hoisted(() => ({ session: false, enabled: false }));
+vi.mock('../services/auth.js', () => ({
+ isAuthEnabled: async () => auth.enabled,
+ verifyRequestSession: async () => auth.session,
+}));
+vi.mock('../services/settings.js', () => ({ settingsEvents: new EventEmitter(), getSettings: async () => ({}) }));
+vi.mock('../services/cos.js', () => ({}));
+vi.mock('../services/agentOrchestrator.js', () => ({}));
+vi.mock('../services/agentSecurityScan.js', () => ({ runAgentSecurityScan: vi.fn(async () => ({ evidence: { status: 'running' } })) }));
+
+import { authGate, hostControlRouteGate } from '../services/authGate.js';
+import { runAgentSecurityScan } from '../services/agentSecurityScan.js';
+import router from './cosAgentRoutes.js';
+
+const appFor = address => {
+ const app = express();
+ app.use((req, _res, next) => { Object.defineProperty(req.socket, 'remoteAddress', { value: address }); next(); });
+ app.use(authGate, hostControlRouteGate, express.json());
+ app.use('/api/cos', router);
+ app.use(errorMiddleware);
+ return app;
+};
+const endpoint = '/api/cos/agents/agent-example/security-scan';
+const input = { prompt: 'Audit the selected source boundary.', paths: ['server/routes'] };
+beforeEach(() => { vi.clearAllMocks(); auth.session = false; auth.enabled = false; });
+
+it('requires existing host authority before consuming a scanner grant', async () => {
+ const denied = await request(appFor('192.0.2.10')).post(endpoint).send(input);
+ expect(denied.status).toBe(403);
+ expect(runAgentSecurityScan).not.toHaveBeenCalled();
+ expect((await request(appFor('127.0.0.1')).post(endpoint).send(input)).status).toBe(200);
+ auth.session = true; auth.enabled = true;
+ expect((await request(appFor('192.0.2.10')).post(endpoint).send(input)).status).toBe(200);
+ expect(runAgentSecurityScan).toHaveBeenCalledTimes(2);
+});
+
+it('rejects model, effort and budget overrides at the public request boundary', async () => {
+ const result = await request(appFor('127.0.0.1')).post(endpoint).send({ ...input, model: 'another-model', effort: 'high', maxCostUsd: 10 });
+ expect(result.status).toBe(400);
+ expect(runAgentSecurityScan).not.toHaveBeenCalled();
+});
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 05c47d5cb7..b525949cbb 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -1154,6 +1154,12 @@ export function dispatchRecoveredTaskOutputHook({ agentId, task, success, worksp
* private-security override), so callers that branch on it don't have to re-derive it
*/
export async function retireDeadAgent({ agent, task, success, exitCode, duration, errorMessage, category, agentResultExtra = {} }) {
+ if (agent.metadata?.taskAnalysisType === 'security' && agent.metadata.useRunner) {
+ const { settleAgentSecurityScan } = await import('./agentSecurityScan.js');
+ const scanner = await settleAgentSecurityScan(agent.id);
+ if (scanner?.status === 'refused') agent = { ...agent, metadata: { ...agent.metadata,
+ executionInterruption: { category: 'content-refusal', source: 'security-scanner' } } };
+ }
const isPrivateSecurity = isPrivateSecurityTask(task) || isPrivateSecurityTask(agent);
const interruption = agent.metadata?.executionInterruption;
const refused = ['content-refusal', 'content-filtered'].includes(interruption?.category);
@@ -1335,6 +1341,16 @@ export async function finalizeAgent({
prExpected = false,
startedAt = null,
}) {
+ if (resolveTaskHookType(task) === 'security') {
+ const { settleAgentSecurityScan } = await import('./agentSecurityScan.js');
+ const scanner = await settleAgentSecurityScan(agentId);
+ if (scanner?.status === 'refused') {
+ reportedSuccess = false;
+ reportedErrorAnalysis = { category: 'content-refusal', origin: 'provider', permanent: true, actionable: false,
+ requiresFallback: false, message: 'Security scanner safety refusal; automatic continuation, retries and provider fallback are disabled.' };
+ executionInterruption = { category: 'content-refusal', source: 'security-scanner' };
+ }
+ }
if (['content-refusal', 'content-filtered'].includes(reportedErrorAnalysis?.category)) {
executionInterruption ||= { category: reportedErrorAnalysis.category, source: reportedErrorAnalysis.origin || 'provider' };
reportedSuccess = false;
@@ -1997,7 +2013,8 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, a
const evidence = parseSecurityScanEvidence(summary);
// Record even on failed delivery; absence must not erase earlier evidence
// during completion replay. This stays in the machine-local agent record.
- if (evidence) await updateAgent(agentId, { metadata: { securityScan: evidence } }).catch(err => {
+ const existing = await getAgentRecord(agentId);
+ if (evidence && existing?.metadata?.securityScan?.source !== 'runner') await updateAgent(agentId, { metadata: { securityScan: evidence } }).catch(err => {
emitLog('warn', `⚠️ Scanner diagnostics were not saved for ${agentId}: ${err.message}`, { agentId });
});
}
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 93ff4112e2..4d77957d94 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -248,6 +248,7 @@ export async function spawnViaRunner(agentId, task, opts) {
workspacePath,
model,
providerAuth: cliProviderAuthDescriptor(provider),
+ securityScanGrant: opts.securityScanGrant,
// A DELTA, not a full env — the cos-runner bases it on its own process.env
// and does the PWD pin / CLAUDECODE strip. composeProviderEnv owns the layer
// order: forgeTokenEnv before provider.envVars so an explicit provider
diff --git a/server/services/agentManagement.claimResume.test.js b/server/services/agentManagement.claimResume.test.js
index 0073d0e931..95be02813e 100644
--- a/server/services/agentManagement.claimResume.test.js
+++ b/server/services/agentManagement.claimResume.test.js
@@ -4,7 +4,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
-const f = vi.hoisted(() => ({ tasks: {}, state: null, disk: null, prompt: null }));
+const f = vi.hoisted(() => ({ tasks: {}, state: null, disk: null, prompt: null, cliConfig: null }));
const persist = () => { f.disk = structuredClone(f.state); };
vi.mock('./cosState.js', () => ({
withStateLock: createFileWriteQueue(),
@@ -62,7 +62,7 @@ vi.mock('./agentWorkspacePrep.js', () => ({ prepareAgentWorkspace: async () => (
workspacePath: '/repos/example', worktreeInfo: null,
}) }));
vi.mock('./agentCliSpawning.js', () => ({
- buildCliSpawnConfig: () => ({ command: 'codex' }), isClaudeCliProvider: () => false,
+ buildCliSpawnConfig: () => f.cliConfig || ({ command: 'codex' }), isClaudeCliProvider: () => false,
isTuiProvider: () => false, getClaudeSettingsEnv: async () => ({}),
spawnDirectly: vi.fn(async ({ prompt }) => { f.prompt = prompt; return 'replacement-agent'; }),
}));
@@ -107,7 +107,7 @@ vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettle
import { resumeAgent } from './agentManagement.js';
import { dispatchAgentRun } from './agentSpawnDispatch.js';
import { forceSpawnTask, addTask, getTaskById } from './cos.js';
-import { completeAgent } from './cosAgentLifecycle.js';
+import { completeAgent, updateAgent } from './cosAgentLifecycle.js';
import { spawnDirectly } from './agentCliSpawning.js';
import { setUseRunner } from './agentState.js';
import { updateClaimOwnership } from './cosClaimOwnership.js';
@@ -118,7 +118,7 @@ const reviewers = ['provider:antigravity-cli'];
const reviewConfig = { reviewers, optionalReviewers: reviewers, reviewerMaxRounds: { 'provider:antigravity-cli': 2 },
reviewerModels: { 'provider:antigravity-cli': 'gemini-3.8-flash' }, reviewerEfforts: { 'provider:antigravity-cli': 'low' } };
beforeEach(() => {
- vi.clearAllMocks(); setUseRunner(false); f.prompt = null;
+ vi.clearAllMocks(); setUseRunner(false); f.prompt = null; f.cliConfig = null;
f.tasks = { original: { id: 'original', taskType: 'user', status: 'blocked', description: CLAIM_PROSE,
metadata: { claimFlow: true, swarmCount: 6, ...reviewConfig, reviewLoop: true, useWorktree: false, openPR: false,
prompt: CLAIM_PROSE, blockedCategory: 'agent-paused', pausedAgentId: 'prior', app: 'example' } } };
@@ -196,3 +196,18 @@ describe('claim resume contract through spawn', () => {
expect(f.state).toEqual(before);
});
});
+
+it('pins a security scanner grant to effective CLI settings and registers aliased task eligibility', async () => {
+ setUseRunner(true);
+ f.cliConfig = { command: 'codex', args: ['--model', 'saved-model', '-c', 'model_reasoning_effort=high'] };
+ const task = f.tasks.original = { id: 'original', taskType: 'security', description: 'Synthetic source audit',
+ metadata: { useWorktree: false, openPR: false, effort: 'medium' } };
+ const spawnViaRunner = vi.fn();
+ await dispatchAgentRun({ task, agentId: 'agent-scanner', instanceId: 'instance-example', toolExecution: { id: 'exec-example' }, laneName: 'standard',
+ blockAndBail: message => { throw new Error(JSON.stringify(message)); }, cleanupOnError: message => { throw new Error(message); },
+ }, { spawnViaRunner });
+ expect(spawnViaRunner).toHaveBeenCalledWith('agent-scanner', task, expect.objectContaining({
+ securityScanGrant: { model: 'saved-model', effort: 'high', auth: 'chatgpt', maxCostUsd: 2, timeLimitSeconds: 180 },
+ }));
+ expect(updateAgent).toHaveBeenCalledWith('agent-scanner', { metadata: expect.objectContaining({ taskAnalysisType: 'security', securityScanGrant: expect.any(Object) }) });
+});
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index c869832fc7..e9081d06f3 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -1054,7 +1054,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t
contractSections.push(UNATTENDED_RUN_RULE);
if (task.metadata?.prCompletion === PR_COMPLETIONS.DRAFT) contractSections.push(DRAFT_PR_RULE);
if (isUiAuditTask(task)) contractSections.push(UI_AUDIT_RUNTIME_RULE);
- const securityAuditRuntime = buildSecurityAuditRuntimeSection(task, { providerId, providerCommand });
+ const securityAuditRuntime = buildSecurityAuditRuntimeSection(task, { providerId, providerCommand, agentId });
if (securityAuditRuntime) contractSections.push(securityAuditRuntime);
// --- Issue filing labels and planner attribution --------------------------
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 4496c52637..3d9ca25c3a 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -693,7 +693,9 @@ describe('buildLightContextPrompt', () => {
expect(prompt.userPrompt).toContain('Custom security mission');
expect(prompt.systemPrompt).toContain('## Codex Security Audit Runtime');
- expect(prompt.systemPrompt).toContain('--auth chatgpt --headless --json');
+ expect(prompt.systemPrompt).toContain('/security-scan');
+ expect(prompt.systemPrompt).toContain('subscription ChatGPT authentication');
+ expect(prompt.systemPrompt).not.toContain('npx --yes');
expect(prompt.systemPrompt).toContain('deliver supported findings even when another probe is blocked');
expect(prompt.systemPrompt).toContain('## Completion (No Code Output)');
expect(prompt.systemPrompt).toContain('## Required audit assessment handoff');
diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.js
index 4c5cd16531..8bc6a1f51a 100644
--- a/server/services/agentRunnerSync.js
+++ b/server/services/agentRunnerSync.js
@@ -67,6 +67,10 @@ export async function syncRunnerAgents() {
let syncedCount = 0;
for (const agent of agents) {
+ if (agent.securityScan) {
+ const { persistAgentSecurityScan } = await import('./agentSecurityScan.js');
+ await persistAgentSecurityScan(agent.id, agent.securityScan);
+ }
// A stale runner handle (listed, process gone) is not a survivor to
// re-adopt — adopting it would put it in runnerAgents and the orphan
// sweep would treat that local map as ownership. Live rows still sync.
diff --git a/server/services/agentSecurityScan.js b/server/services/agentSecurityScan.js
new file mode 100644
index 0000000000..034361aaf1
--- /dev/null
+++ b/server/services/agentSecurityScan.js
@@ -0,0 +1,56 @@
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { getAgentRecord, updateAgent } from './cosAgentLifecycle.js';
+import { getAgentDir } from './cosAgentIndex.js';
+import { requestSecurityScanViaRunner } from './cosRunnerClient.js';
+import { parseRunnerSecurityScanEvidence } from '../lib/securityScanEvidence.js';
+import { ServerError } from '../lib/errorHandler.js';
+
+export async function persistAgentSecurityScan(agentId, value) {
+ const evidence = parseRunnerSecurityScanEvidence(value);
+ if (!evidence) return null;
+ const terminal = !['not-run', 'running'].includes(evidence.status);
+ const executionInterruption = evidence.status === 'refused'
+ ? { category: 'content-refusal', source: 'security-scanner', at: new Date().toISOString() } : null;
+ const updated = await updateAgent(agentId, { metadata: { securityScan: evidence, ...(terminal ? { securityScanControl: null } : {}), ...(executionInterruption ? { executionInterruption } : {}) } });
+ return updated?.metadata?.securityScan || evidence;
+}
+
+async function readSavedEvidence(agent) {
+ const date = agent.completedAt?.slice(0, 10);
+ for (const dir of [getAgentDir(agent.id, date), getAgentDir(agent.id)]) {
+ const value = await readFile(join(dir, 'security-scan.json'), 'utf8').then(JSON.parse).catch(() => null);
+ const evidence = parseRunnerSecurityScanEvidence(value);
+ if (evidence) return evidence;
+ }
+ return parseRunnerSecurityScanEvidence(agent.metadata?.securityScan);
+}
+
+// Called before every completion, including user termination and recovery.
+// The runner file is a recovery receipt inside the existing agent archive;
+// the ordinary agent metadata remains the card's authoritative record.
+export async function settleAgentSecurityScan(agentId) {
+ const agent = await getAgentRecord(agentId);
+ if (!agent || agent.metadata?.taskAnalysisType !== 'security' || !agent.metadata?.useRunner) return null;
+ let evidence;
+ let unreachable = false;
+ try { evidence = (await requestSecurityScanViaRunner(agentId, { stop: true })).evidence; }
+ catch (err) { unreachable = true; console.warn(`⚠️ Scanner cleanup could not be confirmed for ${agentId} (${err.status || 'runner-unreachable'})`); }
+ evidence = parseRunnerSecurityScanEvidence(evidence) || await readSavedEvidence(agent);
+ if (unreachable && evidence?.status === 'running') {
+ // Connection loss is a server observation, never a forged runner revision.
+ await updateAgent(agentId, { metadata: { securityScanControl: { status: 'interrupted', cleanup: 'unconfirmed' } } });
+ return { ...evidence, status: 'interrupted', cleanup: 'unconfirmed' };
+ }
+ return evidence ? persistAgentSecurityScan(agentId, evidence) : null;
+}
+
+export async function runAgentSecurityScan(agentId, input) {
+ const agent = await getAgentRecord(agentId);
+ if (!agent || agent.status !== 'running' || agent.metadata?.taskAnalysisType !== 'security' || !agent.metadata?.useRunner) {
+ throw new ServerError('Security scanner requires its active runner-owned audit', { status: 409 });
+ }
+ const result = await requestSecurityScanViaRunner(agentId, { input });
+ await persistAgentSecurityScan(agentId, result.evidence);
+ return result;
+}
diff --git a/server/services/agentSpawnDispatch.js b/server/services/agentSpawnDispatch.js
index 8396a7cace..2e51d7ef67 100644
--- a/server/services/agentSpawnDispatch.js
+++ b/server/services/agentSpawnDispatch.js
@@ -11,7 +11,7 @@ import { isAuditTaskType } from '../lib/auditCatalog.js';
import { resolveTaskHookType } from './taskTypeHooks.js';
import { capturePrimaryCheckoutState } from '../lib/primaryCheckoutGuard.js';
import { buildAgentPrompt, getAppWorkspace, isClaimFlowTask, promptOpensOwnPr } from './agentPromptBuilder.js';
-import { isOllamaClaudeProvider, isClaudeCommand } from '../lib/providerModels.js';
+import { isOllamaClaudeProvider, isClaudeCommand, isCodexProvider } from '../lib/providerModels.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';
import { dropUnsupportedOllamaThinking } from './ollamaAgentContext.js';
@@ -25,7 +25,8 @@ import { PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from '../lib/agentExecutionPr
import { formatPublicReviewInputPrompt } from '../lib/modelAbuseGuard.js';
import { validatePublicReviewModel } from './modelAbuseGuard.js';
import { loadPublicReviewSpawnInput } from './publicReviewSpawnInput.js';
-import { registerAgent } from './cosAgentLifecycle.js';
+import { securityScanGrantFromArgs } from '../lib/securityScanEvidence.js';
+import { registerAgent, updateAgent } from './cosAgentLifecycle.js';
import { createAgentRun } from './agentRunTracking.js';
import { useRunner } from './agentState.js';
import { cloudSwarmThreadCapacity, localEndpointOfProvider, providerBaseUrl } from './cosLocalEndpointSlots.js';
@@ -269,6 +270,10 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {
const cliConfig = !spawnHeadless
? buildTuiSpawnConfig(runProvider, selectedModel, { systemPromptFile, effort: taskEffort, maxConcurrentThreads, safetyProfile })
: buildCliSpawnConfig(runProvider, selectedModel, cliSettingsEnv, { systemPromptFile, effort: taskEffort, maxConcurrentThreads, safetyProfile });
+ const securityScanGrant = dispatchUseRunner && resolveTaskHookType(task) === 'security' && isCodexProvider(runProvider)
+ ? securityScanGrantFromArgs(cliConfig.args)
+ : null;
+ if (securityScanGrant) await updateAgent(agentId, { metadata: { securityScanGrant, taskAnalysisType: 'security' } });
emitLog('success', `Spawning agent for task ${task.id}`, {
agentId,
@@ -297,10 +302,11 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {
prOpenedBy,
useDurableRunner: dispatchUseRunner,
safetyProfile,
+ securityScanGrant,
});
}
if (dispatchUseRunner) {
- return await spawnViaRunner(agentId, task, { prompt, workspacePath, model: selectedModel, provider: runProvider, runId, cliConfig, executionId: toolExecution.id, laneName });
+ return await spawnViaRunner(agentId, task, { prompt, workspacePath, model: selectedModel, provider: runProvider, runId, cliConfig, executionId: toolExecution.id, laneName, securityScanGrant });
}
return await spawnDirectly({
agentId,
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 3907adb567..0602944aac 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -118,6 +118,7 @@ export async function createAgentTuiSession({
forgeTokenEnv = {},
agentApiEnv = {},
doneSentinelPath = null,
+ securityScanGrant = null,
launchShape,
safetyProfile = null,
onData,
@@ -180,6 +181,7 @@ export async function createAgentTuiSession({
envVars: env,
providerAuth: cliProviderAuthDescriptor(provider),
doneSentinelPath,
+ securityScanGrant,
onData,
onExit,
});
@@ -272,6 +274,7 @@ export async function spawnTuiAgent({
prOpenedBy,
leanMode = false,
useDurableRunner = false,
+ securityScanGrant = null,
// The public-content execution profile this run enforces (null for an
// ordinary agent task). Threaded through to the session so the PTY child
// gets the same allowlisted environment its headless sibling would.
@@ -474,6 +477,7 @@ export async function spawnTuiAgent({
forgeTokenEnv,
agentApiEnv,
doneSentinelPath,
+ securityScanGrant,
launchShape,
safetyProfile,
onData: (...args) => maintenance.withResource('agent', agentId, () => controller.handleData(...args)),
@@ -617,6 +621,7 @@ export async function spawnTuiAgent({
executionId,
laneName,
tuiSessionId: sessionId,
+ refuseScanner: controller.refuseScanner,
});
// Arm prompt delivery, the provider-signal gates and the sentinel watcher.
diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.js
index 338aaf1afe..132d9bc713 100644
--- a/server/services/agentTuiSpawning/sessionController.js
+++ b/server/services/agentTuiSpawning/sessionController.js
@@ -1948,6 +1948,14 @@ export function createTuiSessionController({
return {
handleData,
handleExit,
+ refuseScanner: () => {
+ terminalRefusal = { category: 'content-refusal', origin: 'provider', permanent: true, actionable: false, requiresFallback: false,
+ message: 'Security scanner safety refusal; automatic continuation, retries and provider fallback are disabled.' };
+ executionInterruption = { category: 'content-refusal', source: 'security-scanner' };
+ immediateFallbackAnalysis = terminalRefusal;
+ pasteController?.cancel();
+ return finish({ success: false, exitCode: 1, error: terminalRefusal.message, reason: 'content-refusal' });
+ },
markCommandInjected: () => { commandInjected = true; },
isTerminal,
finish,
diff --git a/server/services/agentTuiSpawning/sessionController.test.js b/server/services/agentTuiSpawning/sessionController.test.js
index 5acf16bc71..08cf1d3d1b 100644
--- a/server/services/agentTuiSpawning/sessionController.test.js
+++ b/server/services/agentTuiSpawning/sessionController.test.js
@@ -284,6 +284,19 @@ describe('Codex terminal model-access rejection (#9319)', () => {
return subject;
};
+ it('stops all recovery when a trusted scanner refusal arrives before the outer TUI exits', async () => {
+ const { controller, ...seams } = await submitted();
+ seams.write.mockClear();
+ seams.paste.mockClear();
+ await controller.refuseScanner();
+ await vi.advanceTimersByTimeAsync(STALL_NUDGE_IDLE_MS + 10000);
+ expect(seams.write).not.toHaveBeenCalled();
+ expect(seams.paste).not.toHaveBeenCalled();
+ expect(seams.finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({ success: false,
+ executionInterruption: { category: 'content-refusal', source: 'security-scanner' },
+ errorAnalysis: expect.objectContaining({ requiresFallback: false }) }));
+ });
+
it('latches a policy refusal while persistence is pending, outranking a concurrent success without nudges', async () => {
const { controller, updateAgent, paste, write, finalizeAgent, kill } = await submitted();
let rejectWrite;
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index 2b7beb3e3d..7ee3fff95a 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -53,6 +53,15 @@ export async function updateAgent(agentId, updates) {
return null;
}
+ // Socket events, reconnect snapshots and finalization may arrive out of
+ // order. Runner receipts outrank agent claims and only advance revision.
+ const previousScan = state.agents[agentId].metadata?.securityScan;
+ const incomingScan = updates.metadata?.securityScan;
+ if (previousScan?.source === 'runner' && incomingScan
+ && (incomingScan.source !== 'runner' || incomingScan.sequence <= previousScan.sequence)) {
+ updates = { ...updates, metadata: { ...updates.metadata, securityScan: previousScan } };
+ }
+
// Merge metadata if present in updates
if (updates.metadata) {
state.agents[agentId] = {
@@ -127,6 +136,12 @@ async function archiveCompletedAgent(agentId, agent) {
}
export async function completeAgent(agentId, result = {}) {
+ const existing = await getAgentRecord(agentId);
+ if (existing?.metadata?.taskAnalysisType === 'security' && existing.metadata.useRunner) {
+ const { settleAgentSecurityScan } = await import('./agentSecurityScan.js');
+ const scanner = await settleAgentSecurityScan(agentId);
+ if (scanner?.status === 'refused') result = { ...result, success: false, error: 'Security scanner safety refusal; automatic retry stopped' };
+ }
// Set inside the lock when the record is already terminal, so the post-lock
// tail below (budget ledger + `agent:completed`) is skipped too — see #3384.
let alreadyCompleted = false;
diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.js
index aecff73658..4dc4103b4e 100644
--- a/server/services/cosAgentLifecycle.test.js
+++ b/server/services/cosAgentLifecycle.test.js
@@ -61,6 +61,7 @@ vi.mock('fs/promises', async (importOriginal) => {
vi.mock('./cosRunnerClient.js', () => ({
getActiveAgentsFromRunner: vi.fn().mockResolvedValue([]),
+ requestSecurityScanViaRunner: vi.fn(),
}));
import { getAgent, getAgentPrompt, createAgentOutputBatcher, completeAgent, updateAgent, registerAgent, cleanupZombieAgents, filterLiveAgentIds, readAgentRecordOrUnreadable, AGENT_RECORD_UNREADABLE, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';
@@ -68,7 +69,8 @@ import { saveState, loadState, readAgentsStateForSafetyCheck } from './cosState.
import { recordDomainUsage } from './domainUsage.js';
import { cosEvents } from './cosEvents.js';
import { loadAgentIndex } from './cosAgentIndex.js';
-import { getActiveAgentsFromRunner } from './cosRunnerClient.js';
+import { getActiveAgentsFromRunner, requestSecurityScanViaRunner } from './cosRunnerClient.js';
+import { persistAgentSecurityScan } from './agentSecurityScan.js';
import { activeAgents, runnerAgents, spawningTasks } from './agentState.js';
describe('cosAgentLifecycle', () => {
@@ -85,6 +87,38 @@ describe('cosAgentLifecycle', () => {
await rm(mockCosState.agentsDir, { recursive: true, force: true });
});
+ it('keeps trusted terminal scanner receipts across stale reconnects, agent claims and missing completion', async () => {
+ mockCosState.state.stats = { agentsSpawned: 0, agentsCompleted: 0, agentsFailed: 0 };
+ await registerAgent('agent-scanner', 'task-example', { taskAnalysisType: 'security', useRunner: true });
+ const evidence = { version: 1, source: 'runner', sequence: 3, status: 'refused', model: 'example-model', effort: 'medium', auth: 'chatgpt',
+ maxCostUsd: 2, estimatedCostUsd: null, timeLimitSeconds: 180, exitCode: 143,
+ artifacts: { findings: false, coverage: false }, cleanup: 'confirmed' };
+ await persistAgentSecurityScan('agent-scanner', evidence);
+ await persistAgentSecurityScan('agent-scanner', { ...evidence, sequence: 2, status: 'running', exitCode: null });
+ await updateAgent('agent-scanner', { metadata: { securityScan: { ...evidence, source: 'agent-report', status: 'completed', exitCode: 0 } } });
+ vi.mocked(requestSecurityScanViaRunner).mockResolvedValue({ evidence });
+ await completeAgent('agent-scanner', { success: true });
+ const agent = await getAgent('agent-scanner');
+ expect(agent.metadata.securityScan).toEqual(evidence);
+ expect(agent.metadata.executionInterruption.category).toBe('content-refusal');
+ expect(agent.result.success).toBe(false);
+ expect(agent.result.error).toContain('safety refusal');
+ });
+
+ it('records uncertain cleanup if the runner disappears before outer completion', async () => {
+ mockCosState.state.stats = { agentsSpawned: 0, agentsCompleted: 0, agentsFailed: 0 };
+ await registerAgent('agent-scanner', 'task-example', { taskAnalysisType: 'security', useRunner: true });
+ await persistAgentSecurityScan('agent-scanner', { version: 1, source: 'runner', sequence: 2, status: 'running', model: 'example-model', effort: 'medium', auth: 'chatgpt',
+ maxCostUsd: 2, estimatedCostUsd: null, timeLimitSeconds: 180, exitCode: null,
+ artifacts: { findings: null, coverage: null }, cleanup: 'unconfirmed' });
+ vi.mocked(requestSecurityScanViaRunner).mockRejectedValue(new Error('synthetic runner loss'));
+ await completeAgent('agent-scanner', { success: false, error: 'Terminated' });
+ expect((await getAgent('agent-scanner')).metadata).toMatchObject({ securityScan: { sequence: 2, status: 'running', exitCode: null }, securityScanControl: { status: 'interrupted', cleanup: 'unconfirmed' } });
+ const observed = (await getAgent('agent-scanner')).metadata.securityScan;
+ await persistAgentSecurityScan('agent-scanner', { ...observed, sequence: 3, status: 'refused', exitCode: 143, cleanup: 'confirmed' });
+ expect((await getAgent('agent-scanner')).metadata).toMatchObject({ securityScan: { status: 'refused', cleanup: 'confirmed' }, securityScanControl: null });
+ });
+
it('keeps archived prompts readable after state eviction, with UTF-8 byte counts', async () => {
const id = 'agent-archived-prompt';
const date = '2026-01-01';
diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.js
index 5cfbabe69c..766e942ec6 100644
--- a/server/services/cosRunnerClient.js
+++ b/server/services/cosRunnerClient.js
@@ -157,6 +157,7 @@ export function initCosRunnerConnection() {
socket.on('agent:output', (data) => dispatch('agent:output', data));
socket.on('agent:completed', (data) => dispatch('agent:completed', data));
socket.on('agent:error', (data) => dispatch('agent:error', data));
+ socket.on('agent:security-scan', (data) => dispatch('agent:security-scan', data));
socket.on('agent:btw', (data) => dispatch('agent:btw', data));
socket.on('tui:output', (data) => dispatchTuiEvent('tui:output', data));
socket.on('tui:exit', (data) => dispatchTuiEvent('tui:exit', data));
@@ -413,6 +414,7 @@ export async function spawnAgentViaRunner(options) {
model,
envVars,
providerAuth,
+ securityScanGrant,
// New: CLI-agnostic parameters
cliCommand,
cliArgs,
@@ -428,6 +430,7 @@ export async function spawnAgentViaRunner(options) {
model,
envVars,
providerAuth,
+ securityScanGrant,
cliCommand,
cliArgs,
claudePath
@@ -449,6 +452,17 @@ export async function spawnAgentViaRunner(options) {
return readRunnerJson(response);
}
+export async function requestSecurityScanViaRunner(agentId, { input, stop = false } = {}) {
+ const path = `/agents/${encodeURIComponent(agentId)}/security-scan${stop ? '/stop' : ''}`;
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}${path}`, {
+ method: input || stop ? 'POST' : 'GET',
+ ...(input ? { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) } : {}),
+ }, input ? 190000 : 15000);
+ const result = await readRunnerJson(response);
+ if (!response.ok) throw Object.assign(new Error(result.error || 'Scanner runner unavailable'), { status: response.status });
+ return result;
+}
+
/**
* Get list of active agents from runner
*/
diff --git a/server/services/promptSections/securityAudit.js b/server/services/promptSections/securityAudit.js
index 39025ce26b..ad1e429e13 100644
--- a/server/services/promptSections/securityAudit.js
+++ b/server/services/promptSections/securityAudit.js
@@ -1,9 +1,11 @@
import { isCodexProvider } from '../../lib/providerModels.js';
import { resolveTaskHookType } from '../taskTypeHooks.js';
+import { localApiBaseUrl } from '../../lib/networkExposure.js';
+import { agentApiCurl } from '../../lib/agentApiToken.js';
// Resolve at dispatch, rather than changing only the shipped security mission:
// customized prompts and already-queued audits need the same scanner guidance.
-export function buildSecurityAuditRuntimeSection(task, { providerId, providerCommand } = {}) {
+export function buildSecurityAuditRuntimeSection(task, { providerId, providerCommand, agentId } = {}) {
// Match the identity used by source evidence, completion and score recording.
const taskType = resolveTaskHookType(task);
// An explicit executable wins over a stale provider id. Custom ids still
@@ -11,19 +13,20 @@ export function buildSecurityAuditRuntimeSection(task, { providerId, providerCom
const provider = { id: providerCommand ? null : providerId, command: providerCommand };
if (taskType !== 'security' || !isCodexProvider(provider)) return '';
+ const endpoint = `/api/cos/agents/${encodeURIComponent(agentId || '<agent-id>')}/security-scan`;
+ const command = agentApiCurl({ apiBase: localApiBaseUrl(), path: endpoint });
return `## Codex Security Audit Runtime
-This security audit is running in a Codex agent. Run the scanner phase through Codex Security after reading the target's threat model and completing the required repository-wide discovery. Use an available Codex Security scan capability, or the official local CLI; opening Codex Security Cloud alone does not run a scan.
+After reading the target threat model and completing repository-wide discovery, request the scanner phase through the PortOS runner. Write a private JSON request file containing only:
+{ "prompt": "The actual threat model, selected audit area and report-only restrictions", "paths": ["relative/source/path"], "knowledgeBase": ["AGENTS.md"] }
+Choose real workspace-relative files; include available architecture/security documents in knowledgeBase. Keep outer issue-filing and completion commands out of the scanner prompt.
-- For the CLI, inspect its installed help/version, then run a report-only scan non-interactively: \`npx --yes @openai/codex-security scan "<repo-root>" --auth chatgpt --headless --json --model "<authorized-model>" --effort "<authorized-effort>" --output-dir "<private-dir-outside-repo>"\`. Resolve the placeholders first, close stdin, and keep scan artifacts/state outside the repository with private permissions. Remove unrelated application/provider credentials from the scanner's child environment, including PORTOS_API_TOKEN, while preserving its authorized scanner sign-in and required runtime variables; never print credentials. Use existing authorized credentials; never start login/device-auth, change accounts, purchase access, or wait for a human. Do not silently switch to an environment API key.
-- Supply the project's security/architecture documents with \`--knowledge-base\` and a scoped \`--scan-prompt-file\` describing the actual threat model, selected audit area and report-only restrictions. Keep outer issue-filing and completion commands out of that file. Explicitly select an accessible model and effort within this run's configured permissions, quota and budget before starting; do not inherit more expensive CLI defaults or launch extra workers/categories. If that cannot be established, record the limitation and continue permitted source review.
-- The scanner supplies evidence, not authority. Preserve the task's file-issues versus remediation mode, independent review, validation and delivery requirements. Never use \`--patch\`, \`--create-pr\`, \`publish\`, or hook installation as part of the scan. Check the checkout's branch/status before and after; report unexpected changes without discarding anyone's work. Read findings and coverage artifacts, challenge reachability against callers/tests/history, redact evidence, and de-duplicate before filing.
-- A cybersecurity/content-policy refusal is terminal for this request: stop clearly, preserve evidence, and do not automatically continue, retry, rephrase to evade the refusal, or switch providers. This overrides recovery guidance below.
-- If the module is missing, access is denied, a permission review refuses an action, or a quota/time limit stops the scan, preserve completed evidence and name the concrete failure. Do not repeat a refused action through another tool or treat a dry run as proof of scan access. Continue independent permitted inspection and deliver supported findings even when another probe is blocked; do not strand an unattended run on a setup or approval prompt.
-- Report scanner execution separately from delivery and quality assessment. Preserve the actual resolved scanner model/effort/auth, configured limits (including wrapper time limits), estimated API-equivalent cost when reported, process exit, and whether findings/coverage artifacts were actually saved. A successful outer task or saved assessment does not make an interrupted scanner successful. Do not increase limits or infer charges from estimates.
-- Include one single-line SCANNER_STATUS_JSON in the completion sentinel summary and final response. Replace values with observed scanner evidence; null means unknown, including a budget that was never established. Never include paths, credentials, findings or raw logs in this record:
-SCANNER_STATUS_JSON: {"version":1,"status":"not-run","model":null,"effort":null,"auth":"unknown","maxCostUsd":null,"estimatedCostUsd":null,"timeLimitSeconds":null,"exitCode":null,"artifacts":{"findings":null,"coverage":null}}
-Allowed status: not-run, unavailable, completed, failed, time-limit, budget-limit, refused. Use completed only for confirmed successful scanner exit; report time-limit/budget-limit even when partial artifacts exist. Artifacts are true only when verified present, false when verified absent, otherwise null.
-- Finish with the required sentinel and exactly one QUALITY_AUDIT_JSON assessment based on work actually performed. Scanner completion does not certify every file: retain exclusions, deferred areas and uncertainty, and use partial/unavailable coverage when warranted.
+Call once: \`${command} --data-binary @<private-request-file>\`.
+The runner owns the installed Codex Security CLI, enforces this run's resolved model and effort, subscription ChatGPT authentication, a $2 API-equivalent estimated-cost cap and a 180-second scan limit. Those settings cannot be changed in the request. No installation, API-key fallback, additional workers, patching or publication is permitted. Do not invoke a separate CLI, SDK or cloud scan: an unavailable runner/installation/model is a visible limitation, not permission for a different execution path.
-CLI contract: https://learn.chatgpt.com/docs/security/cli`;
+The response contains trusted runner evidence plus a private artifactDirectory. Read any saved findings/coverage there, challenge reachability against callers/tests/history, and preserve this task's remediation/file-issues mode and delivery requirements. Do not call the scanner again after any result or transport error; the runner retains one attempt and its diagnostics independently of your completion. Finish permitted source inspection and deliver supported findings even when another probe is blocked.
+
+A cybersecurity/content-policy refusal is terminal for this request: stop clearly. Do not continue, retry, rephrase to evade a refusal, or switch providers. This overrides recovery guidance below. The runner also stops the outer request on a scanner refusal.
+
+Report scanner execution separately from delivery and quality assessment. Runner-observed model/effort/auth, limits, exit and artifact evidence are authoritative; a saved assessment or successful outer task does not make an interrupted scan successful. Estimated cost is API-equivalent usage, not proof of charges. Do not claim unknown evidence as zero or success. Complete the normal sentinel and exactly one QUALITY_AUDIT_JSON assessment for work actually performed, with partial/unavailable coverage when warranted. SCANNER_STATUS_JSON is a legacy agent-report format; it cannot override runner evidence.
+`;
}
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index ed41cfbd51..9cd9d9ab6a 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -45,7 +45,7 @@ import { handleAgentCompletion } from './agentLifecycle.js';
import { cleanupOrphanedAgents } from './agentManagement.js';
import { completeAgentRun } from './agentRunTracking.js';
import { appendRunEvent } from './agentRunEventLog.js';
-import { runnerAgents, setUseRunner, useRunner } from './agentState.js';
+import { activeAgents, runnerAgents, setUseRunner, useRunner } from './agentState.js';
import { releaseAppReviewMarker } from './appActivity.js';
import { isUpdateInProgress } from './updateChecker.js';
import { loadState } from './cosState.js';
@@ -322,8 +322,9 @@ async function runInitSpawner() {
// in the CoS log stream the UI reads, or a remote install sees the outage
// reported and never its resolution.
emitLog('info', '🔼 CoS Runner came up — promoting agent spawning from direct to runner mode');
- runnerRecovery = recoverRunnerAgents();
}
+ // Refresh receipts even for locally owned agents after a brief socket gap.
+ runnerRecovery = runnerRecovery.then(() => recoverRunnerAgents());
clearTimeout(reconnectDequeueTimer);
reconnectDequeueTimer = setTimeout(() => {
// Resume only once reconciliation has settled, so the dequeue counts the
@@ -385,6 +386,14 @@ async function runInitSpawner() {
}
});
+ onCosRunnerEvent('agent:security-scan', async ({ agentId, evidence }) => {
+ const { persistAgentSecurityScan } = await import('./agentSecurityScan.js');
+ const { parseRunnerSecurityScanEvidence } = await import('../lib/securityScanEvidence.js');
+ const observed = parseRunnerSecurityScanEvidence(evidence);
+ const refusal = observed?.status === 'refused' ? activeAgents.get(agentId)?.refuseScanner?.() : null;
+ await Promise.all([refusal, persistAgentSecurityScan(agentId, evidence)]);
+ });
+
onCosRunnerEvent('agent:completed', async (data) => {
const { agentId, exitCode, success, duration } = data;
const agent = runnerAgents.get(agentId);
diff --git a/server/services/subAgentSpawner.runnerPromotion.test.js b/server/services/subAgentSpawner.runnerPromotion.test.js
index ddcd0e7e9f..3c176db4da 100644
--- a/server/services/subAgentSpawner.runnerPromotion.test.js
+++ b/server/services/subAgentSpawner.runnerPromotion.test.js
@@ -35,6 +35,7 @@ vi.mock('./cosEvents.js', () => ({
vi.mock('./providerStatus.js', () => ({ initProviderStatus: vi.fn().mockResolvedValue(undefined) }));
vi.mock('./agentRunnerSync.js', () => ({ syncRunnerAgents: vi.fn().mockResolvedValue(0) }));
vi.mock('./cosAgentLifecycle.js', () => ({ updateAgent: vi.fn() }));
+vi.mock('./agentSecurityScan.js', () => ({ persistAgentSecurityScan: vi.fn() }));
vi.mock('./agentRunnerOutputBatchers.js', () => ({
getRunnerOutputBatcher: vi.fn(),
flushRunnerOutputBatcher: vi.fn().mockResolvedValue(undefined),
@@ -60,6 +61,7 @@ import { initSpawner } from './subAgentSpawner.js';
import { initCosRunnerConnection } from './cosRunnerClient.js';
import { syncRunnerAgents } from './agentRunnerSync.js';
import { cosEvents, emitLog } from './cosEvents.js';
+import { persistAgentSecurityScan } from './agentSecurityScan.js';
import * as agentState from './agentState.js';
// Read through the module namespace: `useRunner` is reassigned by `setUseRunner`,
@@ -107,6 +109,25 @@ describe('subAgentSpawner — runner promotion (#4134)', () => {
}
});
+ it('owns refusal finalization even when saving the same receipt also fails', async () => {
+ const refusalError = new Error('synthetic refusal finalization outage');
+ const refuseScanner = vi.fn().mockRejectedValue(refusalError);
+ agentState.activeAgents.set('agent-scanner-example', { refuseScanner });
+ vi.mocked(persistAgentSecurityScan).mockRejectedValueOnce(new Error('synthetic receipt outage'));
+ try {
+ await expect(runnerHandlers.get('agent:security-scan')({ agentId: 'agent-scanner-example', evidence: {
+ version: 1, source: 'runner', sequence: 2, status: 'refused', model: 'example-model', effort: 'medium', auth: 'chatgpt',
+ maxCostUsd: 2, estimatedCostUsd: null, timeLimitSeconds: 180, exitCode: null,
+ artifacts: { findings: null, coverage: null }, cleanup: 'confirmed'
+ } })).rejects.toBe(refusalError);
+ await new Promise(resolve => setImmediate(resolve));
+ expect(refuseScanner).toHaveBeenCalledOnce();
+ expect(persistAgentSecurityScan).toHaveBeenCalledOnce();
+ } finally {
+ agentState.activeAgents.delete('agent-scanner-example');
+ }
+ });
+
it('promotes to runner mode when the runner comes up after the server', () => {
expect(currentMode()).toBe(false);
@@ -125,21 +146,22 @@ describe('subAgentSpawner — runner promotion (#4134)', () => {
expect(promotions[0][0]).toBe('info');
});
- it('reconciles agents a runner that was already up owns, on promotion', () => {
+ it('reconciles agents a runner that was already up owns, on promotion', async () => {
runnerHandlers.get('connection:ready')();
// Adopts only agents this process does not already own, so an agent spawned
// DIRECTLY before the promotion keeps completing through its own close
// handler (`isAgentOwnedLocally`, covered in agentRunnerSync.test.js).
- expect(syncRunnerAgents).toHaveBeenCalledTimes(1);
+ await vi.waitFor(() => expect(syncRunnerAgents).toHaveBeenCalledTimes(1));
});
- it('promotes once — a later reconnect in runner mode does not re-reconcile', () => {
+ it('refreshes runner receipts on each reconnect without promoting twice', async () => {
runnerHandlers.get('connection:ready')();
runnerHandlers.get('connection:ready')();
runnerHandlers.get('connection:ready')();
- expect(syncRunnerAgents).toHaveBeenCalledTimes(1);
+ await vi.waitFor(() => expect(syncRunnerAgents).toHaveBeenCalledTimes(3));
+ expect(vi.mocked(emitLog).mock.calls.filter(([, message]) => /promoting/.test(message))).toHaveLength(1);
});
it('survives a reconciliation failure without leaving the process unpromoted', async () => {