Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

refactor(plugin): simplify Deep Scan worker launch (#1212)

mldangelo-oai634532d7f7fb
diff --git a/plugins/codex-security/mcp-app/artifact-writer-main.ts b/plugins/codex-security/mcp-app/artifact-writer-main.ts
index be11c3df2..233eb6882 100644
--- a/plugins/codex-security/mcp-app/artifact-writer-main.ts
+++ b/plugins/codex-security/mcp-app/artifact-writer-main.ts
@@ -7,7 +7,7 @@ import {
} from "./src/artifact-context.js";
import { CODEX_SANDBOX_STATE_META_CAPABILITY } from "./src/deep-scan/parent-sandbox.js";
import { registerCompactWorkerArtifactTools } from "./src/server/compact-artifact-tools.js";
-import { MCP_APP_VERSION } from "./src/version.js";
+import { version as MCP_APP_VERSION } from "./package.json";
import { isRecord } from "./src/record.js";
/** Build the narrow worker-only MCP from coordinator-inherited state. */
diff --git a/plugins/codex-security/mcp-app/server.ts b/plugins/codex-security/mcp-app/server.ts
index 01a4124b3..1eeea354a 100644
--- a/plugins/codex-security/mcp-app/server.ts
+++ b/plugins/codex-security/mcp-app/server.ts
@@ -12,7 +12,7 @@ import {
missingPythonHelperMessage,
resolvePythonCommand,
} from "./src/python_command.js";
-import { MCP_APP_VERSION } from "./src/version.js";
+import { version as MCP_APP_VERSION } from "./package.json";
import {
handoffClaimTokenSchema,
recoveryHandoffClaimTokenSchema,
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
index b1b6b7d3d..82cc562ad 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
@@ -162,27 +162,27 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
try {
const { events } = await thread.runStreamed(input, {
signal: controller.signal,
- ...(runtimeSettings.cyberAccessProgram === undefined
- ? {}
- : { cyberAccessProgram: runtimeSettings.cyberAccessProgram }),
+ cyberAccessProgram: runtimeSettings.cyberAccessProgram,
});
let threadId: string | undefined;
let turnCompleted = false;
let lastStreamError: string | undefined;
const diagnostics: CodexWorkerDiagnostic[] = [];
for await (const event of events) {
- if (event.type === "thread.started") {
- threadId = event.thread_id;
- await request.onThreadStarted?.(threadId);
- } else if (event.type === "item.completed") {
- const fallbackError =
- event.item.type === "error"
- ? deepScanPermissionProfileFallbackError(event.item.message)
- : undefined;
+ const item = event.type === "item.completed" ? event.item : event;
+ if (item.type === "error") {
+ const fallbackError = deepScanPermissionProfileFallbackError(
+ item.message,
+ );
if (fallbackError) {
controller.abort(fallbackError);
throw fallbackError;
}
+ }
+ if (event.type === "thread.started") {
+ threadId = event.thread_id;
+ await request.onThreadStarted?.(threadId);
+ } else if (event.type === "item.completed") {
appendSafeItemDiagnostic(diagnostics, event.item);
} else if (event.type === "turn.completed") {
turnCompleted = true;
@@ -191,13 +191,6 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
} else if (event.type === "turn.failed") {
throw new Error(event.error.message);
} else if (event.type === "error") {
- const fallbackError = deepScanPermissionProfileFallbackError(
- event.message,
- );
- if (fallbackError) {
- controller.abort(fallbackError);
- throw fallbackError;
- }
// Codex exec currently emits retry-in-progress notifications as error events.
lastStreamError = event.message;
appendCodeModeFrameDiagnostic(diagnostics, event.message);
@@ -323,24 +316,17 @@ type TomlValue = string | number | boolean | TomlObject;
type TomlObject = { [key: string]: TomlValue };
function workerPermissionProfile(sandbox: DeepWorkerParentSandbox): TomlObject {
- const filesystemEntries: Array<[string, TomlValue]> = [[":root", "read"]];
- const seenFilesystemKeys = new Set<string>();
-
- for (const key of sandbox.filesystemDenies) {
- if (seenFilesystemKeys.has(key)) continue;
- seenFilesystemKeys.add(key);
- filesystemEntries.push([key, "deny"]);
- }
-
- if (sandbox.globScanMaxDepth !== undefined) {
- filesystemEntries.push(["glob_scan_max_depth", sandbox.globScanMaxDepth]);
- }
-
return {
extends: ":read-only",
// Object.fromEntries preserves literal keys such as "__proto__" without
// letting a denied path mutate the serializer object prototype.
- filesystem: Object.fromEntries(filesystemEntries) as TomlObject,
+ filesystem: Object.fromEntries([
+ [":root", "read"],
+ ...Array.from(sandbox.filesystemDenies, (key) => [key, "deny"]),
+ ...(sandbox.globScanMaxDepth === undefined
+ ? []
+ : [["glob_scan_max_depth", sandbox.globScanMaxDepth]]),
+ ]),
network: { enabled: false },
};
}
@@ -672,10 +658,7 @@ function resolveFromSearchPath(
originalCwd: string,
): string | undefined {
for (const directory of searchPath?.split(delimiter) ?? []) {
- const candidate = join(
- absoluteSearchDirectory(directory, originalCwd),
- executableName,
- );
+ const candidate = join(resolve(originalCwd, directory), executableName);
if (isExecutableFile(candidate)) return candidate;
}
return undefined;
@@ -687,10 +670,7 @@ function resolveWindowsDirectFromSearchPath(
originalCwd: string,
): string | undefined {
for (const directory of searchPath?.split(delimiter) ?? []) {
- const candidate = join(
- absoluteSearchDirectory(directory, originalCwd),
- executableName,
- );
+ const candidate = join(resolve(originalCwd, directory), executableName);
if (!isWindowsAppsPath(candidate) && existsSync(candidate))
return candidate;
}
@@ -703,7 +683,7 @@ function resolveWindowsCodexFromSearchPath(
originalCwd: string,
): string | undefined {
for (const directory of searchPath?.split(delimiter) ?? []) {
- const absoluteDirectory = absoluteSearchDirectory(directory, originalCwd);
+ const absoluteDirectory = resolve(originalCwd, directory);
const directBinary = join(absoluteDirectory, "codex.exe");
if (!isWindowsAppsPath(directBinary) && existsSync(directBinary))
return directBinary;
@@ -773,13 +753,6 @@ function isExecutableFile(value: string): boolean {
}
}
-function absoluteSearchDirectory(
- directory: string,
- originalCwd: string,
-): string {
- return resolve(originalCwd, directory || ".");
-}
-
function absoluteCodexPath(
value: string,
platform: NodeJS.Platform,
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts b/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts
index 7365adf0f..9d1e9b6ec 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts
@@ -1,4 +1,4 @@
-import { asRecord as record } from "../record.js";
+import { asRecord as record, isNonEmptyString } from "../record.js";
import { isAbsolute } from "node:path";
import { fileURLToPath } from "node:url";
import { isDeepStrictEqual } from "node:util";
@@ -274,10 +274,6 @@ function isValidSpecialPath(value: Record<string, unknown>): boolean {
return false;
}
-function isNonEmptyString(value: unknown): value is string {
- return typeof value === "string" && value.trim().length > 0;
-}
-
function hasGlobMetacharacters(value: string): boolean {
return value.includes("*") || value.includes("?") || value.includes("[");
}
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
index 2b8bc312b..64babd9cf 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
@@ -1,8 +1,9 @@
-import { asRecord as record } from "../record.js";
+import type { JsonObject as JsonRecord } from "../types.js";
+import { asRecord as record, isNonEmptyString } from "../record.js";
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { createInterface, type Interface } from "node:readline";
import { isDeepStrictEqual } from "node:util";
-import { MCP_APP_VERSION } from "../version.js";
+import { version as MCP_APP_VERSION } from "../../package.json";
import { DeepScanNonRetryableError } from "./errors.js";
import { executablePathForSpawn } from "./executable-path.js";
@@ -30,8 +31,6 @@ export interface DeepScanPermissionProfilePreflightOptions {
readonly signal: AbortSignal;
}
-type JsonRecord = Record<string, unknown>;
-
type PendingRequest = {
readonly id: number;
readonly method: string;
@@ -140,12 +139,11 @@ class AppServerPreflightClient {
crlfDelay: Infinity,
});
this.stdoutLines.on("line", (line) => this.consumeStdoutLine(line));
- this.stdoutLines.on("error", () => {
- this.fail(codexExecutableStdioError(options.codexPath));
- });
- this.child.stdin.on("error", () => {
+ const onStdioError = () => {
this.fail(codexExecutableStdioError(options.codexPath));
- });
+ };
+ this.stdoutLines.on("error", onStdioError);
+ this.child.stdin.on("error", onStdioError);
this.child.on("error", (error) => {
this.fail(codexExecutableStartError(options.codexPath, error));
});
@@ -427,10 +425,10 @@ function validateOptions(
options: DeepScanPermissionProfilePreflightOptions,
): void {
if (
- !nonEmptyString(options.codexPath) ||
- !nonEmptyString(options.cwd) ||
+ !isNonEmptyString(options.codexPath) ||
+ !isNonEmptyString(options.cwd) ||
!Array.isArray(options.configOverrides) ||
- options.configOverrides.some((value) => !nonEmptyString(value)) ||
+ options.configOverrides.some((value) => !isNonEmptyString(value)) ||
!record(options.expectedProfile) ||
!options.signal ||
typeof options.signal.addEventListener !== "function"
@@ -440,10 +438,6 @@ function validateOptions(
comparableProfile(options.expectedProfile);
}
-function nonEmptyString(value: unknown): value is string {
- return typeof value === "string" && value.trim().length > 0;
-}
-
// Verified permission incompatibilities explicitly stop the scan. A failed
// transport attempt alone does not establish that the scan cannot proceed.
function disallowedProfileAllowlistError(): DeepScanNonRetryableError {
@@ -504,14 +498,13 @@ function jsonRpcPreflightError(
? error.code
: undefined;
if (code === -32601) return unsupportedCodexApiError(codexPath, method);
- const codeDetail = code === undefined ? "" : " (JSON-RPC code " + code + ")";
return new Error(
"Deep Scan cannot safely verify its read-only worker permission profile because " +
"the selected Codex executable " +
JSON.stringify(codexPath) +
" returned an error for " +
JSON.stringify(method) +
- codeDetail +
+ (code === undefined ? "" : " (JSON-RPC code " + code + ")") +
". Check the Codex configuration and retry. Deep Scan did not run.",
);
}
@@ -523,11 +516,10 @@ function codexExecutableStartError(codexPath: string, error: Error): Error {
? value
: undefined;
const codeDetail = code === undefined ? "" : " (" + code + ")";
- const message = codexExecutableFailureMessage(
- codexPath,
- "could not start" + codeDetail,
+ return new Error(
+ codexExecutableFailureMessage(codexPath, "could not start" + codeDetail),
+ { cause: error },
);
- return new Error(message, { cause: error });
}
function codexExecutableExitError(
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/templates.ts b/plugins/codex-security/mcp-app/src/deep-scan/templates.ts
index ad0ed287e..78beff015 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/templates.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/templates.ts
@@ -11,11 +11,6 @@ export interface DiscoveryPromptInput {
subagents: number;
}
-export interface DedupPromptInput {
- reducerLabel: string;
- claimedWorkerIds: string[];
-}
-
// Every worker starts in a fresh Codex thread. A single typed JSON object
// makes its complete input explicit without duplicating raw and escaped values.
@@ -23,17 +18,19 @@ export function renderDiscoveryPrompt(
input: DiscoveryPromptInput,
falsePositiveFeedbackPath?: string,
): string {
- const prompt = renderDeepScanTemplate(discoveryTemplate, {
- DISCOVERY_CONTEXT_JSON: formattedJson({
- scanId: input.scanId,
- pluginRoot: input.pluginRoot,
- targetPath: input.targetPath,
- scope: input.scope,
- userContext: input.userContext ?? null,
- workerLabel: input.workerLabel,
- subagents: input.subagents,
- }),
+ const context = formattedJson({
+ scanId: input.scanId,
+ pluginRoot: input.pluginRoot,
+ targetPath: input.targetPath,
+ scope: input.scope,
+ userContext: input.userContext ?? null,
+ workerLabel: input.workerLabel,
+ subagents: input.subagents,
});
+ const prompt = discoveryTemplate.replaceAll(
+ "{{DISCOVERY_CONTEXT_JSON}}",
+ () => context,
+ );
if (!falsePositiveFeedbackPath) return prompt;
return (
`${prompt.trimEnd()}\n\nDuring validation, read existing reviewer false-positive feedback at ` +
@@ -42,34 +39,15 @@ export function renderDiscoveryPrompt(
);
}
-export function renderDedupPrompt(input: DedupPromptInput): string {
- return renderDeepScanTemplate(dedupTemplate, {
- DEDUP_CONTEXT_JSON: formattedJson({
- reducerLabel: input.reducerLabel,
- claimedWorkerIds: input.claimedWorkerIds,
- }),
- });
-}
-
-function renderDeepScanTemplate(
- template: string,
- values: Record<string, string>,
+export function renderDedupPrompt(
+ reducerLabel: string,
+ claimedWorkerIds: string[],
): string {
- const placeholders = [...template.matchAll(/\{\{([A-Z0-9_]+)\}\}/g)];
- const missing = placeholders
- .map((match) => match[1])
- .filter(
- (key): key is string => key !== undefined && !Object.hasOwn(values, key),
- );
- if (missing.length > 0) {
- throw new Error(
- `Missing Deep Scan template values: ${[...new Set(missing)].join(", ")}`,
- );
- }
- return template.replace(
- /\{\{([A-Z0-9_]+)\}\}/g,
- (_placeholder, key: string) => String(values[key]),
- );
+ const context = formattedJson({
+ reducerLabel,
+ claimedWorkerIds,
+ });
+ return dedupTemplate.replaceAll("{{DEDUP_CONTEXT_JSON}}", () => context);
}
function formattedJson(value: unknown): string {
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.ts
index 5a3f46935..b8822f166 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
@@ -263,15 +263,13 @@ export class DeepScanWorkerRunner {
const promptRoot = join(reducerRoot, "prompts");
const resultPath = join(artifactDir, "result.json");
await fs.mkdir(artifactDir, { recursive: true });
- const basePrompt = renderDedupPrompt({
- reducerLabel,
- claimedWorkerIds: consumed.map((worker) => worker.id),
- });
+ const workerIds = consumed.map((worker) => worker.id);
+ const basePrompt = renderDedupPrompt(reducerLabel, workerIds);
await writePrivateFile(promptPath, basePrompt);
await this.options.store.claimDedup({
id: reducerId,
scanId: run.scanId,
- workerIds: consumed.map((worker) => worker.id),
+ workerIds,
promptPath,
artifactDir,
});
diff --git a/plugins/codex-security/mcp-app/src/record.ts b/plugins/codex-security/mcp-app/src/record.ts
index 74d5b9775..57deeeb70 100644
--- a/plugins/codex-security/mcp-app/src/record.ts
+++ b/plugins/codex-security/mcp-app/src/record.ts
@@ -5,3 +5,7 @@ export function isRecord(value: unknown): value is Record<string, unknown> {
export function asRecord(value: unknown): Record<string, unknown> | undefined {
return isRecord(value) ? value : undefined;
}
+
+export function isNonEmptyString(value: unknown): value is string {
+ return typeof value === "string" && value.trim().length > 0;
+}
diff --git a/plugins/codex-security/mcp-app/src/version.ts b/plugins/codex-security/mcp-app/src/version.ts
deleted file mode 100644
index 37bd91abc..000000000
--- a/plugins/codex-security/mcp-app/src/version.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { version } from "../package.json";
-
-export const MCP_APP_VERSION = version;
diff --git a/plugins/codex-security/mcp-app/tests/support/reducer-paging/deep-reducer-paging.mjs b/plugins/codex-security/mcp-app/tests/support/reducer-paging/deep-reducer-paging.mjs
index ad9a501f9..06ee9aaba 100644
--- a/plugins/codex-security/mcp-app/tests/support/reducer-paging/deep-reducer-paging.mjs
+++ b/plugins/codex-security/mcp-app/tests/support/reducer-paging/deep-reducer-paging.mjs
@@ -57,10 +57,7 @@ export async function runReducerPagingEval({
const claimedWorkerIds = fixture.context.deepReducer.claimedWorkers.map(
(worker) => worker.id,
);
- const prompt = renderDedupPrompt({
- reducerLabel: "paging-eval",
- claimedWorkerIds,
- });
+ const prompt = renderDedupPrompt("paging-eval", claimedWorkerIds);
assert.deepEqual(JSON.parse(prompt.match(/```json\n([\s\S]*?)\n```/)[1]), {
reducerLabel: "paging-eval",
claimedWorkerIds,
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs
index 2c7f9bd77..224969a17 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs
@@ -1,20 +1,19 @@
import { assertFlagPair } from "./assertions.mjs";
+import { createTemporaryDirectories } from "./support/temporary-directories.mjs";
+import { mock } from "node:test";
import assert from "node:assert/strict";
import childProcess, { spawnSync } from "node:child_process";
import {
chmod,
copyFile,
mkdir,
- mkdtemp,
readFile,
realpath,
- rm,
symlink,
utimes,
writeFile,
} from "node:fs/promises";
import { syncBuiltinESMExports } from "node:module";
-import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { importModule, importSource } from "./import-module.mjs";
@@ -32,7 +31,11 @@ const {
},
stdin: {
// Test the environment snapshot without adding a production export.
- contents: `${await readFile(executorSource, "utf8")}\nexport { snapshotWorkerEnvironment, appendSafeItemDiagnostic };`,
+ contents: [
+ await readFile(executorSource, "utf8"),
+ "export { snapshotWorkerEnvironment, appendSafeItemDiagnostic };",
+ 'export * from "./errors.js";',
+ ].join("\n"),
loader: "ts",
resolveDir: path.dirname(fileURLToPath(executorSource)),
sourcefile: fileURLToPath(executorSource),
@@ -46,7 +49,7 @@ const {
} = await importSource(
fileURLToPath(new URL("../src/deep-scan/errors.ts", import.meta.url)),
);
-const temporaryRoots = [];
+const temporaryDirectories = createTemporaryDirectories();
const previousMarker = process.env.FAKE_CODEX_MARKER;
const trustedParentSandbox = Object.freeze({
filesystemDenies: [],
@@ -181,9 +184,7 @@ try {
}
} finally {
restoreEnv("FAKE_CODEX_MARKER", previousMarker);
- await Promise.all(
- temporaryRoots.map((root) => rm(root, { recursive: true, force: true })),
- );
+ await temporaryDirectories.cleanup();
}
function testOsErrorCodesRemainRetryable() {
@@ -290,10 +291,9 @@ async function testWindowsRootRelativePathsStayBoundToOriginalDrive() {
"D:\\Tools\\codex.exe",
);
- const root = await mkdtemp(
- path.join(tmpdir(), "codex-security-windows-home-"),
+ const root = await temporaryDirectories.create(
+ "codex-security-windows-home-",
);
- temporaryRoots.push(root);
const target = path.join(root, "target", "nested");
await Promise.all([
mkdir(target, { recursive: true }),
@@ -441,10 +441,7 @@ async function testWindowsLongExecutableLaunches() {
}
async function testWindowsWorkerEnvironmentPreservesMixedCaseKeys() {
- const root = await mkdtemp(
- path.join(tmpdir(), "codex-security-windows-env-"),
- );
- temporaryRoots.push(root);
+ const root = await temporaryDirectories.create("codex-security-windows-env-");
const names = [
"CODEX_CLI_PATH",
"CODEX_HOME",
@@ -484,10 +481,9 @@ async function testWindowsWorkerEnvironmentPreservesMixedCaseKeys() {
}
async function testWindowsAppsCodexFallsBackToRelocatedBinary() {
- const root = await mkdtemp(
- path.join(tmpdir(), "codex-security-windows-cache-"),
+ const root = await temporaryDirectories.create(
+ "codex-security-windows-cache-",
);
- temporaryRoots.push(root);
const localAppData = path.join(root, "LocalAppData");
const olderBinary = path.join(
localAppData,
@@ -639,10 +635,9 @@ async function testWindowsAppsCodexFallsBackToRelocatedBinary() {
}
async function testWindowsLauncherSkipsExtensionlessNpmShim() {
- const root = await mkdtemp(
- path.join(tmpdir(), "codex-security-windows-launcher-"),
+ const root = await temporaryDirectories.create(
+ "codex-security-windows-launcher-",
);
- temporaryRoots.push(root);
const shimDirectory = path.join(root, "npm-shims");
const binaryDirectory = path.join(root, "native-bin");
await Promise.all([mkdir(shimDirectory), mkdir(binaryDirectory)]);
@@ -674,10 +669,7 @@ async function testWindowsLauncherSkipsExtensionlessNpmShim() {
}
async function testWindowsNpmPackageResolution(installation = "global") {
- const root = await mkdtemp(
- path.join(tmpdir(), "codex-security-windows-npm-"),
- );
- temporaryRoots.push(root);
+ const root = await temporaryDirectories.create("codex-security-windows-npm-");
const architecture = process.arch === "arm64" ? "arm64" : "x64";
const targetTriple =
architecture === "arm64"
@@ -926,7 +918,7 @@ async function testSdkInvocationAndThreadCapture() {
await mkdir(workingDirectory);
assert.equal(workingDirectory.startsWith("/repo/"), false);
await writeFile(promptPath, "fixture worker prompt\n");
- let callbackThreadId;
+ const onThreadId = mock.fn();
const result = await new CodexSdkWorkerExecutor({
model: "gpt-5.6-luna",
reasoningEffort: "xhigh",
@@ -937,11 +929,10 @@ async function testSdkInvocationAndThreadCapture() {
workingDirectory,
subagents: 3,
signal: new AbortController().signal,
- onThreadStarted: (threadId) => {
- callbackThreadId = threadId;
- },
+ onThreadStarted: onThreadId,
});
assert.equal(result.threadId, "fixture-thread-id");
+ const callbackThreadId = onThreadId.mock.calls.at(-1)?.arguments[0];
assert.equal(callbackThreadId, "fixture-thread-id");
const invocation = JSON.parse(await readFile(fixture.markerPath, "utf8"));
assert.equal(invocation.stdin, "fixture worker prompt\n");
@@ -954,10 +945,11 @@ async function testSdkInvocationAndThreadCapture() {
"--experimental-json",
]);
assertFlagPair(invocation.argv, "--model", "gpt-5.6-luna");
- assert.equal(
- invocation.argv.includes('model_reasoning_effort="xhigh"'),
- true,
- );
+ assertConfigOverrides(invocation.argv, {
+ model_reasoning_effort: "xhigh",
+ "mcp_servers.codex-security.command": "node",
+ "mcp_servers.codex-security.enabled": false,
+ });
assertReadOnlyWorkerPolicy(invocation.argv);
assert.equal(
workerPermissionProfileOverride(invocation.argv),
@@ -966,14 +958,6 @@ async function testSdkInvocationAndThreadCapture() {
assertWorkerSubagentPolicy(invocation.argv, 3);
assertFlagPair(invocation.argv, "--cd", workingDirectory);
assert.equal(invocation.argv.includes("--skip-git-repo-check"), true);
- assert.equal(
- invocation.argv.includes('mcp_servers.codex-security.command="node"'),
- true,
- );
- assert.equal(
- invocation.argv.includes("mcp_servers.codex-security.enabled=false"),
- true,
- );
} finally {
restoreEnv("CODEX_CLI_PATH", previousPath);
}
@@ -1645,22 +1629,11 @@ async function testArtifactServerUsesExtendedStartupTimeout() {
});
assert.equal(result.threadId, "fixture-thread-id");
const invocation = JSON.parse(await readFile(fixture.markerPath, "utf8"));
- assert.equal(
- invocation.argv.includes(
- "mcp_servers.cs_artifacts.startup_timeout_sec=180",
- ),
- true,
- );
- assert.equal(
- invocation.argv.includes("mcp_servers.cs_artifacts.required=true"),
- true,
- );
- assert.equal(
- invocation.argv.includes(
- "mcp_servers.cs_artifacts.tool_timeout_sec=86400",
- ),
- true,
- );
+ assertConfigOverrides(invocation.argv, {
+ "mcp_servers.cs_artifacts.startup_timeout_sec": 180,
+ "mcp_servers.cs_artifacts.required": true,
+ "mcp_servers.cs_artifacts.tool_timeout_sec": 86400,
+ });
} finally {
restoreEnv("CODEX_CLI_PATH", previousPath);
}
@@ -1694,10 +1667,7 @@ async function testSdkResumesExistingThread() {
assert.notEqual(resumeIndex, -1);
assert.equal(invocation.argv[resumeIndex + 1], "fixture-existing-thread");
assertFlagPair(invocation.argv, "--model", "gpt-5.6-sol");
- assert.equal(
- invocation.argv.includes('model_reasoning_effort="ultra"'),
- true,
- );
+ assertConfigOverrides(invocation.argv, { model_reasoning_effort: "ultra" });
assertReadOnlyWorkerPolicy(invocation.argv);
assertWorkerSubagentPolicy(invocation.argv, 3);
assert.equal(invocation.stdin, "continue the existing worker\n");
@@ -1727,10 +1697,9 @@ async function testRetryNotificationDoesNotInterruptTurn() {
assert.equal(result.threadId, "fixture-thread-id");
const invocation = JSON.parse(await readFile(fixture.markerPath, "utf8"));
assert.equal(invocation.argv.includes("--model"), false);
- assert.equal(
- invocation.argv.some((arg) => arg.startsWith("model_reasoning_effort=")),
- false,
- );
+ assertConfigOverrides(invocation.argv, {
+ model_reasoning_effort: undefined,
+ });
} finally {
restoreEnv("CODEX_CLI_PATH", previousPath);
}
@@ -2198,7 +2167,7 @@ async function testMalformedCommandEventsRemainRetryable() {
promptPath,
`MALFORMED_COMMAND_EVENT\n${JSON.stringify(output)}\n`,
);
- let threadId;
+ const onThreadId = mock.fn();
await assert.rejects(
new CodexSdkWorkerExecutor({
parentSandbox: trustedParentSandbox,
@@ -2208,9 +2177,7 @@ async function testMalformedCommandEventsRemainRetryable() {
workingDirectory,
subagents: 0,
signal: new AbortController().signal,
- onThreadStarted: (value) => {
- threadId = value;
- },
+ onThreadStarted: onThreadId,
}),
(error) =>
error?.name === "Error" &&
@@ -2220,6 +2187,7 @@ async function testMalformedCommandEventsRemainRetryable() {
error.message.includes(JSON.stringify(output)),
`Malformed command output must remain retryable: ${output}`,
);
+ const threadId = onThreadId.mock.calls.at(-1)?.arguments[0];
assert.equal(threadId, "fixture-thread-id");
} finally {
restoreEnv("CODEX_CLI_PATH", previousPath);
@@ -2419,10 +2387,9 @@ async function fakeCodexFixture(
preflightAllowed = true,
accountResult = { account: { type: "apiKey" }, requiresOpenaiAuth: true },
) {
- const root = await mkdtemp(
- path.join(tmpdir(), "codex-security-sdk-executor-"),
+ const root = await temporaryDirectories.create(
+ "codex-security-sdk-executor-",
);
- temporaryRoots.push(root);
const markerPath = path.join(root, "invocation.json");
const preflightMarkerPath = path.join(root, "preflight.json");
const scriptPath = path.join(root, "fake-codex.mjs");
@@ -2541,7 +2508,6 @@ async function fakeCodexFixture(
function assertReadOnlyWorkerPolicy(args) {
assert.equal(args.includes("--sandbox"), false);
assert.equal(args.includes("--add-dir"), false);
- assert.equal(args.includes('approval_policy="never"'), true);
assert.deepEqual(
args.filter((arg) => arg.startsWith("approval_policy=")),
['approval_policy="never"'],
@@ -2570,51 +2536,39 @@ function workerPermissionProfileOverride(args) {
}
function assertWorkerSubagentPolicy(args, subagents) {
- assert.equal(args.includes("features.multi_agent_v2.enabled=false"), true);
+ assertConfigOverrides(args, {
+ "features.multi_agent_v2.enabled": false,
+ "features.multi_agent_v2.max_concurrent_threads_per_session": subagents + 1,
+ "features.multi_agent": undefined,
+ "features.code_mode.excluded_tool_namespaces": undefined,
+ ...(subagents === 0
+ ? {
+ "agents.max_threads": undefined,
+ "features.enable_fanout": false,
+ "features.code_mode.enabled": undefined,
+ }
+ : {
+ "agents.max_threads": subagents,
+ "features.enable_fanout": undefined,
+ }),
+ });
assert.equal(args.includes("features.multi_agent_v2.enabled=true"), false);
- assert.equal(
- args.includes(
- `features.multi_agent_v2.max_concurrent_threads_per_session=${subagents + 1}`,
- ),
- true,
- );
- assert.equal(
- args.some((arg) => arg.startsWith("features.multi_agent=")),
- false,
- );
-
- if (subagents === 0) {
- assert.equal(
- args.some((arg) => arg.startsWith("agents.max_threads=")),
- false,
- );
- assert.equal(args.includes("features.enable_fanout=false"), true);
- assert.equal(
- args.some((arg) =>
- arg.startsWith("features.code_mode.excluded_tool_namespaces="),
- ),
- false,
- );
- assert.equal(
- args.some((arg) => arg.startsWith("features.code_mode.enabled=")),
- false,
- );
- } else {
- assert.equal(args.includes(`agents.max_threads=${subagents}`), true);
- assert.equal(
- args.some((arg) => arg.startsWith("features.enable_fanout=")),
- false,
- );
- assert.equal(
- args.some((arg) =>
- arg.startsWith("features.code_mode.excluded_tool_namespaces="),
- ),
- false,
- );
- }
}
function restoreEnv(name, value) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
+
+function assertConfigOverrides(args, values) {
+ for (const [key, value] of Object.entries(values)) {
+ if (value === undefined) {
+ assert.equal(
+ args.some((arg) => arg.startsWith(`${key}=`)),
+ false,
+ );
+ } else {
+ assert.equal(args.includes(`${key}=${JSON.stringify(value)}`), true);
+ }
+ }
+}
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjs b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjs
index a90ad3e10..4a18c2c52 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjs
@@ -1,10 +1,10 @@
+import { temporaryDirectory } from "./support/temporary-directories.mjs";
import assert from "node:assert/strict";
import childProcess from "node:child_process";
import {
chmod,
copyFile,
mkdir,
- mkdtemp,
readFile,
realpath,
rm,
@@ -18,7 +18,7 @@ import { fileURLToPath } from "node:url";
import { importSource } from "./import-module.mjs";
const {
- DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID,
+ DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID: profileId,
deepScanPermissionProfileFallbackError,
preflightDeepScanWorkerPermissionProfile,
} = await importSource(
@@ -30,7 +30,6 @@ const {
),
);
-const profileId = DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID;
const expectedProfile = {
description: "Generated Deep Scan worker profile.",
filesystem: {
@@ -44,6 +43,10 @@ const rawOverrides = [
`permissions.${profileId}={filesystem={":root"="read","/repo/.env"="deny"},network={enabled=false}}`,
];
+const unsupportedConfiguration = (error) =>
+ error?.name === "Error" &&
+ error.message.includes("with this Codex configuration");
+
await testAllowedProfileAndRawArgv();
await testPreflightStartsInWorkerCwd();
await testProvidedEnvForwardedWithoutMutation();
@@ -282,9 +285,7 @@ async function testMalformedStreamFailsClosed() {
async ({ codexPath, cwd, terminatedPath, children }) => {
await assert.rejects(
preflight(codexPath, cwd),
- (error) =>
- error?.name === "Error" &&
- error.message.includes("with this Codex configuration"),
+ unsupportedConfiguration,
);
await assertPreflightStopped(children, terminatedPath);
},
@@ -302,12 +303,7 @@ async function testRepeatedCatalogCursorFailsClosed() {
],
},
async ({ codexPath, cwd, callsPath }) => {
- await assert.rejects(
- preflight(codexPath, cwd),
- (error) =>
- error?.name === "Error" &&
- error.message.includes("with this Codex configuration"),
- );
+ await assert.rejects(preflight(codexPath, cwd), unsupportedConfiguration);
const calls = await readJsonLines(callsPath);
assert.equal(
calls.filter((call) => call.method === "permissionProfile/list").length,
@@ -442,8 +438,7 @@ async function testSelectedProfileClassificationRequiresVerifiedString() {
selected === ":read-only"
? error?.name === "DeepScanNonRetryableError" &&
error.message.includes("did not select the required")
- : error?.name === "Error" &&
- error.message.includes("with this Codex configuration"),
+ : unsupportedConfiguration(error),
);
await assertPreflightStopped(children, terminatedPath);
},
@@ -463,12 +458,7 @@ async function testMalformedAndUnsupportedResponsesFailClosed() {
],
},
async ({ codexPath, cwd }) => {
- await assert.rejects(
- preflight(codexPath, cwd),
- (error) =>
- error?.name === "Error" &&
- error.message.includes("with this Codex configuration"),
- );
+ await assert.rejects(preflight(codexPath, cwd), unsupportedConfiguration);
},
);
@@ -483,8 +473,7 @@ async function testMalformedAndUnsupportedResponsesFailClosed() {
await assert.rejects(
preflight(codexPath, cwd),
(error) =>
- error?.name === "Error" &&
- error.message.includes("with this Codex configuration") &&
+ unsupportedConfiguration(error) &&
!error.message.includes("does not support"),
);
},
@@ -759,9 +748,7 @@ async function withFakeCodex(
callback,
{ longExecutable = false } = {},
) {
- const root = await mkdtemp(
- path.join(tmpdir(), "deep-scan-profile-preflight-"),
- );
+ const root = await temporaryDirectory("deep-scan-profile-preflight-");
const scriptPath = path.join(root, "fake-codex.mjs");
let codexPath = scriptPath;
const argvPath = path.join(root, "argv.json");
@@ -935,11 +922,7 @@ function send(id, result, error) {
async function readJsonLines(file) {
const content = await readFile(file, "utf8");
- return content
- .trim()
- .split(/\r?\n/u)
- .filter(Boolean)
- .map((line) => JSON.parse(line));
+ return content.trim().split(/\r?\n/u).filter(Boolean).map(JSON.parse);
}
async function waitForFile(file) {
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_templates.mjs b/plugins/codex-security/mcp-app/tests/test_deep_scan_templates.mjs
index c8f156e7c..f8ac9e838 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_templates.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_templates.mjs
@@ -1,3 +1,4 @@
+import { readFile } from "node:fs/promises";
import assert from "node:assert/strict";
import { importSource } from "./import-module.mjs";
@@ -6,6 +7,16 @@ const { renderDedupPrompt, renderDiscoveryPrompt } = await importSource(
{ loader: { ".md": "text" } },
);
+for (const name of ["discovery", "dedup"]) {
+ const template = await readFile(
+ new URL(`../templates/deep-scan/${name}.md`, import.meta.url),
+ "utf8",
+ );
+ for (const key of template.match(/\{\{[A-Z0-9_]+\}\}/g) ?? []) {
+ assert.equal(key, `{{${name.toUpperCase()}_CONTEXT_JSON}}`);
+ }
+}
+
const discoveryInput = {
scanId: "a0d89285-66b7-4e4f-b51a-e21b93b7081b",
pluginRoot: "/fixture/plugins/codex-security",
@@ -51,16 +62,7 @@ const withFeedback = renderDiscoveryPrompt({ ...discoveryInput }, feedbackPath);
assert.deepEqual(firstJsonBlock(withFeedback), discoveryContext);
assert.equal(withFeedback.includes(JSON.stringify(feedbackPath)), true);
-const dedup = renderDedupPrompt({
- reducerLabel: "dedup-0001",
- claimedWorkerIds: ["worker-001"],
- discoveries: [
- {
- workerId: "worker-001",
- resultPath: "/fixture/worker/result.json",
- },
- ],
-});
+const dedup = renderDedupPrompt("dedup-0001", ["worker-001"]);
const dedupContext = firstJsonBlock(dedup);
assert.doesNotMatch(dedup, /\bcoverage\b/i);
assert.match(
@@ -85,12 +87,7 @@ for (const field of [
assert.equal(Object.hasOwn(dedupContext, field), false);
}
-const previousReduction = firstJsonBlock(
- renderDedupPrompt({
- reducerLabel: "dedup-0002",
- claimedWorkerIds: [],
- }),
-);
+const previousReduction = firstJsonBlock(renderDedupPrompt("dedup-0002", []));
assert.deepEqual(previousReduction, {
reducerLabel: "dedup-0002",
claimedWorkerIds: [],