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 artifact storage boundaries (#1206)

mldangelo-oai26db495ff9a4
diff --git a/plugins/codex-security/mcp-app/artifact-writer-main.ts b/plugins/codex-security/mcp-app/artifact-writer-main.ts
index 505fc29b1..be11c3df2 100644
--- a/plugins/codex-security/mcp-app/artifact-writer-main.ts
+++ b/plugins/codex-security/mcp-app/artifact-writer-main.ts
@@ -1,11 +1,14 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
- createWorkerArtifactContext,
+ canonicalDirectory,
+ defined,
+ type ArtifactContext,
type DeepReducerContext,
} 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 { isRecord } from "./src/record.js";
/** Build the narrow worker-only MCP from coordinator-inherited state. */
export async function createCodexSecurityArtifactWriterServer(
@@ -30,24 +33,35 @@ export async function createCodexSecurityArtifactWriterServer(
);
}
- const context = await createWorkerArtifactContext({
- root,
- repoRoot,
+ /**
+ * Bind a lightweight worker to host-supplied state, never model-supplied paths.
+ */
+ const scanId = environment.CODEX_SECURITY_SCAN_ID
+ ? environment.CODEX_SECURITY_SCAN_ID
+ : undefined;
+ const scope = environment.CODEX_SECURITY_SCOPE
+ ? environment.CODEX_SECURITY_SCOPE
+ : undefined;
+ const pluginRoot = environment.CODEX_SECURITY_PLUGIN_ROOT
+ ? environment.CODEX_SECURITY_PLUGIN_ROOT
+ : undefined;
+ const pythonCommand = environment.CODEX_SECURITY_PYTHON_COMMAND
+ ? environment.CODEX_SECURITY_PYTHON_COMMAND
+ : undefined;
+ // Preserve the asynchronous context boundary before server construction.
+ const context: ArtifactContext = await (async () => ({
+ root: await canonicalDirectory(root, "Codex Security worker artifact root"),
+ repoRoot: await canonicalDirectory(
+ repoRoot,
+ "Codex Security worker target root",
+ ),
layout,
- ...(environment.CODEX_SECURITY_SCAN_ID
- ? { scanId: environment.CODEX_SECURITY_SCAN_ID }
- : {}),
- ...(environment.CODEX_SECURITY_SCOPE
- ? { scope: environment.CODEX_SECURITY_SCOPE }
- : {}),
- ...(environment.CODEX_SECURITY_PLUGIN_ROOT
- ? { pluginRoot: environment.CODEX_SECURITY_PLUGIN_ROOT }
- : {}),
- ...(environment.CODEX_SECURITY_PYTHON_COMMAND
- ? { pythonCommand: environment.CODEX_SECURITY_PYTHON_COMMAND }
- : {}),
- ...(deepReducer ? { deepReducer } : {}),
- });
+ ...defined("scanId", scanId),
+ ...defined("scope", scope),
+ ...defined("pluginRoot", pluginRoot),
+ ...defined("pythonCommand", pythonCommand),
+ ...defined("deepReducer", deepReducer),
+ }))();
const server = new McpServer(
{ name: "codex-security-artifacts", version: MCP_APP_VERSION },
{
@@ -84,15 +98,13 @@ function parseReducerContext(value: string): DeepReducerContext {
);
}
if (
- !parsed ||
- typeof parsed !== "object" ||
- Array.isArray(parsed) ||
- typeof (parsed as Record<string, unknown>).scanRoot !== "string" ||
- !Array.isArray((parsed as Record<string, unknown>).claimedWorkers)
+ !isRecord(parsed) ||
+ typeof parsed.scanRoot !== "string" ||
+ !Array.isArray(parsed.claimedWorkers)
) {
throw new Error(
"The coordinator-bound Deep reducer context is incomplete.",
);
}
- return parsed as DeepReducerContext;
+ return parsed as unknown as DeepReducerContext;
}
diff --git a/plugins/codex-security/mcp-app/server.ts b/plugins/codex-security/mcp-app/server.ts
index 230e47102..48ee45d44 100644
--- a/plugins/codex-security/mcp-app/server.ts
+++ b/plugins/codex-security/mcp-app/server.ts
@@ -11,7 +11,6 @@ import {
missingPythonHelperMessage,
resolvePythonCommand,
} from "./src/python_command.js";
-import type { ScanResults } from "./src/types.js";
import { MCP_APP_VERSION } from "./src/version.js";
import {
handoffClaimTokenSchema,
@@ -129,7 +128,7 @@ async function scanRoot(): Promise<string> {
interface WorkspaceState extends JsonObject {
id: string;
- results?: ScanResults & JsonObject;
+ results?: JsonObject;
setup: {
submitted: boolean;
};
diff --git a/plugins/codex-security/mcp-app/src/artifact-context.ts b/plugins/codex-security/mcp-app/src/artifact-context.ts
index 688e2b4a7..22b87eace 100644
--- a/plugins/codex-security/mcp-app/src/artifact-context.ts
+++ b/plugins/codex-security/mcp-app/src/artifact-context.ts
@@ -22,13 +22,6 @@ export interface ScanArtifactContextOptions {
pythonCommand?: string;
}
-export interface WorkerArtifactContextInput extends Omit<
- ArtifactContext,
- "layout"
-> {
- layout?: "worker" | "reducer";
-}
-
/**
* Resolve parent artifacts from their authoritative, persisted workbench scan.
*/
@@ -108,45 +101,6 @@ export async function createScanArtifactContext(
};
}
-/**
- * Bind a lightweight worker to host-supplied state, never model-supplied paths.
- */
-export async function createWorkerArtifactContext(
- input: WorkerArtifactContextInput,
-): Promise<ArtifactContext> {
- const layout = input.layout ?? "worker";
- if (layout !== "worker" && layout !== "reducer") {
- throw new Error("Codex Security worker artifact layout is invalid.");
- }
- const context: ArtifactContext = {
- root: await canonicalDirectory(
- input.root,
- "Codex Security worker artifact root",
- ),
- repoRoot: await canonicalDirectory(
- input.repoRoot,
- "Codex Security worker target root",
- ),
- layout,
- ...defined("scanId", input.scanId),
- ...defined("scope", input.scope),
- ...defined("pluginRoot", input.pluginRoot),
- ...defined("pythonCommand", input.pythonCommand),
- ...defined("targetContract", input.targetContract),
- ...defined("targetRevision", input.targetRevision),
- ...defined("handoffClaimToken", input.handoffClaimToken),
- ...defined("status", input.status),
- ...defined("mode", input.mode),
- ...defined("deepReducer", input.deepReducer),
- };
- if (context.deepReducer && layout !== "reducer") {
- throw new Error(
- "Codex Security reducer state requires a reducer-bound context.",
- );
- }
- return context;
-}
-
function scanRecord(
result: Record<string, unknown>,
scanId: string,
@@ -162,7 +116,7 @@ function scanRecord(
return scan;
}
-async function canonicalDirectory(
+export async function canonicalDirectory(
value: string,
label: string,
): Promise<string> {
@@ -170,8 +124,7 @@ async function canonicalDirectory(
throw new Error(label + " must be an absolute directory.");
}
const requested = resolve(value);
- const metadata = await fs.lstat(requested).catch(() => undefined);
- if (!metadata || metadata.isSymbolicLink() || !metadata.isDirectory()) {
+ if (!(await fs.lstat(requested).catch(() => undefined))?.isDirectory()) {
throw new Error(label + " is not a safe regular directory.");
}
try {
@@ -191,7 +144,7 @@ function optionalString(value: unknown): string | undefined {
return typeof value === "string" && value.trim() ? value : undefined;
}
-function defined<Key extends string, Value>(
+export function defined<Key extends string, Value>(
key: Key,
value: Value | undefined,
): Partial<Record<Key, Value>> {
diff --git a/plugins/codex-security/mcp-app/src/artifact-inventory.ts b/plugins/codex-security/mcp-app/src/artifact-inventory.ts
index 007720791..f174c6375 100644
--- a/plugins/codex-security/mcp-app/src/artifact-inventory.ts
+++ b/plugins/codex-security/mcp-app/src/artifact-inventory.ts
@@ -44,30 +44,12 @@ export const prepareReviewItemsInputSchema = loadArtifactZodSchema(
"prepareInput",
) as z.ZodType<{ scanId: string; handoffClaimToken?: string }>;
-export const prepareReviewItemsOutputSchema = loadArtifactZodSchema(
- documents,
- reviewItemsSchema.$id,
- "prepareOutput",
-) as z.ZodType<PreparedReviewItems>;
-
export const reviewItemsReaderInputSchema = loadArtifactZodSchema(
documents,
reviewItemsSchema.$id,
"reviewItemsInput",
) as z.ZodType<{ scanId: string; handoffClaimToken?: string } & ArtifactPage>;
-export const reviewItemsWorkerReaderInputSchema = loadArtifactZodSchema(
- documents,
- reviewItemsSchema.$id,
- "reviewItemsWorkerInput",
-) as z.ZodType<ArtifactPage>;
-
-export const reviewItemsReaderOutputSchema = loadArtifactZodSchema(
- documents,
- reviewItemsSchema.$id,
- "reviewItemsOutput",
-) as z.ZodType<ReviewItemsResult>;
-
const reviewItemSchema = loadArtifactZodSchema(
documents,
reviewItemsSchema.$id,
diff --git a/plugins/codex-security/mcp-app/src/artifact-io.ts b/plugins/codex-security/mcp-app/src/artifact-io.ts
index 2d6e6a6d4..d8e19a61d 100644
--- a/plugins/codex-security/mcp-app/src/artifact-io.ts
+++ b/plugins/codex-security/mcp-app/src/artifact-io.ts
@@ -1,7 +1,8 @@
+import { canonicalDirectory } from "./artifact-context.js";
import { isRecord } from "./record.js";
import { randomUUID } from "node:crypto";
import { constants as fsConstants, promises as fs } from "node:fs";
-import { dirname, isAbsolute, join, resolve, sep } from "node:path";
+import { dirname, isAbsolute, join, sep } from "node:path";
export interface DeepReducerWorkerContext {
id: string;
@@ -101,10 +102,7 @@ async function artifactSourcePath(
throw new Error(label + ": the requested artifact is unavailable.");
}
const isLast = index === components.length - 1;
- if (
- metadata.isSymbolicLink() ||
- (isLast ? !metadata.isFile() : !metadata.isDirectory())
- ) {
+ if (isLast ? !metadata.isFile() : !metadata.isDirectory()) {
throw new Error(
label + ": the requested artifact is not a safe regular file.",
);
@@ -226,7 +224,7 @@ export async function artifactDestination(
}
metadata = await inspectOptionalPath(directory, label);
}
- if (!metadata || metadata.isSymbolicLink() || !metadata.isDirectory()) {
+ if (!metadata || !metadata.isDirectory()) {
throw new Error(
label + ": destination directory is not a regular directory.",
);
@@ -241,8 +239,7 @@ export async function artifactDestination(
if (!destination.startsWith(root + sep)) {
throw new Error(label + ": destination escaped its bound context.");
}
- const metadata = await inspectOptionalPath(destination, label);
- if (metadata && (metadata.isSymbolicLink() || !metadata.isFile())) {
+ if ((await inspectOptionalPath(destination, label))?.isFile() === false) {
throw new Error(label + ": destination is not a regular file.");
}
return destination;
@@ -338,27 +335,16 @@ function validateArtifactComponents(
}
}
-export async function requireArtifactRoot(
+export function requireArtifactRoot(
artifactRoot: string,
label: string,
): Promise<string> {
if (!artifactRoot || !isAbsolute(artifactRoot)) {
- throw new Error(
- label + ": artifact context must have an absolute bound root.",
+ return Promise.reject(
+ new Error(label + ": artifact context must have an absolute bound root."),
);
}
- const requested = resolve(artifactRoot);
- const metadata = await fs.lstat(requested).catch(() => undefined);
- if (!metadata || metadata.isSymbolicLink() || !metadata.isDirectory()) {
- throw new Error(
- label + ": artifact context is not a safe regular directory.",
- );
- }
- try {
- return await fs.realpath(requested);
- } catch {
- throw new Error(label + ": artifact context cannot be resolved.");
- }
+ return canonicalDirectory(artifactRoot, label + ": artifact context");
}
async function inspectOptionalPath(
diff --git a/plugins/codex-security/mcp-app/src/artifact-scan-draft.ts b/plugins/codex-security/mcp-app/src/artifact-scan-draft.ts
index 9e5793e98..d0e661a41 100644
--- a/plugins/codex-security/mcp-app/src/artifact-scan-draft.ts
+++ b/plugins/codex-security/mcp-app/src/artifact-scan-draft.ts
@@ -1,3 +1,4 @@
+import type { JsonObject } from "./types.js";
import { isRecord as isObject } from "./record.js";
import { createHash, randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
@@ -21,8 +22,6 @@ import {
} from "./artifact-schema-loader.js";
import { saveThreatModelDocument } from "./threat-model-document.js";
-type JsonObject = Record<string, unknown>;
-
export interface ScanDraftInput {
scanId: string;
complete?: boolean;
@@ -1126,10 +1125,7 @@ async function readSavedCheckpoints(
let checkpointRoot = join(context.root, "checkpoints");
const checkpointRootMetadata = await lstatIfExists(checkpointRoot);
if (checkpointRootMetadata === undefined) return [];
- if (
- checkpointRootMetadata.isSymbolicLink() ||
- !checkpointRootMetadata.isDirectory()
- ) {
+ if (!checkpointRootMetadata.isDirectory()) {
throw new Error(
`scan checkpoint: ${kind} checkpoint set is not a safe directory.`,
);
@@ -1165,7 +1161,7 @@ async function readSavedCheckpoints(
for (const entry of entries) {
const checkpointPath = join(checkpointRoot, entry.name);
const checkpointMetadata = await fs.lstat(checkpointPath);
- if (checkpointMetadata.isSymbolicLink() || !checkpointMetadata.isFile()) {
+ if (!checkpointMetadata.isFile()) {
throw new Error(
`scan checkpoint: ${kind} checkpoint is not a safe file.`,
);
@@ -1326,7 +1322,7 @@ async function readArchivedWorkerCheckpoints(
const attemptsRoot = join(workerRoot, "attempts");
const attemptsMetadata = await lstatIfExists(attemptsRoot);
if (attemptsMetadata === undefined) return [];
- if (attemptsMetadata.isSymbolicLink() || !attemptsMetadata.isDirectory()) {
+ if (!attemptsMetadata.isDirectory()) {
throw new Error(
"scan checkpoint: archived attempts are not a safe directory.",
);
@@ -1345,10 +1341,11 @@ async function readArchivedWorkerCheckpoints(
const attempts = (
await fs.readdir(canonicalAttemptsRoot, { withFileTypes: true })
)
- .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
+ .filter((entry) => entry.isDirectory())
.sort(
(left, right) =>
- archivedAttemptNumber(right.name) - archivedAttemptNumber(left.name) ||
+ Number(/^attempt-(\d+)$/.exec(right.name)?.[1] ?? -1) -
+ Number(/^attempt-(\d+)$/.exec(left.name)?.[1] ?? -1) ||
right.name.localeCompare(left.name),
);
for (const attempt of attempts) {
@@ -1382,7 +1379,7 @@ async function readArchivedWorkerCheckpoints(
join(attemptRoot, "result.json"),
);
if (resultMetadata !== undefined) {
- if (resultMetadata.isSymbolicLink() || !resultMetadata.isFile()) {
+ if (!resultMetadata.isFile()) {
throw new Error("scan checkpoint: archived result is not a safe file.");
}
const saved = await readArtifactTextWithMetadata(
@@ -1436,11 +1433,6 @@ async function readArchivedWorkerCheckpoints(
return archived;
}
-function archivedAttemptNumber(name: string): number {
- const match = /^attempt-(\d+)$/.exec(name);
- return match ? Number(match[1]) : -1;
-}
-
async function lstatIfExists(
path: string,
): Promise<Awaited<ReturnType<typeof fs.lstat>> | undefined> {
@@ -2241,29 +2233,27 @@ function buildScope(
): JsonObject {
const includePaths = trustedScope.requiredIncludePaths;
const excludePaths = trustedScope.requiredExcludePaths;
- const resolvedIncludePaths =
- includePaths === undefined
- ? [
- typeof trustedScope.requestedPath === "string"
- ? trustedScope.requestedPath
- : (context.scope ?? "."),
- ]
- : requireTextArray(
- includePaths,
- "scan draft: authoritative included scope",
- );
- const resolvedExcludePaths =
- excludePaths === undefined
- ? []
- : requireTextArray(
- excludePaths,
- "scan draft: authoritative excluded scope",
- );
return {
...semanticScope,
- includePaths: resolvedIncludePaths,
- excludePaths: resolvedExcludePaths,
+ includePaths:
+ includePaths === undefined
+ ? [
+ typeof trustedScope.requestedPath === "string"
+ ? trustedScope.requestedPath
+ : (context.scope ?? "."),
+ ]
+ : requireTextArray(
+ includePaths,
+ "scan draft: authoritative included scope",
+ ),
+ excludePaths:
+ excludePaths === undefined
+ ? []
+ : requireTextArray(
+ excludePaths,
+ "scan draft: authoritative excluded scope",
+ ),
};
}
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.ts
index 3dacd96df..121359c1c 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
@@ -1,5 +1,6 @@
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { ZodType } from "zod/v4";
+import type { JsonObject as JsonRecord } from "../types.js";
import {
createScanArtifactContext,
type ArtifactContext,
@@ -52,8 +53,6 @@ import {
type ArtifactLocation,
} from "../artifact-storage.js";
-type JsonRecord = Record<string, unknown>;
-
export interface CompactArtifactToolOptions {
runWorkbench: RunArtifactWorkbench;
pluginRoot: string;
diff --git a/plugins/codex-security/mcp-app/src/server/handoff-tools.ts b/plugins/codex-security/mcp-app/src/server/handoff-tools.ts
index 863850c81..0a68592d0 100644
--- a/plugins/codex-security/mcp-app/src/server/handoff-tools.ts
+++ b/plugins/codex-security/mcp-app/src/server/handoff-tools.ts
@@ -1,13 +1,11 @@
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import * as z from "zod/v4";
-import type { ScanResults } from "../types.js";
-
-type JsonObject = Record<string, unknown>;
+import type { JsonObject } from "../types.js";
export interface HandoffWorkspaceState extends JsonObject {
id: string;
- results?: ScanResults & JsonObject;
+ results?: JsonObject;
setup: {
submitted: boolean;
};
diff --git a/plugins/codex-security/mcp-app/src/types.ts b/plugins/codex-security/mcp-app/src/types.ts
index 6808e8f49..84f16550a 100644
--- a/plugins/codex-security/mcp-app/src/types.ts
+++ b/plugins/codex-security/mcp-app/src/types.ts
@@ -1,49 +1 @@
-export type Mode = "diff" | "standard" | "deep";
-export type DiffTargetKind = "working_tree" | "commit" | "range";
export type JsonObject = Record<string, unknown>;
-
-export interface DiffTarget {
- baseRevision?: string;
- contentDigest?: string;
- headRevision?: string;
- kind: DiffTargetKind;
-}
-
-export interface ScanArtifacts {
- coverage?: string;
- findings?: string;
- manifest?: string;
- markdownReport?: string;
- sarifReport?: string;
- threatModel?: string;
-}
-
-export interface ScanResults {
- artifacts: ScanArtifacts;
- canceledAt?: string;
- diffTarget?: DiffTarget;
- findingCount: number;
- findings: JsonObject[];
- findingsTruncated?: boolean;
- failureMessage?: string;
- handoffClaimedAt?: string;
- handoffClaimToken?: string;
- handoffStatus: "delivered" | "pending";
- mode: Mode;
- progress?: JsonObject;
- remediationAvailable?: boolean;
- remediationUnavailableReason?: string;
- resultsRecoveryNeeded: boolean;
- scanDir: string;
- scanId: string;
- scope?: string;
- severityCounts?: Record<string, number>;
- targetPath: string;
- targetRevision?: string;
- targetSummary?: string | null;
- threatModelAvailable: boolean;
- threatModelPath?: string;
- threatModelProvenance?: JsonObject;
- updatedAt?: string;
- userContext?: string;
-}
diff --git a/plugins/codex-security/mcp-app/tests/support/reducer-paging/controlled-code-mode.mjs b/plugins/codex-security/mcp-app/tests/support/reducer-paging/controlled-code-mode.mjs
index 6ab985280..7af70e079 100644
--- a/plugins/codex-security/mcp-app/tests/support/reducer-paging/controlled-code-mode.mjs
+++ b/plugins/codex-security/mcp-app/tests/support/reducer-paging/controlled-code-mode.mjs
@@ -1,8 +1,8 @@
+import { temporaryDirectory } from "../temporary-directories.mjs";
import { spawn } from "node:child_process";
-import { mkdir, mkdtemp, rm } from "node:fs/promises";
+import { mkdir, rm } from "node:fs/promises";
import { createServer } from "node:http";
import { createRequire } from "node:module";
-import { tmpdir } from "node:os";
import path from "node:path";
function responseEvents(id, item) {
@@ -41,9 +41,7 @@ export async function runControlledCodeMode({
"bin",
"codex.js",
);
- const fixtureRoot = await mkdtemp(
- path.join(tmpdir(), "codex-controlled-ipc-"),
- );
+ const fixtureRoot = await temporaryDirectory("codex-controlled-ipc-");
const codexHome = path.join(fixtureRoot, "home");
const toolOutputs = new Map();
const serverErrors = [];
diff --git a/plugins/codex-security/mcp-app/tests/support/reducer-paging/deep-reducer-paging-fixture.mjs b/plugins/codex-security/mcp-app/tests/support/reducer-paging/deep-reducer-paging-fixture.mjs
index 293f18349..60a76de6c 100644
--- a/plugins/codex-security/mcp-app/tests/support/reducer-paging/deep-reducer-paging-fixture.mjs
+++ b/plugins/codex-security/mcp-app/tests/support/reducer-paging/deep-reducer-paging-fixture.mjs
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { mkdir, readFile, realpath, writeFile } from "node:fs/promises";
import path from "node:path";
+import { sourceReferences } from "../source-references.mjs";
// This is the existing code-mode transport ceiling, used only to size the eval.
const IPC_FRAME_LIMIT_BYTES = 64 * 1024 * 1024;
@@ -103,13 +104,7 @@ export async function createReducerPagingFixture(root) {
workerId,
result: {
...result,
- findings: currentFindings.map((value, index) => ({
- ...value,
- provenance: {
- ...value.provenance,
- sourceFindingIds: [`${workerId}:${index}`],
- },
- })),
+ findings: currentFindings.map(sourceReferences({ id: workerId })),
},
},
],
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 7d22a9485..ad9a501f9 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
@@ -54,9 +54,16 @@ export async function runReducerPagingEval({
const { renderDedupPrompt } = await import(
pathToFileURL(promptModulePath).href
);
+ const claimedWorkerIds = fixture.context.deepReducer.claimedWorkers.map(
+ (worker) => worker.id,
+ );
const prompt = renderDedupPrompt({
reducerLabel: "paging-eval",
- discoveries: fixture.context.deepReducer.claimedWorkers,
+ claimedWorkerIds,
+ });
+ assert.deepEqual(JSON.parse(prompt.match(/```json\n([\s\S]*?)\n```/)[1]), {
+ reducerLabel: "paging-eval",
+ claimedWorkerIds,
});
const mcpServers = {
cs_artifacts: {
diff --git a/plugins/codex-security/mcp-app/tests/support/source-references.mjs b/plugins/codex-security/mcp-app/tests/support/source-references.mjs
new file mode 100644
index 000000000..037fab583
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/support/source-references.mjs
@@ -0,0 +1,7 @@
+export const sourceReferences = (worker) => (finding, index) => ({
+ ...finding,
+ provenance: {
+ ...finding.provenance,
+ sourceFindingIds: [`${worker.id}:${index}`],
+ },
+});
diff --git a/plugins/codex-security/mcp-app/tests/support/temporary-directories.d.mts b/plugins/codex-security/mcp-app/tests/support/temporary-directories.d.mts
new file mode 100644
index 000000000..6b4a225db
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/support/temporary-directories.d.mts
@@ -0,0 +1,9 @@
+export function createTemporaryDirectories(canonicalize?: boolean): {
+ create(prefix: string): Promise<string>;
+ cleanup(): Promise<void[]>;
+};
+
+export function temporaryDirectory(
+ prefix: string,
+ canonicalize?: boolean,
+): Promise<string>;
diff --git a/plugins/codex-security/mcp-app/tests/support/temporary-directories.mjs b/plugins/codex-security/mcp-app/tests/support/temporary-directories.mjs
new file mode 100644
index 000000000..89d977306
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/support/temporary-directories.mjs
@@ -0,0 +1,24 @@
+import { mkdtemp, realpath, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+export function createTemporaryDirectories(canonicalize = false) {
+ const roots = [];
+ return {
+ async create(prefix) {
+ const root = await temporaryDirectory(prefix, canonicalize);
+ roots.push(root);
+ return root;
+ },
+ cleanup() {
+ return Promise.all(
+ roots.map((root) => rm(root, { recursive: true, force: true })),
+ );
+ },
+ };
+}
+
+export async function temporaryDirectory(prefix, canonicalize = false) {
+ const directory = await mkdtemp(join(tmpdir(), prefix));
+ return canonicalize ? realpath(directory) : directory;
+}
diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_attack_path.mjs b/plugins/codex-security/mcp-app/tests/test_artifact_attack_path.mjs
index 600183892..5546c6911 100644
--- a/plugins/codex-security/mcp-app/tests/test_artifact_attack_path.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_artifact_attack_path.mjs
@@ -1,13 +1,6 @@
+import { createTemporaryDirectories } from "./support/temporary-directories.mjs";
import assert from "node:assert/strict";
-import {
- mkdir,
- mkdtemp,
- readFile,
- realpath,
- rm,
- writeFile,
-} from "node:fs/promises";
-import { tmpdir } from "node:os";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { importSource } from "./import-module.mjs";
@@ -19,7 +12,7 @@ const {
);
const scanId = "11111111-1111-4111-8111-111111111111";
-const temporaryRoots = [];
+const temporaryDirectories = createTemporaryDirectories(true);
try {
await testSchemaMatchesDocumentedAttackPathDecisions();
@@ -32,14 +25,7 @@ try {
await testMalformedLedgerIsNotReplaced();
await testEmptyLedgerAcceptsAnEmptyBatch();
} finally {
- await Promise.all(
- temporaryRoots.map((root) =>
- rm(root, {
- recursive: true,
- force: true,
- }),
- ),
- );
+ await temporaryDirectories.cleanup();
}
async function testSchemaMatchesDocumentedAttackPathDecisions() {
@@ -293,15 +279,9 @@ async function testEmptyLedgerAcceptsAnEmptyBatch() {
}
async function createFixture(label, originalRows) {
- const root = await realpath(
- await mkdtemp(
- path.join(
- tmpdir(),
- `codex-security-attack-path-${label.replace(/\s+/gu, "-")}-`,
- ),
- ),
+ const root = await temporaryDirectories.create(
+ `codex-security-attack-path-${label.replace(/\s+/gu, "-")}-`,
);
- temporaryRoots.push(root);
const ledgerPath = path.join(
root,
"artifacts",
@@ -374,10 +354,7 @@ function attackPath(decision = "reportable") {
async function readRows(fixture) {
const content = await readFile(fixture.ledgerPath, "utf8");
- return content
- .split(/\r?\n/u)
- .filter(Boolean)
- .map((line) => JSON.parse(line));
+ return content.split(/\r?\n/u).filter(Boolean).map(JSON.parse);
}
async function assertUnchanged(fixture) {
diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer.mjs b/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer.mjs
index 3f7a17725..257dcef2f 100644
--- a/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer.mjs
@@ -1,15 +1,8 @@
+import { sourceReferences } from "./support/source-references.mjs";
+import { temporaryDirectory } from "./support/temporary-directories.mjs";
import { finding, scanId, workerDraft } from "./scan-draft-fixture.mjs";
import assert from "node:assert/strict";
-import {
- mkdir,
- mkdtemp,
- readFile,
- readdir,
- realpath,
- rm,
- writeFile,
-} from "node:fs/promises";
-import { tmpdir } from "node:os";
+import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { importSource } from "./import-module.mjs";
@@ -56,9 +49,7 @@ assert.equal(
false,
);
-const root = await realpath(
- await mkdtemp(path.join(tmpdir(), "codex-security-deep-reducer-")),
-);
+const root = await temporaryDirectory("codex-security-deep-reducer-", true);
try {
const scanRoot = path.join(root, "scan");
const workersRoot = path.join(
@@ -536,13 +527,7 @@ function withSourceRefs(worker) {
const { coverage: _coverage, ...result } = worker.result;
return {
...result,
- findings: worker.result.findings.map((finding, index) => ({
- ...finding,
- provenance: {
- ...finding.provenance,
- sourceFindingIds: [`${worker.id}:${index}`],
- },
- })),
+ findings: worker.result.findings.map(sourceReferences(worker)),
};
}
diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer_pages.mjs b/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer_pages.mjs
index b5ce6f922..e74510204 100644
--- a/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer_pages.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_artifact_deep_reducer_pages.mjs
@@ -1,13 +1,6 @@
+import { temporaryDirectory } from "./support/temporary-directories.mjs";
import assert from "node:assert/strict";
-import {
- mkdir,
- mkdtemp,
- readFile,
- realpath,
- rm,
- writeFile,
-} from "node:fs/promises";
-import { tmpdir } from "node:os";
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { importModule } from "./import-module.mjs";
@@ -45,9 +38,7 @@ assert.equal(
);
const scanId = "7fc17317-9594-49e0-b06a-d72fd7e14bba";
-const root = await realpath(
- await mkdtemp(path.join(tmpdir(), "reducer-pages-")),
-);
+const root = await temporaryDirectory("reducer-pages-", true);
try {
const scanRoot = path.join(root, "scan");
const workerRoot = path.join(
diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_discovery.mjs b/plugins/codex-security/mcp-app/tests/test_artifact_discovery.mjs
index 5938d163a..8a582d4c6 100644
--- a/plugins/codex-security/mcp-app/tests/test_artifact_discovery.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_artifact_discovery.mjs
@@ -1,16 +1,13 @@
+import { createTemporaryDirectories } from "./support/temporary-directories.mjs";
import assert from "node:assert/strict";
import {
copyFile,
mkdir,
- mkdtemp,
readFile,
readdir,
- realpath,
- rm,
symlink,
writeFile,
} from "node:fs/promises";
-import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
@@ -86,9 +83,8 @@ assert.deepEqual(toolSchemas.$defs.workbenchListCandidatesInput.required, [
"scanId",
]);
-const root = await realpath(
- await mkdtemp(path.join(tmpdir(), "security-artifact-discovery-")),
-);
+const rootDirectories = createTemporaryDirectories(true);
+const root = await rootDirectories.create("security-artifact-discovery-");
const runtimePluginRoot = path.join(root, "plugin");
try {
await build({
@@ -134,7 +130,7 @@ try {
await verifyMalformedLedgerIsNotModified(root, repoRoot);
await verifySymlinkRejection(root, repoRoot);
} finally {
- await rm(root, { recursive: true, force: true });
+ await rootDirectories.cleanup();
}
async function verifyInputSchema() {
@@ -446,10 +442,7 @@ async function verifyReaderPreservesSharedPhaseRecords(context) {
"candidate_ledger.jsonl",
);
const original = await readFile(destination, "utf8");
- const rows = original
- .trimEnd()
- .split("\n")
- .map((line) => JSON.parse(line));
+ const rows = original.trimEnd().split("\n").map(JSON.parse);
rows[0].validation = {
disposition: "reportable",
evidence: "The existing validation phase confirmed the affected code path.",
@@ -458,10 +451,7 @@ async function verifyReaderPreservesSharedPhaseRecords(context) {
disposition: "reportable",
evidence: "The existing attack-path phase confirmed request reachability.",
};
- await writeFile(
- destination,
- `${rows.map((row) => JSON.stringify(row)).join("\n")}\n`,
- );
+ await writeFile(destination, `${rows.map(JSON.stringify).join("\n")}\n`);
const page = await listCodexSecurityCandidates({}, context);
assert.deepEqual(page.rows, rows);
diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_foundation.mjs b/plugins/codex-security/mcp-app/tests/test_artifact_foundation.mjs
index 5a23f5727..0cd79c660 100644
--- a/plugins/codex-security/mcp-app/tests/test_artifact_foundation.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_artifact_foundation.mjs
@@ -18,12 +18,25 @@ const compiled = await build({
entryPoints: [
new URL("../src/artifact-io.ts", import.meta.url).pathname,
new URL("../src/artifact-context.ts", import.meta.url).pathname,
+ new URL("../artifact-writer-main.ts", import.meta.url).pathname,
new URL("../src/artifact-schema-loader.ts", import.meta.url).pathname,
],
format: "esm",
outdir: "codex-security-artifact-foundation",
platform: "node",
write: false,
+ plugins: [
+ {
+ name: "observe-worker-context",
+ setup(builder) {
+ builder.onLoad({ filter: /compact-artifact-tools\.ts$/ }, () => ({
+ contents:
+ "export function registerCompactWorkerArtifactTools(server, context) { server.context = context; }",
+ loader: "js",
+ }));
+ },
+ },
+ ],
});
const modules = new Map(
compiled.outputFiles.map((file) => [
@@ -34,6 +47,7 @@ const modules = new Map(
);
const io = await import(modules.get("artifact-io.js"));
const contextApi = await import(modules.get("artifact-context.js"));
+const writerApi = await import(modules.get("artifact-writer-main.js"));
const schemas = await import(modules.get("artifact-schema-loader.js"));
const fixture = await realpath(
await mkdtemp(path.join(tmpdir(), "codex-security-artifact-foundation-")),
@@ -272,12 +286,14 @@ async function testWorkerStandardLayout() {
const root = path.join(fixture, "worker", "output");
const repoRoot = path.join(fixture, "repository");
await mkdir(root, { recursive: true });
- const context = await contextApi.createWorkerArtifactContext({
- root,
- repoRoot,
- scope: ".",
- pluginRoot: "/fixture/plugin",
- });
+ const environment = {
+ CODEX_SECURITY_ARTIFACT_ROOT: root,
+ CODEX_SECURITY_REPO_ROOT: repoRoot,
+ CODEX_SECURITY_SCOPE: ".",
+ CODEX_SECURITY_PLUGIN_ROOT: "/fixture/plugin",
+ };
+ const { context } =
+ await writerApi.createCodexSecurityArtifactWriterServer(environment);
const inventory = await io.artifactDestination(
context,
["artifacts", "02_discovery", "in_scope_files.txt"],
@@ -310,24 +326,26 @@ async function testWorkerStandardLayout() {
assert.equal(context.scope, ".");
await assert.rejects(
- contextApi.createWorkerArtifactContext({
- root,
- repoRoot,
- deepReducer: { scanRoot: root, claimedWorkers: [] },
+ writerApi.createCodexSecurityArtifactWriterServer({
+ ...environment,
+ CODEX_SECURITY_REDUCER_CONTEXT_JSON: JSON.stringify({
+ scanRoot: root,
+ claimedWorkers: [],
+ }),
}),
- /reducer-bound context/,
- );
- const reducer = await contextApi.createWorkerArtifactContext({
- root,
- repoRoot,
- layout: "reducer",
- deepReducer: {
- scanRoot: root,
- claimedWorkers: [
- { id: "worker-1", resultPath: path.join(root, "worker-result.json") },
- ],
- },
- });
+ /coordinator-bound reducer context/,
+ );
+ const { context: reducer } =
+ await writerApi.createCodexSecurityArtifactWriterServer({
+ ...environment,
+ CODEX_SECURITY_ARTIFACT_LAYOUT: "reducer",
+ CODEX_SECURITY_REDUCER_CONTEXT_JSON: JSON.stringify({
+ scanRoot: root,
+ claimedWorkers: [
+ { id: "worker-1", resultPath: path.join(root, "worker-result.json") },
+ ],
+ }),
+ });
assert.equal(reducer.layout, "reducer");
assert.equal(reducer.deepReducer.claimedWorkers[0].id, "worker-1");
}
@@ -480,6 +498,8 @@ async function testUnsafeArtifacts() {
const outside = path.join(fixture, "outside");
await mkdir(outside, { recursive: true });
+ const outsideFile = path.join(outside, "candidate_ledger.jsonl");
+ await writeFile(outsideFile, "outside remains unchanged\n");
const symlinkPath = path.join(context.root, "linked");
await symlink(outside, symlinkPath);
await assert.rejects(
@@ -491,12 +511,20 @@ async function testUnsafeArtifacts() {
/not a regular directory/,
);
+ assert.equal(
+ await readFile(outsideFile, "utf8"),
+ "outside remains unchanged\n",
+ );
const linkedFile = path.join(context.root, "linked.json");
- await symlink(path.join(outside, "outside.json"), linkedFile);
+ await symlink(outsideFile, linkedFile);
await assert.rejects(
io.artifactDestination(context, ["linked.json"], "scan_manifest"),
/not a regular file/,
);
+ assert.equal(
+ await readFile(outsideFile, "utf8"),
+ "outside remains unchanged\n",
+ );
const linkedRoot = path.join(fixture, "linked-root");
await symlink(context.root, linkedRoot);
diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_inventory.mjs b/plugins/codex-security/mcp-app/tests/test_artifact_inventory.mjs
index db5265d14..6a759d39c 100644
--- a/plugins/codex-security/mcp-app/tests/test_artifact_inventory.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_artifact_inventory.mjs
@@ -1,22 +1,13 @@
+import { createTemporaryDirectories } from "./support/temporary-directories.mjs";
import assert from "node:assert/strict";
import { execFile as nodeExecFile } from "node:child_process";
-import {
- mkdir,
- mkdtemp,
- readFile,
- realpath,
- rm,
- symlink,
- unlink,
- writeFile,
-} from "node:fs/promises";
-import { tmpdir } from "node:os";
+import { mkdir, readFile, symlink, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { importSource } from "./import-module.mjs";
const execFile = promisify(nodeExecFile);
-const temporaryRoots = [];
+const temporaryDirectories = createTemporaryDirectories(true);
const inventory = await importSource(
new URL("../src/artifact-inventory.ts", import.meta.url).pathname,
@@ -39,16 +30,13 @@ try {
await testBoundScopeFailurePreservesPreviousInventory();
await testInvalidDiffTargetPreservesPreviousInventory();
} finally {
- await Promise.all(
- temporaryRoots.map((root) => rm(root, { force: true, recursive: true })),
- );
+ await temporaryDirectories.cleanup();
}
async function testSchemasAreBoundAndExact() {
const scanId = "f84c8312-a602-4660-8e01-518a176cd75a";
const prepare = inventory.prepareReviewItemsInputSchema;
const parent = inventory.reviewItemsReaderInputSchema;
- const worker = inventory.reviewItemsWorkerReaderInputSchema;
assert.equal(prepare.safeParse({ scanId }).success, true);
assert.equal(
@@ -65,33 +53,6 @@ async function testSchemasAreBoundAndExact() {
assert.equal(parent.safeParse({ scanId, limit: 0 }).success, false);
assert.equal(parent.safeParse({ scanId, limit: 1001 }).success, false);
assert.equal(parent.safeParse({ scanId, cursor: "-1" }).success, false);
- assert.equal(worker.safeParse({ limit: 2, cursor: "0" }).success, true);
- assert.equal(worker.safeParse({ scanId }).success, false);
- assert.equal(worker.safeParse({ scope: "." }).success, false);
- assert.equal(
- inventory.prepareReviewItemsOutputSchema.safeParse({ reviewItemsTotal: 0 })
- .success,
- true,
- );
- assert.equal(
- inventory.prepareReviewItemsOutputSchema.safeParse({
- reviewItemsTotal: 0,
- path: "leaked",
- }).success,
- false,
- );
- assert.equal(
- inventory.reviewItemsReaderOutputSchema.safeParse({
- items: [{ path: "src/a.ts" }],
- }).success,
- true,
- );
- assert.equal(
- inventory.reviewItemsReaderOutputSchema.safeParse({
- items: [{ path: "src/a.ts", area: "src" }],
- }).success,
- false,
- );
}
async function testPrepareUsesTheExistingStandardGenerator() {
@@ -462,10 +423,9 @@ async function testInvalidDiffTargetPreservesPreviousInventory() {
}
async function createFixture(label) {
- const root = await realpath(
- await mkdtemp(path.join(tmpdir(), "security-artifact-inventory-")),
+ const root = await temporaryDirectories.create(
+ "security-artifact-inventory-",
);
- temporaryRoots.push(root);
const fixtureRoot = path.join(root, label);
const repoRoot = path.join(fixtureRoot, "repository");
const scanRoot = path.join(fixtureRoot, "scan");
diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_scan_draft.mjs b/plugins/codex-security/mcp-app/tests/test_artifact_scan_draft.mjs
index 952ad2785..c95bcb9c2 100644
--- a/plugins/codex-security/mcp-app/tests/test_artifact_scan_draft.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_artifact_scan_draft.mjs
@@ -1,19 +1,18 @@
+import { mock } from "node:test";
+import { temporaryDirectory } from "./support/temporary-directories.mjs";
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { promises as fsPromises } from "node:fs";
import {
mkdir,
- mkdtemp,
readdir,
readFile,
- realpath,
rename,
rm,
symlink,
utimes,
writeFile,
} from "node:fs/promises";
-import { tmpdir } from "node:os";
import path from "node:path";
import {
claimToken,
@@ -32,9 +31,9 @@ const {
scanDraftInputSchema,
} = draftApi;
-const root = await realpath(
- await mkdtemp(path.join(tmpdir(), "codex-security-scan-draft-")),
-);
+const surfaceDisposition = ({ id, disposition }) => ({ id, disposition });
+
+const root = await temporaryDirectory("codex-security-scan-draft-", true);
try {
const { context } = draftFixture(root, "standard");
@@ -337,14 +336,9 @@ try {
...workerInput,
complete: false,
});
- const {
- scope: _scope,
- threatModel: _threatModel,
- ...workerWithoutContext
- } = workerInput;
await recordCodexSecurityWorkerScanDraft(
carriedContext,
- workerWithoutContext,
+ withoutScanContext(workerInput),
);
const carriedWorker = JSON.parse(
await readFile(path.join(carriedContextRoot, "result.json"), "utf8"),
@@ -394,13 +388,9 @@ try {
const progressedCoverage = JSON.parse(
await readFile(path.join(coverageProgressRoot, "result.json"), "utf8"),
).coverage;
- assert.deepEqual(
- progressedCoverage.surfaces.map(({ id, disposition }) => ({
- id,
- disposition,
- })),
- [{ id: "surface-archive", disposition: "reported" }],
- );
+ assert.deepEqual(progressedCoverage.surfaces.map(surfaceDisposition), [
+ { id: "surface-archive", disposition: "reported" },
+ ]);
assert.deepEqual(progressedCoverage.openQuestions ?? [], []);
assert.equal(progressedCoverage.completeness, "complete");
@@ -719,14 +709,9 @@ try {
true,
);
- const {
- scope: _parentScope,
- threatModel: _parentThreatModel,
- ...parentWithoutContext
- } = input;
await recordCodexSecurityScanDraft(
{ ...context, root: parentCheckpointRoot },
- parentWithoutContext,
+ withoutScanContext(input),
);
const carriedParentManifest = await readJson(
parentCheckpointRoot,
@@ -866,34 +851,31 @@ try {
"obsolete.json",
);
await writeFile(obsoleteCheckpointPath, "{malformed obsolete checkpoint\n");
- let deepWorkbenchWrites = 0;
+ const deepWorkbenchWrites = mock.fn(async (arguments_) => {
+ assert.deepEqual(arguments_.slice(0, 3), [
+ "write-scan-draft",
+ "--scan-id",
+ scanId,
+ ]);
+ assert.equal(arguments_.includes("--expected-draft-digest"), false);
+ assert.deepEqual(arguments_.slice(-2), ["--claim-token", claimToken]);
+ const draftPath = arguments_[arguments_.indexOf("--draft-path") + 1];
+ const checkpointPath =
+ arguments_[arguments_.indexOf("--checkpoint-path") + 1];
+ const staged = JSON.parse(await readFile(draftPath, "utf8"));
+ const stagedCheckpoint = JSON.parse(await readFile(checkpointPath, "utf8"));
+ assert.deepEqual(staged.findings, acceptedDeepFindings);
+ assert.deepEqual(staged.coverage, acceptedDeepCoverage);
+ assert.deepEqual(stagedCheckpoint.findings, acceptedDeepDraft.findings);
+ assert.equal(stagedCheckpoint.handoffClaimToken, undefined);
+ });
await recordCodexSecurityScanDraftViaWorkbench(
deepParentContext,
acceptedDeepDraft,
- async (arguments_) => {
- deepWorkbenchWrites += 1;
- assert.deepEqual(arguments_.slice(0, 3), [
- "write-scan-draft",
- "--scan-id",
- scanId,
- ]);
- assert.equal(arguments_.includes("--expected-draft-digest"), false);
- assert.deepEqual(arguments_.slice(-2), ["--claim-token", claimToken]);
- const draftPath = arguments_[arguments_.indexOf("--draft-path") + 1];
- const checkpointPath =
- arguments_[arguments_.indexOf("--checkpoint-path") + 1];
- const staged = JSON.parse(await readFile(draftPath, "utf8"));
- const stagedCheckpoint = JSON.parse(
- await readFile(checkpointPath, "utf8"),
- );
- assert.deepEqual(staged.findings, acceptedDeepFindings);
- assert.deepEqual(staged.coverage, acceptedDeepCoverage);
- assert.deepEqual(stagedCheckpoint.findings, acceptedDeepDraft.findings);
- assert.equal(stagedCheckpoint.handoffClaimToken, undefined);
- },
+ deepWorkbenchWrites,
);
assert.equal(
- deepWorkbenchWrites,
+ deepWorkbenchWrites.mock.callCount(),
1,
"terminal Deep drafts still publish through the workbench lock despite obsolete malformed checkpoints",
);
@@ -1782,23 +1764,22 @@ try {
assert.equal(retried.status, "draft_written");
const conflictAbort = new AbortController();
- let abortedConflictAttempts = 0;
+ const abortedConflictAttempts = mock.fn(async () => {
+ conflictAbort.abort(new Error("draft publication canceled"));
+ throw Object.assign(new Error("scan_draft_conflict"), {
+ code: "scan_draft_conflict",
+ });
+ });
await assert.rejects(
recordCodexSecurityScanDraft(
context,
input,
- async () => {
- abortedConflictAttempts += 1;
- conflictAbort.abort(new Error("draft publication canceled"));
- throw Object.assign(new Error("scan_draft_conflict"), {
- code: "scan_draft_conflict",
- });
- },
+ abortedConflictAttempts,
conflictAbort.signal,
),
/draft publication canceled/,
);
- assert.equal(abortedConflictAttempts, 1);
+ assert.equal(abortedConflictAttempts.mock.callCount(), 1);
const monotonicRoot = path.join(root, "monotonic-final-draft");
await mkdir(monotonicRoot);
@@ -1849,13 +1830,9 @@ try {
);
}
assert.notEqual(staged.manifest.scan.complete, false);
- assert.deepEqual(
- staged.coverage.surfaces.map(({ id, disposition }) => ({
- id,
- disposition,
- })),
- [{ id: "surface-archive", disposition: "reported" }],
- );
+ assert.deepEqual(staged.coverage.surfaces.map(surfaceDisposition), [
+ { id: "surface-archive", disposition: "reported" },
+ ]);
},
);
assert.equal(monotonicWrites, 2);
@@ -1884,13 +1861,8 @@ try {
path.join(archivedRetryRoot, "attempts", "attempt-01"),
);
await mkdir(archivedRetryOutput);
- const {
- scope: _archivedScope,
- threatModel: _archivedThreatModel,
- ...replacementAttempt
- } = workerInput;
await recordCodexSecurityWorkerScanDraft(archivedRetryContext, {
- ...replacementAttempt,
+ ...withoutScanContext(workerInput),
findings: [],
});
const archivedRetryResult = JSON.parse(
@@ -1947,7 +1919,7 @@ try {
);
await mkdir(archivedResolutionOutput);
await recordCodexSecurityWorkerScanDraft(archivedResolutionContext, {
- ...replacementAttempt,
+ ...withoutScanContext(workerInput),
findings: [],
});
const archivedResolutionResult = JSON.parse(
@@ -2023,7 +1995,7 @@ try {
);
await mkdir(repeatedCheckpointOutput);
await recordCodexSecurityWorkerScanDraft(repeatedCheckpointContext, {
- ...replacementAttempt,
+ ...withoutScanContext(workerInput),
findings: [],
});
const repeatedCheckpointResult = JSON.parse(
@@ -2053,7 +2025,7 @@ try {
);
await mkdir(multiAttemptOutput);
await recordCodexSecurityWorkerScanDraft(multiAttemptContext, {
- ...replacementAttempt,
+ ...withoutScanContext(workerInput),
complete: false,
findings: [],
coverage: {
@@ -2069,7 +2041,7 @@ try {
);
await mkdir(multiAttemptOutput);
await recordCodexSecurityWorkerScanDraft(multiAttemptContext, {
- ...replacementAttempt,
+ ...withoutScanContext(workerInput),
findings: [],
});
const multiAttemptResult = JSON.parse(
@@ -2111,7 +2083,7 @@ try {
);
await mkdir(malformedArchivedOutput);
await recordCodexSecurityWorkerScanDraft(malformedArchivedContext, {
- ...replacementAttempt,
+ ...withoutScanContext(workerInput),
findings: [],
});
assert.deepEqual(
@@ -2146,7 +2118,7 @@ try {
await mkdir(crossScanRetryOutput);
await assert.rejects(
recordCodexSecurityWorkerScanDraft(crossScanRetryContext, {
- ...replacementAttempt,
+ ...withoutScanContext(workerInput),
findings: [],
}),
/scanId does not match the authoritative workbench scan/u,
@@ -3463,3 +3435,11 @@ async function recordFreshScanDraft(context, input) {
]);
return recordCodexSecurityScanDraft(context, input);
}
+
+function withoutScanContext({
+ scope: _scope,
+ threatModel: _threatModel,
+ ...input
+}) {
+ return input;
+}
diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_storage.mjs b/plugins/codex-security/mcp-app/tests/test_artifact_storage.mjs
index 030004e83..048974c9e 100644
--- a/plugins/codex-security/mcp-app/tests/test_artifact_storage.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_artifact_storage.mjs
@@ -1,8 +1,8 @@
+import { temporaryDirectory } from "./support/temporary-directories.mjs";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import {
mkdir,
- mkdtemp,
readFile,
realpath,
rm,
@@ -17,9 +17,7 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
import { applicationRoot, buildServer } from "./build-server.mjs";
-const fixture = await realpath(
- await mkdtemp(path.join(tmpdir(), "codex-security-storage-test-")),
-);
+const fixture = await temporaryDirectory("codex-security-storage-test-", true);
const stateRoot = path.join(fixture, "state");
const repository = path.join(fixture, "repository");
const bundle = path.join(fixture, "server.cjs");
diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_validation_phase.mjs b/plugins/codex-security/mcp-app/tests/test_artifact_validation_phase.mjs
index d99107fbe..4146c7fd1 100644
--- a/plugins/codex-security/mcp-app/tests/test_artifact_validation_phase.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_artifact_validation_phase.mjs
@@ -1,15 +1,7 @@
+import { temporaryDirectory } from "./support/temporary-directories.mjs";
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
-import {
- mkdir,
- mkdtemp,
- readFile,
- realpath,
- rm,
- symlink,
- writeFile,
-} from "node:fs/promises";
-import { tmpdir } from "node:os";
+import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { importSource } from "./import-module.mjs";
@@ -93,9 +85,7 @@ assert.equal(
false,
);
-const root = await realpath(
- await mkdtemp(path.join(tmpdir(), "codex-security-validation-phase-")),
-);
+const root = await temporaryDirectory("codex-security-validation-phase-", true);
try {
const context = await scanContext(root, "scan", scanId);
const ledger = path.join(
@@ -297,9 +287,7 @@ async function assertNoMutation(context, ledger, input, expectedError) {
async function writeJsonl(file, rows) {
await writeFile(
file,
- rows.length > 0
- ? `${rows.map((row) => JSON.stringify(row)).join("\n")}\n`
- : "",
+ rows.length > 0 ? `${rows.map(JSON.stringify).join("\n")}\n` : "",
);
}
diff --git a/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.mjs b/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.mjs
index cbdbf33fc..af975d9e5 100644
--- a/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.mjs
@@ -1,4 +1,5 @@
import { gitText } from "../scripts/git.mjs";
+import { temporaryDirectory } from "./support/temporary-directories.mjs";
import { readOnlyParentSandboxState } from "./sandbox-state.mjs";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
@@ -11,7 +12,6 @@ import {
rm,
writeFile,
} from "node:fs/promises";
-import { tmpdir } from "node:os";
import path from "node:path";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
@@ -22,9 +22,7 @@ const pluginRoot = path.resolve(applicationRoot, "..");
const bundledPluginRoot = process.env.CODEX_SECURITY_TEST_PLUGIN_ROOT
? path.resolve(process.env.CODEX_SECURITY_TEST_PLUGIN_ROOT)
: path.resolve(applicationRoot, "../../../sdk/typescript/_bundled_plugin");
-const temporaryRoot = await mkdtemp(
- path.join(tmpdir(), "codex-security-artifact-mcp-"),
-);
+const temporaryRoot = await temporaryDirectory("codex-security-artifact-mcp-");
try {
const runtimeBundle = path.join(temporaryRoot, "server.cjs");
@@ -93,12 +91,7 @@ async function testCompactDiffScanCompletion(bundle, runtimeLabel) {
CODEX_SECURITY_STATE_DIR: stateRoot,
});
const ownerThread = `compact-diff-owner-${runtimeLabel}`;
- const call = (name, arguments_) =>
- client.callTool({
- name,
- arguments: arguments_,
- _meta: { "openai/threadId": ownerThread },
- });
+ const call = toolCaller(client, ownerThread);
try {
const selection = {
@@ -303,12 +296,7 @@ async function testSemanticScanDraftCompletion(bundle, runtimeLabel) {
CODEX_SECURITY_STATE_DIR: stateRoot,
});
const ownerThread = `semantic-draft-owner-${runtimeLabel}`;
- const call = (name, arguments_) =>
- client.callTool({
- name,
- arguments: arguments_,
- _meta: { "openai/threadId": ownerThread },
- });
+ const call = toolCaller(client, ownerThread);
try {
const opened = requireSuccessfulTool(
@@ -904,12 +892,7 @@ async function testClaimedParentArtifactOperations(bundle, runtimeLabel) {
});
const ownerThread = `compact-artifact-owner-${runtimeLabel}`;
const otherThread = `compact-artifact-other-${runtimeLabel}`;
- const call = (name, arguments_, threadId = ownerThread) =>
- client.callTool({
- name,
- arguments: arguments_,
- ...(threadId == null ? {} : { _meta: { "openai/threadId": threadId } }),
- });
+ const call = toolCaller(client, ownerThread);
try {
const opened = requireSuccessfulTool(
@@ -1738,3 +1721,12 @@ async function startClient(bundle, environment) {
await client.connect(transport);
return client;
}
+
+function toolCaller(client, ownerThread) {
+ return (name, arguments_, threadId = ownerThread) =>
+ client.callTool({
+ name,
+ arguments: arguments_,
+ ...(threadId == null ? {} : { _meta: { "openai/threadId": threadId } }),
+ });
+}