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(artifacts): reject non-finite values in retained scan drafts (#1783)

Michael D'Angelo118e2a1a15a4
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 1fdd1bc12..a598dad64 100644
--- a/plugins/codex-security/mcp-app/src/artifact-scan-draft.ts
+++ b/plugins/codex-security/mcp-app/src/artifact-scan-draft.ts
@@ -17,6 +17,7 @@ import {
import { artifactSchemaDocuments } from "./artifact-contracts.js";
import { projectArtifactToolSchema } from "./artifact-schema-loader.js";
import { saveThreatModelDocument } from "./threat-model-document.js";
+import { requireFiniteNumbers } from "./helpers/json.js";
const draftDefinitions = artifactSchemaDocuments["tools/scan-draft"].$defs;
export const scanDraftInputSchema = projectArtifactToolSchema(
@@ -111,6 +112,9 @@ export async function recordCodexSecurityScanDraftViaWorkbench(
trustedScope.filePaths as string[] | undefined,
)
: reconciled.findings;
+ // Coordinator publication also carries retained historical payloads.
+ if (finalDeepDraft && publication === undefined)
+ requireFiniteNumbers({ ...parsed, findings: scopedFindings });
const findings = buildFindings(scopedFindings, context.mode);
const coverage = buildCoverage(
context,
@@ -329,6 +333,7 @@ async function preserveScanDraft(
input: ScanDraftInput,
saveCheckpoint = true,
): Promise<{ input: ScanDraftInput; previousDigest: string }> {
+ requireFiniteNumbers(input);
const currentCheckpointName = scanDraftCheckpointName(input);
const requiresClosureValidation = resolvedDeferred(input.coverage).length > 0;
if (saveCheckpoint && !requiresClosureValidation)
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.ts b/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.ts
index 3421de7a6..b3a99b3ae 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/artifact-validation.ts
@@ -3,6 +3,7 @@ import { dirname, relative, sep } from "node:path";
import type { JsonObject } from "../types.js";
import { artifactSchemaDocuments } from "../artifact-contracts.js";
import { projectArtifactToolSchema } from "../artifact-schema-loader.js";
+import { requireFiniteNumbers } from "../helpers/json.js";
import {
parsePersistedScanDraft,
preserveFindingDetails,
@@ -188,6 +189,18 @@ export function reconcileDeepReduction(
discoveries: DeepReductionSources["discoveries"],
previous: DeepReductionInput | null,
): DeepReductionInput {
+ // Check retained fresh data before merging historical sources. The host
+ // replaces submitted sourceFindings with the original source payloads below.
+ requireFiniteNumbers({
+ ...input,
+ findings: input.findings.map((finding) => ({
+ ...finding,
+ provenance: {
+ ...(finding.provenance as JsonObject),
+ sourceFindings: undefined,
+ },
+ })),
+ });
const result = structuredClone(input);
for (const source of [
...discoveries.map((discovery) => discovery.result),
diff --git a/plugins/codex-security/mcp-app/src/helpers/json.ts b/plugins/codex-security/mcp-app/src/helpers/json.ts
index a6d5ac7bc..c39898d1e 100644
--- a/plugins/codex-security/mcp-app/src/helpers/json.ts
+++ b/plugins/codex-security/mcp-app/src/helpers/json.ts
@@ -1,5 +1,14 @@
export { isRecord as object } from "../record.ts";
+export function requireFiniteNumbers(value: unknown): void {
+ if (typeof value === "number" && !Number.isFinite(value))
+ throw new TypeError(
+ "Stored finding JSON cannot contain non-finite numbers.",
+ );
+ if (value !== null && typeof value === "object")
+ for (const item of Object.values(value)) requireFiniteNumbers(item);
+}
+
export function escapeControls(text: string): string {
return text.replace(/[\p{Cc}\p{Cf}]/gu, (character) => {
const point = character.codePointAt(0)!;
diff --git a/plugins/codex-security/mcp-app/src/workbench/findings.ts b/plugins/codex-security/mcp-app/src/workbench/findings.ts
index 7ef9f0010..01d37bbbc 100644
--- a/plugins/codex-security/mcp-app/src/workbench/findings.ts
+++ b/plugins/codex-security/mcp-app/src/workbench/findings.ts
@@ -1,6 +1,11 @@
import type { DatabaseSync } from "node:sqlite";
import { isDeepStrictEqual } from "node:util";
-import { escapeControls, parseJson, stringifyJson } from "../helpers/json";
+import {
+ escapeControls,
+ parseJson,
+ requireFiniteNumbers,
+ stringifyJson,
+} from "../helpers/json";
import { requireSqliteText } from "./database";
import { transaction } from "./transaction";
@@ -19,15 +24,6 @@ export interface EmbeddedFinding {
class FindingConflict extends Error {}
-function requireFiniteNumbers(value: unknown): void {
- if (typeof value === "number" && !Number.isFinite(value))
- throw new TypeError(
- "Stored finding JSON cannot contain non-finite numbers.",
- );
- if (value !== null && typeof value === "object")
- for (const item of Object.values(value)) requireFiniteNumbers(item);
-}
-
// The fresh document comes from stringifyJson after the command's finite-number
// check. Keep this comparison private: it is not equality for arbitrary JSON pairs.
function storedFindingJsonMatches(previous: string, fresh: string): boolean {
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_reducer_finite_writes.ts b/plugins/codex-security/mcp-app/tests/test_deep_reducer_finite_writes.ts
new file mode 100644
index 000000000..d518b35ac
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/test_deep_reducer_finite_writes.ts
@@ -0,0 +1,198 @@
+import assert from "node:assert/strict";
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { test, type TestContext } from "node:test";
+import { importSource } from "./import-module.ts";
+import { finding, scanId, workerDraft } from "./scan-draft-fixture.ts";
+
+const reducer = await importSource("src/artifact-deep-reducer.ts");
+const validation = await importSource("src/deep-scan/artifact-validation.ts");
+const { createDeepScanArtifacts } = await importSource(
+ "src/deep-scan/artifacts.ts",
+);
+const marker = "overflow-number";
+const finiteError = {
+ name: "TypeError",
+ message: "Stored finding JSON cannot contain non-finite numbers.",
+};
+const sourceFinding = () => finding("shared", "api/source.py");
+const draft = () => ({ scanId, findings: [sourceFinding()] });
+const wire = (value: unknown) =>
+ JSON.stringify(value).replaceAll(JSON.stringify(marker), "1e400");
+
+async function fixture(
+ t: TestContext,
+ route: "mcp" | "file",
+ historical?: "discovery" | "previous",
+) {
+ const root = await mkdtemp(join(tmpdir(), "reducer-finite-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const artifacts = createDeepScanArtifacts(join(root, "scan"));
+ const output = join(artifacts.dedupRoot, "reducer-001", "output");
+ const resultPath = join(output, "result.json");
+ const workerPath = join(
+ artifacts.workersRoot,
+ "worker-001",
+ "output",
+ "result.json",
+ );
+ const legacy = {
+ scanId,
+ findings: [{ ...sourceFinding(), extensions: { measurement: marker } }],
+ threatModel: { summary: "API model", measurement: marker },
+ };
+ await mkdir(dirname(workerPath), { recursive: true });
+ await mkdir(output, { recursive: true });
+ await writeFile(
+ workerPath,
+ wire(
+ historical === "discovery"
+ ? workerDraft(legacy.findings, { threatModel: legacy.threatModel })
+ : workerDraft(historical === "previous" ? [] : [sourceFinding()]),
+ ),
+ );
+ const previousReducerResultPath =
+ historical === "previous"
+ ? join(artifacts.dedupRoot, "previous.json")
+ : undefined;
+ if (previousReducerResultPath)
+ await writeFile(previousReducerResultPath, wire(legacy));
+ const context = {
+ root: output,
+ repoRoot: root,
+ scanId,
+ layout: "reducer",
+ deepReducer: {
+ scanRoot: artifacts.scanDir,
+ claimedWorkers: [{ id: "worker-001", resultPath: workerPath }],
+ previousReducerResultPath,
+ },
+ };
+ const sources = await reducer.getCodexSecurityDeepReducerInputs(context);
+ const admission = {
+ artifacts,
+ artifactDir: output,
+ resultPath,
+ reducerId: "reducer-001",
+ sources,
+ };
+ return {
+ output,
+ resultPath,
+ admission,
+ async write(value: unknown) {
+ const raw = wire(value);
+ if (route === "file") {
+ await writeFile(resultPath, raw);
+ return validation.validateReducerArtifacts(admission, scanId);
+ }
+ const input = JSON.parse(raw);
+ const before = structuredClone(input);
+ try {
+ return await reducer.recordCodexSecurityDeepReduction(context, input);
+ } finally {
+ assert.deepEqual(input, before);
+ }
+ },
+ };
+}
+
+async function storedDrafts(output: string) {
+ const checkpoints = await readdir(join(output, "checkpoints"));
+ assert.ok(checkpoints.length > 0);
+ return Promise.all(
+ [
+ "result.json",
+ ...checkpoints.map((name) => join("checkpoints", name)),
+ ].map(async (name) =>
+ JSON.parse(await readFile(join(output, name), "utf8")),
+ ),
+ );
+}
+
+for (const route of ["mcp", "file"] as const) {
+ for (const field of [
+ "threatModel",
+ "extensions",
+ "previousFindings",
+ "originalCandidates",
+ ]) {
+ test(`${route} reducer rejects retained ${field} overflow before checkpointing`, async (t) => {
+ const f = await fixture(t, route);
+ const input = draft();
+ if (field === "threatModel")
+ Object.assign(input, {
+ threatModel: { summary: "API model", measurement: marker },
+ });
+ else if (field === "extensions")
+ Object.assign(input.findings[0], {
+ extensions: { measurement: marker },
+ });
+ else
+ Object.assign(input.findings[0].provenance, {
+ [field]: [{ measurement: marker }],
+ });
+ await assert.rejects(f.write(input), finiteError);
+ assert.deepEqual(
+ await readdir(f.output),
+ route === "file" ? ["result.json"] : [],
+ );
+ if (route === "file")
+ assert.equal(await readFile(f.resultPath, "utf8"), wire(input));
+ });
+ }
+
+ test(`${route} reducer replaces submitted source payloads before retaining them`, async (t) => {
+ const f = await fixture(t, route);
+ const input = draft();
+ Object.assign(input.findings[0].provenance, {
+ sourceFindings: [{ id: "discarded", finding: { measurement: marker } }],
+ });
+ await f.write(input);
+ for (const saved of await storedDrafts(f.output)) {
+ const sources = saved.findings[0].provenance.sourceFindings;
+ assert.equal(sources.length, 1);
+ assert.deepEqual(sources[0].finding, sourceFinding());
+ }
+ });
+
+ for (const historical of ["discovery", "previous"] as const) {
+ test(`${route} reducer retains historical ${historical} payloads without fresh validation`, async (t) => {
+ const f = await fixture(t, route, historical);
+ await f.write(draft());
+ for (const saved of await storedDrafts(f.output)) {
+ assert.equal(saved.threatModel.measurement, null);
+ assert.equal(
+ saved.findings[0].provenance.sourceFindings[0].finding.extensions
+ .measurement,
+ null,
+ );
+ }
+ });
+ }
+}
+
+test("historical reducer validation reads overflow without rewriting the artifact", async (t) => {
+ const f = await fixture(t, "file");
+ const input = {
+ ...draft(),
+ threatModel: { summary: "API model", measurement: marker },
+ };
+ await writeFile(f.resultPath, wire(input));
+ const { sources: _sources, ...historical } = f.admission;
+ const validated = await validation.validateReducerArtifacts(
+ historical,
+ scanId,
+ );
+ assert.equal(validated.result.threatModel.measurement, Infinity);
+ assert.equal(await readFile(f.resultPath, "utf8"), wire(input));
+ assert.deepEqual(await readdir(f.output), ["result.json"]);
+});
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_finite_publication.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_finite_publication.ts
new file mode 100644
index 000000000..3ae3e338a
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_finite_publication.ts
@@ -0,0 +1,149 @@
+import assert from "node:assert/strict";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { after, test } from "node:test";
+import type { CoordinatorOptions } from "../src/deep-scan/coordinator.js";
+import type { CodexWorkerRequest } from "../src/deep-scan/types.js";
+import { importSource } from "./import-module.ts";
+import {
+ DeepScanCoordinatorRegistry,
+ FakeStore,
+ fixtureRun,
+ temporaryDirectories,
+} from "./deep_scan_coordinator_fixture.ts";
+import { draftFixture } from "./scan-draft-recovery-fixture.ts";
+import { finding, workerDraft } from "./scan-draft-fixture.ts";
+
+const { startDeepScanEngine } = await importSource("src/deep-scan/engine.ts", {
+ loader: { ".md": "text" },
+ define: {
+ "import.meta.url": JSON.stringify(
+ new URL("../src/deep-scan/engine.ts", import.meta.url).href,
+ ),
+ },
+});
+const { recordCodexSecurityDeepReduction } = await importSource(
+ "src/artifact-deep-reducer.ts",
+);
+after(() => temporaryDirectories.cleanup());
+
+for (const route of ["mcp", "file"] as const) {
+ test(`Deep engine publishes historical metadata inherited by a ${route} reducer`, async () => {
+ const fixture = await fixtureRun({ maxDiscoveryRuns: 1 });
+ const store = new FakeStore(fixture.run);
+ const registry = new DeepScanCoordinatorRegistry();
+ const run = store.run;
+ const source = finding("shared", "api/source.py");
+ const legacy = {
+ scanId: run.scanId,
+ findings: [{ ...source, extensions: { measurement: "OVERFLOW" } }],
+ threatModel: { summary: "Historical model", measurement: "OVERFLOW" },
+ };
+ const encode = (value: unknown) =>
+ JSON.stringify(value).replaceAll('"OVERFLOW"', "1e400");
+ const deepRoot = join(run.scanDir, "artifacts/deep_discovery");
+ const workerPath = join(
+ deepRoot,
+ "workers/discovery-0001/output/result.json",
+ );
+ await mkdir(dirname(workerPath), { recursive: true });
+ await mkdir(run.targetPath, { recursive: true });
+ const rawWorker = encode({ ...workerDraft(legacy.findings), ...legacy });
+ await writeFile(workerPath, rawWorker);
+ const worker = {
+ id: "historical-worker",
+ scanId: run.scanId,
+ kind: "discovery" as const,
+ status: "succeeded" as const,
+ attempt: 1,
+ promptPath: join(dirname(workerPath), "../prompt.md"),
+ artifactDir: dirname(workerPath),
+ resultManifestPath: workerPath,
+ completionSequence: 1,
+ mergeState: "buffered" as const,
+ };
+ store.workers.set(worker.id, worker);
+ run.persistedWorkers = [worker];
+ run.dispatchedCount = 1;
+ let reducerCalls = 0;
+ const start = registry.start.bind(registry);
+ registry.start = (options: CoordinatorOptions) =>
+ start({
+ ...options,
+ executor: {
+ async run(request: CodexWorkerRequest) {
+ assert.equal(request.kind, "dedup");
+ assert.ok(request.artifactContext);
+ reducerCalls += 1;
+ const input = { scanId: run.scanId, findings: [source] };
+ if (route === "mcp") {
+ await recordCodexSecurityDeepReduction(
+ request.artifactContext,
+ input,
+ );
+ } else {
+ await writeFile(
+ join(request.artifactContext.root, "result.json"),
+ JSON.stringify(input),
+ );
+ }
+ return {};
+ },
+ },
+ });
+ const staged: { draft: string; checkpoint: string }[] = [];
+ const context = draftFixture(run.scanDir, "deep").context;
+ const { coordinator } = await startDeepScanEngine({
+ run,
+ store,
+ registry,
+ pluginRoot: fixture.pluginRoot,
+ pythonCommand: "fixture-python",
+ parentSandbox: { filesystemDenies: [] },
+ threadId: "fixture-owner",
+ runWorkbench: async (args: string[]) => {
+ if (args[0] === "get-scan")
+ return {
+ scan: {
+ scanId: run.scanId,
+ scanDir: run.scanDir,
+ targetPath: run.targetPath,
+ scope: ".",
+ mode: "deep",
+ status: "running",
+ contract: context.targetContract,
+ targetRevision: context.targetRevision,
+ },
+ };
+ if (args[0] === "preserve-scan-results") return {};
+ assert.equal(args[0], "write-scan-draft");
+ staged.push({
+ draft: await readFile(args[args.indexOf("--draft-path") + 1], "utf8"),
+ checkpoint: await readFile(
+ args[args.indexOf("--checkpoint-path") + 1],
+ "utf8",
+ ),
+ });
+ return {};
+ },
+ });
+ const terminal = await coordinator.wait(undefined, 30_000);
+ assert.equal(terminal?.status, "succeeded", terminal?.error);
+ assert.equal(reducerCalls, 1);
+ assert.equal(staged.length, 1);
+ const draft = JSON.parse(staged[0].draft);
+ const checkpoint = JSON.parse(staged[0].checkpoint);
+ assert.equal(draft.manifest.scan.threatModel.measurement, null);
+ assert.equal(checkpoint.threatModel.measurement, null);
+ const selectedPath = store.dedupCommits.at(-1)!.resultManifestPath;
+ assert.equal(draft.deepScanPublication.resultPath, selectedPath);
+ const retained = checkpoint.findings[0];
+ assert.equal(
+ retained.provenance.sourceFindings[0].finding.extensions.measurement,
+ null,
+ );
+ assert.equal(await readFile(workerPath, "utf8"), rawWorker);
+ const saved = JSON.parse(await readFile(selectedPath, "utf8"));
+ assert.equal(saved.threatModel.measurement, null);
+ });
+}
diff --git a/plugins/codex-security/mcp-app/tests/test_scan_draft_finite_writes.ts b/plugins/codex-security/mcp-app/tests/test_scan_draft_finite_writes.ts
new file mode 100644
index 000000000..7927b6112
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/test_scan_draft_finite_writes.ts
@@ -0,0 +1,203 @@
+import assert from "node:assert/strict";
+import { readFile, readdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { test } from "node:test";
+import { deserializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
+import { CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
+import { finding } from "./scan-draft-fixture.ts";
+import {
+ draftApi,
+ fixture,
+ interruptDraftWrite,
+} from "./scan-draft-recovery-fixture.ts";
+import { readJson } from "./support/json.ts";
+
+const marker = "overflow-number";
+const finiteError = {
+ name: "TypeError",
+ message: "Stored finding JSON cannot contain non-finite numbers.",
+};
+
+// JSON exponent overflow survives the MCP decoder and registered tool schema.
+function requestInput(draft: unknown, token = "1e400") {
+ const line = JSON.stringify({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: { name: "record_codex_security_scan_draft", arguments: draft },
+ }).replaceAll(JSON.stringify(marker), token);
+ const request = CallToolRequestSchema.parse(deserializeMessage(line));
+ return draftApi.scanDraftInputSchema.parse(request.params.arguments);
+}
+
+function markedFinding(repositoryPath = "api/source.py") {
+ return {
+ ...finding("overflow", repositoryPath),
+ extensions: { audit: { measurement: marker } },
+ };
+}
+
+async function checkpoints(root: string) {
+ const names = await readdir(join(root, "checkpoints"));
+ assert.ok(names.length > 0);
+ return Promise.all(names.map((name) => readJson(root, "checkpoints", name)));
+}
+
+for (const layout of ["standard", "diff", "deep", "worker"] as const) {
+ for (const complete of layout === "deep" ? [false, true] : [true]) {
+ test(`${layout} ${complete ? "terminal" : "progress"} rejects retained overflow before writing`, async (t) => {
+ const f = await fixture(t, layout);
+ const input = requestInput({
+ ...f.draft({}, complete),
+ findings: [markedFinding()],
+ });
+ assert.equal(input.findings[0].extensions.audit.measurement, Infinity);
+ const before = structuredClone(input);
+ await assert.rejects(f.write(input), finiteError);
+ assert.deepEqual(await readdir(f.root), []);
+ assert.deepEqual(input, before);
+ });
+ }
+}
+
+for (const layout of ["standard", "deep"] as const) {
+ test(`${layout} progress retains outside findings in its authored checkpoint`, async (t) => {
+ const f = await fixture(t, layout);
+ Object.assign(f.context.targetContract!.scope as object, {
+ requiredIncludePaths: ["api"],
+ });
+ const input = requestInput(
+ { ...f.draft(), findings: [markedFinding("outside/source.py")] },
+ "-1e400",
+ );
+ await assert.rejects(f.write(input), finiteError);
+ assert.deepEqual(await readdir(f.root), []);
+ });
+}
+
+for (const layout of ["worker", "deep"] as const) {
+ test(`${layout} drops outside overflow before saving a terminal draft`, async (t) => {
+ const f = await fixture(t, layout);
+ f.context.scope = "api";
+ Object.assign(f.context.targetContract!.scope as object, {
+ requiredIncludePaths: ["api"],
+ });
+ const kept = finding("kept", "api/source.py");
+ const input = requestInput({
+ ...f.draft({ completeness: marker }, true),
+ findings: [kept, markedFinding("outside/source.py")],
+ });
+ const before = structuredClone(input);
+ assert.equal((await f.write(input)).findingCount, 1);
+ const saved =
+ layout === "worker"
+ ? await readJson(f.root, "result.json")
+ : {
+ ...(await readJson(f.root, "findings.json")),
+ coverage: await readJson(f.root, "coverage.json"),
+ };
+ for (const document of [saved, ...(await checkpoints(f.root))]) {
+ assert.deepEqual(document.findings, [kept]);
+ assert.equal(Object.hasOwn(document.coverage, "completeness"), false);
+ }
+ assert.deepEqual(input, before);
+ if (layout === "deep")
+ assert.deepEqual(await readdir(join(f.root, "drafts")), []);
+ });
+
+ test(`${layout} retains overflow when a later finding location matches scope`, async (t) => {
+ const f = await fixture(t, layout);
+ f.context.scope = "api";
+ Object.assign(f.context.targetContract!.scope as object, {
+ requiredIncludePaths: ["api"],
+ });
+ const mixed = markedFinding("outside/source.py");
+ mixed.locations.push({ path: "api/source.py", startLine: 3, endLine: 4 });
+ const input = requestInput(
+ { ...f.draft({}, true), findings: [mixed] },
+ "-1e400",
+ );
+ await assert.rejects(f.write(input), finiteError);
+ assert.deepEqual(await readdir(f.root), []);
+ });
+
+ for (const field of ["deferred", "surfaces", "threatModel"] as const) {
+ test(`${layout} rejects overflow in retained ${field} metadata`, async (t) => {
+ const f = await fixture(t, layout);
+ const metadata = { audit: { measurement: marker } };
+ const input = requestInput({
+ ...f.draft(
+ field === "deferred"
+ ? { deferred: [{ reason: "Review API", ...metadata }] }
+ : field === "surfaces"
+ ? {
+ surfaces: [
+ {
+ label: "API",
+ disposition: "needs_follow_up",
+ ...metadata,
+ },
+ ],
+ }
+ : {},
+ true,
+ ),
+ ...(field === "threatModel"
+ ? { threatModel: { summary: "API model", ...metadata } }
+ : {}),
+ });
+ const before = structuredClone(input);
+ await assert.rejects(f.write(input), finiteError);
+ assert.deepEqual(await readdir(f.root), []);
+ assert.deepEqual(input, before);
+ });
+ }
+}
+
+test("Deep retains historical threat-model reader behavior", async (t) => {
+ const f = await fixture(t, "deep");
+ const manifest =
+ '{"scan":{"threatModel":{"summary":"Earlier model","audit":{"measurement":1e400}}}}\n';
+ await writeFile(join(f.root, "scan-manifest.json"), manifest, "utf8");
+ const input = requestInput(f.draft({}, true));
+ let calls = 0;
+ await draftApi.recordCodexSecurityScanDraftViaWorkbench(
+ f.context,
+ input,
+ async (args: string[]) => {
+ calls++;
+ const draft = await readJson(args[args.indexOf("--draft-path") + 1]);
+ const checkpoint = await readJson(
+ args[args.indexOf("--checkpoint-path") + 1],
+ );
+ assert.equal(draft.manifest.scan.threatModel.audit.measurement, null);
+ assert.equal(checkpoint.threatModel.audit.measurement, null);
+ return {};
+ },
+ );
+ assert.equal(calls, 1);
+ assert.equal(
+ await readFile(join(f.root, "scan-manifest.json"), "utf8"),
+ manifest,
+ );
+ assert.deepEqual(await readdir(join(f.root, "drafts")), []);
+ assert.equal(Object.hasOwn(input, "threatModel"), false);
+});
+
+test("worker recovers finite nested values after an interrupted result write", async (t) => {
+ const f = await fixture(t, "worker");
+ let nested: unknown = 1.25e300;
+ for (let depth = 0; depth < 300; depth++) nested = [nested];
+ const kept = {
+ ...finding("finite", "api/source.py"),
+ extensions: {
+ values: [null, true, false, 0, -1.25e300, "Infinity", "λ 🧪"],
+ nested,
+ },
+ };
+ const input = requestInput({ ...f.draft(), findings: [kept] });
+ await interruptDraftWrite(join(f.root, "result.json"), () => f.write(input));
+ assert.deepEqual((await checkpoints(f.root))[0].findings, [kept]);
+ await f.write(f.draft());
+ assert.deepEqual((await readJson(f.root, "result.json")).findings, [kept]);
+});