OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(deep-scan): finalize runs, preserve findings, and honor project budgets (#1912)
Michael D'Angelod329d8dce5d2
diff --git a/docs/project-configuration.md b/docs/project-configuration.mdindex 707434f91..0fe923ba5 100644--- a/docs/project-configuration.md+++ b/docs/project-configuration.md@@ -76,6 +76,48 @@ cd ../..node sdk/typescript/bin/codex-security.mjs scan . -c docs/examples/codex-security.yaml --dry-run --json```+## Desktop and conversational Deep Scans++Deep Scan setup accepts an explicitly selected `.yaml`, `.yml`, or `.json` project+file using the same format. For example:++```yaml+scan:+ mode: deep+ max_time_minutes: 30+ deep:+ workers: 2+ subagents_per_worker: 1+ stop_after_no_new: 2+ max_discovery_runs: 4+```++The plugin's `inspect_codex_security_setup` tool accepts `projectConfigPath` and+returns `setup.deepScanConfig`: effective worker count, subagents per worker,+novelty-stop threshold, consecutive-error threshold, review cap, and discovery+time limit, with the source of each value. Desktop setup clients should display+these values before starting a scan. Conversational scans inspect the same setup+before passing `projectConfigPath` to `start_codex_security_deep_scan`.++Explicit project settings override per-user `[deep_scan]` settings, which override+built-in defaults. The per-user file remains+`$CODEX_HOME/codex-security/config.toml`, or the existing+`CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH` selection. The project selection does not+change that file or unrelated scans. No repository configuration is discovered or+activated automatically.++This integration supports `scan.mode: deep`, `scan.max_time_minutes`, and all+`scan.deep` fields listed below. Other configured fields, including `codex`,+`auth`, scope, context files, cost limits, output, and exit policy, are rejected+with their names before model work starts. Use CLI/SDK configuration for those+settings. If both minute and hour limits are present, they must agree.++Saving native setup freezes the effective settings and their sources. Headless+scans freeze them when first started. Reconnecting or resuming with the returned+scan ID uses that snapshot even if the selected file or global defaults change.+The time limit bounds discovery; scans may stop sooner after novelty or review+limits, and aggregation and reporting can continue afterward.+## Settings| Field | Meaning | Default |diff --git a/plugins/codex-security/mcp-app/package.json b/plugins/codex-security/mcp-app/package.jsonindex 8ce3af9d0..e4324bfe0 100644--- a/plugins/codex-security/mcp-app/package.json+++ b/plugins/codex-security/mcp-app/package.json@@ -14,7 +14,8 @@"@openai/codex-sdk": "0.164.0","ajv": "8.20.0","smol-toml": "1.9.1",- "zod": "^4.6.7"+ "zod": "^4.6.7",+ "yaml": "2.9.1"},"devDependencies": {"@types/node": "^26.6.5",diff --git a/plugins/codex-security/mcp-app/pnpm-lock.yaml b/plugins/codex-security/mcp-app/pnpm-lock.yamlindex cc3651658..00b4688c6 100644--- a/plugins/codex-security/mcp-app/pnpm-lock.yaml+++ b/plugins/codex-security/mcp-app/pnpm-lock.yaml@@ -20,6 +20,9 @@ importers:smol-toml:specifier: 1.9.1version: 1.9.1+ yaml:+ specifier: 2.9.1+ version: 2.9.1zod:specifier: ^4.6.7version: 4.6.7@@ -747,6 +750,11 @@ packages:resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}+ resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==}+ engines: {node: '>= 14.6'}+ hasBin: true+resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==}peerDependencies:@@ -1381,6 +1389,8 @@ snapshots:+ [email protected]: {}+dependencies:zod: 4.6.7diff --git a/plugins/codex-security/mcp-app/server.ts b/plugins/codex-security/mcp-app/server.tsindex c212a1b5c..7d18141d7 100644--- a/plugins/codex-security/mcp-app/server.ts+++ b/plugins/codex-security/mcp-app/server.ts@@ -1,4 +1,5 @@import { workbenchArgs } from "./src/workbench-arguments.js";+import { CodexSecurityStdioTransport } from "./src/stdio-transport.js";import {readingAnnotations,writingAnnotations,@@ -21,6 +22,7 @@ import { registerCompactArtifactTools } from "./src/server/compact-artifact-toolimport { registerFindingIssueTools } from "./src/server/finding-issue-tools.js";import {DeepScanCoordinatorRegistry,+ DeepScanCoordinator,AsyncLock,} from "./src/deep-scan/registry.js";import { startDeepScanEngine } from "./src/deep-scan/engine.js";@@ -31,6 +33,7 @@ import {type DeepWorkerParentSandbox,} from "./src/deep-scan/parent-sandbox.js";import { WorkbenchDeepScanStore } from "./src/deep-scan/store.js";+import { readDeepScanProjectConfig } from "./src/deep-scan/project-config.js";import type { DeepScanRunState } from "./src/deep-scan/types.js";import { PLUGIN_ROOT, runWorkbench, scanRoot } from "./src/workbench-client.js";@@ -245,7 +248,13 @@ const requestUserInputSchema = {const targetInspectionSchema = {targetPath: pathSchema,};+const projectConfigPathSchema = pathSchema+ .optional()+ .describe(+ "Project YAML/JSON configuration explicitly selected by the user. Never discover or select a repository file automatically. Supported for Deep Scan only.",+ );const submissionSchema = {+ projectConfigPath: projectConfigPathSchema,diffTarget: diffTargetSchema.optional(),mode: z.enum(["diff", "standard", "deep"]),scope: pathSchema,@@ -255,6 +264,7 @@ const submissionSchema = {userContext: trimmedText.optional(),};const setupInspectionSchema = {+ projectConfigPath: projectConfigPathSchema,diffTarget: diffTargetSchema.optional(),mode: z.enum(["diff", "standard", "deep"]),scope: pathSchema,@@ -262,6 +272,7 @@ const setupInspectionSchema = {};const scanSchema = { scanId: z.string().uuid() };const startDeepScanSchema = {+ projectConfigPath: projectConfigPathSchema,scanId: z.string().uuid()@@ -479,6 +490,10 @@ export function createCodexSecurityServer(): McpServer {},);const deepScanCoordinators = new DeepScanCoordinatorRegistry();+ const deepScanCompletions = new WeakMap<+ DeepScanCoordinator,+ Promise<ReturnType<typeof deepScanTerminalResult>>+ >();// Serialize start-or-join so a scan creates only one coordinator.const deepScanStartLock = new AsyncLock();const deepScanStore = new WorkbenchDeepScanStore(runWorkbench);@@ -805,20 +820,25 @@ export function createCodexSecurityServer(): McpServer {{title: "Validate Codex Security Setup",description:- "App-only. Resolve and validate the complete local target, scope, mode, and exact Git change set without saving setup.",+ "Resolve and validate the local target, scope, mode, and exact Git change set without saving setup. Deep Scan returns effective limits and their sources before model work; projectConfigPath must be explicitly selected by the user.",inputSchema: setupInspectionSchema,annotations: readingAnnotations,- _meta: appMeta,+ _meta: { ui: { visibility: ["app", "model"] } },},- async ({ targetPath, scope, mode, diffTarget }) => {+ async ({ targetPath, scope, mode, diffTarget, projectConfigPath }) => {+ const selected = await deepScanProjectSetup(+ targetPath,+ projectConfigPath,+ );const setup = await runWorkbench(["inspect-setup","--target-path",- targetPath,+ selected.targetPath,`--scope=${scope}`,"--mode",mode,...diffTargetArgs(diffTarget),+ ...optionalArg("--deep-scan-project-json", selected.projectConfigJson),]);return scanActionResult({ setup },@@ -845,7 +865,12 @@ export function createCodexSecurityServer(): McpServer {targetSummary,userContext,diffTarget,+ projectConfigPath,}) => {+ const selected = await deepScanProjectSetup(+ targetPath,+ projectConfigPath,+ );return workspaceResult((await runWorkbench([@@ -853,13 +878,17 @@ export function createCodexSecurityServer(): McpServer {"--workspace-id",sessionId,"--target-path",- targetPath,+ selected.targetPath,`--scope=${scope}`,"--mode",mode,...definedArg("--target-summary", targetSummary),...(userContext ? ["--user-context-stdin"] : []),...diffTargetArgs(diffTarget),+ ...optionalArg(+ "--deep-scan-project-json",+ selected.projectConfigJson,+ ),],userContext,)) as WorkspaceState,@@ -896,13 +925,20 @@ export function createCodexSecurityServer(): McpServer {{title: "Start or Join Codex Security Deep Scan",description:- "Run or rejoin independent Standard security scans and semantically merge their validated findings. Pass scanId and its handoffClaimToken to resume, or targetPath to start headlessly. The call blocks until the aggregate draft is ready, fails, or is canceled. On success, use the returned scanId and scanDir; manifestPath identifies the canonical parent scan-manifest.json. Call complete_codex_security_scan once.",+ "Run or rejoin independent Standard security scans and semantically merge their validated findings. Pass scanId and its handoffClaimToken to resume, or targetPath to start headlessly. The coordinator finalizes the parent even if this caller detaches. For an SDK-registered scan it returns the aggregate to the SDK for finalization. Follow the returned instructions for the authoritative scanId, scanDir, and manifestPath.",inputSchema: startDeepScanSchema,annotations: writingAnnotations,_meta: modelActionMeta,},async (- { scanId, targetPath, scope, userContext, handoffClaimToken },+ {+ scanId,+ targetPath,+ scope,+ userContext,+ handoffClaimToken,+ projectConfigPath,+ },extra,) => {const hasScanId = scanId !== undefined;@@ -915,10 +951,12 @@ export function createCodexSecurityServer(): McpServer {}if (hasScanId &&- (scope !== undefined || normalizedUserContext !== undefined)+ (scope !== undefined ||+ normalizedUserContext !== undefined ||+ projectConfigPath !== undefined)) {return toolErrorResult(- "When scanId is present, omit targetPath, scope, and userContext; the persisted scan is authoritative.",+ "When scanId is present, omit targetPath, scope, userContext, and projectConfigPath; the persisted scan is authoritative.",);}if (hasTarget && !wholeTargetScope(scope, targetPath)) {@@ -944,6 +982,41 @@ export function createCodexSecurityServer(): McpServer {} catch (error: unknown) {return toolErrorResult(deepScanInvocationFailureMessage(error));}+ const completeDeepScan = async (run: DeepScanRunState) => {+ if (run.status !== "succeeded" || run.sdkOwnsCompletion)+ return deepScanTerminalResult(run);+ try {+ const turnMetadata = codexTurnMetadataFromExtra(extra);+ const turnId =+ turnMetadata?.thread_source === "security_scan"+ ? turnMetadata.turn_id+ : undefined;+ const completion = await runWorkbench([+ "complete-scan",+ "--scan-id",+ run.scanId,+ ...optionalArg("--claim-token", handoffClaimToken),+ ...optionalArg("--thread-id", threadId),+ ...optionalArg(+ "--turn-id",+ typeof turnId === "string" ? turnId : undefined,+ ),+ ]);+ return deepScanTerminalResult(run, completion);+ } catch (error) {+ logDeepScanEvent({+ event: "coordinator_completion_failed",+ scanId: run.scanId,+ reason: failureDiagnostic(error),+ });+ return {+ ...toolErrorResult(+ `${completionFailureMessage(error)}\nScan ID: ${run.scanId}`,+ ),+ structuredContent: { scanId: run.scanId },+ };+ }+ };const preparation = await deepScanStartLock.run(async () => {const begun = await deepScanStore.begin({@@ -953,6 +1026,7 @@ export function createCodexSecurityServer(): McpServer {userContext: normalizedUserContext,handoffClaimToken,threadId,+ projectConfigPath,...modelSettings,scanRoot: await scanRoot(),});@@ -963,7 +1037,34 @@ export function createCodexSecurityServer(): McpServer {});}const immediate = deepScanTerminalResult(begun);- if (immediate) return { begun, immediate };+ if (immediate) {+ const coordinator = deepScanCoordinators.get(begun.scanId);+ return {+ begun,+ immediate,+ completion: {+ result:+ (coordinator && deepScanCompletions.get(coordinator)) ??+ completeDeepScan(begun),+ },+ };+ }+ const completion: {+ result?: Promise<ReturnType<typeof deepScanTerminalResult>>;+ } = {};+ const onStart = (coordinator: DeepScanCoordinator) => {+ completion.result = deepScanCompletions.get(coordinator);+ if (!completion.result) {+ // The same hook runs when a remote observer adopts an expired lease.+ // Completion belongs to the coordinator, not an abortable RPC waiter.+ completion.result = coordinator+ .settled()+ .then(completeDeepScan, (error) =>+ toolErrorResult(deepScanInvocationFailureMessage(error)),+ );+ deepScanCompletions.set(coordinator, completion.result);+ }+ };const started = await startDeepScanEngine({run: begun,registry: deepScanCoordinators,@@ -977,8 +1078,15 @@ export function createCodexSecurityServer(): McpServer {log: logDeepScanEvent,handoffClaimToken,threadId,+ onStart,});- return { begun, ...started };+ if (+ !completion.result &&+ started.coordinator instanceof DeepScanCoordinator+ ) {+ onStart(started.coordinator);+ }+ return { begun, ...started, completion };}).catch((error: unknown) => ({invocationFailure: toolErrorResult(@@ -987,25 +1095,58 @@ export function createCodexSecurityServer(): McpServer {}));if ("invocationFailure" in preparation)return preparation.invocationFailure;- if (preparation.immediate) return preparation.immediate;- const { begun, coordinator, joined } = preparation;- if (joined) {- logDeepScanEvent({- event: "coordinator_joined",- scanId: begun.scanId,- });+ const { begun } = preparation;+ let result;+ if (preparation.immediate) {+ result = (await preparation.completion.result) ?? preparation.immediate;+ } else {+ const { coordinator, joined } = preparation;+ if (joined) {+ logDeepScanEvent({+ event: "coordinator_joined",+ scanId: begun.scanId,+ });+ }+ const terminal = await coordinator.wait(abortSignalFromExtra(extra));+ result = preparation.completion.result+ ? await preparation.completion.result+ : await completeDeepScan(terminal);}- const terminal = await coordinator.wait(abortSignalFromExtra(extra));- const result = deepScanTerminalResult(terminal);if (!result) {return toolErrorResult(deepScanInvocationFailureMessage(new Error(- `Deep Scan ${terminal.scanId} ended without a terminal result.`,+ `Deep Scan ${begun.scanId} ended without a terminal result.`,),),);}+ // A canceled waiter or a transport size error never delivers the scan ID.+ const transport = server.server.transport;+ if (+ !handoffClaimToken &&+ "structuredContent" in result &&+ "completion" in result.structuredContent &&+ transport instanceof CodexSecurityStdioTransport+ ) {+ transport.afterResultSent(extra.requestId, extra.signal, () =>+ deepScanStartLock.run(async () => {+ try {+ await runWorkbench(+ workbenchArgs("acknowledge-deep-scan-result", {+ scanId: begun.scanId,+ }),+ );+ } catch (error) {+ logDeepScanEvent({+ event: "target_result_acknowledgment_failed",+ scanId: begun.scanId,+ reason: failureDiagnostic(error),+ });+ }+ }),+ );+ }return result;},);@@ -1891,6 +2032,26 @@ async function startHeadlessStandardScan();}+async function deepScanProjectSetup(+ targetPath: string,+ projectConfigPath?: string,+) {+ if (projectConfigPath === undefined) return { targetPath };+ const inspected = await runWorkbench(+ workbenchArgs("inspect-target", { targetPath }),+ );+ if (typeof inspected.targetPath !== "string")+ throw new Error("Missing scan target path.");+ const project = await readDeepScanProjectConfig(+ projectConfigPath,+ inspected.targetPath,+ );+ return {+ targetPath: inspected.targetPath,+ projectConfigJson: JSON.stringify(project),+ };+}+function wholeTargetScope(scope: string | undefined,targetPath: string | undefined,@@ -2069,15 +2230,21 @@ function boundedErrorData(error: unknown): { message: string; name: string } {};}-function deepScanTerminalResult(run: DeepScanRunState) {+function deepScanTerminalResult(+ run: DeepScanRunState,+ completion?: JsonObject,+) {if (run.status === "succeeded") {if (!run.manifestPath) return undefined;- const instructions = `Deep Scan discovery completed. Independent Standard scans have already performed validation and attack-path analysis and have been consolidated into the canonical scan-manifest.json, findings.json, and coverage.json under ${run.scanDir}. The returned manifestPath is the canonical scan-manifest.json, not a legacy discovery manifest. Any instructions requiring parent candidate listing, centralized validation, attack-path analysis, or another draft apply only to the old discovery-only workflow and must be skipped. The authoritative scan ID is ${run.scanId}. Immediately call complete_codex_security_scan once using that scan ID to seal and publish the scan. Return output only after completion succeeds and generated report.md exists. If completion fails, surface that exact error and return no final, no-findings, structured, or benchmark response.`;+ const instructions = run.sdkOwnsCompletion+ ? `Deep Scan ${run.scanId} aggregated its validated findings under ${run.scanDir}. End this turn with the returned scanId and manifestPath. The SDK owns finalization and report generation after the turn ends.`+ : `Deep Scan ${run.scanId} completed. The coordinator validated and sealed scan-manifest.json, findings.json, and coverage.json and generated report.md under ${run.scanDir}. Independent Standard scans have already performed validation and attack-path analysis. Use the returned authoritative scanId, scanDir, and manifestPath. Do not call complete_codex_security_scan again, rerun worker phases, list candidates, submit another draft, or start a replacement scan. Report the completed results and link the generated report.`;return scanActionResult({scanId: run.scanId,scanDir: run.scanDir,manifestPath: run.manifestPath,+ ...(completion === undefined ? {} : { completion }),instructions,},instructions,diff --git a/plugins/codex-security/mcp-app/src/artifact-contracts.ts b/plugins/codex-security/mcp-app/src/artifact-contracts.tsindex 5ef65a7e3..a93b21f20 100644--- a/plugins/codex-security/mcp-app/src/artifact-contracts.ts+++ b/plugins/codex-security/mcp-app/src/artifact-contracts.ts@@ -387,6 +387,15 @@ const draft_scanDraftInput = z.strictObject({coverage: draft_coverage,});+const deep_reductionInput = draft_scanDraftInput+ .omit({ coverage: true })+ .extend({+ complete: z+ .boolean()+ .describe("Omit or set true when submitting the finished aggregate.")+ .optional(),+ });+/** Native tool contracts; JSON resources are generated compatibility exports. */export const artifactSchemaDocuments = {"definitions/artifact-common": {@@ -489,7 +498,7 @@ export const artifactSchemaDocuments = {},"tools/deep-reducer": {title: "Codex Security Deep Scan semantic reducer operations",- $ref: "#/$defs/reductionInput",+ $ref: "#/$defs/reductionSubmission",$defs: {reducerInputs: z.strictObject({cursor: z@@ -507,10 +516,13 @@ export const artifactSchemaDocuments = {).optional(),}),- reductionInput: draft_scanDraftInput.omit({ coverage: true }).extend({- complete: z- .boolean()- .describe("Omit or set true when submitting the finished aggregate.")+ reductionInput: deep_reductionInput,+ reductionSubmission: deep_reductionInput.extend({+ retainedFindingRefs: z+ .array(z.string().regex(/^previous:(0|[1-9][0-9]*)$/))+ .describe(+ "Copy unchanged previous aggregate findings by previous:<zero-based index>. The host preserves their complete bodies, identities, and source references; do not also submit them in findings.",+ ).optional(),}),},diff --git a/plugins/codex-security/mcp-app/src/artifact-deep-reducer.ts b/plugins/codex-security/mcp-app/src/artifact-deep-reducer.tsindex 74f9fa607..3d22beed2 100644--- a/plugins/codex-security/mcp-app/src/artifact-deep-reducer.ts+++ b/plugins/codex-security/mcp-app/src/artifact-deep-reducer.ts@@ -6,6 +6,7 @@ import {saveScanDraftCheckpoint,} from "./artifact-scan-draft.js";import { artifactSchemaDocuments } from "./artifact-contracts.js";+import { projectArtifactToolSchema } from "./artifact-schema-loader.js";import { saveThreatModelDocument } from "./threat-model-document.js";import {createDeepScanArtifacts,@@ -25,7 +26,9 @@ import {const reducerDefinitions = artifactSchemaDocuments["tools/deep-reducer"].$defs;export const deepReducerInputsInputSchema = reducerDefinitions.reducerInputs;-export { deepReductionInputSchema } from "./deep-scan/artifact-validation.js";+export const deepReductionInputSchema = projectArtifactToolSchema(+ reducerDefinitions.reductionSubmission,+);/** Read the findings and scan context assigned to this reducer. */export async function getCodexSecurityDeepReducerInputs(@@ -157,7 +160,9 @@ export async function recordCodexSecurityDeepReduction(}> {return withLogicalReducerErrors(context, async () => {const bound = bindDeepReducer(context);- let reduction = parseDeepReduction(input);+ const { retainedFindingRefs = [], ...submission } =+ deepReductionInputSchema.parse(input);+ let reduction = parseDeepReduction(submission);if (reduction.complete === false)throw new Error("Deep reduction is only a checkpoint, not a complete result.",@@ -176,6 +181,7 @@ export async function recordCodexSecurityDeepReduction(reduction,inputs.discoveries,inputs.previous,+ retainedFindingRefs,);const persisted = deepReductionForPersistence(reduction);diff --git a/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.ts b/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.tsindex 2d58efaea..eb0bd18a6 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.ts@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";import { dirname, posix, relative, sep } from "node:path";import { isDeepStrictEqual } from "node:util";import type { JsonObject } from "../types.js";+import { asRecord } from "../record.js";import type { AcceptedDiscovery } from "./worker-runner.js";import { artifactSourcePath, type ArtifactContext } from "../artifact-io.js";import {@@ -252,20 +253,11 @@ export async function validateReducerArtifacts(} else {validateRetainedFindings(result, [], previous);}- const previousFindingIds = new Set(- input.sources- ? (previous?.findings ?? [])- .flatMap(retainedFindingSources)- .map((source) => source.id)- : (previous?.findings ?? []).map(scanFindingIdentity),- );+ const assignments = previousFindingAssignments(result, previous);return {result,- newFindings: result.findings.filter((finding) =>- input.sources- ? !findingSourceIds(finding).some((id) => previousFindingIds.has(id))- : !previousFindingIds.has(scanFindingIdentity(finding)),- ).length,+ newFindings: result.findings.filter((finding) => !assignments.has(finding))+ .length,};}@@ -274,6 +266,7 @@ export function reconcileDeepReduction(input: DeepReductionInput,discoveries: DeepReductionSources["discoveries"],previous: DeepReductionInput | null,+ retainedFindingRefs: string[] = [],): DeepReductionInput {// Check retained fresh data before merging historical sources. The host// replaces submitted sourceFindings with the original source payloads below.@@ -293,6 +286,18 @@ export function reconcileDeepReduction(throw new Error("Deep reduction is only a checkpoint, not a complete result.",);+ for (const ref of retainedFindingRefs) {+ const index = Number(ref.slice("previous:".length));+ const finding = previous?.findings[index];+ if (!finding)+ throw new Error(+ `Deep reduction retained finding ${ref} is not assigned to this reducer.`,+ );+ const retained = structuredClone(finding);+ (retained.provenance as Record<string, unknown>).sourceFindingIds =+ retainedFindingSources(finding, index).map((source) => source.id);+ result.findings.push(retained);+ }for (const source of [...discoveries.map((discovery) => discovery.result),...(previous ? [previous] : []),@@ -304,25 +309,23 @@ export function reconcileDeepReduction("Deep reduction source is only a checkpoint, not a complete result.",);}- validateRetainedFindings(+ validateReductionHasFindings(result,discoveries.map((discovery) => discovery.result),previous ?? undefined,);retainSourceFindings(result, { discoveries, previous });- for (const [index, finding] of (previous?.findings ?? []).entries()) {- const previousRefs = retainedFindingSources(finding, index).map(- (source) => source.id,- );- const retained = result.findings.find((current) =>- findingSourceIds(current).some((ref) => previousRefs.includes(ref)),- );- if (retained) {- const sourceIds = findingSourceIds(retained);+ for (const [retained, previousFindings] of previousFindingAssignments(+ result,+ previous,+ )) {+ const sourceIds = findingSourceIds(retained);+ for (const finding of previousFindings) {+ validateRetainedFindingContent(retained, finding, sourceIds);preserveFindingDetails(retained, finding);- (retained.provenance as Record<string, unknown>).sourceFindingIds =- sourceIds;}+ (retained.provenance as Record<string, unknown>).sourceFindingIds =+ sourceIds;}retainSourceFindings(result, { discoveries, previous });for (const [field, label] of [@@ -556,6 +559,7 @@ function retainSourceFindings(throw new Error(`Deep reduction attributes source finding ${id} more than once.`,);+ validateRetainedFindingContent(finding, sources.get(id)!, [id]);claimed.add(id);}provenance.sourceFindingIds = refs;@@ -571,8 +575,41 @@ function retainSourceFindings();}-/** Preserve previously accepted identities and never discard every reported finding. */-export function validateRetainedFindings(+/** Reject placeholder substitutions without limiting legitimate synthesis. */+function validateRetainedFindingContent(+ current: Record<string, unknown>,+ previous: Record<string, unknown>,+ sourceRefs: string[],+): void {+ const placeholder = /^(?:x|tbd|todo|\.{3}|…)$/i;+ const compare = (value: unknown, original: unknown, field: string): void => {+ if (+ typeof original === "string" &&+ original.trim() &&+ !placeholder.test(original.trim()) &&+ typeof value === "string" &&+ placeholder.test(value.trim())+ ) {+ throw new Error(+ `Deep reduction replaced ${field} with placeholder text for source findings ${sourceRefs.join(", ")}. Preserve the accepted content or retain the unchanged finding by reference.`,+ );+ }+ const currentFields = asRecord(value);+ const previousFields = asRecord(original);+ if (currentFields && previousFields)+ for (const [name, text] of Object.entries(previousFields))+ compare(currentFields[name], text, `${field}.${name}`);+ };+ for (const field of ["title", "summary", "remediation", "writeup"])+ compare(current[field], previous[field], field);+ compare(+ asRecord(current.rootCause)?.summary ?? current.rootCause,+ asRecord(previous.rootCause)?.summary ?? previous.rootCause,+ "rootCause",+ );+}++function validateReductionHasFindings(result: DeepReductionInput,sources: DeepReductionInput[],previous?: DeepReductionInput,@@ -586,19 +623,94 @@ export function validateRetainedFindings("Deep reduction discarded every accepted Standard scan finding.",);}+}- const currentFindingIds = new Set(result.findings.map(scanFindingIdentity));- for (const finding of previous?.findings ?? []) {- if (currentFindingIds.has(scanFindingIdentity(finding))) continue;- throw Object.assign(- new Error(- "Deep reduction discarded or changed a previously accepted finding identity.",- ),- {- code: "merge_traceability_unstable_candidate_id",- },+/** Each prior source group stays whole, but semantic aliases can share a recipient. */+function previousFindingAssignments(+ result: DeepReductionInput,+ previous?: DeepReductionInput | null,+): Map<DeepReductionInput["findings"][number], DeepReductionInput["findings"]> {+ const assignments = new Map<+ DeepReductionInput["findings"][number],+ DeepReductionInput["findings"]+ >();+ for (const [index, finding] of (previous?.findings ?? []).entries()) {+ const previousRefs = retainedFindingSources(finding, index).map(+ (source) => source.id,);+ const originals = (finding.provenance as { sourceFindings?: unknown[] })+ .sourceFindings;+ const legacy = !originals?.length;+ let matches = result.findings.filter((current) => {+ const refs = new Set(findingSourceIds(current));+ return previousRefs.every((ref) => refs.has(ref));+ });+ if (legacy && matches.length === 0) {+ matches = result.findings.filter(+ (current) =>+ scanFindingIdentity(current) === scanFindingIdentity(finding),+ );+ }+ if (matches.length !== 1) {+ throw Object.assign(+ new Error(+ `Deep reduction discarded, split, or ambiguously reassigned a previously accepted finding (${previousRefs.join(", ")}).`,+ ),+ { code: "merge_traceability_unstable_candidate_id" },+ );+ }+ const retained = matches[0]!;+ if (+ legacy &&+ scanFindingIdentity(retained) !== scanFindingIdentity(finding)+ ) {+ throw Object.assign(+ new Error(+ "Deep reduction changed a previously accepted finding identity.",+ ),+ { code: "merge_traceability_unstable_candidate_id" },+ );+ }+ const assigned = assignments.get(retained) ?? [];+ assigned.push(finding);+ assignments.set(retained, assigned);}+ for (const [retained, assigned] of assignments) {+ if (+ assigned.length === 1 &&+ scanFindingIdentity(retained) !== scanFindingIdentity(assigned[0]!)+ ) {+ throw Object.assign(+ new Error(+ "Deep reduction changed an independently retained previously accepted finding identity.",+ ),+ { code: "merge_traceability_unstable_candidate_id" },+ );+ }+ }+ return assignments;+}++/** Preserve accepted source groups and keep independent finding identities stable. */+export function validateRetainedFindings(+ result: DeepReductionInput,+ sources: DeepReductionInput[],+ previous?: DeepReductionInput,+): void {+ validateReductionHasFindings(result, sources, previous);+ for (const [current, originals] of previousFindingAssignments(+ result,+ previous,+ ))+ for (const original of originals)+ validateRetainedFindingContent(+ current,+ original,+ findingSourceIds(current),+ );+ for (const [index, finding] of result.findings.entries())+ for (const source of retainedFindingSources(finding, index))+ validateRetainedFindingContent(finding, source.finding, [source.id]);}export function parseStoredScanDraft<Result extends DeepReductionInput>(diff --git a/plugins/codex-security/mcp-app/src/deep-scan/coordinator.ts b/plugins/codex-security/mcp-app/src/deep-scan/coordinator.tsindex f5320869f..83319d8d9 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/coordinator.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/coordinator.ts@@ -93,6 +93,7 @@ export interface CoordinatorOptions {publication: DeepScanPublication,) => Promise<void>;onStopped?: (run: DeepScanRunState) => Promise<void>;+ onStart?: (coordinator: DeepScanCoordinator) => void;}export { DeepScanNonRetryableError } from "./errors.js";diff --git a/plugins/codex-security/mcp-app/src/deep-scan/engine.ts b/plugins/codex-security/mcp-app/src/deep-scan/engine.tsindex 9f619af1c..a1309f2d5 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/engine.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/engine.ts@@ -10,6 +10,7 @@ import {} from "./registry.js";import type { WorkbenchDeepScanStore } from "./store.js";import type { DeepScanLogger, DeepScanRunState } from "./types.js";+import type { CoordinatorOptions } from "./coordinator.js";/** Shared execution behind the SDK engine and the plugin's MCP adapter. */export function startDeepScanEngine(options: {@@ -26,6 +27,7 @@ export function startDeepScanEngine(options: {model?: string;reasoningEffort?: string;log?: DeepScanLogger;+ onStart?: CoordinatorOptions["onStart"];}) {const { run, runWorkbench, pluginRoot, threadId, handoffClaimToken } =options;@@ -37,6 +39,7 @@ export function startDeepScanEngine(options: {executor: new CodexSdkWorkerExecutor({model: options.model,reasoningEffort: options.reasoningEffort,+ deepScanConfig: run.config,parentSandbox: options.parentSandbox,parentTurn: options.parentTurn,artifactContext: {@@ -51,6 +54,7 @@ export function startDeepScanEngine(options: {}),pluginRoot,log: options.log,+ onStart: options.onStart,handoffClaimToken,threadId,onComplete: async (draft, signal, publication) => {diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.tsindex ab0f8d236..31cd89a76 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts@@ -25,7 +25,7 @@ import {type ThreadEvent,} from "@openai/codex-sdk";import { readCodexSessionTurn } from "../../../scripts/codex_session.mjs";-import { parse as parseToml } from "smol-toml";+import { parse as parseToml, stringify as stringifyToml } from "smol-toml";import {createCodexProfileClient,preflightProviderDefinitions,@@ -51,11 +51,13 @@ import type {CodexWorkerExecutor,CodexWorkerRequest,CodexWorkerResult,+ DeepScanConfig,} from "./types.js";export interface CodexSdkWorkerModelSettings {model?: string;reasoningEffort?: string;+ deepScanConfig?: DeepScanConfig;artifactContext?: CodexSdkWorkerArtifactContext;parentSandbox?: DeepWorkerParentSandbox;parentTurn?: DeepScanParentTurn;@@ -98,6 +100,10 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {includePaths === undefined? undefined: resolve(dirname(request.promptPath), `scope-${randomUUID()}.json`);+ const deepConfigFile =+ this.modelSettings.deepScanConfig === undefined+ ? undefined+ : resolve(dirname(request.promptPath), `limits-${randomUUID()}.toml`);try {const parentSandbox = this.modelSettings.parentSandbox;if (!parentSandbox) {@@ -121,6 +127,31 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {}childEnv[name] = value;}+ if (deepConfigFile !== undefined) {+ const config = this.modelSettings.deepScanConfig!;+ // The saved run owns these limits, including after a coordinator restart.+ // Runtime/provider inheritance was read above; workers only need the limits.+ await writePrivateFile(+ deepConfigFile,+ stringifyToml({+ deep_scan: {+ workers: config.workers,+ subagents: config.subagents,+ stop_after_no_new: config.stopAfterNoNew,+ stop_after_consecutive_errors: config.stopAfterConsecutiveErrors,+ max_discovery_runs: config.maxDiscoveryRuns,+ ...(config.maxTimeHours === undefined+ ? {}+ : { max_time_hours: config.maxTimeHours }),+ },+ }),+ );+ for (const name of Object.keys(childEnv)) {+ if (name.toUpperCase() === "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH")+ delete childEnv[name];+ }+ childEnv.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH = deepConfigFile;+ }if (includePathsFile !== undefined) {// Keep host-bound inputs beside the prompt, outside the worker's output root.await writePrivateFile(includePathsFile, scopeInput);@@ -309,6 +340,8 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {} finally {if (includePathsFile !== undefined)await fs.rm(includePathsFile, { force: true });+ if (deepConfigFile !== undefined)+ await fs.rm(deepConfigFile, { force: true });}}diff --git a/plugins/codex-security/mcp-app/src/deep-scan/project-config.schema.json b/plugins/codex-security/mcp-app/src/deep-scan/project-config.schema.jsonnew file mode 100644index 000000000..841ee768d--- /dev/null+++ b/plugins/codex-security/mcp-app/src/deep-scan/project-config.schema.json@@ -0,0 +1,226 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "type": "object",+ "properties": {+ "$schema": {+ "description": "Editor schema URI or relative path. The CLI does not fetch or select a validator from this value.",+ "type": "string",+ "minLength": 1+ },+ "auth": {+ "default": "auto",+ "description": "Credential-source choice only; never a credential value.",+ "type": "string",+ "enum": ["auto", "chatgpt", "api-key"]+ },+ "scan": {+ "type": "object",+ "properties": {+ "mode": {+ "default": "standard",+ "type": "string",+ "enum": ["standard", "deep"]+ },+ "max_time_minutes": {+ "description": "Investigation minutes: advisory in Standard (default: unset); enforced Deep discovery limit (default and maximum: 5760). Scans may finish early; reporting may run longer.",+ "type": "number",+ "exclusiveMinimum": 0+ },+ "cyber_access_program": {+ "description": "Experimental Cyber access program for scan turns (OpenAI provider only). Omit to preserve Codex defaults.",+ "type": "string",+ "enum": ["standard", "daybreak_blue", "daybreak_red"]+ },+ "owner_suggestions": {+ "description": "Generate optional owner-suggestions.json after a committed scan (default: false).",+ "type": "boolean"+ },+ "scope": {+ "description": "One scope variant. Omit for the whole repository. Mode compatibility is checked after overrides.",+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "paths": {+ "minItems": 1,+ "type": "array",+ "items": { "type": "string", "minLength": 1 },+ "description": "Literal paths relative to the selected repository."+ }+ },+ "required": ["paths"],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "diff": {+ "type": "object",+ "properties": {+ "base": { "type": "string", "minLength": 1 },+ "head": {+ "default": "HEAD",+ "type": "string",+ "minLength": 1+ }+ },+ "required": ["base"],+ "additionalProperties": false+ }+ },+ "required": ["diff"],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "working_tree": {+ "type": "object",+ "properties": {+ "base": {+ "default": "HEAD",+ "type": "string",+ "minLength": 1+ }+ },+ "additionalProperties": false+ }+ },+ "required": ["working_tree"],+ "additionalProperties": false+ }+ ]+ },+ "knowledge_base": {+ "description": "Context files or directories, relative to this file. An empty list selects no additional context.",+ "type": "array",+ "items": { "type": "string", "minLength": 1 }+ },+ "instructions_file": {+ "description": "Additional scan instructions, relative to this file.",+ "type": "string",+ "minLength": 1+ },+ "validation_file": {+ "description": "Custom validation instructions, relative to this file; not supported in active deep scans.",+ "type": "string",+ "minLength": 1+ },+ "deep": {+ "description": "Deep defaults; a valid block may be retained while standard mode is selected.",+ "type": "object",+ "properties": {+ "workers": {+ "default": 4,+ "description": "Maximum concurrent deep-scan discovery workers.",+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "subagents_per_worker": {+ "default": 3,+ "description": "Subagents available to each deep-scan worker. Zero is valid.",+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "stop_after_no_new": {+ "default": 4,+ "description": "Stop after this many runs find no new issues.",+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "stop_after_consecutive_errors": {+ "default": 3,+ "description": "Stop after this many consecutive discovery errors.",+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "max_discovery_runs": {+ "default": 40,+ "description": "Maximum deep-scan discovery runs.",+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "max_time_hours": {+ "default": 96,+ "deprecated": true,+ "description": "Deprecated Deep-only alias for maxTimeMinutes / --max-time, in hours (default: 96; maximum: 96).",+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 96+ }+ },+ "additionalProperties": false+ }+ },+ "additionalProperties": false+ },+ "codex": {+ "description": "Native Codex overrides. Common key types are checked here; existing native and wrapper restrictions still apply.",+ "type": "object",+ "properties": {+ "model": { "type": "string", "minLength": 1 },+ "model_reasoning_effort": { "type": "string", "minLength": 1 },+ "model_provider": { "type": "string", "minLength": 1 }+ },+ "additionalProperties": { "$ref": "#/definitions/__schema0" }+ },+ "limits": {+ "type": "object",+ "properties": {+ "max_cost_usd_per_scan": {+ "description": "Estimated USD limit per launched scan attempt, not a total batch budget. Omit for no limit.",+ "type": "number",+ "exclusiveMinimum": 0+ }+ },+ "additionalProperties": false+ },+ "policy": {+ "type": "object",+ "properties": {+ "fail_on_severity": {+ "description": "Exit threshold; does not filter retained findings. Omit for report-only behavior.",+ "type": "string",+ "enum": ["critical", "high", "medium", "low"]+ }+ },+ "additionalProperties": false+ },+ "output": {+ "type": "object",+ "properties": {+ "directory": {+ "description": "Artifact directory relative to this file; existing outside-worktree checks still apply.",+ "type": "string",+ "minLength": 1+ }+ },+ "additionalProperties": false+ }+ },+ "additionalProperties": false,+ "definitions": {+ "__schema0": {+ "anyOf": [+ { "type": "string" },+ { "type": "number" },+ { "type": "boolean" },+ { "type": "null" },+ { "type": "array", "items": { "$ref": "#/definitions/__schema0" } },+ {+ "type": "object",+ "propertyNames": { "type": "string" },+ "additionalProperties": { "$ref": "#/definitions/__schema0" }+ }+ ]+ }+ },+ "title": "Codex Security project configuration",+ "description": "Input schema for explicitly selected YAML or JSON project files. Filesystem, active scan combinations, native configuration, and runtime availability are checked separately.",+ "$comment": "Generated from ProjectConfigInputSchema. Defaults are annotations; apply defaults only after merging input layers."+}diff --git a/plugins/codex-security/mcp-app/src/deep-scan/project-config.ts b/plugins/codex-security/mcp-app/src/deep-scan/project-config.tsnew file mode 100644index 000000000..016a4f10b--- /dev/null+++ b/plugins/codex-security/mcp-app/src/deep-scan/project-config.ts@@ -0,0 +1,110 @@+import { readFile, realpath } from "node:fs/promises";+import { homedir } from "node:os";+import { extname, isAbsolute, resolve } from "node:path";+import Ajv from "ajv";+import { parseDocument } from "yaml";+import schema from "./project-config.schema.json";++const validate = new Ajv({ allErrors: true }).compile(schema);+const fields = {+ workers: "workers",+ subagents_per_worker: "subagents",+ stop_after_no_new: "stopAfterNoNew",+ stop_after_consecutive_errors: "stopAfterConsecutiveErrors",+ max_discovery_runs: "maxDiscoveryRuns",+ max_time_hours: "maxTimeHours",+} as const;++export interface DeepScanProjectConfig {+ path: string;+ settings: Partial<Record<(typeof fields)[keyof typeof fields], number>>;+}++/** Read only an explicitly selected file; repository configuration is never discovered. */+export async function readDeepScanProjectConfig(+ file: string | undefined,+ canonicalTarget: string,+): Promise<DeepScanProjectConfig | undefined> {+ if (file === undefined) return undefined;+ const selected = file.replace(/^~(?=$|[/\\])/, () => homedir());+ const extension = extname(selected).toLowerCase();+ if (![".json", ".yaml", ".yml"].includes(extension)) {+ throw new Error(+ "Project configuration must be a .yaml, .yml, or .json file.",+ );+ }+ let requested = selected;+ if (process.platform === "win32")+ requested = resolve(canonicalTarget, selected);+ // Preserve POSIX symlink traversal before a subsequent "..".+ else if (!isAbsolute(selected)) requested = `${canonicalTarget}/${selected}`;+ const path = await realpath(requested);+ const text = await readFile(path, "utf8");+ let value: unknown;+ try {+ if (extension === ".json") value = JSON.parse(text);+ else {+ const document = parseDocument(text, { prettyErrors: false });+ if (document.errors.length > 0) throw document.errors[0];+ value = document.toJS({ maxAliasCount: 10_000 });+ }+ } catch (error) {+ throw new Error(+ `Cannot parse project configuration at ${path}: ${error instanceof Error ? error.message : String(error)}`,+ { cause: error },+ );+ }+ if (!validate(value)) {+ throw new Error(+ `Invalid project configuration at ${path}: ${validate.errors!.map((issue) => `${issue.instancePath || "configuration"}: ${issue.keyword === "additionalProperties" ? `Unknown key ${issue.params["additionalProperty"]}.` : issue.message}`).join("; ")}`,+ );+ }+ const input = value as {+ scan?: {+ mode?: string;+ max_time_minutes?: number;+ deep?: Record<keyof typeof fields, number>;+ };+ [key: string]: unknown;+ };+ const unsupported = [+ ...Object.keys(input).filter((key) => !["$schema", "scan"].includes(key)),+ ...Object.keys(input.scan ?? {})+ .filter((key) => !["mode", "max_time_minutes", "deep"].includes(key))+ .map((key) => `scan.${key}`),+ ];+ if (unsupported.length > 0) {+ throw new Error(+ `Unsupported native Deep Scan project settings: ${unsupported.join(", ")}. Only scan.mode, scan.max_time_minutes, and scan.deep are supported.`,+ );+ }+ if (input.scan?.mode !== undefined && input.scan.mode !== "deep") {+ throw new Error(+ "The selected project configuration must use scan.mode: deep or omit scan.mode.",+ );+ }+ const settings: DeepScanProjectConfig["settings"] = {};+ for (const [field, name] of Object.entries(fields)) {+ const value = input.scan?.deep?.[field as keyof typeof fields];+ if (value !== undefined) settings[name] = value;+ }+ const minutes = input.scan?.max_time_minutes;+ if (minutes !== undefined) {+ if (minutes > 5760)+ throw new Error(+ "Deep Scan scan.max_time_minutes must be no greater than 5760 minutes.",+ );+ const hours = minutes / 60;+ if (+ settings.maxTimeHours !== undefined &&+ Math.abs(settings.maxTimeHours - hours) >+ Number.EPSILON * Math.max(settings.maxTimeHours, hours)+ ) {+ throw new Error(+ "Conflicting scan.max_time_minutes and scan.deep.max_time_hours settings.",+ );+ }+ settings.maxTimeHours = hours;+ }+ return { path, settings };+}diff --git a/plugins/codex-security/mcp-app/src/deep-scan/registry.ts b/plugins/codex-security/mcp-app/src/deep-scan/registry.tsindex 38eb9dc28..f95bc28ae 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/registry.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/registry.ts@@ -52,6 +52,7 @@ export class DeepScanCoordinatorRegistry {}};void coordinator.settled().then(removeCoordinator, removeCoordinator);+ options.onStart?.(coordinator);coordinator.start();return coordinator;}diff --git a/plugins/codex-security/mcp-app/src/deep-scan/response.ts b/plugins/codex-security/mcp-app/src/deep-scan/response.tsindex fbde85b76..75822038c 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/response.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/response.ts@@ -76,6 +76,7 @@ export const runSchema = zincludePaths: z.array(z.string()).optional(),filePaths: z.array(z.string()).optional(),scanId: requiredString,+ sdkOwnsCompletion: z.boolean().optional(),coordinatorGeneration: optionalValue(positiveInteger),createdAt: optionalString,updatedAt: optionalString,diff --git a/plugins/codex-security/mcp-app/src/deep-scan/store.ts b/plugins/codex-security/mcp-app/src/deep-scan/store.tsindex 72beffb37..8017448b1 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/store.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/store.ts@@ -1,4 +1,5 @@import { workbenchArgs } from "../workbench-arguments.js";+import { readDeepScanProjectConfig } from "./project-config.js";import { availableParallelism } from "node:os";import { join } from "node:path";import { setTimeout as delay } from "node:timers/promises";@@ -133,6 +134,7 @@ export class WorkbenchDeepScanStore {targetPath?: string;scope?: string;userContext?: string;+ projectConfigPath?: string;handoffClaimToken?: string;model?: string;reasoningEffort?: string;@@ -140,22 +142,44 @@ export class WorkbenchDeepScanStore {scanRoot: string;}): Promise<DeepScanRunState> {const userContext = input.userContext;- const result = await this.enqueueWrite(+ const args = {+ threadId: input.threadId,+ scanId: input.scanId || undefined,+ targetPath: input.targetPath || undefined,+ projectConfigPath: input.projectConfigPath,+ scope: input.scope || undefined,+ userContextStdin: Boolean(userContext),+ claimToken: input.handoffClaimToken || undefined,+ model: input.model || undefined,+ reasoningEffort: input.reasoningEffort || undefined,+ scanRoot: input.scanRoot,+ availableParallelism: availableParallelism(),+ workflowVersion: WORKFLOW_VERSION,+ };+ let result = await this.enqueueWrite(workbenchArgs("begin-deep-scan", {- threadId: input.threadId,- scanId: input.scanId || undefined,- targetPath: input.targetPath || undefined,- scope: input.scope || undefined,- userContextStdin: Boolean(userContext),- claimToken: input.handoffClaimToken || undefined,- model: input.model || undefined,- reasoningEffort: input.reasoningEffort || undefined,- scanRoot: input.scanRoot,- availableParallelism: availableParallelism(),- workflowVersion: WORKFLOW_VERSION,+ ...args,+ joinOnly: input.projectConfigPath !== undefined,}),userContext,);+ if (+ input.projectConfigPath !== undefined &&+ typeof result.newScanTarget === "string"+ ) {+ const project = await readDeepScanProjectConfig(+ input.projectConfigPath,+ result.newScanTarget,+ );+ result = await this.enqueueWrite(+ workbenchArgs("begin-deep-scan", {+ ...args,+ targetPath: result.newScanTarget,+ deepScanProjectJson: JSON.stringify(project),+ }),+ userContext,+ );+ }const run = parseDeepScan(result);const startDisposition = result.startDisposition;if (startDisposition !== "created" && startDisposition !== "joined") {diff --git a/plugins/codex-security/mcp-app/src/deep-scan/worker-runner.ts b/plugins/codex-security/mcp-app/src/deep-scan/worker-runner.tsindex f1666bf38..f38719571 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/worker-runner.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/worker-runner.ts@@ -663,7 +663,7 @@ function reducerCompletionContinuation(attempt: number): string {return [`Continue the existing Deep Scan reducer after attempt ${attempt} ended without its required result.`,...reducerInputRecoveryInstructions(),- "Submit the aggregate with record_codex_security_deep_reduction({ scanId, findings, threatModel?, scope? }).",+ "Submit the aggregate with record_codex_security_deep_reduction({ scanId, findings, retainedFindingRefs?, threatModel?, scope? }).","If the tool rejects the arguments, use its error to correct them and retry the call until it succeeds.","Do not end your turn, write the result directly, or call the tool again after it succeeds.",].join("\n");@@ -675,6 +675,7 @@ function reducerInputRecoveryInstructions(): string[] {"If inputs have not been read yet, paginate all assigned findings and the previous aggregate. Follow nextCursor until absent and assemble the json fragments in order for each findingRef. Check MCP isError before reading a page.","Without code mode, call the input and submission tools directly. With code mode, persist fragments, cursor: nextCursor ?? null, and completion together in one store value after each successful page. Resume from the next unread page.","Preserve pages already read and account for every finding before submitting the aggregate.",+ 'Carry unchanged previous findings forward with retainedFindingRefs:["previous:N"] using their zero-based indices, and omit their bodies from findings. The host copies their full content and source refs. Submit new or synthesized findings in findings; never replace accepted descriptions with placeholders.',];}diff --git a/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.ts b/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.tsindex 0cb1481e9..f5a3c7538 100644--- a/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.ts+++ b/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.ts@@ -309,7 +309,7 @@ export function registerCompactWorkerArtifactTools(name: "record_codex_security_deep_reduction",title: "Record Codex Security Deep Reduction",description:- "Record the merged findings and context for this Deep scan. Preserve every assigned provenance.sourceFindingIds reference; omit retained provenance.sourceFindings bodies." ++ 'Record the merged findings and context for this Deep scan. Preserve every assigned provenance.sourceFindingIds reference; omit retained provenance.sourceFindings bodies. Use retainedFindingRefs:["previous:N"] to copy unchanged previous findings without resubmitting their bodies.' +semanticFindingGuidance,inputSchema: deepReductionInputSchema,readOnly: false,diff --git a/plugins/codex-security/mcp-app/src/stdio-transport.ts b/plugins/codex-security/mcp-app/src/stdio-transport.tsindex cece2e585..4f66c16e5 100644--- a/plugins/codex-security/mcp-app/src/stdio-transport.ts+++ b/plugins/codex-security/mcp-app/src/stdio-transport.ts@@ -1,8 +1,10 @@+import { finished, type Readable, type Writable } from "node:stream";import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";import { serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";import {ErrorCode,type JSONRPCMessage,+ type RequestId,} from "@modelcontextprotocol/sdk/types.js";// The native client's rmcp transport drops lines above 16 MiB, including the LF,@@ -10,6 +12,41 @@ import {const NATIVE_STDIO_LINE_LIMIT_BYTES = 16 * 1024 * 1024;export class CodexSecurityStdioTransport extends StdioServerTransport {+ private readonly stdout: Writable;+ private readonly resultReceipts = new Map<+ RequestId,+ () => Promise<unknown>+ >();++ constructor(+ stdin?: Readable,+ stdout: Writable = process.stdout,+ options?: ConstructorParameters<typeof StdioServerTransport>[2],+ ) {+ super(stdin, stdout, options);+ this.stdout = stdout;+ }++ afterResultSent(+ id: RequestId,+ signal: AbortSignal,+ receipt: () => Promise<unknown>,+ ) {+ if (signal.aborted) return;+ const attachedReceipt = async () => {+ if (!signal.aborted) await receipt();+ };+ this.resultReceipts.set(id, attachedReceipt);+ signal.addEventListener(+ "abort",+ () => {+ if (this.resultReceipts.get(id) === attachedReceipt)+ this.resultReceipts.delete(id);+ },+ { once: true },+ );+ }+override async send(message: JSONRPCMessage): Promise<void> {if (!("result" in message || "error" in message) ||@@ -18,8 +55,16 @@ export class CodexSecurityStdioTransport extends StdioServerTransport {return super.send(message);}- const bytes = Buffer.byteLength(serializeMessage(message), "utf8");- if (bytes <= NATIVE_STDIO_LINE_LIMIT_BYTES) return super.send(message);+ const receipt = this.resultReceipts.get(message.id);+ this.resultReceipts.delete(message.id);+ const line = serializeMessage(message);+ const bytes = Buffer.byteLength(line, "utf8");+ if (bytes <= NATIVE_STDIO_LINE_LIMIT_BYTES) {+ if (!receipt || !("result" in message)) return super.send(message);+ await this.writeResult(line);+ await receipt();+ return;+ }return super.send({jsonrpc: "2.0",@@ -33,4 +78,25 @@ export class CodexSecurityStdioTransport extends StdioServerTransport {},});}++ private writeResult(line: string): Promise<void> {+ return new Promise((resolve, reject) => {+ // A disconnected stdout can close without invoking the write callback.+ const cleanup = finished(this.stdout, { readable: false }, (error) => {+ cleanup();+ reject(+ error ?? new Error("stdout closed before the MCP result was written"),+ );+ });+ this.stdout.write(line, (error) => {+ if (error) {+ // Keep the error listener for the stream event emitted after this callback.+ reject(error);+ } else if (!this.stdout.destroyed) {+ cleanup();+ resolve();+ }+ });+ });+ }}diff --git a/plugins/codex-security/mcp-app/src/workbench/migrations.ts b/plugins/codex-security/mcp-app/src/workbench/migrations.tsindex 86da3ab78..1f74e4517 100644--- a/plugins/codex-security/mcp-app/src/workbench/migrations.ts+++ b/plugins/codex-security/mcp-app/src/workbench/migrations.ts@@ -224,7 +224,9 @@ export function applyMigrations();} else if (item.version === 16) backfill = repairStableTargets(database);else if (applied.has(item.version)) {- if ([2, 12, 13, 26, 28, 31, 32, 42, 47, 50].includes(item.version))+ if (+ [2, 12, 13, 26, 28, 31, 32, 42, 47, 50, 54, 55].includes(item.version)+ )repairAdditive(database, item.version);else if (item.version === 11) repairDeepScan(database);} else {diff --git a/plugins/codex-security/mcp-app/templates/deep-scan/dedup.md b/plugins/codex-security/mcp-app/templates/deep-scan/dedup.mdindex 521ed4bbf..c208e24f1 100644--- a/plugins/codex-security/mcp-app/templates/deep-scan/dedup.md+++ b/plugins/codex-security/mcp-app/templates/deep-scan/dedup.md@@ -49,10 +49,12 @@ Read every finding and the previous aggregate. Merge only the same actionable roDo not merge findings merely because they share a subsystem, CWE, route or file family, sink family, or attack language. Keep them separate whenever any source/control/sink/impact tuple or independently reachable instance would remain after the proposed common fix. Related findings may be cross-referenced without being collapsed.-For a valid merge, synthesize one stronger finding while preserving every materially useful non-redundant detail: narrower exploit framings, affected subpaths, preconditions, distinct source/control/sink nuances, contradictory or strengthening evidence, affected locations, and remediation-relevant subcases. Omit only genuinely duplicate or superseded detail. Preserve previously established finding identities.+For a valid merge, synthesize one stronger finding while preserving every materially useful non-redundant detail: narrower exploit framings, affected subpaths, preconditions, distinct source/control/sink nuances, contradictory or strengthening evidence, affected locations, and remediation-relevant subcases. Omit only genuinely duplicate or superseded detail. Preserve the identity of each independently retained finding. Semantically equivalent previous aliases may consolidate under one retained or synthesized identity when each complete prior source group maps to that single recipient; never split a prior source group across output findings.Account for every input finding using the host-supplied `provenance.sourceFindingIds`. Copy the refs for retained findings; union them for a valid merge, preserving previous refs. Never invent, omit, or reuse a ref across independent output findings. The host retains original source payloads and rejects unaccounted input. Identity collisions do not establish that findings are duplicates.+Carry unchanged previous findings forward with `retainedFindingRefs: ["previous:0", "previous:1", ...]`, using their zero-based indices in the previous aggregate. The host copies their full bodies, identities, source refs, and retained history. Omit those findings from `findings`; submit only new or synthesized findings there. Never replace descriptive text with placeholders to fit a submission. When code mode is available, build the submission object and call the record tool inside a cell without printing the complete aggregate.+Preserve the threat-model context and scope as needed, omitting scope `includePaths` and `excludePaths`. You cannot resolve or reject a source finding without inspecting code, which is outside this reducer's role.-Call `record_codex_security_deep_reduction({ scanId, findings, threatModel?, scope? })` until it succeeds; correct a reported validation error and retry in the same conversation. After the first successful call, do not call it again. The host derives convergence and worker attribution from its existing state.+Call `record_codex_security_deep_reduction({ scanId, findings, retainedFindingRefs?, threatModel?, scope? })` until it succeeds; correct a reported validation error and retry in the same conversation. After the first successful call, do not call it again. The host derives convergence and worker attribution from its existing state.diff --git a/plugins/codex-security/mcp-app/tests/deep_scan_context_snapshot_cases.ts b/plugins/codex-security/mcp-app/tests/deep_scan_context_snapshot_cases.tsindex f40d8b583..bd76b448a 100644--- a/plugins/codex-security/mcp-app/tests/deep_scan_context_snapshot_cases.ts+++ b/plugins/codex-security/mcp-app/tests/deep_scan_context_snapshot_cases.ts@@ -4,7 +4,7 @@ import { randomUUID } from "node:crypto";import { mkdir, readFile, writeFile } from "node:fs/promises";import path from "node:path";import { fileURLToPath } from "node:url";-import { parse as parseToml, type TomlTable } from "smol-toml";+import { parse as parseToml } from "smol-toml";import { importModule } from "./import-module.ts";import type { WorkbenchDeepScanStore as Store } from "../src/deep-scan/store.js";import type { DeepScanWorkerRunner as Runner } from "../src/deep-scan/worker-runner.js";@@ -66,15 +66,12 @@ export async function testDeepScanContextSnapshots({const targetPath = path.join(fixture.root, "target");await mkdir(targetPath);await writeFile(path.join(targetPath, "fixture.py"), "print('fixture')\n");- await Promise.all(+ const outcomes = await Promise.allSettled(["Review authentication only.", undefined].map(async (userContext, index) => {const deepConfig = path.join(fixture.root, `deep-${index}.toml`);const maxTimeHours = 1.5 + index;- await writeFile(- deepConfig,- `[deep_scan]\nmax_time_hours = ${maxTimeHours}\n`,- );+ await writeFile(deepConfig, `[deep_scan]\nmax_time_hours = 48\n`);const command = async (args: string[], input?: string) => {const result = spawnSync(process.env.PYTHON?.trim() || "python3",@@ -92,22 +89,42 @@ export async function testDeepScanContextSnapshots({return JSON.parse(result.stdout);};const threadId = `context-owner-${index}`;+ const projectConfigPath = path.join(+ fixture.root,+ `selected-${index}.json`,+ );+ await writeFile(+ projectConfigPath,+ JSON.stringify({+ scan: {+ deep: {+ max_time_hours: maxTimeHours,+ subagents_per_worker: index,+ },+ },+ }),+ );let store = new WorkbenchDeepScanStore(command);let run = await store.begin({targetPath,scope: ".",threadId,userContext,+ projectConfigPath,scanRoot: path.join(fixture.root, "scans"),});const createdAt = run.createdAt;assert.ok(createdAt);assert.equal(run.config.maxTimeHours, maxTimeHours);+ assert.equal(run.config.subagents, index);const invocations: {kind: DeepScanWorkerKind;invocation: { argv: string[]; stdin: string; deepConfig: string };}[] = [];- const sdk = new CodexSdkWorkerExecutor({ parentSandbox });+ let sdk = new CodexSdkWorkerExecutor({+ parentSandbox,+ deepScanConfig: run.config,+ });const executor = {async run(request: CodexWorkerRequest) {process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH = deepConfig;@@ -180,6 +197,10 @@ export async function testDeepScanContextSnapshots({});assert.equal(run.config.maxTimeHours, maxTimeHours);assert.equal(run.createdAt, createdAt);+ sdk = new CodexSdkWorkerExecutor({+ parentSandbox,+ deepScanConfig: run.config,+ });const second = await runner().runDiscoveryWorker(randomUUID(),"after-edit",@@ -205,10 +226,17 @@ export async function testDeepScanContextSnapshots({assert.equal(fresh.invocation.argv.includes("resume"), false);assert.equal(resumed.invocation.argv.includes("resume"), true);for (const { invocation } of [fresh, resumed]) {- assert.equal(- (parseToml(invocation.deepConfig).deep_scan as TomlTable)- .max_time_hours,- maxTimeHours,+ assert.deepEqual(+ { ...(parseToml(invocation.deepConfig).deep_scan as object) },+ {+ workers: run.config.workers,+ subagents: index,+ stop_after_no_new: run.config.stopAfterNoNew,+ stop_after_consecutive_errors:+ run.config.stopAfterConsecutiveErrors,+ max_discovery_runs: run.config.maxDiscoveryRuns,+ max_time_hours: maxTimeHours,+ },);}const context = JSON.parse(@@ -244,6 +272,9 @@ export async function testDeepScanContextSnapshots({},),);+ for (const outcome of outcomes) {+ if (outcome.status === "rejected") throw outcome.reason;+ }} finally {if (previousPath === undefined) delete process.env.CODEX_CLI_PATH;else process.env.CODEX_CLI_PATH = previousPath;diff --git a/plugins/codex-security/mcp-app/tests/deep_scan_coverage_fixture.ts b/plugins/codex-security/mcp-app/tests/deep_scan_coverage_fixture.tsindex 63c9d0967..7ae56363e 100644--- a/plugins/codex-security/mcp-app/tests/deep_scan_coverage_fixture.ts+++ b/plugins/codex-security/mcp-app/tests/deep_scan_coverage_fixture.ts@@ -3,12 +3,12 @@ import { execFile } from "node:child_process";import { randomUUID } from "node:crypto";import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";import path from "node:path";-import { fileURLToPath, pathToFileURL } from "node:url";+import { fileURLToPath } from "node:url";import { promisify } from "node:util";-import { build } from "esbuild";import type { JsonObject } from "../src/types.js";import type { CodexWorkerRequest } from "../src/deep-scan/types.js";+import { importModule } from "./import-module.ts";import { readJson } from "./support/json.ts";import { temporaryDirectory } from "./support/temporary-directories.ts";@@ -84,8 +84,16 @@ export async function readFixtureCoverage(const pluginRoot = fileURLToPath(new URL("../../", import.meta.url));const exec = promisify(execFile);-const bundled = await build({- bundle: true,+const {+ archiveDirectory,+ getCodexSecurityCompletedScan,+ DeepScanCoordinator,+ WorkbenchDeepScanStore,+ createScanArtifactContext,+ recordCodexSecurityScanDraftViaWorkbench,+ recordCodexSecurityWorkerScanDraft,+ recordCodexSecurityDeepReduction,+} = (await importModule({stdin: {contents: ['export { archiveDirectory } from "./src/deep-scan/artifacts.ts";',@@ -97,11 +105,8 @@ const bundled = await build({].join("\n"),resolveDir: path.join(pluginRoot, "mcp-app"),},- format: "esm",- platform: "node",loader: { ".md": "text" },- write: false,-});+})) as FixtureRuntime;export async function publishReceiptFixture(options: CoverageFixtureOptions) {const root = await temporaryDirectory("retry-coverage-receipts-");try {@@ -139,18 +144,6 @@ export async function publishCoverageFixture(interruptPublication = false,}: CoverageFixtureOptions = {},) {- const runtimePath = path.join(root, "fixture-runtime.mjs");- await writeFile(runtimePath, bundled.outputFiles![0]!.contents);- const {- archiveDirectory,- getCodexSecurityCompletedScan,- DeepScanCoordinator,- WorkbenchDeepScanStore,- createScanArtifactContext,- recordCodexSecurityScanDraftViaWorkbench,- recordCodexSecurityWorkerScanDraft,- recordCodexSecurityDeepReduction,- } = (await import(pathToFileURL(runtimePath).href)) as FixtureRuntime;const targetPath = path.join(root, "target");const codexHome = path.join(root, "codex-home");const scanRoot = path.join(root, "scans");diff --git a/plugins/codex-security/mcp-app/tests/import-module.ts b/plugins/codex-security/mcp-app/tests/import-module.tsindex c15cbc6fd..8fe422814 100644--- a/plugins/codex-security/mcp-app/tests/import-module.ts+++ b/plugins/codex-security/mcp-app/tests/import-module.ts@@ -15,6 +15,10 @@ process.once("exit", () =>export async function importModule(options: BuildOptions) {const result = await build({+ // Bundled CommonJS dependencies such as yaml load Node builtins.+ banner: {+ js: 'const require = process.getBuiltinModule("node:module").createRequire(import.meta.url);',+ },bundle: true,format: "esm",platform: "node",diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer.ts b/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer.tsindex 7bf807ccc..c4fea4e3a 100644--- a/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer.ts+++ b/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer.ts@@ -54,6 +54,7 @@ assert.equal(const root = await temporaryDirectory("codex-security-deep-reducer-", true);try {+ await testRetainedFindingContent(root);const scanRoot = path.join(root, "scan");const workersRoot = path.join(scanRoot,@@ -328,8 +329,7 @@ try {});await assert.rejects(recordCodexSecurityDeepReduction(nextContext, reduction([shared])),- (error: NodeJS.ErrnoException) =>- error.code === "merge_traceability_unstable_candidate_id",+ /unaccounted source findings: worker-002:1/,);assert.deepEqual(await recordCodexSecurityDeepReduction(nextContext, merged),@@ -450,6 +450,181 @@ try {console.log("artifact deep reducer tests passed");+async function testRetainedFindingContent(root: string) {+ const scanRoot = path.join(root, "content");+ const deepRoot = path.join(scanRoot, "artifacts", "deep_discovery");+ const original = {+ ...finding("retained", "src/handler.ts"),+ rootCause: { summary: "The response omits encoding of request input." },+ writeup: {+ reportPath: "findings/retained/retained.md",+ description: "A crafted query is rendered as executable HTML.",+ },+ };+ const worker = await createWorker({+ workersRoot: path.join(deepRoot, "workers"),+ label: "discovery-0001",+ id: "worker-content",+ result: workerDraft([original]),+ });+ const outputRoot = path.join(deepRoot, "dedup", "first", "output");+ await mkdir(outputRoot, { recursive: true });+ const context = {+ root: outputRoot,+ repoRoot: root,+ scanId,+ layout: "reducer",+ deepReducer: { scanRoot, claimedWorkers: [worker] },+ };+ const replacements = [+ { title: "X" },+ { summary: "X" },+ { rootCause: { summary: "TBD" } },+ { remediation: "..." },+ { writeup: { ...original.writeup, description: "X" } },+ ];+ for (const replacement of replacements) {+ await assert.rejects(+ recordCodexSecurityDeepReduction(+ context,+ reduction([{ ...original, ...replacement }]),+ ),+ /placeholder.*worker-content:0/i,+ "a reducer cannot replace accepted source text with placeholders",+ );+ await assert.rejects(readFile(path.join(outputRoot, "result.json")), {+ code: "ENOENT",+ });+ await assert.rejects(readdir(path.join(outputRoot, "checkpoints")), {+ code: "ENOENT",+ });+ }+ await recordCodexSecurityDeepReduction(context, reduction([original]));+ const accepted = await readJson(outputRoot, "result.json");+ // This detail exists only in the previous aggregate, beyond its originals.+ accepted.findings[0].writeup.additionalProof =+ "A second response branch reaches the same vulnerable HTML sink.";+ await writeJson(path.join(outputRoot, "result.json"), accepted);+ const empty = await createWorker({+ workersRoot: path.join(deepRoot, "workers"),+ label: "discovery-0002",+ id: "worker-empty",+ result: workerDraft([]),+ });+ const nextRoot = path.join(deepRoot, "dedup", "second", "output");+ await mkdir(nextRoot, { recursive: true });+ const nextContext = {+ ...context,+ root: nextRoot,+ deepReducer: {+ scanRoot,+ claimedWorkers: [empty],+ previousReducerResultPath: path.join(outputRoot, "result.json"),+ },+ };+ await assert.rejects(+ recordCodexSecurityDeepReduction(+ nextContext,+ reduction([+ {+ ...accepted.findings[0],+ writeup: { ...accepted.findings[0].writeup, additionalProof: "X" },+ },+ ]),+ ),+ /placeholder.*worker-content:0/i,+ "details synthesized by an earlier reducer must also be preserved",+ );+ await recordCodexSecurityDeepReduction(+ nextContext,+ reduction([], { retainedFindingRefs: ["previous:0"] }),+ );+ assert.deepEqual(+ await readJson(nextRoot, "result.json"),+ accepted,+ "reference-only retention copies the complete body and history verbatim",+ );+ assert.deepEqual(+ (+ await getCodexSecurityDeepReducerInputs({+ ...nextContext,+ deepReducer: {+ ...nextContext.deepReducer,+ previousReducerResultPath: path.join(nextRoot, "result.json"),+ },+ })+ ).previous,+ accepted,+ "reopening the reduction retains substantive text and exact locations",+ );+ for (const retainedFindingRefs of [+ ["previous:1"],+ ["previous:0", "previous:0"],+ ]) {+ await assert.rejects(+ recordCodexSecurityDeepReduction(+ nextContext,+ reduction([], { retainedFindingRefs }),+ ),+ /not assigned|more than once/,+ );+ assert.deepEqual(await readJson(nextRoot, "result.json"), accepted);+ }+ await recordCodexSecurityDeepReduction(+ nextContext,+ reduction([+ { ...accepted.findings[0], summary: "Reflected HTML injection." },+ ]),+ );+ assert.equal(+ (await readJson(nextRoot, "result.json")).findings[0].summary,+ "Reflected HTML injection.",+ "concise substantive synthesis remains allowed without length heuristics",+ );+ for (const legacyRefs of [undefined, ["historical:0"]]) {+ const legacyFinding = {+ ...original,+ summary: "An earlier review recorded a separate response route.",+ provenance: { ...original.provenance, sourceFindingIds: legacyRefs },+ };+ const previousReducerResultPath = path.join(+ deepRoot,+ "dedup",+ "legacy.json",+ );+ await writeJson(previousReducerResultPath, reduction([legacyFinding]));+ await recordCodexSecurityDeepReduction(+ {+ ...nextContext,+ deepReducer: {+ scanRoot,+ claimedWorkers: [worker],+ previousReducerResultPath,+ },+ },+ reduction(+ [+ {+ ...original,+ provenance: {+ ...original.provenance,+ sourceFindingIds: ["worker-content:0"],+ },+ },+ ],+ { retainedFindingRefs: ["previous:0"] },+ ),+ );+ const retained = (await readJson(nextRoot, "result.json")).findings[1];+ assert.equal(retained.summary, legacyFinding.summary);+ assert.deepEqual(+ retained.provenance.sourceFindingIds,+ ["previous:0"],+ "legacy references are explicit even when a fresh finding has the same identity",+ );+ }+}+async function createWorker({workersRoot,label,diff --git a/plugins/codex-security/mcp-app/tests/test_deep_reducer_finite_writes.ts b/plugins/codex-security/mcp-app/tests/test_deep_reducer_finite_writes.tsindex d518b35ac..166ea85bd 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_reducer_finite_writes.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_reducer_finite_writes.ts@@ -196,3 +196,12 @@ test("historical reducer validation reads overflow without rewriting the artifacassert.equal(await readFile(f.resultPath, "utf8"), wire(input));assert.deepEqual(await readdir(f.output), ["result.json"]);});++test("reference retention copies historical payloads without treating them as fresh model output", async (t) => {+ const f = await fixture(t, "mcp", "previous");+ await f.write({ scanId, findings: [], retainedFindingRefs: ["previous:0"] });+ for (const saved of await storedDrafts(f.output)) {+ assert.equal(saved.findings[0].extensions.measurement, null);+ assert.equal(saved.threatModel.measurement, null);+ }+});diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_artifact_validation.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_artifact_validation.tsindex eeb227ec3..3aef464f2 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_artifact_validation.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_artifact_validation.ts@@ -23,6 +23,7 @@ const {validateReducerArtifacts,aggregateDiscoveryCoverage,aggregateSourceCoverage,+ deepReductionForPersistence,projectDiscoveryCoverage,} = await importSource(path.join(import.meta.dirname, "../src/deep-scan/artifact-validation.ts"),@@ -71,6 +72,7 @@ try {for (const reverse of [false, true])await testCurrentAnonymousReceiptSelection(root, candidate, reverse);await testReducerValidation(root);+ await testReducerLineageConvergence(root);await testEmptyDiscoveryAndReduction(root);} finally {await rm(root, { recursive: true, force: true });@@ -1340,6 +1342,242 @@ async function testReducerValidation(root: string) {}}+async function testReducerLineageConvergence(root: string) {+ const { artifacts } = await createWorker(+ path.join(root, "lineage-convergence"),+ "worker-lineage",+ draft([]),+ );+ const artifactDir = path.join(artifacts.dedupRoot, "dedup-current", "output");+ const resultPath = path.join(artifactDir, "result.json");+ const previousReducerResultPath = path.join(+ artifacts.dedupRoot,+ "dedup-previous",+ "output",+ "result.json",+ );+ await mkdir(artifactDir, { recursive: true });+ await mkdir(path.dirname(previousReducerResultPath), { recursive: true });+ const originals = {+ a: finding("root-a", "src/a.js"),+ b: finding("alias-b", "src/b.js"),+ c: finding("fresh-c", "src/c.js"),+ };+ const referenced = (name: string, refs: string[]) => ({+ ...finding(name, `src/${name}.js`),+ provenance: { source: "local_plugin", sourceFindingIds: refs },+ });+ const retained = (name: string, keys: (keyof typeof originals)[]) => ({+ ...referenced(+ name,+ keys.map((key) => `origin:${key}`),+ ),+ provenance: {+ source: "local_plugin",+ sourceFindingIds: keys.map((key) => `origin:${key}`),+ sourceFindings: keys.map((key) => ({+ id: `origin:${key}`,+ finding: originals[key],+ })),+ },+ });+ const previousA = retained("root-a", ["a"]);+ const previousB = {+ ...retained("alias-b", ["b"]),+ rootCause:+ "The previous reduction established another reachable response branch.",+ };+ const discoveries = [{ workerId: "fresh", result: reduction([originals.c]) }];+ for (const [label, previous, output, newFindings] of [+ [+ "retain-canonical-alias",+ [previousA, previousB],+ [referenced("root-a", ["origin:a", "origin:b", "fresh:0"])],+ 0,+ ],+ [+ "new-canonical-alias",+ [previousA, previousB],+ [referenced("merged-root", ["origin:a", "origin:b", "fresh:0"])],+ 0,+ ],+ [+ "independent-root",+ [previousA, previousB],+ [+ referenced("merged-root", ["origin:a", "origin:b"]),+ referenced("fresh-c", ["fresh:0"]),+ ],+ 1,+ ],+ [+ "keep-independent-instances",+ [previousA, previousB],+ [+ referenced("root-a", ["origin:a", "fresh:0"]),+ referenced("alias-b", ["origin:b"]),+ ],+ 0,+ ],+ ] as const) {+ await writeResult(resultPath, reduction([...output]));+ await writeResult(previousReducerResultPath, reduction([...previous]));+ const input = { artifacts, artifactDir, resultPath, reducerId: label };+ const accepted = await validateReducerArtifacts(+ {+ ...input,+ sources: { discoveries, previous: reduction([...previous]) },+ },+ scanId,+ );+ assert.equal(accepted.newFindings, newFindings, label);+ const saved = await readJson(resultPath);+ assert.deepEqual(deepReductionForPersistence(accepted.result), saved);+ assert.equal(+ (+ await validateReducerArtifacts(+ { ...input, previousReducerResultPath },+ scanId,+ )+ ).newFindings,+ newFindings,+ `${label}: reopening the saved reduction must reconstruct the same novelty`,+ );+ if (label === "new-canonical-alias") {+ assert.deepEqual(+ saved.findings[0].provenance.previousFindings.map(+ (item: JsonObject) => item.title,+ ),+ [previousA.title, previousB.title],+ "semantic consolidation keeps both prior canonical bodies",+ );+ for (const field of ["summary", "rootCause"]) {+ const degraded = structuredClone(saved);+ degraded.findings[0][field] = "X";+ await writeResult(resultPath, degraded);+ await assert.rejects(+ validateReducerArtifacts(+ {+ ...input,+ sources: { discoveries, previous: reduction([...previous]) },+ },+ scanId,+ ),+ /placeholder.*origin:/,+ "renaming merged aliases cannot bypass original or synthesized content preservation",+ );+ await assert.rejects(+ validateReducerArtifacts(+ { ...input, previousReducerResultPath },+ scanId,+ ),+ /placeholder.*origin:/,+ "stored recovery rejects the same content loss as live reduction",+ );+ assert.deepEqual(await readJson(resultPath), degraded);+ }+ }+ }+ for (const [label, previous, output] of [+ [+ "split-previous-group",+ [retained("root-a", ["a", "b"])],+ [+ referenced("root-a", ["origin:a"]),+ referenced("alias-b", ["origin:b", "fresh:0"]),+ ],+ ],+ [+ "rename-independent-root",+ [previousA],+ [referenced("renamed-root", ["origin:a", "fresh:0"])],+ ],+ [+ "ambiguous-previous-group",+ [previousA],+ [+ referenced("root-a", ["origin:a"]),+ referenced("alias-b", ["origin:a", "fresh:0"]),+ ],+ ],+ ] as const) {+ await writeResult(resultPath, reduction([...output]));+ await writeResult(previousReducerResultPath, reduction([...previous]));+ const input = { artifacts, artifactDir, resultPath, reducerId: label };+ await assert.rejects(+ validateReducerArtifacts(+ {+ ...input,+ sources: { discoveries, previous: reduction([...previous]) },+ },+ scanId,+ ),+ /previously accepted finding|more than once/,+ label,+ );+ await assert.rejects(+ validateReducerArtifacts({ ...input, previousReducerResultPath }, scanId),+ /previously accepted finding/,+ `${label}: stored recovery must enforce the same assignment`,+ );+ }+ const legacy = reduction([originals.a, originals.b]);+ const legacyMerge = reduction([+ referenced("merged-root", ["previous:0", "previous:1"]),+ ]);+ const validateLegacy = (previous: typeof legacy) =>+ validateReducerArtifacts(+ {+ artifacts,+ artifactDir,+ resultPath,+ reducerId: "legacy-consolidation",+ sources: { discoveries: [], previous },+ },+ scanId,+ );+ await writeResult(resultPath, legacyMerge);+ await assert.rejects(+ validateLegacy(legacy),+ /previously accepted finding identity/,+ "legacy findings without retained source bodies keep their identities",+ );+ await writeResult(resultPath, legacy);+ const upgraded = (await validateLegacy(legacy)).result;+ assert.deepEqual(+ upgraded.findings.map(+ (item: { provenance: { sourceFindingIds: string[] } }) =>+ item.provenance.sourceFindingIds,+ ),+ [["previous:0"], ["previous:1"]],+ );+ await writeResult(resultPath, legacyMerge);+ assert.equal(+ (await validateLegacy(upgraded)).newFindings,+ 0,+ "host-retained legacy source bodies support later alias consolidation",+ );+ await writeResult(+ previousReducerResultPath,+ deepReductionForPersistence(upgraded),+ );+ assert.equal(+ (+ await validateReducerArtifacts(+ {+ artifacts,+ artifactDir,+ resultPath,+ reducerId: "legacy-consolidation-recovery",+ previousReducerResultPath,+ },+ scanId,+ )+ ).newFindings,+ 0,+ );+}+async function testEmptyDiscoveryAndReduction(root: string) {const { artifacts, ...worker } = await createWorker(path.join(root, "empty"),diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_coordinator.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_coordinator.tsindex 990e48fc9..659d3e656 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_coordinator.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_coordinator.ts@@ -1501,7 +1501,7 @@ async function testMissingReducerResultResumesExistingThread(assert.equal(new Set(executor.dedupThreadIds).size, 1);assert.match(executor.dedupContinuationPrompts[1] ?? "",- /record_codex_security_deep_reduction\(\{ scanId, findings, threatModel\?, scope\? \}\)/,+ /record_codex_security_deep_reduction\(\{ scanId, findings, retainedFindingRefs\?, threatModel\?, scope\? \}\)/,);assert.doesNotMatch(executor.dedupContinuationPrompts[1] ?? "",diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_detached_completion.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_detached_completion.tsnew file mode 100644index 000000000..ea7ab7600--- /dev/null+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_detached_completion.ts@@ -0,0 +1,56 @@+import assert from "node:assert/strict";+import { after, test } from "node:test";+import type { DeepScanRunState } from "../src/deep-scan/types.ts";+import type { CoordinatorOptions } from "../src/deep-scan/coordinator.ts";+import {+ DeepScanCoordinatorRegistry,+ DeepScanRemoteCoordinator,+ FakeExecutor,+ FakeStore,+ fixtureRun,+ immediateClock,+ temporaryDirectories,+} from "./deep_scan_coordinator_fixture.ts";++after(() => temporaryDirectories.cleanup());++test("an adopted coordinator retains its completion observer after the RPC waiter detaches", async () => {+ const fixture = await fixtureRun();+ const store = new FakeStore({+ ...fixture.run,+ coordinatorGeneration: 1,+ updatedAt: "2000-01-01T00:00:00Z",+ });+ store.claimCoordinator = async () => {+ store.run = { ...store.run, coordinatorGeneration: 2 };+ return { run: store.run, acquired: true };+ };+ const request = new AbortController();+ let completion: Promise<DeepScanRunState> | undefined;+ let starts = 0;+ const options: Omit<CoordinatorOptions, "run"> = {+ store,+ executor: new FakeExecutor(),+ pluginRoot: fixture.pluginRoot,+ clock: immediateClock,+ threadId: "synthetic-owner",+ onStart: (coordinator) => {+ starts += 1;+ completion = coordinator.settled();+ request.abort(new Error("synthetic RPC waiter detached"));+ },+ };+ const observer = new DeepScanRemoteCoordinator({+ run: store.run,+ registry: new DeepScanCoordinatorRegistry(),+ options,+ });+ observer.nextClaimAt = 0;++ await assert.rejects(observer.wait(request.signal), { name: "AbortError" });+ assert.equal(starts, 1);+ assert.ok(completion);+ const terminal = await completion;+ assert.equal(terminal.status, "succeeded");+ assert.equal(terminal.coordinatorGeneration, 2);+});diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.tsindex f331fd504..3fb5bfae2 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts@@ -1951,6 +1951,14 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,(modelSettings, index) =>new CodexSdkWorkerExecutor({...modelSettings,+ deepScanConfig: {+ workers: index + 1,+ subagents: index,+ stopAfterNoNew: 2,+ stopAfterConsecutiveErrors: 3,+ maxDiscoveryRuns: 9,+ maxTimeHours: index + 0.5,+ },parentSandbox: workerConfigurations[index].parentSandbox,artifactContext: {pluginRoot: path.join(fixture.root, `plugin-${index}`),@@ -2062,8 +2070,11 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,workerLaunch.environment!.CODEX_SECURITY_CONFIG_PATH,workerConfigurations[index].path,);- assert.equal(- workerLaunch.environment!.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,+ const deepConfigPath =+ workerLaunch.environment!.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH!;+ assert.ok(path.isAbsolute(deepConfigPath));+ assert.notEqual(+ deepConfigPath,workerConfigurations[index].workerConfigPath,);assert.deepEqual(@@ -2133,10 +2144,19 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,temporaryEnvironments.at(-1)![name],);}- assert.equal(- invocation.deepConfigPath,- workerConfigurations[index].workerConfigPath,+ assert.equal(invocation.deepConfigPath, deepConfigPath);+ assert.deepEqual(+ { ...(parseToml(invocation.deepConfig).deep_scan as object) },+ {+ workers: index + 1,+ subagents: index,+ stop_after_no_new: 2,+ stop_after_consecutive_errors: 3,+ max_discovery_runs: 9,+ max_time_hours: index + 0.5,+ },);+ await assert.rejects(readFile(deepConfigPath), { code: "ENOENT" });assert.equal(invocation.runtimeEnvironment.CODEX_SECURITY_STATE_DIR,path.join(fixture.root, `state-${index}`),@@ -2353,10 +2373,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,await assert.rejects(readFile(scopeFile), { code: "ENOENT" });} else assert.equal(scopeFile, undefined);assert.equal(process.env.PYTHON, python);- assert.equal(- invocation.deepConfigPath,- workerConfigurations[index].workerConfigPath,- );+ assert.equal(invocation.deepConfigPath, deepConfigPath);assert.deepEqual(JSON.parse(JSON.stringify(diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_lineage_convergence.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_lineage_convergence.tsnew file mode 100644index 000000000..dff6f5b71--- /dev/null+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_lineage_convergence.ts@@ -0,0 +1,93 @@+import assert from "node:assert/strict";+import path from "node:path";+import { readJson, writeJson } from "./support/json.ts";+import {+ claimDedupInputs,+ coordinatorFixture,+ FakeExecutor,+ runCoordinator,+ temporaryDirectories,+} from "./deep_scan_coordinator_fixture.ts";++try {+ const { fixture, store } = await coordinatorFixture({+ workers: 1,+ stopAfterNoNew: 2,+ maxDiscoveryRuns: 4,+ });+ const executor = new FakeExecutor({+ discoveryCandidates: {+ "discovery-0001": "root-a",+ "discovery-0002": "alias-b",+ "discovery-0003": "root-a",+ "discovery-0004": "root-a",+ },+ });+ const run = executor.run.bind(executor);+ executor.run = async (request) => {+ const outcome = await run(request);+ const resultPath = path.join(request.artifactContext!.root, "result.json");+ const result = await readJson(resultPath);+ if (request.kind === "discovery") {+ for (const finding of result.findings) {+ finding.identity = { anchor: finding.provenance.candidateId };+ }+ } else if (executor.dedupCalls > 1) {+ // The semantic reducer identifies the two prior identities as aliases.+ // Later observations add evidence to that same root issue.+ const [finding] = result.findings;+ result.findings = [+ {+ ...finding,+ identity: { anchor: "merged-root" },+ provenance: {+ ...finding.provenance,+ sourceFindingIds: result.findings.flatMap(+ (item: { provenance: { sourceFindingIds: string[] } }) =>+ item.provenance.sourceFindingIds,+ ),+ },+ },+ ];+ }+ await writeJson(resultPath, result);+ return outcome;+ };+ const terminal = await runCoordinator(fixture, store, executor);+ assert.equal(terminal?.status, "succeeded", terminal?.error);+ assert.equal(terminal.terminalReason, "saturated");+ assert.equal(store.dedupCommits[0].newFindings, 2);+ assert.ok(+ store.dedupCommits.slice(1).every((commit) => commit.newFindings === 0),+ );+ assert.equal(store.run.noNewStreak, 2);+ const manifest = await readJson(terminal.manifestPath);+ assert.equal(manifest.findings.length, 1);+ assert.equal(manifest.findings[0].identity.anchor, "merged-root");+ assert.equal(manifest.findings[0].provenance.sourceFindingIds.length, 4);++ store.run = {+ ...store.run,+ status: "running",+ terminalReason: undefined,+ manifestPath: undefined,+ persistedWorkers: structuredClone([...store.workers.values()]),+ persistedDedupInputs: store.dedupClaims.flatMap(claimDedupInputs),+ };+ const replacement = new FakeExecutor();+ const resumed = await runCoordinator(fixture, store, replacement, {+ run: store.run,+ });+ assert.equal(resumed?.status, "succeeded", resumed?.error);+ assert.equal(resumed.terminalReason, "saturated");+ assert.equal(store.run.noNewStreak, 2);+ assert.equal(replacement.discoveryCalls + replacement.dedupCalls, 0);+ assert.deepEqual(+ (await readJson(resumed.manifestPath)).findings,+ manifest.findings,+ );+} finally {+ await temporaryDirectories.cleanup();+}++console.log("deep scan lineage convergence tests passed");diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_project_config.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_project_config.tsnew file mode 100644index 000000000..cc857be79--- /dev/null+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_project_config.ts@@ -0,0 +1,216 @@+import assert from "node:assert/strict";+import { mkdir, rm, symlink, writeFile } from "node:fs/promises";+import { join, resolve, sep } from "node:path";+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";+import { applicationRoot, buildServer } from "./build-server.ts";+import { test } from "node:test";+import { importSource } from "./import-module.ts";+import { temporaryDirectory } from "./support/temporary-directories.ts";+import type { readDeepScanProjectConfig as Reader } from "../src/deep-scan/project-config.js";++const { readDeepScanProjectConfig } = (await importSource(+ join(import.meta.dirname, "../src/deep-scan/project-config.ts"),+)) as { readDeepScanProjectConfig: typeof Reader };++await test("explicit YAML and JSON selection use the CLI project format and minute budget", async () => {+ const root = await temporaryDirectory("deep-project-config-", true);+ try {+ for (const [name, content] of [+ [+ "security.yaml",+ "scan:\n mode: deep\n max_time_minutes: 30\n deep:\n workers: 2\n subagents_per_worker: 1\n stop_after_no_new: 2\n max_discovery_runs: 4\n",+ ],+ [+ "security.json",+ JSON.stringify({+ scan: {+ mode: "deep",+ max_time_minutes: 30,+ deep: {+ workers: 2,+ subagents_per_worker: 1,+ stop_after_no_new: 2,+ max_discovery_runs: 4,+ },+ },+ }),+ ],+ ]) {+ await writeFile(join(root, name), content);+ assert.deepEqual(await readDeepScanProjectConfig(name, root), {+ path: join(root, name),+ settings: {+ workers: 2,+ subagents: 1,+ stopAfterNoNew: 2,+ maxDiscoveryRuns: 4,+ maxTimeHours: 0.5,+ },+ });+ }+ assert.equal(+ await readDeepScanProjectConfig(undefined, root),+ undefined,+ "A repository configuration must not activate without explicit selection.",+ );+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++await test("unsupported settings and contradictory time aliases fail before launch", async () => {+ const root = await temporaryDirectory("deep-project-rejections-");+ try {+ const path = join(root, "security.json");+ for (const [input, message] of [+ [{ scan: { deep: { workers: 0 } } }, /Invalid project configuration/],+ [{ scan: { deep: { unknown: 1 } } }, /Unknown key unknown/],+ [+ { scan: { max_time_minutes: 30, deep: { max_time_hours: 1 } } },+ /Conflicting/,+ ],+ [{ scan: { max_time_minutes: 5761 } }, /no greater than 5760/],+ [{ scan: { mode: "standard" } }, /scan.mode: deep/],+ [+ {+ codex: { model: "fixture" },+ scan: { knowledge_base: ["context.md"] },+ },+ /Unsupported.*codex, scan.knowledge_base/,+ ],+ ] as const) {+ await writeFile(path, JSON.stringify(input));+ await assert.rejects(readDeepScanProjectConfig(path, root), message);+ }+ await mkdir(join(root, "nested"));+ await writeFile(+ path,+ JSON.stringify({+ scan: {+ max_time_minutes: 30,+ deep: { max_time_hours: 0.5, subagents_per_worker: 0 },+ },+ }),+ );+ assert.equal(+ (+ await readDeepScanProjectConfig(+ "../security.json",+ join(root, "nested"),+ )+ )?.settings.subagents,+ 0,+ );+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++await test("built MCP setup previews and saves the selected project before scan launch", async () => {+ const root = await temporaryDirectory("deep-project-mcp-", true);+ const bundle = join(root, "server.cjs");+ const targetPath = join(root, "repository");+ const projectConfigPath = join(targetPath, "selected.yaml");+ const legacyConfigPath = join(root, "defaults.toml");+ const client = new Client({+ name: "deep-project-config-test",+ version: "1.0.0",+ });+ try {+ await mkdir(targetPath);+ await writeFile(join(targetPath, "fixture.py"), "print('fixture')\n");+ await writeFile(+ projectConfigPath,+ "scan:\n mode: deep\n max_time_minutes: 30\n deep:\n workers: 2\n subagents_per_worker: 1\n stop_after_no_new: 2\n max_discovery_runs: 4\n",+ );+ await writeFile(+ legacyConfigPath,+ "[deep_scan]\nworkers=7\nmax_time_hours=4\n",+ );+ await buildServer(bundle, {+ logOverride: { "empty-import-meta": "silent" },+ });+ await client.connect(+ new StdioClientTransport({+ command: process.execPath,+ args: [bundle, "--stdio"],+ cwd: applicationRoot,+ env: {+ ...process.env,+ HOME: root,+ USERPROFILE: root,+ CODEX_HOME: join(root, "home"),+ CODEX_SECURITY_PLUGIN_ROOT: resolve(applicationRoot, ".."),+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ CODEX_SECURITY_SCAN_ROOT: join(root, "scans"),+ CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH: legacyConfigPath,+ } as Record<string, string>,+ }),+ );+ const call = async (name: string, arguments_: Record<string, unknown>) => {+ const result = await client.callTool({+ name,+ arguments: arguments_,+ _meta: { "openai/threadId": "project-owner" },+ });+ assert.notEqual(result.isError, true, JSON.stringify(result.content));+ return result.structuredContent as Record<string, any>;+ };+ const selection = {+ targetPath: "~/repository",+ scope: ".",+ mode: "deep",+ projectConfigPath: "selected.yaml",+ };+ const preview = (await call("inspect_codex_security_setup", selection))+ .setup.deepScanConfig;+ assert.equal(preview.settings.maxTimeHours, 0.5);+ assert.equal(preview.settings.workers, 2);+ assert.equal(preview.sources.workers, "project");+ assert.equal(preview.projectConfigPath, projectConfigPath);+ if (process.platform === "win32" && /^[A-Za-z]:/.test(targetPath)) {+ selection.projectConfigPath = `${targetPath.slice(0, 2)}selected.yaml`;+ const driveRelative = (+ await call("inspect_codex_security_setup", selection)+ ).setup;+ assert.deepEqual(driveRelative.deepScanConfig, preview);+ } else if (process.platform !== "win32") {+ await mkdir(join(targetPath, "subdirectory"));+ await symlink(join(targetPath, "subdirectory"), join(root, "link"));+ await writeFile(+ join(root, "selected.yaml"),+ "scan: {deep: {workers: 7}}",+ );+ selection.targetPath = `${join(root, "link")}${sep}..`;+ const throughLink = (+ await call("inspect_codex_security_setup", selection)+ ).setup;+ assert.equal(throughLink.target.targetPath, targetPath);+ assert.deepEqual(throughLink.deepScanConfig, preview);+ }+ const workspace = (+ await call("open_codex_security_workspace", {+ targetPath,+ mode: "deep",+ })+ ).workspace;+ const saved = (+ await call("submit_codex_security_setup", {+ ...selection,+ sessionId: workspace.id,+ })+ ).workspace;+ assert.equal(saved.targetPath, targetPath);+ assert.deepEqual(saved.deepScanConfig, preview);+ await rm(projectConfigPath);+ await writeFile(legacyConfigPath, "invalid TOML");+ const started = (+ await call("start_codex_security_scan", { sessionId: workspace.id })+ ).workspace;+ assert.deepEqual(started.deepScanConfig, preview);+ } finally {+ await client.close();+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.tsindex bb3845559..4e0e1c76d 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts@@ -48,6 +48,7 @@ async function testDeepScanStdioLifecycle() {const codexHome = path.join(fixtureRoot, "codex [home]");const installedPluginRoot = path.join(codexHome, "plugins", "installed");const runtimeConfigPath = path.join(fixtureRoot, "active-config.toml");+ const projectConfigPath = path.join(fixtureRoot, "selected.yaml");const startLogPath = path.join(fixtureRoot, "fake-codex-started.jsonl");const exitLogPath = path.join(fixtureRoot, "fake-codex-exited.jsonl");const restartControlPath = path.join(@@ -65,6 +66,10 @@ async function testDeepScanStdioLifecycle() {"fail-next-cancel-scan",);const cancelLogPath = path.join(fixtureRoot, "cancel-scan-calls.jsonl");+ const completionFailureControlPath = path.join(+ fixtureRoot,+ "fail-next-complete-scan",+ );const workbenchLaunchLogPath = path.join(fixtureRoot,"workbench-launches.jsonl",@@ -142,6 +147,7 @@ max_discovery_runs = 2.join("\n") + "\n",);await writeFakeCodex(fakeCodexPath);+ await writeFile(projectConfigPath, "scan: {max_time_minutes: 30}\n");await writeFile(runtimeConfigPath,`model_reasoning_summary = "detailed"@@ -169,6 +175,7 @@ model_reasoning_summary = "none"REAL_PYTHON: process.env.PYTHON?.trim() || "python3",FAKE_WORKBENCH_CANCEL_FAILURE_CONTROL: cancelFailureControlPath,FAKE_WORKBENCH_CANCEL_LOG: cancelLogPath,+ FAKE_WORKBENCH_COMPLETION_FAILURE_CONTROL: completionFailureControlPath,FAKE_WORKBENCH_LAUNCH_LOG: workbenchLaunchLogPath,FAKE_CODEX_EXIT_LOG: exitLogPath,FAKE_CODEX_RESTART_CONTROL: restartControlPath,@@ -245,12 +252,36 @@ model_reasoning_summary = "none");assert.deepEqual(await readLogLines(startLogPath), []);+ const missingConfig = await server.request(+ 4,+ "tools/call",+ toolCall(+ "start_codex_security_deep_scan",+ {+ targetPath,+ projectConfigPath: "missing.yaml",+ },+ threadId,+ ),+ );+ assert.equal(missingConfig.result.isError, true);+ assert.match(missingConfig.result.content[0].text, /ENOENT.*missing\.yaml/);+ assert.deepEqual(+ (await runWorkbench(environment, ["list-scans"])).scans,+ [],+ );+server.sendRequest(10,"tools/call",toolCall("start_codex_security_deep_scan",- { targetPath, scope: ".", userContext: "stdio lifecycle fixture" },+ {+ targetPath,+ scope: ".",+ userContext: "stdio lifecycle fixture",+ projectConfigPath,+ },threadId,{model: "gpt-5.5",@@ -268,6 +299,8 @@ model_reasoning_summary = "none"const workerContext = discoveryPromptContext(startedWorker.stdin);assert.match(startedWorker.stdin, /record_codex_security_scan_draft/);const startedState = await getDeepScan({ environment, scanId, threadId });+ assert.equal(startedState.config.maxTimeHours, 0.5);+ await rm(projectConfigPath);const startedArtifactRoot = startedState.workers.find((worker: PersistedDeepScanWorker) => worker.kind === "discovery",)?.artifactDir;@@ -377,11 +410,20 @@ model_reasoning_summary = "none"assertProcessAlive(startedWorker.pid);assert.equal((await readLogLines(startLogPath)).length, 1);- // Two live calls with the persisted scanId must join the one coordinator.+ // Both forms rejoin the same coordinator after the selected file is removed.server.sendRequest(11,"tools/call",- toolCall("start_codex_security_deep_scan", { scanId }, threadId),+ toolCall(+ "start_codex_security_deep_scan",+ {+ targetPath,+ scope: ".",+ userContext: "stdio lifecycle fixture",+ projectConfigPath,+ },+ threadId,+ ),);server.sendRequest(12,@@ -396,7 +438,7 @@ model_reasoning_summary = "none"(event) =>event.event === "coordinator_joined" && event.scanId === scanId,).length >= 2,- "both scanId callers to join the coordinator",+ "both callers to join the coordinator",);assert.equal((await readLogLines(startLogPath)).length, 1);@@ -858,7 +900,7 @@ model_reasoning_summary = "none"},}),);- const resumed = await restartedServer.request(+ restartedServer.sendRequest(2,"tools/call",toolCall(@@ -868,6 +910,53 @@ model_reasoning_summary = "none"{ model: "gpt-6.1-sol", reasoning_effort: "max" },),);+ await waitFor(+ () =>+ restartedServer+ .stderrEvents()+ .some(+ (event) =>+ event.event === "coordinator_started" &&+ event.scanId === resumedScanId,+ ),+ "the resumed coordinator to start before detaching its waiter",+ );+ restartedServer.notify("notifications/cancelled", {+ requestId: 2,+ reason: "the owning response ended before coordinator completion",+ });+ await waitFor(async () => {+ const run = await getDeepScan({+ environment,+ scanId: resumedScanId,+ threadId: resumedThreadId,+ });+ if (run.status === "failed") throw new Error(run.error);+ return run.status === "succeeded";+ }, "the detached coordinator to persist its successful aggregate");+ await waitFor(async () => {+ const scan = await runWorkbench(environment, [+ "get-scan",+ "--scan-id",+ resumedScanId,+ ]);+ return scan.scan.progress.status === "complete";+ }, "the detached coordinator to finalize without another tool call");+ const sealedBeforeRejoin = await readFile(manifestPath, "utf8");+ const reportBeforeRejoin = await readFile(+ path.join(resumedScan.scanDir, "report.md"),+ "utf8",+ );+ const resumed = await restartedServer.request(+ 3,+ "tools/call",+ toolCall(+ "start_codex_security_deep_scan",+ { scanId: resumedScanId, handoffClaimToken },+ resumedThreadId,+ { model: "gpt-6.1-sol", reasoning_effort: "max" },+ ),+ );assertNoError(resumed);const modelRows = await execFileAsync(process.env.PYTHON?.trim() || "python3",@@ -882,21 +971,17 @@ model_reasoning_summary = "none"const instructions = resumed.result.structuredContent.instructions;assert.match(instructions,- /Immediately call complete_codex_security_scan once/,- );- assert.match(- instructions,- /Return output only after completion succeeds/,- );- assert.match(- instructions,- /If completion fails, surface that exact error/,+ /Do not call complete_codex_security_scan again/,);+ const completion = resumed.result.structuredContent.completion;+ assert.equal(completion.scan.progress.status, "complete");+ assert.equal(completion.scan.reportAvailable, true);assert.deepEqual(resumed.result.structuredContent, {scanId: resumedScanId,scanDir: resumedScan.scanDir,manifestPath,instructions,+ completion,});assert.deepEqual(resumed.result.content, [{ type: "text", text: instructions },@@ -906,7 +991,7 @@ model_reasoning_summary = "none"item.text.includes(resumedScanId),),true,- "the successful tool response must expose the authoritative scan ID for completion",+ "the successful tool response must expose the authoritative scan ID",);const finished = await getDeepScan({environment,@@ -947,19 +1032,6 @@ model_reasoning_summary = "none"(await readJson(resumedScan.scanDir, "findings.json")).findings,[],);- const completion = await restartedServer.request(- 3,- "tools/call",- toolCall(- "complete_codex_security_scan",- {- scanId: resumed.result.structuredContent.scanId,- handoffClaimToken,- },- resumedThreadId,- ),- );- assertNoError(completion);const completedScan = resumed.result.structuredContent;const sealedManifest = await readJson(completedScan.manifestPath);assert.equal(sealedManifest.scan.status, "completed");@@ -969,6 +1041,8 @@ model_reasoning_summary = "none""utf8",);assert.ok(report.length > 0);+ assert.equal(await readFile(manifestPath, "utf8"), sealedBeforeRejoin);+ assert.equal(report, reportBeforeRejoin);const helperLaunches = await readLogLines(workbenchLaunchLogPath);for (const command of ["get-scan", "write-scan-draft", "complete-scan"]) {const launches = helperLaunches.filter(@@ -1023,9 +1097,82 @@ model_reasoning_summary = "none").length,1,);+ const retryTarget = path.join(fixtureRoot, "completion-retry-target");+ await mkdir(retryTarget);+ await writeFile(+ path.join(retryTarget, "source.py"),+ "# Synthetic completion retry\n",+ );+ await writeFile(completionFailureControlPath, "fail\n");+ const completionFailed = await restartedServer.request(+ 4,+ "tools/call",+ toolCall(+ "start_codex_security_deep_scan",+ { targetPath: retryTarget },+ resumedThreadId,+ ),+ );+ assert.equal(completionFailed.result?.isError, true);+ assert.match(+ JSON.stringify(completionFailed.result.content),+ /injected complete-scan failure/,+ );+ const retryScanId = completionFailed.result.structuredContent?.scanId;+ assert.ok(+ retryScanId,+ "the caller needs the scan ID to retry finalization",+ );+ assert.ok(completionFailed.result.content[0].text.includes(retryScanId));+ const retryRun = await getDeepScan({+ environment,+ scanId: retryScanId,+ threadId: resumedThreadId,+ });+ assert.equal(retryRun.status, "succeeded");+ const pending = await runWorkbench(environment, [+ "get-scan",+ "--scan-id",+ retryScanId,+ ]);+ assert.equal(pending.scan.progress.status, "running");+ assert.equal(pending.scan.reportAvailable, false);+ const workerCountBeforeRetry = (await readLogLines(startLogPath)).length;+ await writeFile(+ path.join(retryTarget, "source.py"),+ "# Target changed after the failed completion\n",+ );+ const retry = await restartedServer.request(+ 5,+ "tools/call",+ toolCall(+ "start_codex_security_deep_scan",+ { scanId: retryScanId },+ resumedThreadId,+ ),+ );+ assertNoError(retry);+ assert.equal(retry.result.structuredContent.scanId, retryScanId);+ assert.equal(+ retry.result.structuredContent.completion.scan.progress.status,+ "complete",+ );+ assert.equal(+ retry.result.structuredContent.completion.scan.reportAvailable,+ true,+ );+ assert.equal(+ (await readLogLines(startLogPath)).length,+ workerCountBeforeRetry,+ );+ } catch (error) {+ (error as Error).message +=+ `\nRestarted MCP stderr:\n${restartedServer.stderrText()}`;+ throw error;} finally {await restartedServer.stop();}+ await testDetachedTargetReplay(serverBundlePath, environment, targetPath);await testCliDeepScanEngine({fixtureRoot,environment,@@ -1044,6 +1191,63 @@ model_reasoning_summary = "none"}}+async function testDetachedTargetReplay(+ serverBundlePath: string,+ environment: NodeJS.ProcessEnv,+ targetPath: string,+) {+ const threadId = "detached-headless-owner";+ const request = toolCall(+ "start_codex_security_deep_scan",+ { targetPath },+ threadId,+ );+ let server = startServer(serverBundlePath, environment);+ try {+ assertNoError(await server.initialize("detached-target"));+ server.sendRequest(2, "tools/call", request);+ const scanId = await waitForScanId({ server, requestId: 2 });+ server.notify("notifications/cancelled", { requestId: 2 });+ await waitFor(async () => {+ const state = await runWorkbench(environment, [+ "get-scan",+ "--scan-id",+ scanId,+ ]);+ return state.scan.progress.status === "complete";+ }, "the detached target request to finalize");+ assert.equal(server.response(2)?.result?.structuredContent, undefined);+ const { scanDir } = await getDeepScan({ environment, scanId, threadId });+ const report = await readFile(path.join(scanDir, "report.md"), "utf8");+ const launches = await readLogLines(environment.FAKE_CODEX_START_LOG!);+ await server.stop();++ server = startServer(serverBundlePath, environment);+ assertNoError(await server.initialize("detached-target-retry"));+ const replay = await server.callTool(2, request);+ assertNoError(replay);+ const completed = replay.result.structuredContent;+ assert.equal(completed.scanId, scanId);+ assert.equal(completed.scanDir, scanDir);+ assert.equal(completed.completion.scan.reportAvailable, true);+ assert.equal(+ await readFile(path.join(completed.scanDir, "report.md"), "utf8"),+ report,+ );+ assert.equal(+ (await readLogLines(environment.FAKE_CODEX_START_LOG!)).length,+ launches.length,+ );++ server.sendRequest(3, "tools/call", request);+ const fresh = await server.waitForResponse(3, 60_000);+ assertNoError(fresh);+ assert.notEqual(fresh.result.structuredContent.scanId, scanId);+ } finally {+ await server.stop();+ }+}+async function testCliDeepScanEngine({fixtureRoot,environment,@@ -1098,6 +1302,7 @@ async function testCliDeepScanEngine({recipe: {repository,mode: "deep",+ maxCostUsd: 0.004,target: scoped? { kind: "paths", paths }: { kind: "repository", paths: [] },@@ -1187,16 +1392,55 @@ async function testCliDeepScanEngine({}}const count = (await readLogLines(environment.FAKE_CODEX_START_LOG!)).length;+ const unsealed = await readJson(+ path.join(completed.scanDir, "scan-manifest.json"),+ );+ assert.equal(unsealed.scan.sealedAt, undefined);+ await assert.rejects(readFile(path.join(completed.scanDir, "report.md")), {+ code: "ENOENT",+ });await launch(completed.scanId);assert.equal((await readLogLines(environment.FAKE_CODEX_START_LOG!)).length,count,);- await runWorkbench(environment, [- "complete-scan",+ // A resumed SDK scan rejoins through the parent MCP turn after discovery.+ const parent = startServer(serverBundlePath, environment);+ try {+ assertNoError(await parent.initialize("sdk-parent"));+ const joined = await parent.callTool(+ 2,+ toolCall(+ "start_codex_security_deep_scan",+ { scanId: completed.scanId },+ threadId,+ ),+ );+ assertNoError(joined);+ assert.equal(joined.result.structuredContent.scanId, completed.scanId);+ assert.equal(joined.result.structuredContent.completion, undefined);+ assert.match(joined.result.structuredContent.instructions, /SDK/);+ } finally {+ await parent.stop();+ }+ const warning = "The parent turn exceeded the scan cost limit.";+ const recovered = await runWorkbench(environment, [+ "complete-budget-exhausted-scan","--scan-id",completed.scanId,+ "--cost-json",+ JSON.stringify({+ model: "gpt-6.1-sol",+ inputTokens: 1250,+ cachedInputTokens: 200,+ cacheWriteInputTokens: 0,+ outputTokens: 30,+ estimatedUsd: 0.00625,+ }),+ "--message",+ warning,]);+ assert.ok(recovered.scan.warnings.includes(warning));const manifest = await readJson(path.join(completed.scanDir, "scan-manifest.json"),);@@ -1544,6 +1788,12 @@ if (workbenchArgs[0] === 'cancel-scan' && control && existsSync(control)) {console.error('injected cancel-scan failure');process.exit(1);}+const completionControl = process.env.FAKE_WORKBENCH_COMPLETION_FAILURE_CONTROL;+if (workbenchArgs[0] === 'complete-scan' && completionControl && existsSync(completionControl)) {+ unlinkSync(completionControl);+ console.error('injected complete-scan failure');+ process.exit(1);+}const result = spawnSync(process.env.REAL_PYTHON || 'python3', args, { input, stdio: ['pipe', 'inherit', 'inherit'] });if (result.error) throw result.error;process.exit(result.status ?? 1);diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_templates.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_templates.tsindex 295c953fd..dd52559d9 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_templates.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_templates.ts@@ -60,7 +60,7 @@ const dedupContext = firstJsonBlock(dedup);assert.doesNotMatch(dedup, /\bcoverage\b/i);assert.match(dedup,- /record_codex_security_deep_reduction\(\{ scanId, findings, threatModel\?, scope\? \}\)/,+ /record_codex_security_deep_reduction\(\{ scanId, findings, retainedFindingRefs\?, threatModel\?, scope\? \}\)/,);assert.deepEqual(dedupContext, {reducerLabel: "dedup-0001",diff --git a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.tsindex e32d96d24..071a1c3e9 100644--- a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts+++ b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts@@ -1932,7 +1932,7 @@ try {]);assert.deepEqual(submit._meta.ui.visibility, ["app"]);assert.deepEqual(inspectTarget._meta.ui.visibility, ["app"]);- assert.deepEqual(inspectSetup._meta.ui.visibility, ["app"]);+ assert.deepEqual(inspectSetup._meta.ui.visibility, ["app", "model"]);assert.deepEqual(start._meta.ui.visibility, ["app"]);assert.deepEqual(startDeepScan._meta.ui.visibility, ["model"]);assert.ok(startDeepScan.inputSchema.properties.scanId);diff --git a/plugins/codex-security/mcp-app/tests/test_stdio_transport.ts b/plugins/codex-security/mcp-app/tests/test_stdio_transport.tsindex 543bf6bfd..1b7147b95 100644--- a/plugins/codex-security/mcp-app/tests/test_stdio_transport.ts+++ b/plugins/codex-security/mcp-app/tests/test_stdio_transport.ts@@ -24,8 +24,15 @@ function captureTransport() {};}-test("stdio preserves ordinary result and error responses exactly", async () => {+test("stdio preserves ordinary responses and acknowledges only the first successful send", async () => {const { transport, lines } = captureTransport();+ const acknowledged: (number | string)[] = [];+ const signal = new AbortController().signal;+ for (const id of [0, ""]) {+ transport.afterResultSent(id, signal, async () => {+ acknowledged.push(id);+ });+ }const messages: JSONRPCMessage[] = [{ jsonrpc: "2.0", id: 0, result: { text: 'A quote: " and a newline:\n' } },{@@ -36,9 +43,14 @@ test("stdio preserves ordinary result and error responses exactly", async () =>];for (const message of messages) await transport.send(message);assert.deepEqual(lines, messages.map(serializeMessage));+ assert.deepEqual(acknowledged, [0]);+ for (const id of [0, ""]) {+ await transport.send({ jsonrpc: "2.0", id, result: {} });+ }+ assert.deepEqual(acknowledged, [0]);});-test("stdio counts UTF-8 JSON escaping and the LF at the native line boundary", async () => {+test("stdio counts UTF-8 JSON escaping and the LF at the native line boundary", async (t) => {for (const bytes of [nativeLineLimitBytes, nativeLineLimitBytes + 1]) {const { transport, lines } = captureTransport();const message = {@@ -53,6 +65,12 @@ test("stdio counts UTF-8 JSON escaping and the LF at the native line boundary",assert.equal(Buffer.byteLength(serialized), bytes);assert.ok(serialized.length < bytes);+ const acknowledge = t.mock.fn(async () => {});+ transport.afterResultSent(+ message.id,+ new AbortController().signal,+ acknowledge,+ );await transport.send(message);assert.equal(lines.length, 1);if (bytes === nativeLineLimitBytes) {@@ -70,7 +88,80 @@ test("stdio counts UTF-8 JSON escaping and the LF at the native line boundary",response.error.message,/operation may already have completed/,);+ await transport.send({ jsonrpc: "2.0", id: message.id, result: {} });+ }+ assert.equal(+ acknowledge.mock.callCount(),+ bytes === nativeLineLimitBytes ? 1 : 0,+ );+ }+});++test("aborting before or during a backpressured send leaves the result unacknowledged", async (t) => {+ for (const abortBeforeSend of [true, false]) {+ let finishWrite: (() => void) | undefined;+ const stdout = new Writable({+ highWaterMark: 1,+ write(_chunk, _encoding, callback) {+ finishWrite = callback;+ },+ });+ const transport = new CodexSecurityStdioTransport(+ new PassThrough(),+ stdout,+ );+ const waiter = new AbortController();+ const acknowledge = t.mock.fn(async () => {});+ transport.afterResultSent(1, waiter.signal, acknowledge);+ if (abortBeforeSend) waiter.abort();+ const sending = transport.send({ jsonrpc: "2.0", id: 1, result: {} });+ assert.equal(stdout.writableNeedDrain, true);+ assert.equal(acknowledge.mock.callCount(), 0);+ if (!abortBeforeSend) waiter.abort();+ assert.ok(finishWrite);+ finishWrite();+ await sending;+ assert.equal(acknowledge.mock.callCount(), 0);+ }+});++test("a failed or disconnected stdout write leaves the result unacknowledged", async (t) => {+ for (const disconnect of [false, true]) {+ let finishWrite!: (error?: Error | null) => void;+ const lines: string[] = [];+ const stdout = new Writable({+ highWaterMark: disconnect ? 1 : 1024,+ write(chunk: Buffer, _encoding, callback) {+ lines.push(chunk.toString("utf8"));+ finishWrite = callback;+ },+ });+ const transport = new CodexSecurityStdioTransport(+ new PassThrough(),+ stdout,+ );+ const acknowledge = t.mock.fn(async () => {});+ transport.afterResultSent(1, new AbortController().signal, acknowledge);+ const message: JSONRPCMessage = { jsonrpc: "2.0", id: 1, result: {} };+ const sending = transport.send(message);+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(stdout.writableNeedDrain, disconnect);+ assert.equal(acknowledge.mock.callCount(), 0);++ const rejected = assert.rejects(+ sending,+ disconnect ? /close/i : /write failure/,+ );+ if (disconnect) {+ stdout.destroy();+ await rejected;+ finishWrite();+ } else {+ finishWrite(new Error("write failure"));+ await rejected;}+ assert.equal(acknowledge.mock.callCount(), 0);+ assert.deepEqual(lines, [serializeMessage(message)]);}});diff --git a/plugins/codex-security/mcp-app/tests/test_workbench_database.ts b/plugins/codex-security/mcp-app/tests/test_workbench_database.tsindex 976974ed0..af466ebda 100644--- a/plugins/codex-security/mcp-app/tests/test_workbench_database.ts+++ b/plugins/codex-security/mcp-app/tests/test_workbench_database.ts@@ -735,11 +735,22 @@ test("recorded additive migrations restore missing columns and configured errordatabase.exec(`INSERT INTO deep_scan_runs (scan_id, schema_version, workflow_version, status, phase,workers, subagents, stop_after_no_new, max_discovery_runs, created_at, updated_at)VALUES ('scan', 1, 'v1', 'running', 'discovery', 1, 0, 7, 10, 'created', 'updated')`);- for (const version of [27, 28, 31, 32, 47])+ for (const version of [27, 28, 31, 32, 47, 54, 55])database.prepare("INSERT INTO schema_migrations VALUES (?, ?, 'original')").run(version, migrations[version - 1].name);applyMigrations(database);+ assert.equal(+ database.prepare("SELECT deep_scan_config_json FROM workspaces").get()+ ?.deep_scan_config_json,+ null,+ );+ assert.equal(+ database+ .prepare("SELECT pending_target_project_path FROM deep_scan_runs")+ .get()?.pending_target_project_path,+ null,+ );assert.equal(database.prepare("SELECT stop_after_consecutive_errors FROM deep_scan_runs")diff --git a/plugins/codex-security/references/final-report.md b/plugins/codex-security/references/final-report.mdindex 0b11f1ea2..64b55af73 100644--- a/plugins/codex-security/references/final-report.md+++ b/plugins/codex-security/references/final-report.md@@ -8,7 +8,7 @@ The canonical inputs are `scan-manifest.json`, `findings.json`, and `coverage.js| --- | --- | --- || Workbench Standard or diff | `record_codex_security_scan_draft({ scanId, handoffClaimToken?, scope?, threatModel?, findings, coverage, complete? })` | Parent calls `complete_codex_security_scan` after an accepted final draft || Bound Deep Standard worker | Its bound semantic draft tool | Deep coordinator |-| Deep parent | Coordinator's accepted aggregate; do not submit another draft | Parent calls completion after the coordinator returns its canonical manifest |+| Workbench Deep parent | Coordinator's accepted aggregate | Coordinator finalizes the scan and returns `completion` with the sealed manifest || SDK-owned scan | Unsealed canonical files with the SDK-provided identity and metadata, using a bound draft tool when supplied | SDK; do not call completion or a finalizer |Other scans need authoritative managed context; do not substitute shell-authored canonical files. Checkpoint findings, pending candidates, and the threat model with `complete: false`. An accepted `complete: true` draft (or the backwards-compatible omitted flag) ends submission; a checkpoint does not claim completed review.diff --git a/plugins/codex-security/schemas/tools/deep-reducer.schema.json b/plugins/codex-security/schemas/tools/deep-reducer.schema.jsonindex eea8bf7fc..3027ac425 100644--- a/plugins/codex-security/schemas/tools/deep-reducer.schema.json+++ b/plugins/codex-security/schemas/tools/deep-reducer.schema.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","$id": "codex-security://schemas/tools/deep-reducer.schema.json","title": "Codex Security Deep Scan semantic reducer operations",- "$ref": "#/$defs/reductionInput",+ "$ref": "#/$defs/reductionSubmission","$defs": {"reducerInputs": {"type": "object",@@ -54,6 +54,43 @@},"required": ["scanId", "findings"],"additionalProperties": false+ },+ "reductionSubmission": {+ "type": "object",+ "properties": {+ "complete": {+ "type": "boolean",+ "description": "Omit or set true when submitting the finished aggregate."+ },+ "scanId": {+ "$ref": "codex-security://schemas/definitions/artifact-common.schema.json#/$defs/scanId"+ },+ "handoffClaimToken": {+ "$ref": "codex-security://schemas/tools/scan-draft.schema.json#/$defs/handoffClaimToken"+ },+ "scope": {+ "$ref": "codex-security://schemas/tools/scan-draft.schema.json#/$defs/scope"+ },+ "threatModel": {+ "$ref": "codex-security://schemas/tools/scan-draft.schema.json#/$defs/threatModel"+ },+ "findings": {+ "type": "array",+ "items": {+ "$ref": "codex-security://schemas/tools/scan-draft.schema.json#/$defs/finding"+ }+ },+ "retainedFindingRefs": {+ "type": "array",+ "items": {+ "type": "string",+ "pattern": "^previous:(0|[1-9][0-9]*)$"+ },+ "description": "Copy unchanged previous aggregate findings by previous:<zero-based index>. The host preserves their complete bodies, identities, and source references; do not also submit them in findings."+ }+ },+ "required": ["scanId", "findings"],+ "additionalProperties": false}}}diff --git a/plugins/codex-security/scripts/deep_scan_config.py b/plugins/codex-security/scripts/deep_scan_config.pyindex d03e63b1d..a0e200ac5 100644--- a/plugins/codex-security/scripts/deep_scan_config.py+++ b/plugins/codex-security/scripts/deep_scan_config.py@@ -22,14 +22,15 @@ DEFAULT_STOP_AFTER_CONSECUTIVE_ERRORS = DEFAULTS["stopAfterConsecutiveErrors"]DEFAULT_MAX_DISCOVERY_RUNS = DEFAULTS["maxDiscoveryRuns"]DEFAULT_MAX_TIME_HOURS = DEFAULTS["maxTimeHours"]MAX_TIME_HOURS = 96-CONFIG_KEYS = {- "workers",- "subagents",- "stop_after_no_new",- "stop_after_consecutive_errors",- "max_discovery_runs",- "max_time_hours",+CONFIG_FIELDS = {+ "workers": "workers",+ "subagents": "subagents",+ "stopAfterNoNew": "stop_after_no_new",+ "stopAfterConsecutiveErrors": "stop_after_consecutive_errors",+ "maxDiscoveryRuns": "max_discovery_runs",+ "maxTimeHours": "max_time_hours",}+CONFIG_KEYS = set(CONFIG_FIELDS.values())def codex_home() -> Path:@@ -46,11 +47,23 @@ def config_path() -> Path:def resolve_deep_scan_config(available_parallelism: int) -> dict[str, int | float]:+ return resolve_deep_scan_setup(available_parallelism)["settings"]+++def resolve_deep_scan_setup(+ available_parallelism: int, project_json: str | None = None+) -> dict[str, Any]:+ project = json.loads(project_json) if project_json is not None else None+ overrides = project["settings"] if project is not None else {}+ unknown = sorted(set(overrides) - set(CONFIG_FIELDS))+ if unknown:+ raise SystemExit(f"Unknown Deep Scan project settings: {', '.join(unknown)}.")if isinstance(available_parallelism, bool) or available_parallelism < 1:raise SystemExit("Available parallelism must be a positive integer.")path = config_path()configured: dict[str, Any] = {}- if path.exists():+ exists = path.exists()+ if exists and not all(name in overrides for name in CONFIG_FIELDS):try:with path.open("rb") as source:document: object = tomllib.load(source)@@ -70,38 +83,25 @@ def resolve_deep_scan_config(available_parallelism: int) -> dict[str, int | floa)configured = deep_scan- workers: object = configured.get("workers", DEFAULT_WORKERS)- if workers == "auto":- resolved_workers = DEFAULT_WORKERS- else:- resolved_workers = require_integer(workers, "deep_scan.workers", minimum=1)- stop_after_no_new = require_integer(- configured.get("stop_after_no_new", DEFAULT_STOP_AFTER_NO_NEW),- "deep_scan.stop_after_no_new",- minimum=1,- )+ settings: dict[str, int | float] = {}+ sources: dict[str, str] = {}+ for name, key in CONFIG_FIELDS.items():+ value = overrides.get(name, configured.get(key, DEFAULTS[name]))+ sources[name] = (+ "project" if name in overrides else "legacy" if key in configured else "default"+ )+ if name == "workers" and value == "auto":+ value = DEFAULT_WORKERS+ settings[name] = (+ require_positive_number(value, "deep_scan.max_time_hours")+ if name == "maxTimeHours"+ else require_integer(value, f"deep_scan.{key}", minimum=0 if name == "subagents" else 1)+ )return {- "workers": resolved_workers,- "subagents": require_integer(- configured.get("subagents", DEFAULT_SUBAGENTS),- "deep_scan.subagents",- minimum=0,- ),- "stopAfterNoNew": stop_after_no_new,- "stopAfterConsecutiveErrors": require_integer(- configured.get("stop_after_consecutive_errors", DEFAULT_STOP_AFTER_CONSECUTIVE_ERRORS),- "deep_scan.stop_after_consecutive_errors",- minimum=1,- ),- "maxDiscoveryRuns": require_integer(- configured.get("max_discovery_runs", DEFAULT_MAX_DISCOVERY_RUNS),- "deep_scan.max_discovery_runs",- minimum=1,- ),- "maxTimeHours": require_positive_number(- configured.get("max_time_hours", DEFAULT_MAX_TIME_HOURS),- "deep_scan.max_time_hours",- ),+ "settings": settings,+ "sources": sources,+ **({"legacyConfigPath": str(path)} if exists else {}),+ **({"projectConfigPath": project["path"]} if project is not None else {}),}diff --git a/plugins/codex-security/scripts/deep_scan_workbench.py b/plugins/codex-security/scripts/deep_scan_workbench.pyindex ed71e008d..0c122ff17 100644--- a/plugins/codex-security/scripts/deep_scan_workbench.py+++ b/plugins/codex-security/scripts/deep_scan_workbench.py@@ -15,7 +15,7 @@ from typing import Any, Callablesys.path.insert(0, str(Path(__file__).resolve().parent))import workbench_saved_results as saved_results-from deep_scan_config import resolve_deep_scan_config+from deep_scan_config import resolve_deep_scan_setupfrom workbench.handoff import require_current_continuationfrom workbench.storage import create_private_directoryfrom workbench_source_scopes import capture_source_scopes@@ -51,12 +51,18 @@ def register_subcommands(subparsers: Any, positive_int: Callable[[str], int]) ->begin_deep_scan.add_argument("--model")begin_deep_scan.add_argument("--reasoning-effort")begin_deep_scan.add_argument("--available-parallelism", type=positive_int)+ begin_deep_scan.add_argument("--deep-scan-project-json")+ begin_deep_scan.add_argument("--project-config-path")+ begin_deep_scan.add_argument("--join-only", action="store_true")begin_deep_scan.add_argument("--workflow-version", default=DEEP_SCAN_WORKFLOW_VERSION)get_deep_scan = subparsers.add_parser("get-deep-scan")get_deep_scan.add_argument("--scan-id", required=True)get_deep_scan.add_argument("--thread-id", required=True)+ acknowledge_result = subparsers.add_parser("acknowledge-deep-scan-result")+ acknowledge_result.add_argument("--scan-id", required=True)+claim_coordinator = subparsers.add_parser("claim-deep-scan-coordinator")claim_coordinator.add_argument("--scan-id", required=True)claim_coordinator.add_argument("--thread-id", required=True)@@ -428,6 +434,7 @@ def deep_scan_state(connection: sqlite3.Connection, scan_id: str) -> dict[str, A)return {"scanId": run["scan_id"],+ "sdkOwnsCompletion": scan["recipe_json"] is not None,"targetPath": scan["target_path"],"scope": scan["scope"],"includePaths": dependencies().requested_scan_paths(scan),@@ -539,9 +546,13 @@ def deep_scan_result(return result-def effective_deep_scan_config(args: argparse.Namespace) -> dict[str, int | float]:+def effective_deep_scan_config(+ args: argparse.Namespace, workspace: sqlite3.Row | None = None+) -> dict[str, Any]:+ if workspace is not None and workspace["deep_scan_config_json"] is not None:+ return json.loads(workspace["deep_scan_config_json"])available_parallelism = args.available_parallelism or os.cpu_count() or 1- return resolve_deep_scan_config(available_parallelism)+ return resolve_deep_scan_setup(available_parallelism, args.deep_scan_project_json)def ensure_deep_scan_run(@@ -550,6 +561,8 @@ def ensure_deep_scan_run(config: dict[str, int | float],workflow_version: str,timestamp: str,+ *,+ pending_target_project_path: str | None = None,) -> sqlite3.Row:existing = connection.execute("SELECT * FROM deep_scan_runs WHERE scan_id = ?", (scan["id"],)@@ -566,8 +579,8 @@ def ensure_deep_scan_run(scan_id, schema_version, workflow_version, status, phase,workers, subagents, stop_after_no_new, stop_after_consecutive_errors,max_discovery_runs, max_time_hours, discovery_user_context_json,- created_at, updated_at- ) VALUES (?, 1, ?, 'running', 'setup', ?, ?, ?, ?, ?, ?, ?, ?, ?)+ created_at, updated_at, pending_target_project_path+ ) VALUES (?, 1, ?, 'running', 'setup', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",(scan["id"],@@ -581,6 +594,7 @@ def ensure_deep_scan_run(json.dumps(scan["user_context"]),timestamp,timestamp,+ pending_target_project_path,),)return require_deep_scan_run(connection, scan["id"])@@ -613,18 +627,13 @@ def terminal_deep_scan_for_target_snapshot(target_path: str,scope: str,user_context: str | None,+ project_path: str,revision: str,snapshot_digest: str,target_device: int | str,target_inode: int | str,) -> sqlite3.Row | None:- """Find discovery completed before a headless continuation changed thread IDs.-- A continuation may safely consume a finished coordinator manifest while the- parent scan is still open. It must not adopt live orchestration owned by a- different thread, or reuse results for a different repository snapshot or- original discovery context.- """+ """Recover a matching terminal headless result, including after the parent was sealed."""return connection.execute("""SELECT scans.*@@ -635,15 +644,22 @@ def terminal_deep_scan_for_target_snapshot(AND scans.scope = ?AND deep_scan_runs.discovery_user_context_json = ?AND scans.mode = 'deep'- AND scans.status = 'running'+ AND (+ (scans.status = 'running'+ AND COALESCE(scans.deep_scan_owner_thread_id, workspaces.thread_id) <> ?)+ OR (scans.status = 'complete'+ AND deep_scan_runs.pending_target_project_path IS NOT NULL)+ )+ AND (deep_scan_runs.pending_target_project_path IS NULL+ OR deep_scan_runs.pending_target_project_path = ?)AND scans.canceled_at IS NULL+ AND scans.recipe_json IS NULLAND scans.target_revision = ?AND scans.target_snapshot_digest = ?AND scans.target_device = ?AND scans.target_inode = ?AND scans.handoff_status = 'delivered'AND scans.handoff_claim_token IS NULL- AND COALESCE(scans.deep_scan_owner_thread_id, workspaces.thread_id) <> ?AND workspaces.active_scan_id = scans.idAND deep_scan_runs.status = 'succeeded'AND deep_scan_runs.phase = 'terminal'@@ -651,13 +667,16 @@ def terminal_deep_scan_for_target_snapshot(AND deep_scan_runs.terminal_reason IN ('saturated', 'capped')AND deep_scan_runs.manifest_path IS NOT NULLAND deep_scan_runs.completed_at IS NOT NULL- ORDER BY deep_scan_runs.completed_at DESC, scans.updated_at DESC, scans.id+ ORDER BY (COALESCE(scans.deep_scan_owner_thread_id, workspaces.thread_id) = ?) DESC,+ deep_scan_runs.completed_at DESC, scans.updated_at DESC, scans.idLIMIT 1""",(target_path,scope,json.dumps(user_context),+ thread_id,+ project_path,revision,snapshot_digest,target_device,@@ -712,6 +731,11 @@ def begin_deep_scan_for_scan()if scan["mode"] != "deep":raise SystemExit("Deep Scan orchestration requires a scan in deep mode.")+ existing = connection.execute(+ "SELECT scan_id FROM deep_scan_runs WHERE scan_id = ?", (scan_id,)+ ).fetchone()+ if args.join_only and existing is None and workspace["deep_scan_config_json"] is None:+ return {"newScanTarget": scan["target_path"]}model = optional_text(args.model, maximum=200)reasoning_effort = optional_text(args.reasoning_effort, maximum=32)if model is not None or reasoning_effort is not None:@@ -724,12 +748,11 @@ def begin_deep_scan_for_scan((model, reasoning_effort, scan_id),)connection.commit()- existing = connection.execute(- "SELECT scan_id FROM deep_scan_runs WHERE scan_id = ?", (scan_id,)- ).fetchone()if existing is not None:return deep_scan_result(connection, scan_id, start_disposition="joined")- config = effective_deep_scan_config(args)+ workspace = dependencies().require_workspace(connection, scan["workspace_id"])+ configuration = effective_deep_scan_config(args, workspace)+ config = configuration["settings"]workflow_version = optional_text(args.workflow_version, maximum=256)if workflow_version is None:raise SystemExit("workflow-version is required.")@@ -741,6 +764,10 @@ def begin_deep_scan_for_scan(args.claim_token,error_message="Deep Scan orchestration is owned by another continuation.",)+ connection.execute(+ "UPDATE workspaces SET deep_scan_config_json = ? WHERE id = ? AND deep_scan_config_json IS NULL",+ (json.dumps(configuration), workspace["id"]),+ )ensure_deep_scan_run(connection, scan, config, workflow_version, dependencies().now())return deep_scan_result(connection, scan_id, start_disposition="created")@@ -756,6 +783,30 @@ def begin_deep_scan_for_target(if existing is not None:return begin_deep_scan_for_scan(connection, existing["id"], thread_id, args)user_context = user_context_argument(args)+ # Keep the requested spelling so a continuation can match a removed file or symlink.+ # NULL means no result is pending. The empty string denotes a launch with no project file.+ project_path = args.project_config_path or ""+ # Avoid hashing the checkout during this probe when a fresh scan needs its configuration.+ if (+ args.join_only+ and not connection.execute(+ """+ SELECT 1 FROM scans JOIN deep_scan_runs ON deep_scan_runs.scan_id = scans.id+ WHERE scans.target_path = ? AND scans.scope = ?+ AND (scans.status = 'running'+ OR (scans.status = 'complete'+ AND deep_scan_runs.pending_target_project_path IS NOT NULL))+ AND (deep_scan_runs.pending_target_project_path IS NULL+ OR deep_scan_runs.pending_target_project_path = ?)+ AND scans.recipe_json IS NULL+ AND scans.handoff_claim_token IS NULL AND deep_scan_runs.status = 'succeeded'+ AND deep_scan_runs.discovery_user_context_json = ?+ LIMIT 1+ """,+ (target_path, scope, project_path, json.dumps(user_context)),+ ).fetchone()+ ):+ return {"newScanTarget": target_path}target_metadata = target.stat()target_identity = dependencies().scan_target_identity(target, None, metadata=target_metadata)revision, target_snapshot_digest, target_device, target_inode = target_identity@@ -766,23 +817,8 @@ def begin_deep_scan_for_target(with connection:existing = existing_deep_scan_for_target(connection, thread_id, target_path, scope)if existing is not None:- existing_run = connection.execute(- "SELECT 1 FROM deep_scan_runs WHERE scan_id = ?", (existing["id"],)- ).fetchone()- if existing_run is None:- config = effective_deep_scan_config(args)- workflow_version = optional_text(args.workflow_version, maximum=256)- if workflow_version is None:- raise SystemExit("workflow-version is required.")- ensure_deep_scan_run(- connection, existing, config, workflow_version, dependencies().now()- )connection.commit()- return deep_scan_result(- connection,- existing["id"],- start_disposition="joined" if existing_run is not None else "created",- )+ return begin_deep_scan_for_scan(connection, existing["id"], thread_id, args)current_target = dependencies().require_remediation_target(target_path)current_metadata = current_target.stat()if (current_metadata.st_dev, current_metadata.st_ino) != (@@ -798,6 +834,7 @@ def begin_deep_scan_for_target(target_path,scope,user_context,+ project_path,revision,target_snapshot_digest,target_device,@@ -810,12 +847,15 @@ def begin_deep_scan_for_target(terminal["id"],start_disposition="joined",)+ if args.join_only:+ return {"newScanTarget": target_path}source_scopes = capture_source_scopes(target,(revision, target_snapshot_digest, target_device, target_inode),[scope],)- config = effective_deep_scan_config(args)+ configuration = effective_deep_scan_config(args)+ config = configuration["settings"]workflow_version = optional_text(args.workflow_version, maximum=256)if workflow_version is None:raise SystemExit("workflow-version is required.")@@ -834,8 +874,8 @@ def begin_deep_scan_for_target("""INSERT INTO workspaces (id, thread_id, target_id, target_path, target_title, default_scope, default_mode,- user_context, submitted, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, 'deep', ?, 1, ?, ?)+ user_context, submitted, created_at, updated_at, deep_scan_config_json+ ) VALUES (?, ?, ?, ?, ?, ?, 'deep', ?, 1, ?, ?, ?)""",(workspace_id,@@ -847,6 +887,7 @@ def begin_deep_scan_for_target(user_context,timestamp,timestamp,+ json.dumps(configuration),),)workspace = connection.execute(@@ -870,7 +911,14 @@ def begin_deep_scan_for_target(reasoning_effort=reasoning_effort,)scan = dependencies().require_scan(connection, scan_id)- ensure_deep_scan_run(connection, scan, config, workflow_version, timestamp)+ ensure_deep_scan_run(+ connection,+ scan,+ config,+ workflow_version,+ timestamp,+ pending_target_project_path=project_path,+ )return deep_scan_result(connection, scan_id, start_disposition="created")@@ -892,6 +940,24 @@ def get_deep_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dreturn deep_scan_result(connection, scan["id"])+def acknowledge_deep_scan_result(+ connection: sqlite3.Connection, args: argparse.Namespace+) -> dict[str, Any]:+ with connection:+ connection.execute(+ """+ UPDATE deep_scan_runs SET pending_target_project_path = NULL+ WHERE scan_id = ? AND pending_target_project_path IS NOT NULL+ AND status = 'succeeded'+ AND EXISTS (+ SELECT 1 FROM scans WHERE id = deep_scan_runs.scan_id AND status = 'complete'+ )+ """,+ (require_uuid(args.scan_id, "scan-id"),),+ )+ return {}++def coordinator_lease_is_live(connection: sqlite3.Connection,run: sqlite3.Row,diff --git a/plugins/codex-security/scripts/workbench_cli.py b/plugins/codex-security/scripts/workbench_cli.pyindex 34db03779..37df392c0 100644--- a/plugins/codex-security/scripts/workbench_cli.py+++ b/plugins/codex-security/scripts/workbench_cli.py@@ -59,9 +59,11 @@ def parse_args(description: str) -> argparse.Namespace:inspect_setup = add_command("inspect-setup", "--target-path", "--scope")inspect_setup.add_argument("--mode", choices=MODES, required=True)+ inspect_setup.add_argument("--deep-scan-project-json")save_workspace = add_command("save-workspace", "--workspace-id", "--target-path", "--scope")save_workspace.add_argument("--mode", choices=MODES, required=True)+ save_workspace.add_argument("--deep-scan-project-json")save_workspace.add_argument("--target-summary")add_user_context(save_workspace)diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.pyindex 32d10e5a2..71aaaa35b 100644--- a/plugins/codex-security/scripts/workbench_db.py+++ b/plugins/codex-security/scripts/workbench_db.py@@ -43,6 +43,7 @@ import workbench_remediation as remediation_stateimport workbench_saved_results as saved_resultsimport workbench_scan_history as scan_historyimport workbench_scan_usage as scan_usage+from deep_scan_config import resolve_deep_scan_setupfrom finalize_scan_contract import (PRODUCER_NAME,ContractError,@@ -741,10 +742,7 @@ def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -return workspace_state(connection, workspace_id)-def save_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:- workspace = require_workspace(connection, args.workspace_id)- if workspace["active_scan_id"]:- raise SystemExit("This workspace already has a scan. Open a new workspace to change setup.")+def inspect_selected_setup(args: argparse.Namespace) -> dict[str, Any]:inspected = inspect_setup_values(args.target_path,args.scope,@@ -754,6 +752,20 @@ def save_workspace(connection: sqlite3.Connection, args: argparse.Namespace) ->args.diff_head_revision,args.diff_content_digest,)+ if args.mode == "deep":+ inspected["deepScanConfig"] = resolve_deep_scan_setup(+ os.cpu_count() or 1, args.deep_scan_project_json+ )+ elif args.deep_scan_project_json is not None:+ raise SystemExit("Project Deep Scan settings require Deep Scan mode.")+ return inspected+++def save_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:+ workspace = require_workspace(connection, args.workspace_id)+ if workspace["active_scan_id"]:+ raise SystemExit("This workspace already has a scan. Open a new workspace to change setup.")+ inspected = inspect_selected_setup(args)target = Path(inspected["target"]["targetPath"])scope = inspected["scope"]target_path = str(target)@@ -778,7 +790,7 @@ def save_workspace(connection: sqlite3.Connection, args: argparse.Namespace) ->SET target_id = ?, target_path = ?, target_title = ?, target_summary = ?, default_scope = ?,default_mode = ?, user_context = ?, diff_target_kind = ?,diff_base_revision = ?, diff_head_revision = ?, diff_content_digest = ?,- submitted = 1, updated_at = ?+ deep_scan_config_json = ?, submitted = 1, updated_at = ?WHERE id = ? AND active_scan_id IS NULL""",(@@ -790,6 +802,7 @@ def save_workspace(connection: sqlite3.Connection, args: argparse.Namespace) ->args.mode,user_context_argument(args),*scan_diff_identity(diff_target or None),+ json.dumps(inspected["deepScanConfig"]) if "deepScanConfig" in inspected else None,timestamp,workspace["id"],),@@ -2676,6 +2689,11 @@ def workspace_state("mode": workspace["default_mode"],"scope": workspace["default_scope"],"setup": {"submitted": bool(workspace["submitted"])},+ **(+ {"deepScanConfig": json.loads(workspace["deep_scan_config_json"])}+ if workspace["deep_scan_config_json"] is not None+ else {}+ ),"setupValidation": {"error": None, "valid": bool(workspace["submitted"])},"targetPath": workspace["target_path"],"targetSummary": workspace["target_summary"],@@ -3438,16 +3456,7 @@ def main(*, before_archive: Callable[[], None] | None = None) -> None:print(json.dumps(result, allow_nan=False, sort_keys=True))returnif args.command == "inspect-setup":- result = inspect_setup_values(- args.target_path,- args.scope,- args.mode,- args.diff_target_kind,- args.diff_base_revision,- args.diff_head_revision,- args.diff_content_digest,- )- print(json.dumps(result, allow_nan=False, sort_keys=True))+ print(json.dumps(inspect_selected_setup(args), allow_nan=False, sort_keys=True))returnif args.command in {"save-artifact", "read-artifact"}:print(json.dumps(saved_results.read_or_save_artifact(args)))@@ -3465,6 +3474,7 @@ def main(*, before_archive: Callable[[], None] | None = None) -> None:"save-workspace": save_workspace,"start-scan": start_scan,"begin-deep-scan": deep_scan.begin_deep_scan,+ "acknowledge-deep-scan-result": deep_scan.acknowledge_deep_scan_result,"get-deep-scan": deep_scan.get_deep_scan,"claim-deep-scan-coordinator": deep_scan.claim_deep_scan_coordinator,"upsert-deep-scan-worker": deep_scan.upsert_deep_scan_worker,diff --git a/plugins/codex-security/scripts/workbench_schema.py b/plugins/codex-security/scripts/workbench_schema.pyindex d2c940079..4876e3106 100644--- a/plugins/codex-security/scripts/workbench_schema.py+++ b/plugins/codex-security/scripts/workbench_schema.py@@ -75,7 +75,7 @@ def apply_migrations(elif version == 16:should_backfill_targets = repair_stable_targets_migration(connection)elif version in applied:- if version in (2, 12, 13, 26, 28, 31, 32, 42, 47, 50):+ if version in (2, 12, 13, 26, 28, 31, 32, 42, 47, 50, 54, 55):repair_additive_migration(connection, version)elif version == 11:repair_deep_scan_migration(connection)diff --git a/plugins/codex-security/shared/workbench-migrations.json b/plugins/codex-security/shared/workbench-migrations.jsonindex 1fbcef4a9..ba1cc5d9e 100644--- a/plugins/codex-security/shared/workbench-migrations.json+++ b/plugins/codex-security/shared/workbench-migrations.json@@ -441,5 +441,26 @@"statements": ["CREATE TABLE external_source_reports (\n id TEXT PRIMARY KEY,\n repository TEXT NOT NULL,\n provider TEXT NOT NULL,\n source_key TEXT NOT NULL,\n source_finding_id TEXT NOT NULL,\n evidence_json TEXT NOT NULL,\n version INTEGER NOT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n UNIQUE (repository, provider, source_key, source_finding_id)\n);"]+ },+ {+ "version": 54,+ "name": "snapshot deep scan setup configuration",+ "statements": [+ "ALTER TABLE workspaces ADD COLUMN deep_scan_config_json TEXT;"+ ]+ },+ {+ "version": 55,+ "name": "retain undelivered headless deep scan results",+ "statements": [+ "ALTER TABLE deep_scan_runs ADD COLUMN pending_target_project_path TEXT;"+ ]+ },+ {+ "version": 56,+ "name": "recover unfinished legacy headless deep scans",+ "statements": [+ "UPDATE deep_scan_runs\nSET pending_target_project_path = ''\nWHERE pending_target_project_path IS NULL\n AND status IN ('running', 'succeeded') AND cancel_requested = 0\n AND discovery_user_context_json IS NOT NULL\n AND EXISTS (\n SELECT 1 FROM scans JOIN workspaces ON workspaces.id = scans.workspace_id\n WHERE scans.id = deep_scan_runs.scan_id AND scans.mode = 'deep'\n AND scans.status = 'running' AND scans.canceled_at IS NULL\n AND scans.recipe_json IS NULL AND scans.handoff_status = 'delivered'\n AND scans.handoff_claim_token IS NULL AND scans.continuation_thread_id IS NULL\n AND workspaces.active_scan_id = scans.id AND workspaces.deep_scan_config_json IS NULL\n AND workspaces.created_at = scans.created_at AND scans.created_at = deep_scan_runs.created_at\n );"+ ]}]diff --git a/plugins/codex-security/skills/deep-security-scan/SKILL.md b/plugins/codex-security/skills/deep-security-scan/SKILL.mdindex 3edb82d65..9239e925e 100644--- a/plugins/codex-security/skills/deep-security-scan/SKILL.md+++ b/plugins/codex-security/skills/deep-security-scan/SKILL.md@@ -5,7 +5,7 @@ description: Use when the user asks for a deep, exhaustive, multi-pass, or varia# Deep Security Scan-The coordinator runs independent Standard audits, aggregates their validated findings, and writes the parent scan's unsealed canonical artifacts. This thread owns setup, user context, and completion of that same scan. It does not repeat worker phases or aggregate results itself.+The coordinator runs independent Standard audits, aggregates their validated findings, and finalizes plugin-launched scans even if the calling thread detaches. This thread owns setup, user context, and reporting the completed result.## Resolve the Scan@@ -27,27 +27,30 @@ Immediately before the first coordinator call, follow `../../references/access-a```textExisting scan: start_codex_security_deep_scan({ scanId, handoffClaimToken? })-New scan: start_codex_security_deep_scan({ targetPath, scope: ".", userContext? })+New scan: start_codex_security_deep_scan({ targetPath, scope: ".", userContext?, projectConfigPath? })```+Before a new target-based scan, call `inspect_codex_security_setup({ targetPath, scope: ".", mode: "deep", projectConfigPath? })`. Show the worker count, subagents per worker, convergence threshold, review cap, discovery time limit, and their sources from `setup.deepScanConfig`. Supply a project YAML or JSON path only when the user selects it. Pass that same path at launch. Native continuations use the saved `workspace.deepScanConfig`.+Pass the existing handoff token when required, including after a waiter detaches or the server restarts. Preserve exact user context as untrusted analysis data; workers remain offline. They use the immutable context captured at independent-scan start. Persist later user changes through the context-update tool, without restarting completed phases or changing active workers' snapshots.Wait on the coordinator call or its running execution cell. It owns discovery progress, the configured time limit, worker cancellation at that limit, and aggregation. Leave the public phase at preflight before the call; do not publish competing progress while it runs.-An ended turn or host timeout detaches the caller, not the scan. A later continuation can rejoin with the same scan ID and token; a CLI/headless caller can repeat the identical target form to rejoin its owning thread's active scan. Server restart recovery retains completed worker results. A terminal failure is not a detached waiter and must not trigger a replacement scan.+After an ended turn or host timeout, rejoin with the same scan ID and token. If a CLI/headless call detached before returning its ID, repeat the identical target form. It can recover the completed report for the same checkout snapshot, context, and project-file selection after a server restart. Once the report is returned, a later target-based call can start a fresh scan. A terminal failure must not trigger a replacement scan.## Handle the Result-- **Canonical result:** `structuredContent` contains `scanId`, `scanDir`, `manifestPath`, and `instructions`. Confirm that the manifest, `findings.json`, and `coverage.json` exist in the authoritative directory. For the first target-based call, retain the returned scan ID; for a continuation, retain the existing authoritative ID. The unsealed manifest may lack an ID, so do not infer one from it.+- **SDK-registered scan.** The coordinator returns the aggregate's `scanId`, `scanDir`, `manifestPath`, and `instructions`. End the turn with the returned identity and manifest path. The SDK owns finalization and report generation after the turn ends.+- **Plugin-launched scan.** The coordinator also returns `completion`. Use the returned scan ID, sealed artifacts, and generated `report.md` in the authoritative directory.- **Cancelled:** stop without completion. Report retained findings and pending work without claiming a successful scan or generating a replacement report.- **Terminal failure:** surface the exact stable MCP error and read the existing scan context to report preserved results and remaining work. Do not continue analysis, complete or cancel an already terminal scan, or claim a no-findings result.- **Missing or malformed canonical artifacts:** surface the blocker and preserve the existing scan. Do not fabricate a report.-## Complete the Parent Scan+## Report the Completed Parent Scan-After the canonical result is available, call `complete_codex_security_scan({ scanId, handoffClaimToken? })` exactly once. The host seals the existing artifacts and generates `report.md`. Do not submit another semantic draft, rerun validation or attack-path analysis, or write the report yourself.+When the coordinator returns `completion`, the host has sealed the artifacts and generated `report.md`. Read measured usage from `completion.scan.usage`. Do not call completion again, submit another semantic draft, rerun worker phases, or write the report yourself.-If completion fails, surface its exact error without retrying in the same response or changing the durable scan's status. Preserve resumable work and its handoff claim. On explicit cancellation, call `cancel_codex_security_scan` and do not accept subsequent scan progress as success.+If completion fails, surface its exact error. Preserve the accepted aggregate and handoff claim. A later continuation can rejoin the same scan to retry finalization. On explicit cancellation, call `cancel_codex_security_scan` and do not accept subsequent scan progress as success.Return the report and canonical artifact links after completion succeeds and `report.md` exists. Report usage according to `../../references/final-report.md`. Distinguish an empty finding set after completed review from a time limit reached before any source review finished.diff --git a/plugins/codex-security/tests/test_deep_scan_project_config.py b/plugins/codex-security/tests/test_deep_scan_project_config.pynew file mode 100644index 000000000..74e610cb5--- /dev/null+++ b/plugins/codex-security/tests/test_deep_scan_project_config.py@@ -0,0 +1,104 @@+from __future__ import annotations++import json+import uuid++from workbench_test_support import (+ begin_deep_scan,+ create_workspace,+ get_scan,+ resume_deep_scan,+ run_workbench,+ save_workspace,+ start_workspace_scan,+)+++def test_native_setup_snapshots_limits_before_first_coordinator(tmp_path, monkeypatch):+ state = tmp_path / "state"+ target = tmp_path / "repository"+ target.mkdir()+ (target / "fixture.py").write_text("print('fixture')\n")+ legacy = tmp_path / "defaults.toml"+ legacy.write_text("[deep_scan]\nworkers=7\nsubagents=2\nmax_time_hours=4\n")+ monkeypatch.setenv("CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH", str(legacy))+ project = {+ "path": str(target / "security.yaml"),+ "settings": {+ "workers": 2,+ "subagents": 1,+ "stopAfterNoNew": 2,+ "maxDiscoveryRuns": 4,+ "maxTimeHours": 0.5,+ },+ }+ selection = ("--deep-scan-project-json", json.dumps(project))+ preview = run_workbench(+ state,+ "inspect-setup",+ "--target-path",+ str(target),+ "--scope",+ ".",+ "--mode",+ "deep",+ *selection,+ )["deepScanConfig"]+ assert preview["settings"] == project["settings"] | {"stopAfterConsecutiveErrors": 3}+ assert preview["projectConfigPath"] == project["path"]+ assert preview["sources"]["workers"] == "project"+ assert preview["sources"]["stopAfterConsecutiveErrors"] == "default"+ workspace_id = str(uuid.uuid4())+ create_workspace(state, workspace_id, "--thread-id", "project-owner")+ saved = save_workspace(state, workspace_id, str(target), ".", "deep", *selection)+ assert saved["deepScanConfig"] == preview+ # The original settings survive changes even before the coordinator starts.+ legacy.write_text("invalid TOML")+ scan_id, _ = start_workspace_scan(state, workspace_id, tmp_path / "scans")+ initial = resume_deep_scan(state, scan_id, "project-owner")["deepScan"]+ assert initial["config"] == preview["settings"]+ assert (+ resume_deep_scan(state, scan_id, "project-owner")["deepScan"]["config"] == initial["config"]+ )+ assert get_scan(state, scan_id)["workspace"]["deepScanConfig"] == preview+++def test_headless_project_limits_are_isolated_from_unrelated_scans(tmp_path, monkeypatch):+ state = tmp_path / "state"+ target = tmp_path / "repository"+ target.mkdir()+ (target / "fixture.py").write_text("print('fixture')\n")+ legacy = tmp_path / "defaults.toml"+ legacy.write_text("[deep_scan]\nworkers=7\nmax_time_hours=4\n")+ monkeypatch.setenv("CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH", str(legacy))+ first = begin_deep_scan(+ state,+ "project-owner",+ "--target-path",+ str(target),+ "--scan-root",+ str(tmp_path / "scans"),+ "--deep-scan-project-json",+ json.dumps(+ {"path": str(target / "security.json"), "settings": {"workers": 2, "maxTimeHours": 0.5}}+ ),+ )["deepScan"]+ assert begin_deep_scan(state, "other-owner", "--target-path", str(target), "--join-only") == {+ "newScanTarget": str(target.resolve())+ }+ second = begin_deep_scan(+ state, "other-owner", "--target-path", str(target), "--scan-root", str(tmp_path / "scans")+ )["deepScan"]+ assert first["config"]["workers"] == 2+ assert first["config"]["maxTimeHours"] == 0.5+ assert second["config"]["workers"] == 7+ assert second["config"]["maxTimeHours"] == 4+ repeated = begin_deep_scan(state, "project-owner", "--target-path", str(target), "--join-only")[+ "deepScan"+ ]+ assert repeated["scanId"] == first["scanId"]+ assert repeated["config"] == first["config"]+ assert (+ get_scan(state, second["scanId"])["workspace"]["deepScanConfig"]["sources"]["workers"]+ == "legacy"+ )diff --git a/plugins/codex-security/tests/test_workbench_deep_scan.py b/plugins/codex-security/tests/test_workbench_deep_scan.pyindex d974a0468..7f9a4d31d 100644--- a/plugins/codex-security/tests/test_workbench_deep_scan.py+++ b/plugins/codex-security/tests/test_workbench_deep_scan.py@@ -79,6 +79,13 @@ def begin_target_scan()+def restore_v53_schema(state_dir: Path) -> None:+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:+ connection.execute("ALTER TABLE workspaces DROP COLUMN deep_scan_config_json")+ connection.execute("ALTER TABLE deep_scan_runs DROP COLUMN pending_target_project_path")+ connection.execute("DELETE FROM schema_migrations WHERE version > 53")++def claim_deep_scan_coordinator(state_dir: Path,codex_home: Path,@@ -366,8 +373,10 @@ def test_expired_coordinator_preserves_incomplete_setup(tmp_path: Path) -> None:def test_paused_discovery_resumes_after_restart_with_original_handoff_claim(tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,) -> None:state_dir, codex_home, target = tmp_path / "state", tmp_path / "codex-home", tmp_path / "target"+ monkeypatch.setenv("CODEX_HOME", str(codex_home))target.mkdir()write_deep_config(codex_home,@@ -1376,9 +1385,14 @@ def test_sdk_scan_begin_claims_its_existing_scan(tmp_path: Path) -> None:assert begun["deepScan"]["scanId"] == scan_idassert begun["deepScan"]["scanDir"] == str(scan_dir)assert begun["deepScan"]["userContext"] == user_context+ restore_v53_schema(state_dir)+ get_deep_scan(state_dir, scan_id, "sdk-thread", environment=deep_environment(codex_home))with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:assert connection.execute("SELECT COUNT(*) FROM scans").fetchone() == (1,)assert connection.execute("SELECT thread_id FROM workspaces").fetchone() == ("sdk-thread",)+ assert connection.execute(+ "SELECT pending_target_project_path FROM deep_scan_runs"+ ).fetchone() == (None,)assert connection.execute("SELECT deep_scan_owner_thread_id FROM scans").fetchone() == ("sdk-thread",)@@ -1988,8 +2002,141 @@ def test_target_continuation_does_not_reuse_a_different_snapshot(assert changed["deepScan"]["scanId"] != first_scan_id+def test_sealed_target_result_replays_only_the_pending_request(tmp_path: Path) -> None:+ state_dir, target = tmp_path / "state", tmp_path / "target"+ target.mkdir()+ source = target / "source.py"+ source.write_text("print('source')\n")+ project = tmp_path / "selected.yaml"+ project.write_text("scan: {max_time_minutes: 30}\n")+ selected = "../selected.yaml"+ owner, context = "owner-thread", "Review authentication."++ def begin(thread: str, focus: str = context, selection: str = selected, *extra: str):+ return begin_deep_scan(+ state_dir,+ thread,+ "--target-path",+ str(target),+ "--scan-root",+ str(tmp_path / "scans"),+ "--user-context",+ focus,+ "--project-config-path",+ selection,+ *extra,+ environment=deep_environment(tmp_path / "home"),+ )++ launched = begin(+ owner,+ context,+ selected,+ "--deep-scan-project-json",+ json.dumps(+ {+ "path": str(project),+ "settings": {"maxTimeHours": 0.5},+ }+ ),+ )["deepScan"]+ scan_id, scan_dir = launched["scanId"], Path(launched["scanDir"])+ mark_deep_coordinator_succeeded(state_dir, scan_id, scan_dir)+ write_completed_contract(+ scan_dir, scan_id, target, relative_path="source.py", coverage_mode="deep_repository"+ )+ assert scan_command(state_dir, "complete-scan", scan_id)["scan"]["reportAvailable"]+ project.unlink()++ # A probe neither reopens the selected file nor consumes the result.+ for thread in [owner, "continuation-thread"]:+ replay = begin(thread, context, selected, "--join-only")+ assert replay["startDisposition"] == "joined"+ assert replay["deepScan"]["scanId"] == scan_id+ assert replay["deepScan"]["config"]["maxTimeHours"] == 0.5+ new_target = {"newScanTarget": str(target)}+ assert begin(owner, "Other context", selected, "--join-only") == new_target+ assert begin(owner, context, "../other.yaml", "--join-only") == new_target+ source.write_text("print('changed')\n")+ assert begin(owner, context, selected, "--join-only") == new_target+ source.write_text("print('source')\n")+ assert begin(owner, context, selected, "--join-only")["deepScan"]["scanId"] == scan_id+ scan_command(state_dir, "acknowledge-deep-scan-result", scan_id)+ assert begin(owner, context, selected, "--join-only") == new_target++[email protected]("already_complete", (False, True))+def test_v53_headless_target_recovers_its_unfinished_result_after_upgrade(+ tmp_path: Path, already_complete: bool+) -> None:+ state_dir, target = tmp_path / "state", tmp_path / "target"+ target.mkdir()+ (target / "source.py").write_text("print('source')\n")+ home, scan_root = tmp_path / "home", tmp_path / "scans"+ run = begin_target_scan(state_dir, home, target, scan_root)["deepScan"]+ scan_id, scan_dir = run["scanId"], Path(run["scanDir"])++ def finish() -> None:+ mark_deep_coordinator_succeeded(state_dir, scan_id, scan_dir)+ write_completed_contract(+ scan_dir, scan_id, target, relative_path="source.py", coverage_mode="deep_repository"+ )+ assert scan_command(state_dir, "complete-scan", scan_id)["scan"]["reportAvailable"]++ if already_complete:+ finish()+ restore_v53_schema(state_dir)+ if already_complete:+ assert (+ begin_target_scan(state_dir, home, target, scan_root)["startDisposition"] == "created"+ )+ return++ assert begin_target_scan(state_dir, home, target, scan_root)["deepScan"]["scanId"] == scan_id+ finish()+ different = begin_deep_scan(+ state_dir,+ "replacement-thread",+ "--target-path",+ str(target),+ "--project-config-path",+ "another.yaml",+ "--join-only",+ )+ assert different == {"newScanTarget": str(target)}+ replay = begin_target_scan(state_dir, home, target, scan_root, thread_id="replacement-thread")+ assert replay["startDisposition"] == "joined"+ assert replay["deepScan"]["scanId"] == scan_id+ scan_command(state_dir, "acknowledge-deep-scan-result", scan_id)+ assert begin_target_scan(state_dir, home, target, scan_root)["startDisposition"] == "created"+++def test_sealed_target_prefers_its_own_pending_scan(tmp_path: Path) -> None:+ target, state_dir, home = tmp_path / "target", tmp_path / "state", tmp_path / "home"+ target.mkdir()+ (target / "source.py").write_text("print('source')\n")+ scan_root = tmp_path / "scans"+ owners = ("first-thread", "second-thread")+ runs = [+ begin_target_scan(state_dir, home, target, scan_root, thread_id=thread)["deepScan"]+ for thread in owners+ ]+ for run in runs:+ scan_id, scan_dir = run["scanId"], Path(run["scanDir"])+ mark_deep_coordinator_succeeded(state_dir, scan_id, scan_dir)+ write_completed_contract(+ scan_dir, scan_id, target, relative_path="source.py", coverage_mode="deep_repository"+ )+ scan_command(state_dir, "complete-scan", scan_id)+ for thread, run in zip(owners, runs, strict=True):+ replay = begin_target_scan(state_dir, home, target, scan_root, thread_id=thread)+ assert replay["deepScan"]["scanId"] == run["scanId"]++[email protected]("sealed", (False, True))def test_target_continuation_does_not_reuse_another_threads_app_scan(tmp_path: Path,+ sealed: bool,) -> None:state_dir = tmp_path / "state"codex_home = tmp_path / "codex-home"@@ -2026,15 +2173,27 @@ def test_target_continuation_does_not_reuse_another_threads_app_scan()scan_dir = Path(str(begun["deepScan"]["scanDir"]))mark_deep_coordinator_succeeded(state_dir, app_scan_id, scan_dir)- with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:- connection.execute(- """- UPDATE scans- SET handoff_status = 'delivered', handoff_claim_token = ?- WHERE id = ?- """,- (str(uuid.uuid4()), app_scan_id),+ if sealed:+ # A tokenless desktop run remains ineligible through the upgrade and automatic sealing.+ restore_v53_schema(state_dir)+ write_completed_contract(+ scan_dir,+ app_scan_id,+ target,+ relative_path="fixture.py",+ coverage_mode="deep_repository",)+ scan_command(state_dir, "complete-scan", app_scan_id)+ else:+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:+ connection.execute(+ """+ UPDATE scans+ SET handoff_status = 'delivered', handoff_claim_token = ?+ WHERE id = ?+ """,+ (str(uuid.uuid4()), app_scan_id),+ )headless = begin_target_scan(state_dir,diff --git a/plugins/codex-security/tests/test_workbench_setup_and_migrations.py b/plugins/codex-security/tests/test_workbench_setup_and_migrations.pyindex b4975606c..6bb09bd95 100644--- a/plugins/codex-security/tests/test_workbench_setup_and_migrations.py+++ b/plugins/codex-security/tests/test_workbench_setup_and_migrations.py@@ -95,6 +95,9 @@ EXPECTED_MIGRATIONS = [(51, "preserve deep scan worker thread history"),(52, "record severity classification review counts"),(53, "store external source findings without assessments"),+ (54, "snapshot deep scan setup configuration"),+ (55, "retain undelivered headless deep scan results"),+ (56, "recover unfinished legacy headless deep scans"),]diff --git a/sdk/typescript/scripts/generate-project-config-schema.mjs b/sdk/typescript/scripts/generate-project-config-schema.mjsindex 7a0e1a789..c01a3b104 100644--- a/sdk/typescript/scripts/generate-project-config-schema.mjs+++ b/sdk/typescript/scripts/generate-project-config-schema.mjs@@ -17,18 +17,27 @@ const { projectConfigJsonSchema } = await import(`data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].contents).toString("base64")}`);-const directory = new URL("../schemas/", import.meta.url);-const output = new URL("project-config.schema.json", directory);+const outputs = [+ new URL("../schemas/project-config.schema.json", import.meta.url),+ new URL(+ "../../../plugins/codex-security/mcp-app/src/deep-scan/project-config.schema.json",+ import.meta.url,+ ),+];const contents = await format(JSON.stringify(projectConfigJsonSchema()), {parser: "json",});-if (process.argv.includes("--check")) {- if ((await readFile(output, "utf8")).replaceAll("\r\n", "\n") !== contents) {- throw new Error(- "Project configuration schema is out of date. Run pnpm build.",- );+for (const output of outputs) {+ if (process.argv.includes("--check")) {+ if (+ (await readFile(output, "utf8")).replaceAll("\r\n", "\n") !== contents+ ) {+ throw new Error(+ "Project configuration schema is out of date. Run pnpm build.",+ );+ }+ } else {+ await mkdir(new URL(".", output), { recursive: true });+ await writeFile(output, contents);}-} else {- await mkdir(directory, { recursive: true });- await writeFile(output, contents);}diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex c50b7a8cf..13488260e 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -5278,13 +5278,13 @@ function scanPrompt(: []),"Runtime paths are environment-backed; keep them quoted in POSIX shells and use the corresponding $env: names in PowerShell. Do not copy or reparse their values.",targetInstruction(target, python),- ...(skillName === "security-scan" || enforceCostLimit || customValidation+ ...(mode === "deep"? [- "Write the complete canonical scan-manifest.json, findings.json, and coverage.json, but do not finalize or seal them; the SDK workbench owns authoritative metadata, finalization, report generation, and sealing.",+ "Once the Deep Scan coordinator returns its aggregate, end this turn with the returned scanId and manifestPath. The SDK owns finalization and report generation after the turn ends.",]- : skillName === "deep-security-scan"+ : skillName === "security-scan" || enforceCostLimit || customValidation? [- "The Deep Scan coordinator already wrote the canonical scan artifacts. Call complete_codex_security_scan exactly once without submitting another semantic draft; the workbench owns authoritative metadata, finalization, report generation, and sealing.",+ "Write the complete canonical scan-manifest.json, findings.json, and coverage.json, but do not finalize or seal them; the SDK workbench owns authoritative metadata, finalization, report generation, and sealing.",]: ["Use record_codex_security_scan_draft and complete_codex_security_scan as directed by the selected skill; the workbench owns authoritative metadata, finalization, report generation, and sealing.",diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 841720d46..c1b77c0c3 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -7218,8 +7218,8 @@ describe("CodexSecurity orchestration", () => {);expect(prompt()).not.toContain("$codex-security:");expect(prompt()).not.toContain("record_codex_security_scan_draft");- expect(prompt()).toContain("complete_codex_security_scan");- expect(prompt()).not.toContain("do not finalize or seal them");+ expect(prompt()).not.toContain("complete_codex_security_scan");+ expect(prompt()).toContain("The SDK owns finalization");expect(prompt()).toContain('start_codex_security_deep_scan with {"scanId":"scan_example_001"}',);@@ -7230,7 +7230,7 @@ describe("CodexSecurity orchestration", () => {await expect(client.run(repository, { mode: "deep", maxCostUsd: 1 }),).rejects.toThrow("prompt captured");- expect(prompt()).toContain("do not finalize or seal them");+ expect(prompt()).toContain("The SDK owns finalization");expect(prompt()).not.toContain("complete_codex_security_scan");await expect(diff --git a/sdk/typescript/tests-ts/deep-scan-workbench.test.ts b/sdk/typescript/tests-ts/deep-scan-workbench.test.tsindex e392d8064..d38ac725f 100644--- a/sdk/typescript/tests-ts/deep-scan-workbench.test.ts+++ b/sdk/typescript/tests-ts/deep-scan-workbench.test.ts@@ -40,7 +40,7 @@ const deepScanOwnershipProbe = ["deep_scan.configure(deep_scan)","deep_scan.deep_scan_result = lambda database, value, *, start_disposition=None: {'startDisposition': start_disposition}","try:",- " result = deep_scan.begin_deep_scan_for_scan(connection, scan_id, 'requesting-thread', argparse.Namespace(claim_token=case['suppliedToken'], model=None, reasoning_effort=None))",+ " result = deep_scan.begin_deep_scan_for_scan(connection, scan_id, 'requesting-thread', argparse.Namespace(claim_token=case['suppliedToken'], model=None, reasoning_effort=None, join_only=False))","except SystemExit as error:"," accepted, message, result = False, str(error), None","else:",