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
Stop Codex safety refusals and preserve security scan outcomes
atomantica4695e834fe3
diff --git a/client/src/components/cos/AgentResultLine.jsx b/client/src/components/cos/AgentResultLine.jsxindex ad3c8504dc..05111b0c4d 100644--- a/client/src/components/cos/AgentResultLine.jsx+++ b/client/src/components/cos/AgentResultLine.jsx@@ -1,4 +1,5 @@import { CheckCircle, AlertCircle, RotateCcw } from 'lucide-react';+import { formatCount, formatUsd } from '../../utils/formatters';import { isAgentHandoff, agentHandoffReason } from '../../lib/agentOutcome';/**@@ -24,7 +25,10 @@ export default function AgentResultLine({ agent, className = '' }) {const validationFailed = agent.result.validationPassed === false;const publication = agent.metadata?.publicationValidation;const publicationIncomplete = ['running', 'blocked'].includes(publication?.status);- const incomplete = assessmentUnverified || validationFailed || publicationIncomplete;+ const interruption = agent.metadata?.executionInterruption || agent.result.executionInterruption;+ const scanner = agent.metadata?.securityScan;+ const scanIncomplete = scanner && scanner.status !== 'completed';+ const incomplete = interruption || scanIncomplete || assessmentUnverified || validationFailed || publicationIncomplete;const tone = handoff ? 'text-port-accent' : agent.result.success ? incomplete ? 'text-port-warning' : 'text-port-success' : 'text-port-error';return (@@ -38,6 +42,14 @@ export default function AgentResultLine({ agent, className = '' }) {<><AlertCircle size={14} aria-hidden="true" /> {agent.result.error || 'Failed'}</>)}</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>}{!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>}diff --git a/client/src/components/cos/AgentResultLine.test.jsx b/client/src/components/cos/AgentResultLine.test.jsxindex 1bebf2af56..486baa3773 100644--- a/client/src/components/cos/AgentResultLine.test.jsx+++ b/client/src/components/cos/AgentResultLine.test.jsx@@ -32,3 +32,20 @@ it('does not present blocked publication as completed delivery', () => {expect(screen.getByText('Publication blocked; worktree preserved')).toBeInTheDocument();expect(screen.queryByText('Completed successfully')).not.toBeInTheDocument();});+++it('retains refusal and scanner interruption evidence alongside successful delivery and assessment', () => {+ render(<AgentResultLine agent={{ result: { success: true, auditAssessment: { status: 'recorded' } }, metadata: {+ executionInterruption: { category: 'content-refusal' },+ securityScan: { status: 'time-limit', model: 'example-model', effort: 'low', auth: 'chatgpt',+ estimatedCostUsd: null, maxCostUsd: 0, timeLimitSeconds: 600, exitCode: null,+ artifacts: { findings: true, coverage: null } },+ } }} />);+ expect(screen.getByText('Execution completed')).toBeInTheDocument();+ expect(screen.getByText('Assessment saved')).toBeInTheDocument();+ expect(screen.getByText(/provider safety refusal; automatic retry stopped/)).toBeInTheDocument();+ expect(screen.getByText('Security scanner (agent reported): time-limit')).toBeInTheDocument();+ expect(screen.getByText(/Budget: \$0.00/)).toBeInTheDocument();+ expect(screen.getByText(/Exit: unknown/)).toBeInTheDocument();+ expect(screen.getByText(/findings: saved; coverage: unknown/)).toBeInTheDocument();+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 00067f6839..181044ca93 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -371,6 +371,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. || `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/agentFinalVerdict.js b/server/lib/agentFinalVerdict.jsindex f6594e21ee..e085e878cb 100644--- a/server/lib/agentFinalVerdict.js+++ b/server/lib/agentFinalVerdict.js@@ -108,6 +108,12 @@ export function resolveAgentFinalVerdict({hookResult = null,failureIsTerminal = () => false,}) {+ // Delivery checks cannot turn a provider refusal into an ordinary retryable+ // PR/validation failure. The refusal remains the terminal execution cause.+ if (['content-refusal', 'content-filtered'].includes(errorAnalysis?.category)) {+ return Object.freeze({ source: 'reported', success: false, errorAnalysis,+ error: errorAnalysis.message || error, completionReason: errorAnalysis.category });+ }const driftDowngrade = Boolean(drift?.drifted) && reportedSuccess && !terminatedByUser;const prVerdict = prEvidence.completionVerdict;const delivered = driftDowngradediff --git a/server/lib/agentFinalVerdict.test.js b/server/lib/agentFinalVerdict.test.jsindex e6c2aed312..66e15ec4b7 100644--- a/server/lib/agentFinalVerdict.test.js+++ b/server/lib/agentFinalVerdict.test.js@@ -14,6 +14,12 @@ describe('resolveAgentFinalVerdict', () => {reportedSuccess: true, errorAnalysis: null, error: undefined, completionReason: undefined, prEvidence: PR_OK, ...overrides,});+ it('keeps refusal terminal even when delivery and output checks disagree', () => {+ const errorAnalysis = { category: 'content-refusal', message: 'Stopped' };+ expect(resolve({ errorAnalysis, prEvidence: PR_MISSING, hookResult: rejected({ permanent: true }) }))+ .toMatchObject({ source: 'reported', success: false, errorAnalysis, completionReason: 'content-refusal' });+ });+it('applies drift ahead of a missing PR, and only to an otherwise-successful run', () => {expect(resolve({ drift: DRIFT, prEvidence: PR_MISSING })).toMatchObject({ source: 'drift', success: false, error: 'Primary moved' });expect(resolve({ reportedSuccess: false, errorAnalysis: { category: 'unknown' }, drift: DRIFT }).source).toBe('reported');diff --git a/server/lib/agentOutputMarkers.js b/server/lib/agentOutputMarkers.jsindex 3021ebe6d5..92fefbdb93 100644--- a/server/lib/agentOutputMarkers.js+++ b/server/lib/agentOutputMarkers.js@@ -97,6 +97,7 @@ export const LIFECYCLE_LINES = Object.freeze({startupDialogAnswered: lifecycleLine`📟 ${'message'} for session ${'session'}`,handshakeResubmitted: lifecycleLine`🔁 Provider handshake still open — re-submitted the prompt (attempt ${'attempt'})`,// Provider signals+ contentRefused: lifecycleLine`🛑 Provider refused this request on content/safety grounds — stopped without automatic continuation, retry or fallback.`,providerFallbackSignal: lifecycleLine`⚡ Provider fallback signal: ${'message'}`,providerSignalHolding: lifecycleLine`⏳ Provider signal (self-clearing): ${'message'} — holding the session up to ${'seconds'}s for it to clear`,providerSignalCleared: lifecycleLine`✅ Provider signal cleared — ${'command'} is generating again; continuing the run`,diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.jsindex 3a902167fc..06b11030cc 100644--- a/server/lib/aiToolkit/errorDetection.js+++ b/server/lib/aiToolkit/errorDetection.js@@ -17,11 +17,8 @@ export const ERROR_CATEGORIES = {// An explicitly shortened caller spending cap, not provider health.RUNTIME_BUDGET_EXHAUSTED: 'runtime-budget-exhausted',QUOTA_EXCEEDED: 'quota-exceeded',- // A frontier model declined the prompt on content/safety grounds. NOT a- // provider fault — the provider is healthy and other prompts still work, so- // this must not bench the provider or spawn an investigation task. We do try- // a fallback (a local model often doesn't refuse) and tell the UI what- // happened. See server/index.js#onRunFailed + autoFixer.handleAIProviderError.+ // A model safety refusal is terminal for this request. Never retry it or+ // switch providers; it says nothing about provider health.CONTENT_REFUSAL: 'content-refusal',// A LOCAL inference runtime ran out of accelerator memory mid-request (Metal// on Apple silicon, CUDA elsewhere). Distinct from QUOTA_EXCEEDED (money) and@@ -61,6 +58,39 @@ export const isRuntimeBudgetError = (err) => (|| err?.errorAnalysis?.category === ERROR_CATEGORIES.RUNTIME_BUDGET_EXHAUSTED);+// Provider error vocabulary, shared by streaming chrome and terminal analysis.+const CONTENT_REFUSAL_PATTERN = /limited access to this content for safety|may be used to benefit or to harm|content[_ ]policy[_ ]violation|stop_reason["']?\s*:\s*["']?refusal|"type"\s*:\s*"refusal"|"codex(?:_error_info|ErrorInfo)"\s*:\s*"(?:cyber_policy|cyberPolicy|misalignment_policy_violation|misalignmentPolicyViolation)"|This\s*content\s*(?:was\s*flagged\s*for\s*possible\s*cybersecurity\s*risk|can[’']t\s*be\s*shown)/i;++export const isContentRefusalError = (err) => (+ err?.errorAnalysis?.category === ERROR_CATEGORIES.CONTENT_REFUSAL+ || err?.context?.category === ERROR_CATEGORIES.CONTENT_REFUSAL+ || CONTENT_REFUSAL_PATTERN.test(err?.message || '')+);++/** A bounded Codex chrome detector; ordinary mentions/quoted JSON are not chrome. */+export function createContentRefusalDetector() {+ let buffer = '';+ let truncated = false;+ return (chunk) => {+ const next = `${buffer}${String(chunk || '')}`;+ if (next.length > 4096) truncated = true;+ buffer = next.slice(-4096);+ // Keep cursor moves to column 1 as row boundaries before removing styles.+ // Flattening the PTY first loses the distinction between chrome and quoted+ // text. Buffer raw bytes so a split escape sequence remains parseable.+ const screen = buffer.replace(/\x1b\[\d+;1H/g, '\n').replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '');+ const bounded = truncated ? `x${screen}` : screen;+ if (!/^[ \t]*ⓘ\s*This\s*content\s*can[’']t\s*be\s*shown/im.test(bounded)) return null;+ return {+ hasError: true, category: ERROR_CATEGORIES.CONTENT_REFUSAL,+ message: 'Codex stopped this request on cybersecurity/content policy grounds.',+ requiresFallback: false, actionable: false, permanent: true,+ origin: 'provider',+ suggestedFix: 'Review the refusal. Automatic continuation, retries and provider fallback are disabled.',+ };+ };+}+// A LOCAL inference runtime that ran out of accelerator memory mid-request.//// Observed shape (MTPLX/MLX behind an OpenAI-compatible server, rendered inside@@ -99,11 +129,11 @@ const ERROR_PATTERNS = [// Anthropic surfaces a `refusal` stop reason. Matched FIRST so a refusal is// never misclassified as an auth/unknown failure that would bench the// provider and queue a CoS investigation task.- pattern: /limited access to this content for safety|may be used to benefit or to harm|content[_ ]policy[_ ]violation|stop_reason["']?\s*:\s*["']?refusal|"type"\s*:\s*"refusal"/i,+ pattern: CONTENT_REFUSAL_PATTERN,category: ERROR_CATEGORIES.CONTENT_REFUSAL,- requiresFallback: true,+ requiresFallback: false,actionable: false,- suggestedFix: 'Model declined the prompt on content/safety grounds — retrying with a fallback model.'+ suggestedFix: 'Stopped after a content/safety refusal. Review the refusal; no automatic retry or provider fallback.'},{// A local inference server (MTPLX/MLX, vLLM, llama.cpp, Ollama) whose devicediff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.jsindex 2914b3ecde..aae426b543 100644--- a/server/lib/aiToolkit/errorDetection.test.js+++ b/server/lib/aiToolkit/errorDetection.test.js@@ -1,6 +1,7 @@import { describe, it, expect } from 'vitest';import {analyzeError,+ createContentRefusalDetector,analyzeHttpError,normalizeRateLimitHeaders,createClaudeSessionLimitBannerDetector,@@ -47,7 +48,7 @@ describe('Error Detection', () => {);expect(result.hasError).toBe(true);expect(result.category).toBe(ERROR_CATEGORIES.CONTENT_REFUSAL);- expect(result.requiresFallback).toBe(true);+ expect(result.requiresFallback).toBe(false);expect(result.actionable).toBe(false);});@@ -1086,3 +1087,21 @@ describe('Error Detection', () => {});});});+++describe('terminal content refusals', () => {+ it.each(['cyber_policy', 'cyberPolicy', 'misalignment_policy_violation'])('classifies structured %s without fallback', tag => {+ expect(analyzeError(JSON.stringify({ type: 'task_complete', error: { codex_error_info: tag } })))+ .toMatchObject({ category: 'content-refusal', requiresFallback: false });+ });++ it('detects split cursor-positioned chrome without treating quoted content as a live refusal', () => {+ const detect = createContentRefusalDetector();+ expect(detect('Quoted: "ⓘ This content can’t be shown"\n')).toBeNull();+ expect(detect('{"error":{"codex_error_info":"cyber_policy"}}\n')).toBeNull();+ expect(detect('tool output\x1b[12;')).toBeNull();+ expect(detect('1H\x1b[1mⓘ Thiscontentcan’t')).toBeNull();+ expect(detect('beshown\x1b[13;1HSome cybersecurity requests may still be limited.'))+ .toMatchObject({ category: 'content-refusal', requiresFallback: false, permanent: true });+ });+});diff --git a/server/lib/codexTurn.js b/server/lib/codexTurn.jsindex b48902a630..b8357eeb8b 100644--- a/server/lib/codexTurn.js+++ b/server/lib/codexTurn.js@@ -248,7 +248,7 @@ const RATE_LIMIT_ERROR_INFO = new Set(['rateLimitExceeded', 'serverOverloaded'])const AUTH_ERROR_INFO = new Set(['unauthorized']);const errorInfoTag = (error) => {- const info = error?.codexErrorInfo;+ const info = error?.codexErrorInfo ?? error?.codex_error_info;if (typeof info === 'string') return info;if (info && typeof info === 'object') return Object.keys(info)[0] ?? null;return null;@@ -275,7 +275,7 @@ export const classifyCodexTurnError = (error) => {// than an ERROR_CATEGORIES member: an oversized prompt is REQUEST-specific, so// it must shrink and retry, never bench the subscription for every other call.if (tag === 'contextWindowExceeded') return { category: 'context-length', message };- if (tag === 'cyberPolicy' || tag === 'misalignmentPolicyViolation') {+ if (['cyberPolicy', 'cyber_policy', 'misalignmentPolicyViolation', 'misalignment_policy_violation'].includes(tag)) {return { category: ERROR_CATEGORIES.CONTENT_REFUSAL, message };}if (tag === 'httpConnectionFailed' || tag === 'responseStreamConnectionFailed'diff --git a/server/lib/codexTurn.test.js b/server/lib/codexTurn.test.jsindex 583db4b51e..b77ed1dbfd 100644--- a/server/lib/codexTurn.test.js+++ b/server/lib/codexTurn.test.js@@ -8,6 +8,7 @@ import {CODEX_TURN_NOTIFICATIONS,applyCodexTurnEvent,classifyCodexTransportError,+ classifyCodexTurnError,createTurnAccumulator,finalizeCodexTurn,isCodexTextTransportEnabled,@@ -417,3 +418,12 @@ describe('classifyCodexTransportError', () => {expect(finalizeCodexTurn(acc).category).toBe('context-length');});});+++it.each([+ { codex_error_info: 'cyber_policy' },+ { codexErrorInfo: 'cyberPolicy' },+ { codexErrorInfo: { cyberPolicy: {} } },+])('classifies structured cybersecurity refusal %j', error => {+ expect(classifyCodexTurnError(error).category).toBe(ERROR_CATEGORIES.CONTENT_REFUSAL);+});diff --git a/server/lib/index.js b/server/lib/index.jsindex cbde30e831..7ae33fb1ca 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -879,3 +879,5 @@ export * from './auditWorkflow.js';export * from './musicVideoTransitions.js';export * from './musicVideoImageEffects.js';++export * from './securityScanEvidence.js';diff --git a/server/lib/securityScanEvidence.js b/server/lib/securityScanEvidence.jsnew file mode 100644index 0000000000..f3f700647e--- /dev/null+++ b/server/lib/securityScanEvidence.js@@ -0,0 +1,30 @@+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,+// 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']),+ 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']),+ maxCostUsd: nullableCost,+ estimatedCostUsd: nullableCost,+ timeLimitSeconds: z.number().int().nonnegative().nullable(),+ exitCode: z.number().int().nullable(),+ artifacts: z.object({ findings: z.boolean().nullable(), coverage: z.boolean().nullable() }).strict(),+}).strict().refine(value => value.status !== 'completed' || value.exitCode === 0);++/** Invalid/absent evidence stays unreported; delivery success cannot fill it in. */+export function parseSecurityScanEvidence(summary) {+ if (typeof summary !== 'string') return null;+ const lines = summary.split(/\r?\n/).filter(line => line.startsWith(PREFIX));+ if (lines.length !== 1) return null;+ let raw;+ try { raw = JSON.parse(lines[0].slice(PREFIX.length)); } catch { return null; }+ const result = securityScanEvidenceSchema.safeParse(raw);+ return result.success ? { ...result.data, source: 'agent-report' } : null;+}diff --git a/server/lib/securityScanEvidence.test.js b/server/lib/securityScanEvidence.test.jsnew file mode 100644index 0000000000..8b81110449--- /dev/null+++ b/server/lib/securityScanEvidence.test.js@@ -0,0 +1,22 @@+import { expect, it } from 'vitest';+import { parseSecurityScanEvidence } from './securityScanEvidence.js';++const report = {+ version: 1, status: 'time-limit', model: 'example-model', effort: 'low', auth: 'chatgpt',+ maxCostUsd: 0, estimatedCostUsd: null, timeLimitSeconds: 600, exitCode: null,+ artifacts: { findings: true, coverage: null },+};+const parse = value => parseSecurityScanEvidence(`Delivered the requested change.\nSCANNER_STATUS_JSON: ${JSON.stringify(value)}`);++it('retains timeout evidence and distinguishes a zero budget from unknown values', () => {+ expect(parse(report)).toEqual({ ...report, source: 'agent-report' });+ expect(parse({ ...report, maxCostUsd: null }).maxCostUsd).toBeNull();+});++it('rejects fabricated completion, ambiguous reports and fields that could disclose private data', () => {+ expect(parse({ ...report, status: 'completed' })).toBeNull();+ expect(parse({ ...report, outputDir: '/private/artifacts' })).toBeNull();+ expect(parse({ ...report, model: '/private/model' })).toBeNull();+ expect(parseSecurityScanEvidence('Completed successfully')).toBeNull();+ expect(parseSecurityScanEvidence(`SCANNER_STATUS_JSON: ${JSON.stringify(report)}\nSCANNER_STATUS_JSON: ${JSON.stringify(report)}`)).toBeNull();+});diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex 7fdb8acc22..9649686ad6 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -1,3 +1,5 @@+import { createContentRefusalDetector } from '../lib/aiToolkit/errorDetection.js';+import { classifyCodexTurnError } from '../lib/codexTurn.js';import { PR_COMPLETIONS, resolvePrCompletion } from '../lib/prDisposition.js';import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';/**@@ -771,10 +773,10 @@ export const ERROR_PATTERNS = [pattern: /content.?(?:filter|policy)|safety.?(?:filter|block)|harmful.?content/i,category: 'content-filtered',actionable: true,- escalation: 'Reword the task description to avoid the content that tripped the safety filter, then approve the retry.',+ escalation: 'Review the safety refusal; automatic retry and provider fallback are disabled.',extract: () => ({message: 'Content filtered',- suggestedFix: 'Request was blocked by content safety filter. Rephrase the task description.'+ suggestedFix: 'Request was stopped by a content safety refusal. No automatic continuation, retry or provider fallback.'})}];@@ -1123,6 +1125,28 @@ function structuralReasonAnalysis(def, completionReason, completionError) {};}+function structuredPolicyRefusal(output, analysisOutput) {+ const chromeRefusal = createContentRefusalDetector()(output);+ if (chromeRefusal) return chromeRefusal;+ // A quoted error string or source-code pattern is not a provider verdict.+ // Only inspect the error slot of a complete terminal protocol envelope.+ for (const line of analysisOutput.split('\n')) {+ if (!line.trimStart().startsWith('{')) continue;+ let event;+ try { event = JSON.parse(line); } catch { continue; }+ const error = event.type === 'event_msg' && event.payload?.type === 'task_complete'+ ? event.payload.error+ : event.type === 'turn.failed' ? event.error+ : event.method === 'turn/completed' ? event.params?.turn?.error : null;+ if (!error) continue;+ const refusal = classifyCodexTurnError(error);+ if (refusal.category === 'content-refusal') return { ...refusal, permanent: true,+ actionable: false, requiresFallback: false, origin: 'provider',+ suggestedFix: 'Review the refusal. Automatic continuation, retries and provider fallback are disabled.' };+ }+ return null;+}+/*** Analyze agent failure output and categorize the error.*@@ -1138,6 +1162,8 @@ function structuralReasonAnalysis(def, completionReason, completionError) {export function analyzeAgentFailure(output, task, model, options = {}) {const completionReason = options?.completionReason || null;const analysisOutput = getFailureAnalysisWindow(output || '');+ const refusal = structuredPolicyRefusal(output || '', analysisOutput);+ if (refusal) return refusal;// An idle-out whose transcript ends on an unanswered prompt gets that named as// the cause; every other reason passes through untouched.const structuralDef = refineIdleReasonAnalysis(@@ -1458,7 +1484,7 @@ export function resolveFailedTaskDecision(task, errorAnalysis, { agentId = null,// retry could read differently. Block on the FIRST occurrence, ahead of the// actionable branch, and file NO investigation task: an investigation agent// is another unbounded spawn against a cause the block already names.- if (errorAnalysis?.permanent) {+ if (errorAnalysis?.permanent || ['content-refusal', 'content-filtered'].includes(errorAnalysis?.category)) {return {status: 'blocked',investigationAnalysis: null,diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.jsindex 7d7ac5cdae..9d254cd561 100644--- a/server/services/agentErrorAnalysis.test.js+++ b/server/services/agentErrorAnalysis.test.js@@ -1480,3 +1480,32 @@ it.each(['draft', 'leave-open'])('keeps failed %s tasks from spawning an unrestrawait maybeCreateInvestigationTask('a1', { id: 't1', metadata: { prCompletion } }, { category: 'test-failure', actionable: true });expect(addTask).not.toHaveBeenCalled();});+++it.each([+ 'Reviewing a source pattern: may be used to benefit or to harm',+ 'Quoted JSON: {"codex_error_info":"cyber_policy"}',+ JSON.stringify({ type: 'response_item', payload: { type: 'function_call_output', output: '{"codex_error_info":"cyber_policy"}' } }),+])('does not override the runner verdict with quoted refusal text: %s', output => {+ expect(analyzeAgentFailure(output, {}, 'example-model', { completionReason: 'idle-no-activity' }))+ .toMatchObject({ category: 'startup-failure', origin: 'runner', completionReason: 'idle-no-activity' });+});++it.each([+ { type: 'event_msg', payload: { type: 'task_complete', error: { codex_error_info: 'cyber_policy' } } },+ { type: 'turn.failed', error: { codexErrorInfo: 'cyberPolicy' } },+ { method: 'turn/completed', params: { turn: { error: { codexErrorInfo: 'cyberPolicy' } } } },+])('retains structured policy refusals over a later idle verdict', event => {+ expect(analyzeAgentFailure(JSON.stringify(event), {}, 'example-model', { completionReason: 'idle-no-activity' }))+ .toMatchObject({ category: 'content-refusal', origin: 'provider', permanent: true, requiresFallback: false });+});++it('retains a current provider banner over a later idle verdict', () => {+ expect(analyzeAgentFailure('Work output\u001b[12;1Hⓘ This content can’t be shown', {}, 'example-model', { completionReason: 'idle-no-activity' }))+ .toMatchObject({ category: 'content-refusal', origin: 'provider', permanent: true });+});++it.each(['content-refusal', 'content-filtered'])('blocks %s without automatic retry or investigation', category => {+ expect(resolveFailedTaskDecision({ id: 'example-task', metadata: {} }, { category, actionable: false, message: 'Stopped' }))+ .toMatchObject({ status: 'blocked', investigationAnalysis: null, metadataUpdates: { blockedCategory: category } });+});diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 12f8d300cf..05c47d5cb7 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -1155,7 +1155,14 @@ export function dispatchRecoveredTaskOutputHook({ agentId, task, success, worksp*/export async function retireDeadAgent({ agent, task, success, exitCode, duration, errorMessage, category, agentResultExtra = {} }) {const isPrivateSecurity = isPrivateSecurityTask(task) || isPrivateSecurityTask(agent);- const effectiveSuccess = isPrivateSecurity ? false : success;+ const interruption = agent.metadata?.executionInterruption;+ const refused = ['content-refusal', 'content-filtered'].includes(interruption?.category);+ const effectiveSuccess = isPrivateSecurity || refused ? false : success;+ const errorAnalysis = refused ? {+ category: interruption.category, origin: interruption.source || 'provider',+ message: 'Provider safety refusal; automatic continuation, retries and provider fallback are disabled.',+ permanent: true, actionable: false, requiresFallback: false,+ } : { message: errorMessage, category };await dispatchRecoveredTaskOutputHook({agentId: agent.id,@@ -1183,7 +1190,7 @@ export async function retireDeadAgent({ agent, task, success, exitCode, durationisPrivateSecurity ? 'Private security assessment interrupted; inspect its local assessment archive.' : output,exitCode,duration,- { message: errorMessage, category },+ errorAnalysis,);}@@ -1194,6 +1201,7 @@ export async function retireDeadAgent({ agent, task, success, exitCode, durationorphaned: true,error: errorMessage,...agentResultExtra,+ ...(refused ? { success: false, error: errorAnalysis.message, errorAnalysis, executionInterruption: interruption } : {}),});return { success: effectiveSuccess };@@ -1319,6 +1327,7 @@ export async function finalizeAgent({outputBuffer,finalSummary = null,errorAnalysis: reportedErrorAnalysis,+ executionInterruption = null,terminatedByUser = false,error,completionReason,@@ -1326,6 +1335,14 @@ export async function finalizeAgent({prExpected = false,startedAt = null,}) {+ if (['content-refusal', 'content-filtered'].includes(reportedErrorAnalysis?.category)) {+ executionInterruption ||= { category: reportedErrorAnalysis.category, source: reportedErrorAnalysis.origin || 'provider' };+ reportedSuccess = false;+ }+ if (executionInterruption) {+ await updateAgent(agentId, { metadata: { executionInterruption } })+ .catch(err => emitLog('warn', `Could not persist execution interruption for ${agentId}: ${err.message}`, { agentId }));+ }// The run window the commit criterion is evaluated against (#3637). Callers// that don't track their own start timestamp still know how long the run took,// and `duration` is measured from the same instant, so derive it — a missing@@ -1672,6 +1689,7 @@ export async function finalizeAgent({duration,outputLength: outputBuffer?.length ?? 0,errorAnalysis: verdict.errorAnalysis,+ ...(executionInterruption ? { executionInterruption } : {}),// Recorded whatever the verdict — a `ship` is the evidence that the gate ran// and cleared the run, which is what makes a run with no `goalFidelity` block// legible as "never judged" rather than "judged fine".@@ -1970,6 +1988,19 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, aworkspacePath: hookPayloadDir({ task, workspacePath, recovery }) }) : null;if (!taskType) return { ran: false, ...(deepAudit ? { deepAudit } : {}) };if (isAuditTaskType(taskType)) {+ if (taskType === 'security') {+ const { parseSecurityScanEvidence } = await import('../lib/securityScanEvidence.js');+ const { doneSentinelPath, parseSentinelPayload } = await import('../lib/agentSentinel.js');+ const cwd = hookPayloadDir({ task, workspacePath, recovery });+ const path = doneSentinelPath(cwd, agentId);+ const summary = path ? parseSentinelPayload(await tryReadFile(path)).summary : null;+ 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 => {+ emitLog('warn', `⚠️ Scanner diagnostics were not saved for ${agentId}: ${err.message}`, { agentId });+ });+ }const { recordAuditQuality } = await import('./appQuality.js');const auditAssessment = await recordAuditQuality({ task, taskType, agentId, success, assessedAt,...(isLegacyDeepAudit(task.metadata) ? { deepDiscoveryComplete: deepAudit?.discoveryComplete === true } : {}),diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.jsindex 853d400cf6..9dc286a336 100644--- a/server/services/agentFinalization.outputHooks.test.js+++ b/server/services/agentFinalization.outputHooks.test.js@@ -1,3 +1,8 @@+vi.mock('../lib/fileUtils.js', async importOriginal => {+ const actual = await importOriginal();+ return { ...actual, tryReadFile: vi.fn(actual.tryReadFile) };+});+import { tryReadFile } from '../lib/fileUtils.js';const deep = vi.hoisted(() => ({ checkpointDeepAudit: vi.fn(async () => ({ id: 'deep-1', complete: false, reason: 'Checkpoint partial' })), settleDeepAuditDelivery: vi.fn(async () => ({ id: 'deep-1', complete: false, reason: 'Checkpoint partial' })) }));vi.mock('./deepAudit.js', () => deep);vi.mock('../lib/gitCommitProbe.js', () => ({ committedDuringRun: vi.fn(async () => false) }));@@ -117,6 +122,21 @@ describe('recovery output-hook dispatch (#3182)', () => {getTaskOutputHook.mockResolvedValue(hook);});+ it('persists scanner limits independently of successful assessment delivery and completion replay', async () => {+ const scanner = { version: 1, status: 'time-limit', model: 'example-model', effort: 'low', auth: 'chatgpt',+ maxCostUsd: null, estimatedCostUsd: null, timeLimitSeconds: 600, exitCode: 130,+ artifacts: { findings: true, coverage: false } };+ const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'security', prCompletion: 'draft' } };+ persistedAgent.metadata.executionInterruption = { category: 'content-refusal', source: 'provider' };+ tryReadFile.mockResolvedValueOnce(`Delivered a fix.\nSCANNER_STATUS_JSON: ${JSON.stringify(scanner)}`);+ const args = { agentId: 'agent-scanner', task, success: true, workspacePath: '/worktree' };+ await dispatchTaskOutputHookOnce(args);+ expect(persistedAgent.metadata).toMatchObject({ securityScan: { ...scanner, source: 'agent-report' },+ auditAssessment: { status: 'recorded' }, executionInterruption: { category: 'content-refusal' } });+ await dispatchTaskOutputHookOnce(args);+ expect(persistedAgent.metadata.securityScan.status).toBe('time-limit');+ });+it('captures audit telemetry on the shared completion path without waiving fix-mode delivery criteria', async () => {const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'better-complexity' } };await expect(dispatchTaskOutputHookOnce({ agentId: 'agent-audit', task, success: true, workspacePath: '/worktree' }))@@ -126,6 +146,20 @@ describe('recovery output-hook dispatch (#3182)', () => {expect(updateAgent).toHaveBeenCalledWith('agent-audit', { metadata: { auditAssessment: { status: 'recorded' } } });});+ it('saves the assessment when scanner diagnostic persistence fails', async () => {+ const scanner = { version: 1, status: 'time-limit', model: null, effort: null, auth: 'unknown',+ maxCostUsd: null, estimatedCostUsd: null, timeLimitSeconds: 600, exitCode: null,+ artifacts: { findings: null, coverage: null } };+ const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'security', prCompletion: 'draft' } };+ tryReadFile.mockResolvedValueOnce(`SCANNER_STATUS_JSON: ${JSON.stringify(scanner)}`);+ updateAgent.mockRejectedValueOnce(new Error('diagnostic storage unavailable'));+ await expect(dispatchTaskOutputHookOnce({ agentId: 'agent-diagnostic-failure', task, success: true, workspacePath: '/worktree' }))+ .resolves.toMatchObject({ auditAssessment: { status: 'recorded' } });+ expect(recordAuditQuality).toHaveBeenCalledWith(expect.objectContaining({ task, success: true }));+ expect(persistedAgent.metadata.auditAssessment).toEqual({ status: 'recorded' });+ expect(emitLog).toHaveBeenCalledWith('warn', expect.stringContaining('Scanner diagnostics were not saved'), expect.any(Object));+ });+// Landing the app's `.quality.json` PR is opt-in and runs outside the request// lifecycle, so it must never fire for an un-opted app nor fail a completion.// Each dispatch needs its own agent id — dispatchTaskOutputHookOnce caches by id.diff --git a/server/services/agentFinalization.retireDeadAgent.test.js b/server/services/agentFinalization.retireDeadAgent.test.jsindex ecd4ba0d5d..7b4567c218 100644--- a/server/services/agentFinalization.retireDeadAgent.test.js+++ b/server/services/agentFinalization.retireDeadAgent.test.js@@ -108,6 +108,19 @@ describe('retireDeadAgent (#8440)', () => {expect(completeAgent).toHaveBeenCalledWith('agent-dead', expect.objectContaining({ success: true }));});+ it.each([true, false])('preserves a saved refusal when recovery reports success=%s', async success => {+ const executionInterruption = { category: 'content-refusal', source: 'provider', at: '2026-01-01T00:00:00Z' };+ const result = await retireDeadAgent({+ agent: { ...AGENT, metadata: { runId: 'run-refused', executionInterruption } }, task: TASK,+ success, exitCode: success ? 0 : 143, duration: 100, category: 'interrupted',+ });+ expect(result).toEqual({ success: false });+ expect(completeAgentRun).toHaveBeenCalledWith('run-refused', '', success ? 0 : 143, 100,+ expect.objectContaining({ category: 'content-refusal', origin: 'provider', permanent: true, requiresFallback: false }));+ expect(completeAgent).toHaveBeenCalledWith('agent-dead', expect.objectContaining({ success: false,+ executionInterruption, errorAnalysis: expect.objectContaining({ category: 'content-refusal' }) }));+ });+it('removes the completion sentinel before checking for a runId', async () => {await retireDeadAgent({ agent: AGENT, task: TASK, success: false, exitCode: 1, duration: 0 });diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex e6761c1f49..2ff22d7746 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -1467,9 +1467,9 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentreturn;}- // Never requeue tasks that were explicitly terminated by the user- if (task.status === 'blocked' && task.metadata?.blockedCategory === 'user-terminated') {- emitLog('info', `⏭️ Skipping orphaned task ${taskId} — user-terminated`, { taskId, agentId });+ // User stops and policy refusals remain terminal across recovery sweeps.+ if (task.status === 'blocked' && ['user-terminated', 'content-refusal', 'content-filtered'].includes(task.metadata?.blockedCategory)) {+ emitLog('info', `⏭️ Skipping orphaned task ${taskId} — ${task.metadata.blockedCategory}`, { taskId, agentId });return;}@@ -1506,6 +1506,20 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentreturn;}+ // A crash/restart after the refusal was saved must not authorize a retry or+ // commit rescue. Do not let an older refused run block a newer invocation.+ const interruption = agentMetadata?.executionInterruption;+ if (['content-refusal', 'content-filtered'].includes(interruption?.category)) {+ const startedAt = toEpochMs(agentStartedAt);+ if (startedAt && toEpochMs(task.metadata?.[LAST_SPAWNED_AT_KEY]) > startedAt) return;+ await updateTask(taskId, await stampLiExecutionVerdict({ status: 'blocked', metadata: {+ ...task.metadata, ...clearedRetryHoldMetadata(), executionInterruption: interruption,+ blockedAt: new Date().toISOString(), blockedCategory: interruption.category,+ blockedReason: 'Provider safety refusal; automatic continuation, retries and provider fallback are disabled.',+ } }, task, { success: false }), task.taskType || 'user');+ return;+ }+// Recovery of a dead Deep invocation is a checkpoint, never permission to// auto-launch another provider call or to treat commits as completed coverage.if (isLegacyDeepAudit(task.metadata)) {diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex c314953da3..187a784590 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -449,6 +449,30 @@ describe('handleOrphanedTask — duplicate-investigation guard', () => {pausedAgents.clear();});+ it.each(['content-refusal', 'content-filtered'])('keeps persisted %s terminal after a restart', category => {+ const task = { id: 'task-refused', taskType: 'internal', status: 'in_progress', metadata: {} };+ const executionInterruption = { category, source: 'provider', at: '2026-01-01T00:00:00Z' };+ return handleOrphanedTask(task.id, 'agent-refused', vi.fn().mockResolvedValue(task), {+ interrupted: true, agentMetadata: { executionInterruption },+ }).then(() => {+ expect(updateTask).toHaveBeenCalledWith(task.id, expect.objectContaining({ status: 'blocked',+ metadata: expect.objectContaining({ blockedCategory: category, executionInterruption }),+ }), 'internal');+ expect(addTask).not.toHaveBeenCalled();+ expect(resolveTaskResumePatch).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();+ expect(forceSpawnTask).not.toHaveBeenCalled();+ });+ });++ it('does not revive a refused task when a later sweep lacks the agent record', async () => {+ const task = { id: 'task-refused', status: 'blocked', metadata: { blockedCategory: 'content-refusal' } };+ await handleOrphanedTask(task.id, 'agent-refused', vi.fn().mockResolvedValue(task), { interrupted: true });+ expect(updateTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();+ expect(resolveTaskResumePatch).not.toHaveBeenCalled();+ });+it('blocks an interrupted private assessment without retrying or investigating its transcript', async () => {const task = { id: 'task-private', taskType: 'internal', status: 'in_progress',metadata: { analysisType: 'private-security-assessment', orphanRetryCount: 4 } };diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 2ac0f4954f..4496c52637 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -698,6 +698,8 @@ describe('buildLightContextPrompt', () => {expect(prompt.systemPrompt).toContain('## Completion (No Code Output)');expect(prompt.systemPrompt).toContain('## Required audit assessment handoff');expect(prompt.systemPrompt).toContain('QUALITY_AUDIT_JSON');+ expect(prompt.systemPrompt).toContain('SCANNER_STATUS_JSON');+ expect(prompt.systemPrompt).toContain('refusal is terminal for this request');});it.each([diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.jsindex 4ad5e4c6c9..4e53a034f7 100644--- a/server/services/agentRunTracking.js+++ b/server/services/agentRunTracking.js@@ -126,9 +126,11 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA// the commit subject, because nothing ever emitted such a marker). The window// opens at the run's own startTime, so commits another agent pushed before// this run began don't launder it into a success.+ const refused = ['content-refusal', 'content-filtered'].includes(errorAnalysis?.category);+ if (refused) metadata.executionInterruption ||= { category: errorAnalysis.category, source: errorAnalysis.origin || 'provider', at: metadata.endTime };let success = exitCode === 0;const runStartedAt = Date.parse(metadata.startTime);- if (!success && metadata.taskId && metadata.workspacePath) {+ if (!success && !refused && metadata.taskId && metadata.workspacePath) {if (await committedDuringRun(metadata.workspacePath, runStartedAt)) {console.log(`⚠️ Agent ${metadata.agentId} reported failure (exit ${exitCode}) but work completed - commit found for task ${metadata.taskId}`);success = true;@@ -136,7 +138,7 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA}// An explicit false from the caller is authoritative and outranks both the// exit code and the commit rescue above; null (the default) means "no opinion".- if (successOverride === false) success = false;+ if (successOverride === false || refused) success = false;metadata.success = success;metadata.outputSize = Buffer.byteLength(output || '');diff --git a/server/services/agentRunTracking.test.js b/server/services/agentRunTracking.test.jsindex 771d3ab011..129f265a97 100644--- a/server/services/agentRunTracking.test.js+++ b/server/services/agentRunTracking.test.js@@ -215,6 +215,21 @@ describe('completeAgentRun lifecycle ledger', () => {}));});+ it('keeps a policy interruption independent of exit code and commit rescue', async () => {+ vi.resetModules();+ const atomicWrite = vi.fn();+ vi.doMock('../lib/fileUtils.js', async importOriginal => ({ ...(await importOriginal()), atomicWrite,+ readJSONFile: vi.fn().mockResolvedValue({ id: 'run-refused', endTime: null, agentId: 'agent-example',+ taskId: 'task-example', workspacePath: '/example/repo', startTime: '2026-01-01T00:00:00Z' }),+ }));+ const { completeAgentRun } = await import('./agentRunTracking.js');+ await completeAgentRun('run-refused', 'Partial work', 0, 100, { category: 'content-refusal', message: 'Stopped' });+ expect(atomicWrite).toHaveBeenCalledWith(expect.stringContaining('metadata.json'), expect.objectContaining({+ success: false, exitCode: 0, errorCategory: 'content-refusal',+ executionInterruption: expect.objectContaining({ category: 'content-refusal', source: 'provider' }),+ }));+ });+it('appends nothing for a run that was already closed', async () => {vi.resetModules();appendRunEvent.mockClear();diff --git a/server/services/agentTuiSpawning/finalizeHelpers.js b/server/services/agentTuiSpawning/finalizeHelpers.jsindex db9e0d783a..5c11f47a0a 100644--- a/server/services/agentTuiSpawning/finalizeHelpers.js+++ b/server/services/agentTuiSpawning/finalizeHelpers.js@@ -85,6 +85,7 @@ export async function captureWorktreeDiff(workspacePath, agentDir) {* @returns {Promise<object|null>} The error-analysis object, or null on success.*/export async function resolveErrorAnalysis({ finalSuccess, rawFile, fallbackText, task, model, immediateFallbackAnalysis, completionReason, completionError }) {+ if (immediateFallbackAnalysis?.category === 'content-refusal') return immediateFallbackAnalysis;if (finalSuccess) return null;// Short-circuit BEFORE the tail read: a mid-stream fallback signal already is// the verdict, so reading ~16KB of spool only to discard it is pure waste.diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.jsindex 5961985f45..984e50b32e 100644--- a/server/services/agentTuiSpawning/sessionController.js+++ b/server/services/agentTuiSpawning/sessionController.js@@ -37,7 +37,7 @@ import { missingSentinelLogMessage, parseSentinelPayload } from '../../lib/agentimport { LIFECYCLE_LINES, SENTINEL_COMPLETION_MARKER } from '../../lib/agentOutputMarkers.js';import { resolveMergeGateVerdict, buildMergeGateReprompt } from '../../lib/mergeGateContract.js';import { createStreamingAnsiStripper, stripAnsi } from '../../lib/ansiStrip.js';-import { createClaudeSessionLimitBannerDetector, createImmediateFallbackSignalDetector, createLocalRuntimeOomDetector, createTruncatedResponseDetector } from '../../lib/aiToolkit/errorDetection.js';+import { createContentRefusalDetector, createClaudeSessionLimitBannerDetector, createImmediateFallbackSignalDetector, createLocalRuntimeOomDetector, createTruncatedResponseDetector } from '../../lib/aiToolkit/errorDetection.js';import { isAntigravityCommand } from '../../lib/antigravity.js';import { isCodexCommand } from '../../lib/codex.js';import { isClaudeCommand } from '../../lib/providerModels.js';@@ -534,7 +534,10 @@ export function createTuiSessionController({// and a fresh spawn (a real retry) starts a fresh closure with its own flag.let mergeGateReprompted = false;let immediateFallbackAnalysis = null;+ let terminalRefusal = null;+ let executionInterruption = null;const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();+ const detectContentRefusal = createContentRefusalDetector();const detectClaudeSessionLimitBanner = createClaudeSessionLimitBannerDetector();let claudeLowPriorityPromptResubmitted = false;const mayUseClaudeLowPriority = provider?.type === 'tui'@@ -793,7 +796,7 @@ export function createTuiSessionController({if (sentinelRecoveryRetryTimer || isTerminal()) return;sentinelRecoveryRetryTimer = setTimeout(() => {sentinelRecoveryRetryTimer = null;- if (isTerminal()) return;+ if (isTerminal() || terminalRefusal) return;doneSentinelWatcher?.();doneSentinelWatcher = armSentinelWatcher();}, SENTINEL_RECOVERY_RETRY_MS);@@ -819,6 +822,7 @@ export function createTuiSessionController({const prProbe = await probeMergeGatePr();const verdict = resolveMergeGateVerdict({ prProbe, summary });if (verdict !== 'needs-reprompt') return false;+ if (terminalRefusal) return false;if (!pasteController?.resubmit({ text: buildMergeGateReprompt(prProbe.prUrl || '<PR_URL>'), label: 'merge-gate contract nudge' })) {// Session is already gone — nothing to nudge; fall through to finalize.return false;@@ -923,6 +927,7 @@ export function createTuiSessionController({* whole function settles.*/const runFinishDecision = async ({ success }) => {+ if (terminalRefusal) return { type: 'finalize' };// PortOS is going down. Whatever path got here — the PTY exiting under// TreeKill, a provider-signal failure, a paste that failed because the shell died —// the cause is the host restart, not the agent, so there is no outcome to@@ -949,6 +954,8 @@ export function createTuiSessionController({// what normally calls finish(). Idempotent via `sentinelIngested`.const sentinelSummary = await ingestDoneSentinel();+ if (terminalRefusal) return { type: 'finalize' };+if (sentinelRecoveryPending) {sentinelRecoveryPending = false;scheduleSentinelRecoveryRetry();@@ -996,7 +1003,15 @@ export function createTuiSessionController({}sessionPhase = 'finishing';- const decision = await runFinishDecision({ success });+ let decision = await runFinishDecision({ success });+ // A refusal observed while a sentinel/probe was awaited outranks its result.+ if (terminalRefusal) {+ decision = { type: 'finalize' };+ success = false;+ exitCode = 1;+ error = terminalRefusal.message;+ reason = 'content-refusal';+ }if (decision.type === 'abandon') {await abandonForHostShutdown();@@ -1148,6 +1163,7 @@ export function createTuiSessionController({terminatedByUser,error: finalError || undefined,completionReason: reason,+ ...(executionInterruption ? { executionInterruption } : {}),workspacePath: cwd,prExpected: prOwnership.prClaimExpected,// The run window the commit criterion is evaluated against (#3637).@@ -1245,7 +1261,7 @@ export function createTuiSessionController({const resubmitAfterSignal = () => {// A banner that paints during startup (before the prompt was ever submitted)// has nothing to re-send — the ordinary paste path still owns first delivery.- if (isTerminal() || !promptSubmittedAt) return;+ if (isTerminal() || terminalRefusal || !promptSubmittedAt) return;const attempt = selfClearingGate.takeResubmit(Date.now());if (!attempt) return;// Only claim the re-submission that actually went out — a false return means@@ -1268,7 +1284,7 @@ export function createTuiSessionController({// reached a terminal phase, drop them — appending to the spool, growing// the post-paste accumulator, or mutating timing state is all pointless// after finish has settled.- if (isTerminal()) return;+ if (isTerminal() || terminalRefusal) return;// node-pty surfaces output as already-decoded UTF-8 strings via// shellService's onData hook (StringDecoder handles multi-byte// boundaries internally), so `data` is a string here in normal use.@@ -1302,6 +1318,20 @@ export function createTuiSessionController({if (isCodexSession && !codexComposerReady && !promptSentAt && commandInjected && stripped&& CODEX_COMPOSER_READY_PATTERN.test(stripped)) codexComposerReady = true;const now = Date.now();+ // A policy refusal ends this request before any recovery/nudge machinery.+ const refusal = isCodexSession && promptSubmittedAt ? detectContentRefusal(text) : null;+ if (refusal) {+ terminalRefusal = refusal;+ executionInterruption = { category: refusal.category, source: 'provider', at: new Date(now).toISOString() };+ immediateFallbackAnalysis = refusal;+ await persistence.updateAgent(agentId, { metadata: {+ executionInterruption,+ } }).catch(err => emitLog('warn', `Could not persist refusal for ${agentId}: ${err.message}`, { agentId }));+ appendLine(LIFECYCLE_LINES.contentRefused());+ await finish({ success: false, exitCode: 1, error: refusal.message, reason: 'content-refusal' });+ return;+ }+if (promptSubmittedAt) codexModelRejectionGate?.observe(stripped);// Startup-idle detection (the promptTimer's non-inputReady branch below)// reads lastOutputAt/firstOutputAt to decide the TUI has gone quiet and is@@ -1613,7 +1643,7 @@ export function createTuiSessionController({mcpBoot,isCodexSession,appendLine,- isFinalized: isTerminal,+ isFinalized: () => isTerminal() || !!terminalRefusal,markPromptSent: () => { promptSentAt = Date.now(); },markPromptSubmitted: () => { if (promptSubmittedAt === null) promptSubmittedAt = Date.now(); },finishStartupFailure,@@ -1768,7 +1798,7 @@ export function createTuiSessionController({// Provider-handshake retry timer. It is deliberately not an idle watchdog:// a CoS TUI may remain silent for as long as the provider needs.providerSignalTimer = setInterval(() => {- if (isTerminal()) return;+ if (isTerminal() || terminalRefusal) return;// One clock for every gate on this tick. They all measure the same silence,// so reading the wall four times only invites them to disagree about it.const now = Date.now();diff --git a/server/services/agentTuiSpawning/sessionController.test.js b/server/services/agentTuiSpawning/sessionController.test.jsindex 4b24c7352d..5acf16bc71 100644--- a/server/services/agentTuiSpawning/sessionController.test.js+++ b/server/services/agentTuiSpawning/sessionController.test.js@@ -59,6 +59,7 @@ function makeController({const seams = {closers,watch,+ updateAgent: vi.fn().mockResolvedValue(undefined),releaseRunRecord: vi.fn(),runCompletionCleanup: vi.fn().mockResolvedValue({}),finalizeAgent: vi.fn().mockResolvedValue({ success: true }),@@ -99,7 +100,7 @@ function makeController({hasLiveChild: async () => true,},persistence: {- updateAgent: vi.fn().mockResolvedValue(undefined),+ updateAgent: seams.updateAgent,appendRunEvent: vi.fn(),// THE CASE UNDER TEST: no active-run entry for this agent.readRunRecord: () => undefined,@@ -283,6 +284,29 @@ describe('Codex terminal model-access rejection (#9319)', () => {return subject;};+ 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;+ updateAgent.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectWrite = reject; }));+ const refusing = controller.handleData('\x1b[12;1Hⓘ This content can’t be shown');+ // Let the serialized onData queue reach its metadata write.+ for (let i = 0; i < 10; i++) await Promise.resolve();+ await controller.finish({ success: true, reason: 'agent-signaled-done' });+ await vi.advanceTimersByTimeAsync(STALL_NUDGE_IDLE_MS + 10000);+ rejectWrite(new Error('synthetic persistence failure'));+ await refusing;+ expect(paste).not.toHaveBeenCalled();+ expect(write).not.toHaveBeenCalled();+ expect(finalizeAgent).toHaveBeenCalledTimes(1);+ expect(finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({+ success: false, completionReason: 'content-refusal',+ errorAnalysis: expect.objectContaining({ category: 'content-refusal', requiresFallback: false }),+ executionInterruption: expect.objectContaining({ category: 'content-refusal', source: 'provider' }),+ }));+ expect(kill).toHaveBeenCalledTimes(1);+ expect(controller.isTerminal()).toBe(true);+ });+it('settles a chunked structured rejection, finalizes once, and tears down without continuing', async () => {const { controller, paste, write, finalizeAgent, resolveErrorAnalysis, kill, closers } = await submitted();// A first-request rejection has no work separator: Codex's terminal ■diff --git a/server/services/autoFixer.js b/server/services/autoFixer.jsindex b034fef9e4..030242d0fa 100644--- a/server/services/autoFixer.js+++ b/server/services/autoFixer.js@@ -469,12 +469,12 @@ async function handleAIProviderError(error) {// A content/safety refusal is not a provider fault — we know exactly why it// failed (the model declined the prompt), so there's nothing for a CoS agent- // to investigate. promptRunner.js already retries with a fallback and the UI+ // to investigate. promptRunner.js stops without fallback and the UI// is told what happened. Bail before deferring/creating a task. (server's// onRunFailed already emits a distinct code for refusals so this handler// normally isn't even reached; this guard covers any other emitter.)if (ctx.errorAnalysis?.category === ERROR_CATEGORIES.CONTENT_REFUSAL) {- console.log(`🛟 AI model refused prompt on content/safety grounds: ${ctx.provider} (${ctx.model}) — no investigation task (fallback handles it)`);+ console.warn(`🛟 AI model refused prompt on content/safety grounds: ${ctx.provider} (${ctx.model}) — no investigation task or automatic fallback`);return;}diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex d496c8ebed..bed6a0a3f4 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -217,14 +217,14 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// provider fault. Emit a distinct code + warning severity so (a) the// autofixer skips it (it only spawns investigation tasks for// AI_PROVIDER_EXECUTION_FAILED) and (b) the client shows a calm "model- // declined, trying a fallback" notice instead of a red error toast. The- // fallback retry itself is driven by promptRunner.js.+ // declined, stopped" notice instead of a red error toast. Automatic retry+ // and provider fallback are disabled.const isBudget = metadata.errorAnalysis?.category === ERROR_CATEGORIES.RUNTIME_BUDGET_EXHAUSTED;const isRefusal = metadata.errorAnalysis?.category === ERROR_CATEGORIES.CONTENT_REFUSAL;errorEvents.emit('error', {code: isBudget ? 'AI_RUNTIME_BUDGET_EXHAUSTED' : (isRefusal ? 'AI_PROVIDER_CONTENT_REFUSED' : 'AI_PROVIDER_EXECUTION_FAILED'),message: isBudget ? errorMessage : isRefusal- ? `${metadata.providerName} declined this prompt on content/safety grounds — trying a fallback model if one is configured.`+ ? `${metadata.providerName} declined this prompt on content/safety grounds — stopped without automatic retry or provider fallback.`: `AI provider ${metadata.providerName} execution failed: ${errorMessage}`,severity: isBudget || isRefusal ? 'warning' : 'error',canAutoFix: !isBudget && !isRefusal,diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex 4f1ca68b72..c4de382dd1 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -38,7 +38,7 @@ import { isCompositeProviderId } from '../lib/providerRef.js';// both subtrees in every one of them.import { ServerError } from '../lib/errorHandler.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';-import { analyzeError, ERROR_CATEGORIES, isRunCanceledError, isRuntimeBudgetError } from '../lib/aiToolkit/errorDetection.js';+import { analyzeError, ERROR_CATEGORIES, isRunCanceledError, isRuntimeBudgetError, isContentRefusalError } from '../lib/aiToolkit/errorDetection.js';import { isSchemaTypeCategory, resolveProviderBench } from '../lib/providerCooldown.js';import { isGenerationModel, isVisionCapableCliProvider } from '../lib/localModelHeuristics.js';import { contextWindowRejection, knownContextWindow } from '../lib/aiToolkit/providerStatus.js';@@ -842,7 +842,7 @@ async function runPromptThroughProviderAdmitted(rawArgs) {// Stops and caller spending ceilings carry no provider-health verdict.// Neither enters correction/fallback, benching, or fault investigation.- if (isRunCanceledError(firstError) || isRuntimeBudgetError(firstError)) {+ if (isRunCanceledError(firstError) || isRuntimeBudgetError(firstError) || isContentRefusalError(firstError)) {throw stripFallbackContext(firstError);}@@ -926,8 +926,8 @@ async function runPromptThroughProviderAdmitted(rawArgs) {const primaryKey = { provider: failed.name || failed.id, model: failedModel };const investigation = createRecoveryInvestigationScope({ failed, failedModel, firstError });- const stopOnRuntimeBudget = async (error) => {- if (!isRuntimeBudgetError(error)) return;+ const stopOnTerminalRequest = async (error) => {+ if (!isRuntimeBudgetError(error) && !isContentRefusalError(error)) return;// Caller ceilings settle ownership without declaring a provider fault.await investigation.recoverAll();throw stripFallbackContext(error);@@ -969,7 +969,7 @@ async function runPromptThroughProviderAdmitted(rawArgs) {runId: undefined, // fresh run so the failed primary's record stays intact});} catch (tier1Error) {- await stopOnRuntimeBudget(tier1Error);+ await stopOnTerminalRequest(tier1Error);// The corrected retry failed. If it reached the execution layer, its// onRunFailed queued a task keyed on the EFFECTIVE provider/model// (createRun may have proactively swapped) — record and suppress that@@ -1026,7 +1026,7 @@ async function runPromptThroughProviderAdmitted(rawArgs) {runId: undefined, // fresh run so the failed primary's record stays intact});} catch (tier2Error) {- await stopOnRuntimeBudget(tier2Error);+ await stopOnTerminalRequest(tier2Error);// Same bookkeeping as Tier 1's failed corrected retry: a retry that// reached the execution layer queued its own task keyed on the// EFFECTIVE provider/model — record + suppress it so a slow Tier-3@@ -1102,7 +1102,7 @@ async function runPromptThroughProviderAdmitted(rawArgs) {runId: undefined, // fresh runId so the failed primary's record stays intact});} catch (fallbackError) {- await stopOnRuntimeBudget(fallbackError);+ await stopOnTerminalRequest(fallbackError);// ── Tier 4 — escalate ──: every deterministic tier failed. If the// fallback reached the execution layer, its OWN onRunFailed already// queued an investigation task (its key was never suppressed), so justdiff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.jsindex 0252cd0573..19596d85e4 100644--- a/server/services/promptRunner.test.js+++ b/server/services/promptRunner.test.js@@ -1146,6 +1146,19 @@ describe('promptRunner — retry-with-fallback', () => {// A pin opts out of ROUTING, not out of health reporting. Leaving the mark to// the fallback cascade let a provider fail every pinned call for hours while// the Providers page stayed green and unpinned callers kept choosing it.+ it('stops an initial policy refusal without selecting a provider or scheduling recovery', async () => {+ const status = mockToolkitWithFallback();+ runner.executeApiRun.mockImplementation(async ({ onComplete }) => onComplete({+ success: false, error: 'Policy refusal', errorAnalysis: { category: 'content-refusal' },+ }));+ await expect(runPromptThroughProvider({ provider: primaryApi, prompt: 'p', source: 'test' }))+ .rejects.toMatchObject({ errorAnalysis: { category: 'content-refusal' } });+ expect(runner.createRun).toHaveBeenCalledTimes(1);+ expect(status.getFallbackProvider).not.toHaveBeenCalled();+ expect(status.markUnavailable).not.toHaveBeenCalled();+ expect(autoFixer.escalateProviderFailure).not.toHaveBeenCalled();+ });+it.each([false, true])('rejects caller runtime exhaustion without recovery (allowFallback=%s)', async (allowFallback) => {const status = mockToolkitWithFallback();runner.executeApiRun.mockImplementation(async ({ onComplete }) => onComplete({@@ -2369,6 +2382,22 @@ describe('promptRunner — Tier 2 schema/type correction (issue #2350)', () => {expect(repair).toHaveBeenCalledWith(expect.objectContaining({ phase: 'response' }));});+ it('stops the correction cascade when its retry is refused by policy', async () => {+ const status = mockToolkitWithFallback();+ let attempts = 0;+ runner.executeApiRun.mockImplementation(async ({ onData, onComplete }) => {+ if (++attempts === 1) { onData('not json'); onComplete({ success: true }); }+ else onComplete({ success: false, error: 'Policy refusal', errorAnalysis: { category: 'content-refusal' } });+ });+ await expect(runPromptThroughProvider({ provider: apiProvider({ name: 'P' }), prompt: 'p', source: 'test',+ responseSchema: okShape })).rejects.toMatchObject({ errorAnalysis: { category: 'content-refusal' } });+ expect(attempts).toBe(2);+ expect(status.getFallbackProvider).not.toHaveBeenCalled();+ expect(status.markUnavailable).not.toHaveBeenCalled();+ expect(autoFixer.escalateProviderFailure).not.toHaveBeenCalled();+ expect(autoFixer.noteFallbackFailed).not.toHaveBeenCalled();+ });+it('stops the correction cascade when its retry exhausts a caller runtime budget', async () => {const status = mockToolkitWithFallback();let attempts = 0;diff --git a/server/services/promptSections/securityAudit.js b/server/services/promptSections/securityAudit.jsindex 4d3bb6893b..39025ce26b 100644--- a/server/services/promptSections/securityAudit.js+++ b/server/services/promptSections/securityAudit.js@@ -17,7 +17,12 @@ This security audit is running in a Codex agent. Run the scanner phase through C- 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.CLI contract: https://learn.chatgpt.com/docs/security/cli`;diff --git a/server/services/runner.js b/server/services/runner.jsindex 45ce02997e..2855ef6f43 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -155,7 +155,8 @@ export async function finalizeRunRecord({ runId, output, exitCode, success, erro// output because their provider banner is often the only useful signal.const analyzeError = toolkit.services.errorDetection.analyzeError;const analysisInput = exitCode === 124 ? (error || 'Process timed out') : output;- let errorAnalysis = analyzeError(analysisInput, exitCode);+ let errorAnalysis = extras?.errorAnalysis?.category === ERROR_CATEGORIES.CONTENT_REFUSAL+ ? extras.errorAnalysis : analyzeError(analysisInput, exitCode);// When that scan lands on nothing, the caller's own `error` is the better// evidence — and the run that proved it was a local-LLM playground timeout:// the host aborted its OWN deadline, finalized with exit 1 + `Timed out afterdiff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex 0549939337..c538640d78 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -135,6 +135,16 @@ beforeEach(() => {});describe('finalizeRunRecord — authoritative timeout classification', () => {+ it('preserves a structured refusal even when output contains a competing error or partial result', async () => {+ setAIToolkit(fakeToolkit({ analyzeError }), { dataDir: '/tmp/test-runner' });+ const errorAnalysis = { category: 'content-refusal', hasError: true, requiresFallback: false, message: 'Stopped' };+ const executionInterruption = { category: 'content-refusal', source: 'provider' };+ const result = await finalizeRunRecord({ runId: 'run-refusal', output: 'Partial result mentions billing',+ exitCode: 1, success: false, error: 'Stopped', startTime: Date.now(),+ extras: { errorAnalysis, executionInterruption } });+ expect(result).toMatchObject({ success: false, errorCategory: 'content-refusal', errorAnalysis, executionInterruption });+ });+it('does not let story text misclassify exit 124 as a provider quota failure', async () => {setAIToolkit(fakeToolkit({ analyzeError }), { dataDir: '/tmp/test-runner' });diff --git a/server/services/tuiPromptRunner.js b/server/services/tuiPromptRunner.jsindex edb15691a8..4bb547f8fd 100644--- a/server/services/tuiPromptRunner.js+++ b/server/services/tuiPromptRunner.js@@ -44,6 +44,7 @@ import { ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';import {createClaudeSessionLimitBannerDetector,+ createContentRefusalDetector,createImmediateFallbackSignalDetector,createTerminalModelErrorDetector,createTerminalRequestTimeoutDetector,@@ -415,6 +416,7 @@ ${prompt}`;let firstResponseAt = null;let finalized = false;const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();+ const detectContentRefusal = createContentRefusalDetector();const detectClaudeSessionLimitBanner = createClaudeSessionLimitBannerDetector();const mayUseClaudeLowPriority = provider.type === 'tui'&& provider.lowPriorityOnUsageLimit === true@@ -510,7 +512,7 @@ ${prompt}`;};return new Promise((resolve) => {- const finish = async ({ success, exitCode = 0, error = null, reason = 'completed', canceled = false }) => {+ const finish = async ({ success, exitCode = 0, error = null, reason = 'completed', canceled = false, errorAnalysis = null }) => {if (finalized) return;finalized = true;// Tracks whether the normal-path onComplete was reached, so the catch@@ -556,6 +558,7 @@ ${prompt}`;reportFailure,extras: {completionReason: reason,+ ...(errorAnalysis ? { errorAnalysis, executionInterruption: { category: errorAnalysis.category, source: 'provider' } } : {}),usedResponseFile,outputTruncated: outputBufferTruncated,...(canceled ? { canceled: true } : {}),@@ -566,6 +569,7 @@ ${prompt}`;return {exitCode, success, error: error || err.message,duration: Date.now() - startTime, completionReason: reason,+ ...(errorAnalysis ? { errorAnalysis } : {}),...(canceled ? { canceled: true } : {}),};});@@ -598,6 +602,7 @@ ${prompt}`;onComplete?.({runId, success: false, exitCode, error: `finish() failed: ${err?.message || err}`,duration: Date.now() - startTime, completionReason: reason,+ ...(errorAnalysis ? { errorAnalysis } : {}),...(canceled ? { canceled: true } : {}),});} catch (cbErr) {@@ -649,6 +654,13 @@ ${prompt}`;if (rawBuffer.length > RAW_BUFFER_HEADROOM) rawBuffer = rawBuffer.slice(-RAW_BUFFER_CAP);const stripped = streamingStrip(text);+ const refusal = isCodexCommand(command) && promptSubmittedAt ? detectContentRefusal(text) : null;+ if (refusal) {+ void finish({ success: false, exitCode: 1, error: refusal.message,+ reason: 'content-refusal', errorAnalysis: refusal });+ return;+ }+// The readiness tracker needs both streams: bracketed-paste transitions// survive only in raw output, while startup dialog text is ANSI-stripped.inputReady.observe(text, stripped);diff --git a/server/services/tuiPromptRunner.test.js b/server/services/tuiPromptRunner.test.jsindex dd90169ef9..22e9eacfb2 100644--- a/server/services/tuiPromptRunner.test.js+++ b/server/services/tuiPromptRunner.test.js@@ -1241,6 +1241,32 @@ describe('executeTuiRun', () => {}));});+ it('stops a Codex policy refusal even when a response file is already available', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] });+ const runId = 'run-refusal';+ const provider = { id: 'codex', type: 'tui', command: 'codex', tuiPromptDelayMs: 50 };+ const onComplete = vi.fn();+ const promise = executeTuiRun({ runId, provider, prompt: 'a prompt long enough to submit',+ workspacePath: TEST_WORKSPACE, onComplete, timeout: 60000 });+ await flushAsync();+ const pty = ptyInstances[0];+ pty.emitData('› Ask Codex to do anything\n? for shortcuts');+ await vi.advanceTimersByTimeAsync(6000);+ responseFiles.set(resolve(runsTmpDirRef.current, runId, 'tui-response.txt'), 'partial response');+ pty.emitData('Ordinary output');+ pty.emitData('\x1b[12;1H');+ pty.emitData('ⓘ This content can’t be shown');+ await promise;+ expect(pty.kill).toHaveBeenCalled();+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ success: false, extras: expect.objectContaining({ completionReason: 'content-refusal',+ errorAnalysis: expect.objectContaining({ category: 'content-refusal' }),+ executionInterruption: { category: 'content-refusal', source: 'provider' },+ }),+ }));+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({ success: false }));+ });+it('early-fails with reason "fallback-signal" when Claude switches to extra usage', async () => {const provider = { id: 'claude', type: 'tui', command: 'claude' };const onComplete = vi.fn();