Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: allow scanner input correction before execution
atomantic8d2e6a97ee27
diff --git a/client/src/components/cos/AgentResultLine.jsx b/client/src/components/cos/AgentResultLine.jsxindex 66300f2a5d..239827bf6d 100644--- a/client/src/components/cos/AgentResultLine.jsx+++ b/client/src/components/cos/AgentResultLine.jsx@@ -56,6 +56,8 @@ export function SecurityScanEvidence({ scanner, control }) {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>+ {scanner.status === 'invalid-input' && <div>Input rejected before scanner launch</div>}+ {scanner.preflight && <div>Input rejections: {formatCount(scanner.preflight.rejectedRequests)} · Last: {scanner.preflight.lastError.field} item {formatCount(scanner.preflight.lastError.index + 1)} — {scanner.preflight.lastError.code}</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>diff --git a/client/src/components/cos/AgentResultLine.test.jsx b/client/src/components/cos/AgentResultLine.test.jsxindex 048bcb6848..1562051b27 100644--- a/client/src/components/cos/AgentResultLine.test.jsx+++ b/client/src/components/cos/AgentResultLine.test.jsx@@ -62,3 +62,15 @@ it('distinguishes connection loss from the last trusted runner observation', ()expect(screen.getByText(/interrupted \(runner connection lost\)/)).toBeInTheDocument();expect(screen.getByText('Process cleanup: unconfirmed')).toBeInTheDocument();});++it('keeps input rejection history visible after a corrected scanner execution completes', () => {+ const scanner = { source: 'runner', status: 'invalid-input', auth: 'chatgpt',+ preflight: { rejectedRequests: 1, lastError: { field: 'paths', index: 2, code: 'path-not-found' } } };+ const view = render(<SecurityScanEvidence scanner={scanner} />);+ expect(screen.getByText('Input rejected before scanner launch')).toBeInTheDocument();+ expect(screen.getByText('Input rejections: 1 · Last: paths item 3 — path-not-found')).toBeInTheDocument();+ view.rerender(<SecurityScanEvidence scanner={{ ...scanner, status: 'completed' }} />);+ expect(screen.getByText('Security scanner (runner observed): completed')).toBeInTheDocument();+ expect(screen.queryByText('Input rejected before scanner launch')).not.toBeInTheDocument();+ expect(screen.getByText('Input rejections: 1 · Last: paths item 3 — path-not-found')).toBeInTheDocument();+});diff --git a/docs/SECURITY_SCANNER_RUNTIME.md b/docs/SECURITY_SCANNER_RUNTIME.mdindex be39172f98..80aede29b5 100644--- a/docs/SECURITY_SCANNER_RUNTIME.md+++ b/docs/SECURITY_SCANNER_RUNTIME.md@@ -1,12 +1,29 @@# Codex security scanner runtime-Codex security audits request one scanner attempt through the authenticated+Codex security audits request one scanner execution through the authenticated`POST /api/cos/agents/:id/security-scan` host-control endpoint. The request containsthe actual audit prompt, workspace-relative source paths, and optional knowledgebase paths. The runner resolves paths inside the assigned workspace and launchesan already installed `@openai/codex-security` CLI. It never installs a package orselects another provider after a failure.+Before execution, missing, malformed or out-of-workspace context paths produce+`invalid-input` evidence. This records a rejection count and the last field,+zero-based item index and bounded error code, without publishing paths or raw+errors. After the receipt is saved, the active audit may verify and resubmit+corrected paths. Concurrent requests share the current validation result rather+than queueing executions. Malformed request bodies are rejected by the HTTP+schema before reserving an execution.++Only explicit `invalid-input` evidence permits correction. Runtime failures,+transport errors, missing installations and every result after execution+reservation remain terminal. The `running` receipt is durable before the first+child spawn; a crash in that gap cannot authorize another launch. Stop revokes+correction, and a restarted runner never re-registers an existing grant, even+one with only preflight evidence. A new audit requires a separate grant.+Input rejection diagnostics remain in subsequent running and terminal receipts+so a successful correction does not erase validation history.+The immutable dispatch grant uses the effective outer Codex command's model andeffort, including saved flags and supported-effort clamping. Missing or conflictingpins make the scanner unavailable. The bounded workflow retains explicit ChatGPTdiff --git a/server/cos-runner/securityScan.js b/server/cos-runner/securityScan.jsindex b5dc5b1e37..58a3f520d3 100644--- a/server/cos-runner/securityScan.js+++ b/server/cos-runner/securityScan.js@@ -35,19 +35,27 @@ async function resolveInstalledSecurityScanner({ home = homedir(), root = procesreturn null;}-async function scopePaths(cwd, values) {+async function scopePaths(cwd, values, field) {const root = await realpath(cwd);- return Promise.all(values.map(async value => {- const path = await realpath(resolve(root, value));+ return Promise.all(values.map(async (value, index) => {+ const invalid = code => Object.assign(failure('Invalid scanner context path', 400), {+ preflight: { field, index, code },+ });+ if (value.includes('\0')) throw invalid('invalid-path');+ const path = await realpath(resolve(root, value)).catch(err => {+ if (['ENOENT', 'ENOTDIR'].includes(err.code)) throw invalid('path-not-found');+ if (['ENAMETOOLONG', 'ELOOP'].includes(err.code)) throw invalid('invalid-path');+ throw err;+ });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);+ throw invalid('outside-workspace');}return path;}));}-/** One scanner attempt, owned by the runner rather than by an agent shell. */+/** One scanner execution, with correctable input checks owned by the runner. */export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, trackWork = fn => fn(),resolveCli = resolveInstalledSecurityScanner, spawnProcess = spawn, kill = killProcessTree,environment = process.env, tempRoot = tmpdir(), graceMs = 5000, cleanupGroup = cleanupSecurityScanGroup } = {}) {@@ -110,6 +118,13 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, tif (!entry.terminal) entry.stopReason ||= reason;entry.cancel?.();await entry.promise;+ // An idle correctable grant has no request-finally left to publish Stop.+ if (!entry.promise && !entry.terminal) {+ entry.evidence.status = entry.stopReason;+ entry.terminal = true;+ await persist(id, entry);+ }+ await entry.writes;return entry.evidence;};const start = (id, input) => {@@ -117,19 +132,20 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, tconst 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;+ // Reserve validation synchronously too: overlapping inputs share its result.+ // Only a durably recorded input rejection releases this reservation. Once+ // launch is reserved, duplicate/lost-response requests replay that attempt.+ if (entry.promise) 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;+ let invalidInput = false;try {const [paths, knowledgeBase, cli] = await Promise.all([- scopePaths(agent.workspacePath, request.paths), scopePaths(agent.workspacePath, request.knowledgeBase), resolveCli(),+ scopePaths(agent.workspacePath, request.paths, 'paths'), scopePaths(agent.workspacePath, request.knowledgeBase, '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 }; }@@ -146,6 +162,9 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, tconst 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();+ // Durable reservation precedes the first child spawn. A crash in this+ // gap stays fail-closed; recovery never grants another execution.+ entry.attempted = true;entry.evidence.status = 'running';entry.evidence.cleanup = 'unconfirmed';await persist(id, entry);@@ -246,9 +265,16 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, tconst confirmed = await cleanupGroup(entry.owner).catch(() => false);entry.evidence.cleanup = confirmed ? 'confirmed' : 'unconfirmed';}- entry.evidence.status = entry.stopReason || 'unavailable';+ invalidInput = Boolean(err.preflight && !entry.attempted);+ if (invalidInput) {+ entry.evidence.preflight = {+ rejectedRequests: (entry.evidence.preflight?.rejectedRequests || 0) + 1,+ lastError: err.preflight,+ };+ }+ entry.evidence.status = entry.stopReason || (invalidInput ? 'invalid-input' : 'unavailable');// No provider text, paths or credentials in shared logs.- console.warn(`⚠️ Security scanner ${id} could not complete (${err.code || 'runtime-error'})`);+ console.warn(`⚠️ Security scanner ${id} could not complete (${err.preflight?.code || err.code || 'runtime-error'})`);} finally {clearTimeout(forceTimer);clearTimeout(deadline);@@ -258,15 +284,25 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, tentry.child?.stdout.destroy();entry.child?.stderr.destroy();entry.child?.unref?.();- entry.terminal = true;+ entry.terminal = !invalidInput || Boolean(entry.stopReason);entry.cancel = null;- try { await persist(id, entry); }+ try {+ await persist(id, entry);+ // Stop can arrive while an input rejection is being saved. Preserve+ // it before releasing the request, rather than reopening the grant.+ if (invalidInput && entry.stopReason && entry.evidence.status !== entry.stopReason) {+ entry.evidence.status = entry.stopReason;+ entry.terminal = true;+ await persist(id, entry);+ }+ if (invalidInput && !entry.stopReason) entry.promise = null;+ }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 { evidence: structuredClone(entry.evidence), artifactDirectory: directory || null };});return entry.promise;};diff --git a/server/cos-runner/securityScan.test.js b/server/cos-runner/securityScan.test.jsindex 79edca43fe..fd83c9fcf6 100644--- a/server/cos-runner/securityScan.test.js+++ b/server/cos-runner/securityScan.test.js@@ -44,6 +44,150 @@ function setup({ finish, ...overrides } = {}) {const input = { prompt: 'Report-only source audit of the selected boundary.', paths: ['.'], knowledgeBase: [] };describe.skipIf(process.platform === 'win32')('runner-owned scanner lifecycle', () => {+ it.each(['paths', 'knowledgeBase'])('retains %s rejection evidence while allowing one corrected execution', async field => {+ const h = setup();+ await h.manager.register('agent-example', grant);+ const rejected = await h.manager.start('agent-example', { ...input, [field]: ['missing-source.js'] });+ expect(rejected).toMatchObject({ artifactDirectory: null, evidence: { status: 'invalid-input', cleanup: 'not-needed',+ preflight: { rejectedRequests: 1, lastError: { field, index: 0, code: 'path-not-found' } } } });+ expect(h.spawnProcess).not.toHaveBeenCalled();+ expect(JSON.parse(await readFile(join(root, 'agents/agent-example/security-scan.json'), 'utf8'))).toEqual(rejected.evidence);+ const run = h.manager.start('agent-example', input);+ const { child } = await h.spawned;+ child.emit('close', 0, null);+ const completed = await run;+ expect(completed.evidence).toMatchObject({ status: 'completed', preflight: rejected.evidence.preflight });+ expect(rejected.evidence.status).toBe('invalid-input');+ expect(h.evidence.map(e => e.status)).toEqual(['not-run', 'invalid-input', 'running', 'completed']);+ expect(h.spawnProcess).toHaveBeenCalledOnce();+ expect(await h.manager.start('agent-example', input)).toEqual(completed);+ });++ it('shares concurrent validation and corrected requests without consuming or duplicating execution', async () => {+ const h = setup();+ await h.manager.register('agent-example', grant);+ const first = h.manager.start('agent-example', { ...input, paths: ['missing.js'] });+ expect(h.manager.start('agent-example', input)).toBe(first);+ expect((await first).evidence.status).toBe('invalid-input');+ const corrected = h.manager.start('agent-example', input);+ expect(h.manager.start('agent-example', input)).toBe(corrected);+ const { child } = await h.spawned;+ child.emit('close', 0, null);+ await corrected;+ expect(h.spawnProcess).toHaveBeenCalledOnce();+ });++ it.each(['bad\0path', 'x'.repeat(256)])('rejects malformed context paths before reserving execution (%#)', async path => {+ const h = setup();+ await h.manager.register('agent-example', grant);+ const result = await h.manager.start('agent-example', { ...input, paths: [path] });+ expect(result.evidence).toMatchObject({ status: 'invalid-input', preflight: {+ lastError: { code: 'invalid-path', field: 'paths', index: 0 },+ } });+ expect(h.spawnProcess).not.toHaveBeenCalled();+ const corrected = h.manager.start('agent-example', input);+ const { child } = await h.spawned;+ child.emit('close', 0, null);+ expect((await corrected).evidence.status).toBe('completed');+ expect(h.spawnProcess).toHaveBeenCalledOnce();+ });++ it('keeps a refusal terminal after correcting input and preserves the rejected request history', async () => {+ const h = setup();+ await h.manager.register('agent-example', grant);+ await h.manager.start('agent-example', { ...input, paths: ['..'] });+ 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');+ child.emit('close', 0, null);+ expect((await run).evidence).toMatchObject({ status: 'refused', preflight: {+ rejectedRequests: 1, lastError: { code: 'outside-workspace' },+ } });+ expect((await h.manager.start('agent-example', input)).evidence.status).toBe('refused');+ expect(h.spawnProcess).toHaveBeenCalledOnce();+ expect(h.agent.process.kill).toHaveBeenCalledOnce();+ });++ it('does not release a rejected request until its evidence is durable, and lets Stop win during that write', async () => {+ let release;+ let writing;+ const started = new Promise(resolve => { writing = resolve; });+ const h = setup({ emitEvidence: async (_id, value) => {+ if (value.status === 'invalid-input') { writing(); await new Promise(resolve => { release = resolve; }); }+ } });+ await h.manager.register('agent-example', grant);+ const run = h.manager.start('agent-example', { ...input, paths: ['missing.js'] });+ await started;+ expect(h.manager.start('agent-example', input)).toBe(run);+ const stopped = h.manager.stop('agent-example');+ release();+ expect((await run).evidence).toMatchObject({ status: 'interrupted', preflight: { rejectedRequests: 1 } });+ expect((await stopped).status).toBe('interrupted');+ await h.manager.start('agent-example', input);+ expect(h.spawnProcess).not.toHaveBeenCalled();+ });++ it('revokes correction on Stop and stays fail-closed when rejection persistence fails', async () => {+ const h = setup();+ await h.manager.register('agent-example', grant);+ await h.manager.start('agent-example', { ...input, paths: ['missing.js'] });+ expect(await h.manager.stop('agent-example')).toMatchObject({ status: 'interrupted', preflight: { rejectedRequests: 1 } });+ expect(JSON.parse(await readFile(join(root, 'agents/agent-example/security-scan.json'), 'utf8'))).toMatchObject({ status: 'interrupted', preflight: { rejectedRequests: 1 } });+ expect(() => h.manager.start('agent-example', input)).toThrow('stopped');+ expect(h.spawnProcess).not.toHaveBeenCalled();++ const broken = setup({ emitEvidence: async (_id, value) => {+ if (value.status === 'invalid-input') throw new Error('synthetic receipt failure');+ } });+ await broken.manager.register('agent-other', grant);+ const failure = broken.manager.start('agent-other', { ...input, paths: ['missing.js'] });+ await expect(failure).rejects.toThrow('synthetic receipt failure');+ expect(broken.manager.start('agent-other', input)).toBe(failure);+ expect(broken.spawnProcess).not.toHaveBeenCalled();+ });++ it.each(['invalid-input', 'running', 'refused', 'completed'])('never reissues a grant after restart with prior %s evidence', async status => {+ const h = setup({ getAgent: () => null, cleanupGroup: async () => false });+ await mkdir(join(root, 'agents/agent-prior'), { recursive: true });+ const saved = { version: 1, ...grant, status, source: 'runner', sequence: 3,+ estimatedCostUsd: null, exitCode: status === 'completed' ? 0 : null, cleanup: 'not-needed',+ artifacts: { findings: null, coverage: null },+ preflight: { rejectedRequests: 1, lastError: { field: 'paths', index: 0, code: 'path-not-found' } } };+ await writeFile(join(root, 'agents/agent-prior/security-scan.json'), JSON.stringify(saved));+ expect((await h.manager.recover('agent-prior')).status).toBe(status === 'running' ? 'interrupted' : status);+ await expect(h.manager.register('agent-prior', grant)).rejects.toThrow('already exists');+ expect(() => h.manager.start('agent-prior', input)).toThrow('No active');+ expect(h.spawnProcess).not.toHaveBeenCalled();+ expect((await h.manager.read('agent-prior')).preflight).toEqual(saved.preflight);+ });++ it('makes concurrent Stop callers wait for an idle grant receipt and observe its write failure', async () => {+ let rejectWrite;+ let writing;+ const started = new Promise(resolve => { writing = resolve; });+ const h = setup({ emitEvidence: async (_id, value) => {+ if (value.status === 'interrupted') {+ writing();+ await new Promise((_resolve, reject) => { rejectWrite = reject; });+ }+ } });+ await h.manager.register('agent-example', grant);+ await h.manager.start('agent-example', { ...input, paths: ['missing.js'] });+ const first = h.manager.stop('agent-example');+ const firstCheck = expect(first).rejects.toThrow('synthetic stop receipt failure');+ await started;+ const second = h.manager.stop('agent-example');+ const secondCheck = expect(second).rejects.toThrow('synthetic stop receipt failure');+ let settled = false;+ void second.then(() => { settled = true; }, () => { settled = true; });+ await Promise.resolve();+ expect(settled).toBe(false);+ rejectWrite(new Error('synthetic stop receipt failure'));+ await Promise.all([firstCheck, secondCheck]);+ expect(() => h.manager.start('agent-example', input)).toThrow('stopped');+ expect(h.spawnProcess).not.toHaveBeenCalled();+ });+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);@@ -180,7 +324,7 @@ describe.skipIf(process.platform === 'win32')('runner-owned scanner lifecycle',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((await h.manager.start('agent-other', { ...input, paths: ['..'] })).evidence.status).toBe('invalid-input');expect(h.spawnProcess).not.toHaveBeenCalled();});diff --git a/server/lib/securityScanEvidence.js b/server/lib/securityScanEvidence.jsindex 4afc0b387d..4045dc50d2 100644--- a/server/lib/securityScanEvidence.js+++ b/server/lib/securityScanEvidence.js@@ -7,7 +7,7 @@ const nullableCost = z.number().finite().nonnegative().nullable();// or billing claims cross this boundary; null means not established.export const securityScanEvidenceSchema = z.object({version: z.literal(1),- status: z.enum(['not-run', 'running', 'unavailable', 'completed', 'failed', 'interrupted', 'time-limit', 'budget-limit', 'refused']),+ status: z.enum(['not-run', 'running', 'invalid-input', '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']),@@ -17,6 +17,14 @@ export const securityScanEvidenceSchema = z.object({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(),+ preflight: z.object({+ rejectedRequests: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),+ lastError: z.object({+ field: z.enum(['paths', 'knowledgeBase']),+ index: z.number().int().min(0).max(99),+ code: z.enum(['path-not-found', 'outside-workspace', 'invalid-path']),+ }).strict(),+ }).strict().optional(),}).strict().refine(value => value.status !== 'completed' || value.exitCode === 0);// This grant is set once at agent dispatch, never accepted from the model'sdiff --git a/server/lib/securityScanEvidence.test.js b/server/lib/securityScanEvidence.test.jsindex 5c88994c3b..55e3a4d770 100644--- a/server/lib/securityScanEvidence.test.js+++ b/server/lib/securityScanEvidence.test.js@@ -1,5 +1,5 @@import { expect, it } from 'vitest';-import { parseSecurityScanEvidence, securityScanGrantFromArgs } from './securityScanEvidence.js';+import { parseSecurityScanEvidence, parseRunnerSecurityScanEvidence, securityScanGrantFromArgs } from './securityScanEvidence.js';const report = {version: 1, status: 'time-limit', model: 'example-model', effort: 'low', auth: 'chatgpt',@@ -26,3 +26,15 @@ it('derives scanner pins from effective argv and refuses conflicting or implicitexpect(securityScanGrantFromArgs(['--model=selected-model', '--config=model="another-model"', '-cmodel_reasoning_effort=low'])).toMatchObject({ model: null, effort: 'low' });expect(securityScanGrantFromArgs([])).toMatchObject({ model: null, effort: null });});++it('accepts bounded runner input diagnostics without allowing private paths or errors through', () => {+ const evidence = { ...report, status: 'invalid-input', source: 'runner', sequence: 2,+ preflight: { rejectedRequests: 1, lastError: { field: 'paths', index: 0, code: 'path-not-found' } } };+ expect(parseRunnerSecurityScanEvidence(evidence)).toEqual(evidence);+ expect(parseRunnerSecurityScanEvidence({ ...evidence, preflight: {+ ...evidence.preflight, lastError: { ...evidence.preflight.lastError, path: '/private/source.js' },+ } })).toBeNull();+ expect(parseRunnerSecurityScanEvidence({ ...evidence, preflight: {+ ...evidence.preflight, lastError: { ...evidence.preflight.lastError, code: 'raw private error' },+ } })).toBeNull();+});diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 3d9ca25c3a..6ff05e61c6 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -702,6 +702,8 @@ describe('buildLightContextPrompt', () => {expect(prompt.systemPrompt).toContain('QUALITY_AUDIT_JSON');expect(prompt.systemPrompt).toContain('SCANNER_STATUS_JSON');expect(prompt.systemPrompt).toContain('refusal is terminal for this request');+ expect(prompt.systemPrompt).toContain('Only an explicit runner status of invalid-input permits correction');+ expect(prompt.systemPrompt).toContain('Do not resubmit after any other result or transport error');});it.each([diff --git a/server/services/agentSecurityScan.js b/server/services/agentSecurityScan.jsindex 034361aaf1..e5dd0f4f70 100644--- a/server/services/agentSecurityScan.js+++ b/server/services/agentSecurityScan.js@@ -9,7 +9,7 @@ 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 terminal = !['not-run', 'running', 'invalid-input'].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 } : {}) } });diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.jsindex 4dc4103b4e..a0feec5791 100644--- a/server/services/cosAgentLifecycle.test.js+++ b/server/services/cosAgentLifecycle.test.js@@ -92,7 +92,10 @@ describe('cosAgentLifecycle', () => {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' };+ artifacts: { findings: false, coverage: false }, cleanup: 'confirmed',+ preflight: { rejectedRequests: 1, lastError: { field: 'paths', index: 0, code: 'path-not-found' } } };+ await persistAgentSecurityScan('agent-scanner', { ...evidence, sequence: 1, status: 'invalid-input', exitCode: null, cleanup: 'not-needed' });+ expect((await getAgent('agent-scanner')).metadata.securityScan).toMatchObject({ status: 'invalid-input', preflight: evidence.preflight });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 } } });@@ -108,14 +111,17 @@ describe('cosAgentLifecycle', () => {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',+ await persistAgentSecurityScan('agent-scanner', { version: 1, source: 'runner', sequence: 3, 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' } });+ expect((await getAgent('agent-scanner')).metadata).toMatchObject({ securityScan: { sequence: 3, 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' });+ await persistAgentSecurityScan('agent-scanner', { ...observed, sequence: 2, status: 'invalid-input', cleanup: 'not-needed',+ preflight: { rejectedRequests: 1, lastError: { field: 'paths', index: 0, code: 'path-not-found' } } });+ expect((await getAgent('agent-scanner')).metadata).toMatchObject({ securityScan: { sequence: 3, status: 'running' }, securityScanControl: { status: 'interrupted', cleanup: 'unconfirmed' } });+ await persistAgentSecurityScan('agent-scanner', { ...observed, sequence: 4, status: 'refused', exitCode: 143, cleanup: 'confirmed' });expect((await getAgent('agent-scanner')).metadata).toMatchObject({ securityScan: { status: 'refused', cleanup: 'confirmed' }, securityScanControl: null });});diff --git a/server/services/promptSections/securityAudit.js b/server/services/promptSections/securityAudit.jsindex ad1e429e13..85eccc0422 100644--- a/server/services/promptSections/securityAudit.js+++ b/server/services/promptSections/securityAudit.js@@ -20,10 +20,10 @@ After reading the target threat model and completing repository-wide discovery,{ "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.-Call once: \`${command} --data-binary @<private-request-file>\`.+Request one scanner execution: \`${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.-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.+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. Only an explicit runner status of invalid-input permits correction: no scanner has launched. Use preflight.lastError's field and zero-based index to locate the bad input, verify the replacement in the workspace, and submit corrected paths through this same endpoint. Concurrent requests share the current result. Do not resubmit after any other result or transport error; the runner retains one execution and its diagnostics independently of your completion. A stopped or restarted grant cannot be reopened. 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.