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

fix(deep-scan): pin Deep Scan worker executable (#764)

Soyeon Parke6b960c6d7a0
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 8c5b45a6d..d1d79001f 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import {
accessSync,
+ type BigIntStats,
constants as fsConstants,
existsSync,
promises as fs,
@@ -75,6 +76,11 @@ export interface CodexSdkWorkerArtifactContext {
pythonCommand?: string;
}
+interface BoundCodexExecutable {
+ readonly path: string;
+ readonly identity: BigIntStats;
+}
+
interface CodexSdkWorkerRuntimeSettings {
hasProviderEnvKey?: boolean;
environment?: Record<string, string>;
@@ -87,6 +93,8 @@ interface CodexSdkWorkerRuntimeSettings {
export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
private runtimeSettings?: Promise<CodexSdkWorkerRuntimeSettings>;
+ // Each live coordinator keeps the executable selected for its first worker.
+ private codexExecutable?: Promise<BoundCodexExecutable>;
private parentCyberAccessProgram?: Promise<CyberAccessProgram | undefined>;
constructor(
@@ -265,14 +273,17 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
"CODEX_API_KEY",
process.platform,
)?.trim();
- const codexPath = resolveCodexPath(
+ const executable = await (this.codexExecutable ??= bindCodexExecutable(
childEnv,
- process.platform,
- process.arch,
originalCwd,
- );
+ ).catch((error) => {
+ // A failed first lookup has not pinned an executable yet; allow startup retries.
+ this.codexExecutable = undefined;
+ throw error;
+ }));
+ await verifyBoundCodexExecutable(executable);
const preflightOptions = {
- codexPath,
+ codexPath: executable.path,
cwd: request.workingDirectory,
configOverrides,
providerConfigOverrides: runtimeSettings.preflightProviderOverrides,
@@ -329,7 +340,7 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
? request.prompt
: await fs.readFile(request.promptPath, "utf8");
const codexOptions = {
- codexPathOverride: executablePathForSpawn(codexPath),
+ codexPathOverride: executablePathForSpawn(executable.path),
env: childEnv,
// Codex exec reads CODEX_API_KEY; the SDK maps apiKey to that variable.
// Keep native credentials unless the worker has no configured account.
@@ -372,6 +383,8 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
}
try {
+ // Detect updates during preflight before starting a fresh or resumed worker.
+ await verifyBoundCodexExecutable(executable);
const { events } = await thread.runStreamed(input, {
signal: controller.signal,
...(request.kind === "compare" && { outputSchema: request.schema }),
@@ -662,6 +675,57 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
+async function bindCodexExecutable(
+ env: NodeJS.ProcessEnv,
+ originalCwd: string,
+): Promise<BoundCodexExecutable> {
+ const path = resolveCodexPath(
+ env,
+ process.platform,
+ process.arch,
+ originalCwd,
+ );
+ return { path, identity: await codexExecutableIdentity(path) };
+}
+
+async function verifyBoundCodexExecutable(
+ executable: BoundCodexExecutable,
+): Promise<void> {
+ let identity: BigIntStats;
+ try {
+ identity = await codexExecutableIdentity(executable.path);
+ } catch (error) {
+ throw codexExecutableChangedError(executable.path, error);
+ }
+ if (
+ identity.dev !== executable.identity.dev ||
+ identity.ino !== executable.identity.ino ||
+ identity.size !== executable.identity.size ||
+ identity.mtimeNs !== executable.identity.mtimeNs ||
+ identity.ctimeNs !== executable.identity.ctimeNs
+ ) {
+ throw codexExecutableChangedError(executable.path);
+ }
+}
+
+async function codexExecutableIdentity(path: string): Promise<BigIntStats> {
+ const metadata = await fs.stat(path, { bigint: true });
+ if (!metadata.isFile() || metadata.size === 0n) {
+ throw new Error("Codex executable is not a non-empty file.");
+ }
+ return metadata;
+}
+
+function codexExecutableChangedError(path: string, cause?: unknown): Error {
+ return new DeepScanNonRetryableError(
+ "Deep Scan cannot start this worker because the Codex executable " +
+ `"${path}" changed after this Deep Scan started or is no longer available. ` +
+ "This usually means Codex updated while the scan was running. Retry after the update " +
+ "finishes; completed work remains in the retained partial scan.",
+ { cause },
+ );
+}
+
function mergeConfigTables(
base: Record<string, unknown>,
override: Record<string, unknown>,
@@ -917,7 +981,21 @@ export function resolveCodexPath(
: resolveFromSearchPath(searchPath, executableName, originalCwd);
if (fromSearchPath) return fromSearchPath;
}
- return absoluteCodexPath(configured, platform, originalCwd);
+ const configuredPath = absoluteCodexPath(configured, platform, originalCwd);
+ if (platform === "win32") {
+ // Match Node's spawn lookup before binding the actual file's identity.
+ const suffixBase = configuredPath.endsWith(".")
+ ? configuredPath
+ : `${configuredPath}.`;
+ const hasExtension = /\.[^.]+$/u.test(win32.basename(configuredPath));
+ const candidates = [
+ ...(hasExtension ? [configuredPath] : []),
+ `${suffixBase}com`,
+ `${suffixBase}exe`,
+ ];
+ return candidates.find(isExecutableFile) ?? configuredPath;
+ }
+ return configuredPath;
}
if (platform !== "win32") {
diff --git a/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts b/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts
new file mode 100644
index 000000000..5f0baf339
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/deep_scan_executable_cases.ts
@@ -0,0 +1,372 @@
+import assert from "node:assert/strict";
+import childProcess, { type SpawnOptions } from "node:child_process";
+import {
+ copyFile,
+ mkdir,
+ readFile,
+ realpath,
+ rename,
+ rm,
+ writeFile,
+} from "node:fs/promises";
+import { syncBuiltinESMExports } from "node:module";
+import path from "node:path";
+import { assertFlagPair } from "./assertions.ts";
+import { readJson } from "./support/json.ts";
+import type {
+ CodexSdkWorkerExecutor as WorkerExecutor,
+ resolveCodexPath as ResolveCodexPath,
+} from "../src/deep-scan/executor.js";
+import type { DeepWorkerParentSandbox } from "../src/deep-scan/parent-sandbox.js";
+import type { CodexWorkerRequest } from "../src/deep-scan/types.js";
+
+interface Fixture {
+ root: string;
+ markerPath: string;
+ preflightMarkerPath: string;
+ executablePath: string;
+}
+
+export async function testExecutorExecutablePinning({
+ CodexSdkWorkerExecutor,
+ fakeCodexFixture,
+ parentSandbox,
+ resolveCodexPath,
+}: {
+ CodexSdkWorkerExecutor: typeof WorkerExecutor;
+ fakeCodexFixture: () => Promise<Fixture>;
+ parentSandbox: DeepWorkerParentSandbox;
+ resolveCodexPath: typeof ResolveCodexPath;
+}) {
+ const originalSpawn = childProcess.spawn;
+ const nativeScripts = new Map<string, string>();
+ const nativeLaunches: string[] = [];
+ if (process.platform === "win32") {
+ // Windows needs Node to run the selected script fixture.
+ childProcess.spawn = ((
+ command: string,
+ args: readonly string[] = [],
+ options: SpawnOptions = {},
+ ) => {
+ const script = nativeScripts.get(command);
+ if (script) nativeLaunches.push(command);
+ return originalSpawn(
+ script ? command : process.execPath,
+ [script ?? command, ...args],
+ options,
+ );
+ }) as typeof childProcess.spawn;
+ syncBuiltinESMExports();
+ }
+ try {
+ await testWindowsExecutableSuffixes();
+ await testExecutorRetriesInitialMissingExecutable();
+ await testExecutorPinsCodexExecutableAcrossWorkers();
+ await testExecutorRejectsChangedPinnedExecutable();
+ await testExecutorRejectsReplacementAfterPreflight();
+ } finally {
+ childProcess.spawn = originalSpawn;
+ syncBuiltinESMExports();
+ }
+
+ async function testWindowsExecutableSuffixes() {
+ await withWorkerFixture(async (fixture, promptPath, workingDirectory) => {
+ const binaryPath = path.join(fixture.root, "bin", "custom-codex");
+ await mkdir(path.dirname(binaryPath));
+ await writeFile(`${binaryPath}.exe`, "synthetic executable", {
+ mode: 0o755,
+ });
+ const resolveWindowsPath = (configured: string) =>
+ resolveCodexPath(
+ { CODEX_CLI_PATH: configured },
+ "win32",
+ process.arch,
+ fixture.root,
+ );
+ const configuredPaths = [
+ binaryPath,
+ path.relative(fixture.root, binaryPath),
+ ];
+ for (const configured of configuredPaths) {
+ assert.equal(resolveWindowsPath(configured), `${binaryPath}.exe`);
+ }
+ await writeFile(`${binaryPath}.com`, "synthetic executable", {
+ mode: 0o755,
+ });
+ for (const configured of configuredPaths) {
+ assert.equal(resolveWindowsPath(configured), `${binaryPath}.com`);
+ assert.equal(resolveWindowsPath(`${configured}.`), `${binaryPath}.com`);
+ assert.equal(
+ resolveWindowsPath(`${configured}.exe`),
+ `${binaryPath}.exe`,
+ );
+ }
+ assert.equal(
+ resolveWindowsPath(fixture.executablePath),
+ fixture.executablePath,
+ );
+ const leadingDotPath = path.join(fixture.root, ".custom-codex");
+ await writeFile(leadingDotPath, "synthetic executable", { mode: 0o755 });
+ await writeFile(`${leadingDotPath}.com`, "synthetic executable", {
+ mode: 0o755,
+ });
+ assert.equal(resolveWindowsPath(leadingDotPath), leadingDotPath);
+ if (process.platform === "win32") {
+ await rm(`${binaryPath}.com`);
+ await copyFile(process.execPath, `${binaryPath}.exe`);
+ const command = path.toNamespacedPath(`${binaryPath}.exe`);
+ nativeScripts.set(command, fixture.executablePath);
+ process.env.CODEX_CLI_PATH = binaryPath;
+ await writeFile(
+ promptPath,
+ "fixture extensionless Windows executable\n",
+ );
+ const result = await new CodexSdkWorkerExecutor({ parentSandbox }).run(
+ workerRequest(promptPath, workingDirectory),
+ );
+ assert.equal(result.threadId, "fixture-thread-id");
+ assert.deepEqual(nativeLaunches, [command, command]);
+ }
+ });
+ }
+
+ async function testExecutorRetriesInitialMissingExecutable() {
+ await withWorkerFixture(async (fixture, promptPath, workingDirectory) => {
+ await writeFile(promptPath, "fixture initial missing executable\n");
+ const executor = new CodexSdkWorkerExecutor({ parentSandbox });
+ const request = workerRequest(promptPath, workingDirectory);
+ const parkedExecutable = `${fixture.executablePath}.parked`;
+ await rename(fixture.executablePath, parkedExecutable);
+ await assert.rejects(executor.run(request), {
+ name: "Error",
+ code: "ENOENT",
+ });
+ await assert.rejects(readFile(fixture.preflightMarkerPath), {
+ code: "ENOENT",
+ });
+ await rename(parkedExecutable, fixture.executablePath);
+ assert.equal((await executor.run(request)).threadId, "fixture-thread-id");
+ process.env.CODEX_CLI_PATH = parkedExecutable;
+ assert.equal(
+ (
+ await executor.run({
+ ...request,
+ resumeThreadId: "fixture-resumed-thread",
+ })
+ ).threadId,
+ "fixture-resumed-thread",
+ );
+ const invocation = await readJson(fixture.markerPath);
+ assert.equal(
+ await realpath(invocation.executablePath),
+ fixture.executablePath,
+ );
+ await writeFile(fixture.executablePath, "replaced executable");
+ await assert.rejects(executor.run(request), {
+ name: "DeepScanNonRetryableError",
+ message: /changed after this Deep Scan started/i,
+ });
+ });
+ }
+
+ async function testExecutorPinsCodexExecutableAcrossWorkers() {
+ const previousPath = process.env.CODEX_CLI_PATH;
+ const previousMarker = process.env.FAKE_CODEX_MARKER;
+ const fixtures = [await fakeCodexFixture(), await fakeCodexFixture()];
+ const executors = fixtures.map(
+ () => new CodexSdkWorkerExecutor({ parentSandbox }),
+ );
+ try {
+ for (const fixture of fixtures) {
+ await writeFile(
+ path.join(fixture.root, "prompt.md"),
+ "fixture pinned executable\n",
+ );
+ }
+ for (const turn of ["discovery", "resume", "compare"] as const) {
+ const firstLaunch = turn === "discovery";
+ await Promise.all(
+ fixtures.map((fixture, index) => {
+ process.env.CODEX_CLI_PATH =
+ fixtures[firstLaunch ? index : 1 - index]!.executablePath;
+ process.env.FAKE_CODEX_MARKER = fixture.markerPath;
+ return runTurn(
+ executors[index]!,
+ path.join(fixture.root, "prompt.md"),
+ fixture.root,
+ turn,
+ );
+ }),
+ );
+ for (const fixture of fixtures) {
+ const preflight = await readJson(fixture.preflightMarkerPath);
+ const invocation = await readJson(fixture.markerPath);
+ assert.equal(
+ await realpath(preflight.executablePath),
+ fixture.executablePath,
+ );
+ assert.deepEqual(preflight.requests, [
+ { method: "config/read", cwd: fixture.root },
+ { method: "permissionProfile/list", cwd: fixture.root },
+ ]);
+ assert.equal(
+ await realpath(invocation.executablePath),
+ fixture.executablePath,
+ );
+ assert.equal(invocation.argv.includes("resume"), turn === "resume");
+ if (turn === "resume") {
+ assertFlagPair(invocation.argv, "resume", "fixture-resumed-thread");
+ }
+ assertFlagPair(invocation.argv, "--cd", fixture.root);
+ await rm(fixture.preflightMarkerPath);
+ await rm(fixture.markerPath);
+ }
+ }
+ } finally {
+ restoreEnv("CODEX_CLI_PATH", previousPath);
+ restoreEnv("FAKE_CODEX_MARKER", previousMarker);
+ }
+ }
+
+ async function testExecutorRejectsChangedPinnedExecutable() {
+ for (const change of ["replace", "remove"]) {
+ await withWorkerFixture(async (fixture, promptPath, workingDirectory) => {
+ await writeFile(promptPath, "fixture changed pinned executable\n");
+ const executor = new CodexSdkWorkerExecutor({
+ parentSandbox,
+ });
+ await executor.run(workerRequest(promptPath, workingDirectory));
+ await rm(fixture.preflightMarkerPath);
+ await rm(fixture.markerPath);
+ if (change === "remove") {
+ await rm(fixture.executablePath);
+ } else {
+ const original = await readFile(fixture.executablePath, "utf8");
+ await writeFile(
+ fixture.executablePath,
+ `${original}\n// replaced after scan start\n`,
+ );
+ }
+ for (const turn of ["discovery", "resume", "compare"] as const) {
+ await assert.rejects(
+ runTurn(executor, promptPath, workingDirectory, turn),
+ {
+ name: "DeepScanNonRetryableError",
+ message: /changed after this Deep Scan started/i,
+ },
+ );
+ }
+ await assert.rejects(readFile(fixture.preflightMarkerPath), {
+ code: "ENOENT",
+ });
+ await assert.rejects(readFile(fixture.markerPath), { code: "ENOENT" });
+ });
+ }
+ }
+
+ async function testExecutorRejectsReplacementAfterPreflight() {
+ const previousReplace = process.env.FAKE_CODEX_REPLACE_AFTER_PREFLIGHT;
+ process.env.FAKE_CODEX_REPLACE_AFTER_PREFLIGHT = "1";
+ try {
+ for (const turn of ["discovery", "resume", "compare"] as const) {
+ await withWorkerFixture(
+ async (fixture, promptPath, workingDirectory) => {
+ await writeFile(
+ promptPath,
+ "fixture replacement after preflight\n",
+ );
+ await assert.rejects(
+ runTurn(
+ new CodexSdkWorkerExecutor({ parentSandbox }),
+ promptPath,
+ workingDirectory,
+ turn,
+ ),
+ {
+ name: "DeepScanNonRetryableError",
+ message: /changed after this Deep Scan started/i,
+ },
+ );
+ const preflight = await readJson(fixture.preflightMarkerPath);
+ assert.equal(
+ await realpath(preflight.executablePath),
+ fixture.executablePath,
+ );
+ await assert.rejects(readFile(fixture.markerPath), {
+ code: "ENOENT",
+ });
+ },
+ );
+ }
+ } finally {
+ restoreEnv("FAKE_CODEX_REPLACE_AFTER_PREFLIGHT", previousReplace);
+ }
+ }
+
+ async function withWorkerFixture(
+ action: (
+ fixture: Fixture,
+ promptPath: string,
+ workingDirectory: string,
+ ) => Promise<void>,
+ ) {
+ const previousPath = process.env.CODEX_CLI_PATH;
+ const previousMarker = process.env.FAKE_CODEX_MARKER;
+ try {
+ const fixture = await fakeCodexFixture();
+ process.env.CODEX_CLI_PATH = fixture.executablePath;
+ const workingDirectory = path.join(fixture.root, "artifacts");
+ await mkdir(workingDirectory);
+ await action(
+ fixture,
+ path.join(fixture.root, "prompt.md"),
+ workingDirectory,
+ );
+ } finally {
+ restoreEnv("CODEX_CLI_PATH", previousPath);
+ restoreEnv("FAKE_CODEX_MARKER", previousMarker);
+ }
+ }
+}
+
+function runTurn(
+ executor: WorkerExecutor,
+ promptPath: string,
+ cwd: string,
+ turn: "discovery" | "resume" | "compare",
+) {
+ if (turn === "compare")
+ return executor.compareFindings(
+ "fixture comparison",
+ cwd,
+ new AbortController().signal,
+ { type: "object" },
+ );
+ return executor.run(
+ workerRequest(
+ promptPath,
+ cwd,
+ turn === "resume" ? { resumeThreadId: "fixture-resumed-thread" } : {},
+ ),
+ );
+}
+
+function workerRequest(
+ promptPath: string,
+ workingDirectory: string,
+ options: Partial<CodexWorkerRequest> = {},
+): CodexWorkerRequest {
+ return {
+ kind: "discovery",
+ promptPath,
+ workingDirectory,
+ subagents: 0,
+ signal: new AbortController().signal,
+ ...options,
+ };
+}
+
+function restoreEnv(name: string, value: string | undefined) {
+ if (value === undefined) delete process.env[name];
+ else process.env[name] = value;
+}
diff --git a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts
index e813b5195..2a2559712 100644
--- a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts
+++ b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts
@@ -17,7 +17,7 @@ const accountResult = ${JSON.stringify(accountResult)};
const preflightMarkerPath = process.env.FAKE_CODEX_PREFLIGHT_MARKER ?? ${JSON.stringify(preflightMarkerPath)};
const temporaryEnvironment = Object.fromEntries(['TEMP', 'TMP'].map(name => [name, process.env[name]]));
if (process.argv.includes('app-server')) {
- const preflight = { argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, stateDirectory: process.env.CODEX_SECURITY_STATE_DIR, temporaryEnvironment, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env["LD_LIBRARY_PATH"], cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerHeader: process.env.SYNTHETIC_HEADER_VALUE, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), requests: [] };
+ const preflight = { executablePath: process.argv[1], argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, stateDirectory: process.env.CODEX_SECURITY_STATE_DIR, temporaryEnvironment, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env["LD_LIBRARY_PATH"], cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerHeader: process.env.SYNTHETIC_HEADER_VALUE, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), requests: [] };
writeFileSync(preflightMarkerPath, JSON.stringify(preflight));
${jsonLineInputSource(` if (message.method === 'initialized') continue;
if (message.method === 'config/read' || message.method === 'permissionProfile/list') {
@@ -49,6 +49,7 @@ ${jsonLineInputSource(` if (message.method === 'initialized') continue;
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } }) + '\\n');
continue;
}
+ if (message.method === 'permissionProfile/list' && process.env.FAKE_CODEX_REPLACE_AFTER_PREFLIGHT === '1') writeFileSync(process.argv[1], '#!/usr/bin/env node\\nprocess.exit(97);\\n');
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + '\\n');`)}
process.stdin.on('end', () => process.exit(0));
} else {
@@ -75,7 +76,7 @@ const pythonRuntime = pythonProbe ? JSON.parse(pythonProbe.stdout) : undefined;
const knowledgePath = stdin.includes('synthetic worker configuration fixture') ? process.env.CODEX_SECURITY_KNOWLEDGE_BASE : undefined;
const knowledgeDocuments = knowledgePath === undefined ? undefined : Object.fromEntries(readdirSync(knowledgePath).map(name => [name, readFileSync(join(knowledgePath, name), 'utf8')]));
const deepConfig = process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH ? readFileSync(process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, 'utf8') : undefined;
-writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, codexHome: process.env.CODEX_HOME, temporaryEnvironment, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, bundledTool: toolProbe?.stdout.trim(), pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, codexConfig, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));
+writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ executablePath: process.argv[1], ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, codexHome: process.env.CODEX_HOME, temporaryEnvironment, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, bundledTool: toolProbe?.stdout.trim(), pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, codexConfig, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));
if (stdin.includes('COMPLETE_THEN_HANG')) process.on('SIGTERM', () => { if (!stdin.includes('IGNORE_TERMINATION')) setTimeout(() => process.exit(0), 100); });
if (stdin.includes('THREAD_START_CONFIG_ERROR')) { console.error('Error: thread/start: thread/start failed: agents.max_threads cannot be set when features.multi_agent_v2 is enabled (code -32600)'); process.exit(1); }
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.ts
index 5805deb49..1d721fdb1 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
@@ -30,7 +30,6 @@ import {
} from "./deep_scan_lifecycle_cases.ts";
import {
DeepScanCoordinatorRegistry,
- DeepScanNonRetryableError,
WorkbenchDeepScanStore,
DeepScanRemoteCoordinator,
DeepScanNonRetryableError,
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.ts
index 606064431..7e12d7272 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
@@ -65,6 +65,7 @@ import type {
CodexWorkerDiagnostic,
CodexWorkerRequest,
} from "../src/deep-scan/types.js";
+import { testExecutorExecutablePinning } from "./deep_scan_executable_cases.ts";
import { testWorkerSelectedProfileFiles } from "./deep_scan_profile_file_cases.ts";
import { testConcurrentWorkerExecutableAliases } from "./deep_scan_executable_alias_cases.ts";
import { testDeepScanContextSnapshots } from "./deep_scan_context_snapshot_cases.ts";
@@ -154,6 +155,17 @@ try {
await test("Deep worker executable selection", async (t) => {
await check(t, testConfiguredExecutablePaths);
+ await check(
+ t,
+ () =>
+ testExecutorExecutablePinning({
+ CodexSdkWorkerExecutor,
+ fakeCodexFixture,
+ parentSandbox: trustedParentSandbox,
+ resolveCodexPath,
+ }),
+ "worker executable pinning",
+ );
if (process.platform !== "win32") {
await check(t, testWorkerLaunchesWithoutGlobalCodex);
await check(t, testPreflightBindsExecutableAndHomeBeforeChangingCwd);