OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
refactor(sdk): share progress and event parsing (#1209)
mldangelo-oaib96739d5ba18
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 5c564b20e..6a2a6d0b7 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -306,7 +306,6 @@ type Writable = Pick<NodeJS.WriteStream, "write"> & {};type SignalName = "SIGINT" | "SIGTERM";-const DISPLAY_SEVERITIES: readonly SeverityLevel[] = SCAN_SEVERITIES;const MODEL_REASONING_EFFORTS = ["minimal","low",@@ -9135,10 +9134,8 @@ async function readDeepScanStop(if (state?.terminalReason !== "capped") return undefined;const { maxDiscoveryRuns, maxTimeHours } = state.config;if (state.dispatchedCount >= maxDiscoveryRuns) {- const stillFindingIssues =- state.completionSequence > 0 && state.noNewStreak === 0;return {- reason: `Reached the limit of ${maxDiscoveryRuns} review rounds. ${stillFindingIssues ? "The latest review still found new issues." : "More issues may remain."}`,+ reason: `Reached the limit of ${maxDiscoveryRuns} review rounds. ${state.completionSequence > 0 && state.noNewStreak === 0 ? "The latest review still found new issues." : "More issues may remain."}`,nextStep: `To scan further, rerun with --max-discovery-runs greater than ${maxDiscoveryRuns}.`,};}@@ -9177,12 +9174,9 @@ function printScanSummary((severities.get(finding.severity.level) ?? 0) + 1,);}- const severitySummary = DISPLAY_SEVERITIES.map((severity) => {- const count = severities.get(severity);- return count === undefined ? null : `${count} ${severity}`;- })- .filter((value): value is string => value !== null)- .join(", ");+ const severitySummary = SCAN_SEVERITIES.flatMap((severity) =>+ severities.has(severity) ? `${severities.get(severity)} ${severity}` : [],+ ).join(", ");const started = Date.parse(result.manifest.scan.startedAt);const completed = Date.parse(result.manifest.scan.completedAt);@@ -9643,9 +9637,7 @@ export class Progress {#line(message: string): string {const elapsedSeconds = this.elapsedSeconds;- const minutes = Math.floor(elapsedSeconds / 60);- const seconds = elapsedSeconds % 60;- return `[${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}] ${message}`;+ return `[${String(Math.floor(elapsedSeconds / 60)).padStart(2, "0")}:${String(elapsedSeconds % 60).padStart(2, "0")}] ${message}`;}#observeStreamErrors(): void {diff --git a/sdk/typescript/src/cost-model.ts b/sdk/typescript/src/cost-model.tsindex 15da70d17..20fc85077 100644--- a/sdk/typescript/src/cost-model.ts+++ b/sdk/typescript/src/cost-model.ts@@ -1,4 +1,5 @@import { isRecord } from "./record.js";+import { isSafeNonNegativeInteger } from "./value.js";export interface ScanCost {model: string;@@ -140,9 +141,9 @@ export function tokenUsage(value: unknown): ScanTokenUsage | null {const legacyCacheWrite = value["cache_write_tokens"];const cacheWrite =canonicalCacheWrite === 0 &&- isTokenCount(input) &&- isTokenCount(cached) &&- isTokenCount(legacyCacheWrite) &&+ isSafeNonNegativeInteger(input) &&+ isSafeNonNegativeInteger(cached) &&+ isSafeNonNegativeInteger(legacyCacheWrite) &&legacyCacheWrite > 0 &&cached + legacyCacheWrite <= input? legacyCacheWrite@@ -150,11 +151,11 @@ export function tokenUsage(value: unknown): ScanTokenUsage | null {const output = value["output_tokens"];const reasoning = value["reasoning_output_tokens"] ?? 0;if (- !isTokenCount(input) ||- !isTokenCount(cached) ||- !isTokenCount(cacheWrite) ||- !isTokenCount(output) ||- !isTokenCount(reasoning) ||+ !isSafeNonNegativeInteger(input) ||+ !isSafeNonNegativeInteger(cached) ||+ !isSafeNonNegativeInteger(cacheWrite) ||+ !isSafeNonNegativeInteger(output) ||+ !isSafeNonNegativeInteger(reasoning) ||cached + cacheWrite > input ||reasoning > output) {@@ -339,7 +340,3 @@ export function formatUsd(value: number): string {maximumFractionDigits: 9,}).format(value);}--function isTokenCount(value: unknown): value is number {- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;-}diff --git a/sdk/typescript/src/cost.ts b/sdk/typescript/src/cost.tsindex 29cb3ebfd..fcbf4ced2 100644--- a/sdk/typescript/src/cost.ts+++ b/sdk/typescript/src/cost.ts@@ -17,7 +17,7 @@ import {sessionStartedAt,} from "./scan-sessions.js";import {- scanProgressUpdatesFromEvent,+ scanProgressUpdatesFromText,type ScanProgress,} from "./worker-progress.js";@@ -344,10 +344,9 @@ export class ScanCostTracker {this.#workerProgress.set(session.threadId, progress.filesCompleted);const filesCompleted = Math.min(expectedFilesTotal ?? Number.MAX_SAFE_INTEGER,- [...this.#workerProgress.values()].reduce(- (total, reviewed) => total + reviewed,- 0,- ),+ this.#workerProgress+ .values()+ .reduce((total, reviewed) => total + reviewed, 0),);if (filesCompleted < this.#highestFilesCompleted) continue;const update = {@@ -621,12 +620,7 @@ function readSessionEvent(payload["type"] === "agent_message" &&typeof payload["message"] === "string") {- session.progress.push(- ...scanProgressUpdatesFromEvent({- type: "item.completed",- item: { type: "agent_message", text: payload["message"] },- }),- );+ session.progress.push(...scanProgressUpdatesFromText(payload["message"]));}if (repository === undefined) return;if (payload["type"] !== "agent_message") {@@ -746,13 +740,7 @@ function sessionProgressUpdates(if (payload["type"] === "message" && payload["role"] === "assistant") {const content = payload["content"];if (!Array.isArray(content)) return [];- return scanProgressUpdatesFromEvent({- type: "item.completed",- item: {- type: "agent_message",- text: sessionContentText(content, false),- },- });+ return scanProgressUpdatesFromText(sessionContentText(content, false));}if (payload["type"] !== "function_call_output" &&@@ -771,10 +759,7 @@ function sessionProgressUpdates(if (payload["status"] === "failed" || output === null) {return [];}- return scanProgressUpdatesFromEvent({- type: "item.completed",- item: { type: "command_execution", aggregated_output: output },- });+ return scanProgressUpdatesFromText(output);}function sessionContentText(diff --git a/sdk/typescript/src/deep-progress.ts b/sdk/typescript/src/deep-progress.tsindex 189a4b2ca..20aad58d1 100644--- a/sdk/typescript/src/deep-progress.ts+++ b/sdk/typescript/src/deep-progress.ts@@ -1,4 +1,5 @@import { isRecord } from "./record.js";+import { isSafeNonNegativeInteger } from "./value.js";export interface DeepScanProgress {completed: number;@@ -10,7 +11,6 @@ interface DeepScanProgressTrackerOptions {read: (signal: AbortSignal) => Promise<unknown>;onProgress: (progress: DeepScanProgress) => void;onError?: (error: unknown) => void;- pollIntervalMs?: number;}const DEEP_PROGRESS_POLL_INTERVAL_MS = 5_000;@@ -34,10 +34,7 @@ export class DeepScanProgressTracker {this.#options.onError?.(error);});};- this.#timer = setInterval(- poll,- this.#options.pollIntervalMs ?? DEEP_PROGRESS_POLL_INTERVAL_MS,- );+ this.#timer = setInterval(poll, DEEP_PROGRESS_POLL_INTERVAL_MS);this.#timer.unref();poll();}@@ -95,21 +92,20 @@ export function deepScanProgressFromWorkbench(if (!isRecord(progress)) return null;const independentReviews = progress["independentReviews"];if (independentReviews === undefined) return null;- if (- !isRecord(independentReviews) ||- !isCount(independentReviews["completed"]) ||- !isCount(independentReviews["active"]) ||- !isPositiveCount(independentReviews["maximum"])- ) {- throw new Error(- "Codex Security workbench returned invalid Deep Scan progress.",- );+ if (isRecord(independentReviews)) {+ const { completed, active, maximum } = independentReviews;+ if (+ isSafeNonNegativeInteger(completed) &&+ isSafeNonNegativeInteger(active) &&+ isSafeNonNegativeInteger(maximum) &&+ maximum > 0+ ) {+ return { completed, active, maximum };+ }}- return {- completed: independentReviews["completed"],- active: independentReviews["active"],- maximum: independentReviews["maximum"],- };+ throw new Error(+ "Codex Security workbench returned invalid Deep Scan progress.",+ );}function sameProgress(@@ -123,11 +119,3 @@ function sameProgress(left.maximum === right.maximum);}--function isCount(value: unknown): value is number {- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;-}--function isPositiveCount(value: unknown): value is number {- return isCount(value) && value > 0;-}diff --git a/sdk/typescript/src/patch-tui.tsx b/sdk/typescript/src/patch-tui.tsxindex b9f0c3035..12a049d4e 100644--- a/sdk/typescript/src/patch-tui.tsx+++ b/sdk/typescript/src/patch-tui.tsx@@ -101,9 +101,8 @@ function detailLines(return [];}if (key === "level") {- const level = safeLine(entry);return [- `${indent}${level.replace(/^./u, (match) => match.toUpperCase())}`,+ `${indent}${safeLine(entry).replace(/^./u, (match) => match.toUpperCase())}`,];}if (diff --git a/sdk/typescript/src/scan-activity.ts b/sdk/typescript/src/scan-activity.tsindex 344dc8ee8..b95bd5127 100644--- a/sdk/typescript/src/scan-activity.ts+++ b/sdk/typescript/src/scan-activity.ts@@ -1,4 +1,5 @@import { isRecord } from "./record.js";+import { parseJson } from "./value.js";const MAX_ACTIVITY_PATHS = 8;const MAX_PROSE_CHARACTERS = 1_000;@@ -171,10 +172,8 @@ export function scanActivityFromSessionEvent(? payload["text"]: payload["message"];if (kind === null || typeof text !== "string") return null;- const timestamp =- typeof event["timestamp"] === "string" ? event["timestamp"] : "";return proseActivity(- `${type}:${timestamp}:${text}`,+ `${type}:${typeof event["timestamp"] === "string" ? event["timestamp"] : ""}:${text}`,kind,delta ? "running" : "completed",text,@@ -303,19 +302,13 @@ function prose(text: string, limit?: number): string {function customShellCommand(name: string, value: unknown): string | null {if (name !== "exec" || typeof value !== "string") return null;- const match =+ const quoted =/\b(?:exec_command|shell_command)\s*\(\s*\{[\s\S]{0,1024}?\b(?:cmd|command)["']?\s*:\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`[^`]*`)/u.exec(value,- );- if (match?.[1] === undefined) return null;- const quoted = match[1];+ )?.[1];+ if (quoted === undefined) return null;if (quoted.startsWith('"')) {- try {- const parsed: unknown = JSON.parse(quoted);- return typeof parsed === "string" ? parsed : null;- } catch {- return null;- }+ return parseJson(() => quoted) as string | null;}return quoted.slice(1, -1).replaceAll(/\\(['`\\])/gu, "$1");}@@ -361,12 +354,8 @@ function sessionCallArguments(const value = payload["arguments"] ?? payload["input"];if (isRecord(value)) return value;if (typeof value !== "string") return {};- try {- const parsed: unknown = JSON.parse(value);- return isRecord(parsed) ? parsed : {};- } catch {- return {};- }+ const parsed = parseJson(() => value);+ return isRecord(parsed) ? parsed : {};}function commandRepositoryPaths(command: string, repository: string): string[] {diff --git a/sdk/typescript/src/scan-dashboard.ts b/sdk/typescript/src/scan-dashboard.tsindex 1b41921b9..b6edbf7ef 100644--- a/sdk/typescript/src/scan-dashboard.ts+++ b/sdk/typescript/src/scan-dashboard.ts@@ -600,7 +600,7 @@ export class ScanDashboard {scrollStatus = `Esc components · ${scrollStatus}`;const model = this.#options.model;- const lines = [+ return this.#formatFrame([` CODEX SECURITY · ${publication ? "PUBLISH · " : verification ? "VERIFY-FIX · " : ""}${basename(this.#options.repository)}${this.#options.componentName === undefined ? "" : ` · ${this.#options.componentName}`}${model === undefined ? "" : ` · ${model.model} (${model.reasoningEffort})`}${this.#view === "details" ? ` · DETAILS${this.#source === "all" ? "" : ` · ${typeof this.#source === "number" ? `worker ${this.#source}` : this.#source}`}` : ""}`,divider,...activity,@@ -624,9 +624,7 @@ export class ScanDashboard {]),]),` TIME ${time} · ${this.#budget === null ? scrollStatus : "Enter to apply · Ctrl+C to exit"}`,- ];-- return this.#formatFrame(lines);+ ]);}#formatFrame(lines: (string | DashboardActivityLine)[]): string {@@ -1056,9 +1054,7 @@ function detailsDescription(const itemType = typeof payload["type"] === "string" ? payload["type"] : type;if (itemType === "token_count") return undefined;if (itemType === "message" || itemType === "agent_message") {- const role =- typeof payload["role"] === "string" ? payload["role"] : "assistant";- return `${role}: ${detailsText(payload["content"] ?? payload["message"])}`;+ return `${typeof payload["role"] === "string" ? payload["role"] : "assistant"}: ${detailsText(payload["content"] ?? payload["message"])}`;}if (itemType === "reasoning" || itemType.startsWith("agent_reasoning")) {const text = detailsText(@@ -1269,11 +1265,7 @@ function styleLine(if (kind === "status" || kind === "warning") {return `${prefix}\u001B[${style}m${marker}${separator}${description}\u001B[0m`;}- const workerLabel =- worker === undefined ? "" : `\u001B[36m${worker}\u001B[39m`;- const prose =- kind === "message" ? `\u001B[1m${description}\u001B[22m` : description;- return `${prefix}\u001B[${style}m${marker}\u001B[39m${separator}${workerLabel}${prose}`;+ return `${prefix}\u001B[${style}m${marker}\u001B[39m${separator}${worker === undefined ? "" : `\u001B[36m${worker}\u001B[39m`}${kind === "message" ? `\u001B[1m${description}\u001B[22m` : description}`;}return `\u001B[${style}m${value}\u001B[0m`;}diff --git a/sdk/typescript/src/scan-history-renderer.ts b/sdk/typescript/src/scan-history-renderer.tsindex cb41f101e..e7ffece3f 100644--- a/sdk/typescript/src/scan-history-renderer.ts+++ b/sdk/typescript/src/scan-history-renderer.ts@@ -279,9 +279,7 @@ export function renderScanHistory(lines.push(` ${strong("CONFIGURATION")} ${Object.entries(config).map(([key, value]) => {- const rendered =- typeof value === "object" ? JSON.stringify(value) : value;- return `${clean(key)}=${clean(rendered)}`;+ return `${clean(key)}=${clean(typeof value === "object" ? JSON.stringify(value) : value)}`;}).join(` ${accent("·")} `)}`,);diff --git a/sdk/typescript/src/value.ts b/sdk/typescript/src/value.tsindex 35ecc5497..a27d69655 100644--- a/sdk/typescript/src/value.ts+++ b/sdk/typescript/src/value.ts@@ -8,6 +8,15 @@ export function isNonEmptyString(value: unknown): value is string {return typeof value === "string" && value.length > 0;}+/** @internal */+export function parseJson(read: () => string): unknown {+ try {+ return JSON.parse(read());+ } catch {+ return null;+ }+}+/** @internal */export const findingEntry = <T extends { findingId: string }>(finding: T,diff --git a/sdk/typescript/src/worker-progress.ts b/sdk/typescript/src/worker-progress.tsindex 82012f469..f788078c2 100644--- a/sdk/typescript/src/worker-progress.ts+++ b/sdk/typescript/src/worker-progress.ts@@ -1,4 +1,5 @@import { isRecord } from "./record.js";+import { isSafeNonNegativeInteger, parseJson } from "./value.js";const WORKER_STATUS_PREFIX = "CODEX_SECURITY_WORKER_STATUS ";const SCAN_PROGRESS_PREFIX = "CODEX_SECURITY_SCAN_PROGRESS ";@@ -78,7 +79,10 @@ export function scanProgressUpdatesFromEvent(: item["type"] === "command_execution"? item["aggregated_output"]: null;- if (typeof output !== "string") return [];+ return typeof output === "string" ? scanProgressUpdatesFromText(output) : [];+}++export function scanProgressUpdatesFromText(output: string): ScanProgress[] {const updates: ScanProgress[] = [];let codeFence = false;for (const line of output.split(/\r?\n/u)) {@@ -94,17 +98,12 @@ export function scanProgressUpdatesFromEvent(}function scanProgressFromMarker(marker: string): ScanProgress | null {- let payload: unknown;- try {- payload = JSON.parse(marker.slice(SCAN_PROGRESS_PREFIX.length));- } catch {- return null;- }+ const payload = parseJson(() => marker.slice(SCAN_PROGRESS_PREFIX.length));if (!isRecord(payload) ||!isScanPhase(payload["phase"]) ||- !isProgressCount(payload["filesCompleted"]) ||- !isProgressCount(payload["filesTotal"]) ||+ !isSafeNonNegativeInteger(payload["filesCompleted"]) ||+ !isSafeNonNegativeInteger(payload["filesTotal"]) ||payload["filesCompleted"] > payload["filesTotal"]) {return null;@@ -126,12 +125,7 @@ function preflightStatus() {return null;}- let payload: unknown;- try {- payload = JSON.parse(item["aggregated_output"]);- } catch {- return null;- }+ const payload = parseJson(() => item["aggregated_output"] as string);if (!isRecord(payload) ||(payload["profile"] !== "security_scan" &&@@ -167,7 +161,7 @@ function preflightStatus(const configuredSlots =capacity.length === 1 &&capacityResult !== undefined &&- isProgressCount(capacityResult["actual"])+ isSafeNonNegativeInteger(capacityResult["actual"])? capacityResult["actual"]: null;return { kind: "preflight", delegation, configuredSlots };@@ -182,18 +176,13 @@ function dispatchStatus(.filter((line) => line.startsWith(WORKER_STATUS_PREFIX));const marker = markers[0];if (markers.length !== 1 || marker === undefined) return null;- let payload: unknown;- try {- payload = JSON.parse(marker.slice(WORKER_STATUS_PREFIX.length));- } catch {- return null;- }+ const payload = parseJson(() => marker.slice(WORKER_STATUS_PREFIX.length));if (!isRecord(payload) ||typeof payload["phase"] !== "string" ||!WORKER_PHASES.has(payload["phase"]) ||- !isProgressCount(payload["planned"]) ||- !isProgressCount(payload["started"]) ||+ !isSafeNonNegativeInteger(payload["planned"]) ||+ !isSafeNonNegativeInteger(payload["started"]) ||payload["started"] > payload["planned"]) {return null;@@ -206,10 +195,6 @@ function dispatchStatus(};}-function isProgressCount(value: unknown): value is number {- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;-}-function isScanPhase(value: unknown): value is ScanPhase {return (value === "preflight" ||diff --git a/sdk/typescript/tests-ts/cli-scan-logs.test.ts b/sdk/typescript/tests-ts/cli-scan-logs.test.tsindex 04f31c44d..3d25fbbb2 100644--- a/sdk/typescript/tests-ts/cli-scan-logs.test.ts+++ b/sdk/typescript/tests-ts/cli-scan-logs.test.ts@@ -1,3 +1,4 @@+import { writeJsonLines } from "./support/json.js";import { execFile } from "node:child_process";import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";@@ -12,6 +13,7 @@ import { scanLogsJson } from "../src/cli-scan-logs-json.js";import { readSavedScanLogs } from "../src/scan-logs.js";import { VERSION } from "../src/version.js";import { capture, dependencies } from "./cli-fixtures.js";+import { throwing } from "./support/errors.js";async function fixture() {const state = await realpath(await mkdtemp(join(tmpdir(), "saved-logs-")));@@ -27,19 +29,14 @@ async function fixture() {},},];- await writeFile(- join(home, "sessions", "rollout.jsonl"),- events.map((event) => JSON.stringify(event)).join("\n"),- );+ await writeJsonLines(join(home, "sessions", "rollout.jsonl"), events);const scan = { scanId: "scan-1", continuationThreadId: "thread-1" };const logs = await readSavedScanLogs(scan, home);const deps = dependencies({environment: { CODEX_SECURITY_STATE_DIR: state },onWorkbench: () => ({ scan }),});- deps.createSecurity = () => {- throw new Error("Reading logs must not start Codex");- };+ deps.createSecurity = throwing("Reading logs must not start Codex");return { state, logs, deps };}diff --git a/sdk/typescript/tests-ts/cost.test.ts b/sdk/typescript/tests-ts/cost.test.tsindex 3b2d0781d..4b7b77c72 100644--- a/sdk/typescript/tests-ts/cost.test.ts+++ b/sdk/typescript/tests-ts/cost.test.ts@@ -1,3 +1,4 @@+import { jsonLines } from "./support/json.js";import { spawnSync } from "node:child_process";import { appendFile, mkdir, writeFile } from "node:fs/promises";import { join, parse, sep } from "node:path";@@ -25,9 +26,11 @@ import {scanThreadId,} from "./support/usage-rollout.js";-import { createTemporaryDirectories } from "./support/temporary-directories.js";+import { createApiTestFixtures } from "./support/temporary-directories.js";-const temporaryDirectories = createTemporaryDirectories();+const { temporaryDirectory: codexHome, cleanup } = createApiTestFixtures(+ "codex-security-cost-",+);const parentFields = ["source", "parent_thread_id", "forked_from_id"] as const;type SessionParentField = (typeof parentFields)[number];@@ -49,12 +52,7 @@ async function waitFor(check: () => boolean): Promise<void> {throw new Error("Timed out waiting for the cost tracker.");}-afterEach(temporaryDirectories.cleanup);--async function codexHome(): Promise<string> {- const directory = await temporaryDirectories.create("codex-security-cost-");- return directory;-}+afterEach(cleanup);async function writeSession(home: string,@@ -1067,7 +1065,7 @@ describe("live scan cost tracking", () => {await writeFile(worker,- [+ jsonLines([{type: "session_meta",payload: {@@ -1158,9 +1156,7 @@ describe("live scan cost tracking", () => {},},},- ]- .map((event) => JSON.stringify(event))- .join("\n") + "\n",+ ]) + "\n",);const activities: ScanActivity[] = [];@@ -1242,10 +1238,7 @@ describe("live scan cost tracking", () => {scanThreadId,);const rollout = ownershipRollout(replayedTurnIds);- await writeFile(- rolloutPath,- rollout.map((event) => JSON.stringify(event)).join("\n") + "\n",- );+ await writeFile(rolloutPath, jsonLines(rollout) + "\n");const maxCostUsd = 0.001;const observedCosts: number[] = [];diff --git a/sdk/typescript/tests-ts/deep-progress.test.ts b/sdk/typescript/tests-ts/deep-progress.test.tsindex d1b08377f..7bd8a6269 100644--- a/sdk/typescript/tests-ts/deep-progress.test.ts+++ b/sdk/typescript/tests-ts/deep-progress.test.ts@@ -1,4 +1,5 @@-import { describe, expect, test } from "bun:test";+import { once } from "node:events";+import { describe, expect, test, mock } from "bun:test";import {DeepScanProgressTracker,deepScanProgressFromWorkbench,@@ -53,12 +54,11 @@ describe("Deep Scan progress", () => {workbenchResult({ completed: 1, active: 1, maximum: 40 }),];const progress: DeepScanProgress[] = [];- let readCount = 0;+ const read = mock(async () => {+ return reads.shift() ?? workbenchResult();+ });const tracker = new DeepScanProgressTracker({- read: async () => {- readCount += 1;- return reads.shift() ?? workbenchResult();- },+ read,onProgress: (update) => progress.push(update),});@@ -73,29 +73,19 @@ describe("Deep Scan progress", () => {{ completed: 0, active: 2, maximum: 40 },{ completed: 1, active: 1, maximum: 40 },]);- expect(readCount).toBe(4);+ expect(read).toHaveBeenCalledTimes(4);});test("does not queue or await stalled polls during stop", async () => {const progress: DeepScanProgress[] = [];- let readCount = 0;+ const read = mock(async (signal: AbortSignal) => {+ await once(signal, "abort");+ aborted = true;+ return workbenchResult({ completed: 1, active: 0, maximum: 40 });+ });let aborted = false;const tracker = new DeepScanProgressTracker({- read: async (signal) => {- readCount += 1;- return await new Promise((resolve) => {- signal.addEventListener(- "abort",- () => {- aborted = true;- resolve(- workbenchResult({ completed: 1, active: 0, maximum: 40 }),- );- },- { once: true },- );- });- },+ read,onProgress: (update) => progress.push(update),});@@ -105,7 +95,7 @@ describe("Deep Scan progress", () => {tracker.stop();await Promise.all([first, second]);- expect(readCount).toBe(1);+ expect(read).toHaveBeenCalledTimes(1);expect(aborted).toBe(true);expect(progress).toEqual([]);});diff --git a/sdk/typescript/tests-ts/scan-dashboard.test.ts b/sdk/typescript/tests-ts/scan-dashboard.test.tsindex 2f8c6b58a..ec6401ae9 100644--- a/sdk/typescript/tests-ts/scan-dashboard.test.ts+++ b/sdk/typescript/tests-ts/scan-dashboard.test.ts@@ -2,7 +2,7 @@ import { EventEmitter } from "node:events";import { Writable } from "node:stream";import { pathToFileURL } from "node:url";import { stripVTControlCharacters } from "node:util";-import { describe, expect, test } from "bun:test";+import { describe, expect, test, mock } from "bun:test";import type { ComponentReceipt } from "../src/component-scan.js";import { ScanDashboard } from "../src/scan-dashboard.js";import { capture, fakeResult } from "./cli-fixtures.js";@@ -316,7 +316,7 @@ describe("live scan dashboard", () => {test("navigates a long component list and shows original failure details", () => {const stderr = capture(true);const input = new DashboardTestInput();- let interrupted = false;+ const onInterrupt = mock();const dashboard = new ScanDashboard({ ...stderr.stream, columns: 80, rows: 14 },{@@ -324,9 +324,7 @@ describe("live scan dashboard", () => {presentation: "components",input,clock: fakeClock(),- onInterrupt: () => {- interrupted = true;- },+ onInterrupt,},);const receipts: ComponentReceipt[] = Array.from(@@ -361,7 +359,7 @@ describe("live scan dashboard", () => {input.emit("data", "\r");expect(frame()).not.toContain("COST");input.emit("data", "\u0003");- expect(interrupted).toBe(true);+ expect(onInterrupt).toHaveBeenCalled();dashboard.stop();});@@ -412,31 +410,23 @@ describe("live scan dashboard", () => {test("restores terminal state when dashboard initialization fails", () => {const input = new DashboardTestInput();const output: string[] = [];- let timerCleared = false;+ const clearIntervalMock = mock();const dashboard = new ScanDashboard({- write(chunk: string): boolean {- output.push(chunk);- if (chunk.includes("\u001B[H")) {- throw new Error("Dashboard rendering failed.");- }- return true;- },+ write: failingDashboardOutput(output),},{repository: "/synthetic/repository",input,clock: {...fakeClock(),- clearInterval: () => {- timerCleared = true;- },+ clearInterval: clearIntervalMock,},},);expect(() => dashboard.start()).toThrow("Dashboard rendering failed.");- expect(timerCleared).toBe(true);+ expect(clearIntervalMock).toHaveBeenCalled();expect(input.isRaw).toBe(false);expect(input.listenerCount("data")).toBe(0);expect(output.join("")).toContain("\u001B[?25h\u001B[?1049l");@@ -474,13 +464,7 @@ describe("live scan dashboard", () => {};const dashboard = new ScanDashboard({- write(chunk: string): boolean {- output.push(chunk);- if (chunk.includes("\u001B[H")) {- throw new Error("Dashboard rendering failed.");- }- return true;- },+ write: failingDashboardOutput(output),},{ repository: "/synthetic/repository", input, clock: fakeClock() },);@@ -802,15 +786,13 @@ describe("live scan dashboard", () => {test("scrolls through history while keeping terminal text selectable", () => {const stderr = capture(true);const input = new DashboardTestInput();- let interrupted = false;+ const onInterrupt = mock();const dashboard = new ScanDashboard({ ...stderr.stream, columns: 80, rows: 14 },{repository: "/code/juice-shop",input,- onInterrupt: () => {- interrupted = true;- },+ onInterrupt,clock: fakeClock(),},);@@ -858,7 +840,7 @@ describe("live scan dashboard", () => {expect(frame).not.toContain("ACTIVITY");input.emit("data", "\u0003");- expect(interrupted).toBe(true);+ expect(onInterrupt).toHaveBeenCalled();dashboard.stop();expect(input.isRaw).toBe(false);expect(input.listenerCount("data")).toBe(0);@@ -1563,3 +1545,13 @@ describe("live scan dashboard", () => {);});});++function failingDashboardOutput(output: string[]) {+ return (chunk: string): boolean => {+ output.push(chunk);+ if (chunk.includes("\u001B[H")) {+ throw new Error("Dashboard rendering failed.");+ }+ return true;+ };+}diff --git a/sdk/typescript/tests-ts/scan-logs.test.ts b/sdk/typescript/tests-ts/scan-logs.test.tsindex c4daa6a43..e95366f43 100644--- a/sdk/typescript/tests-ts/scan-logs.test.ts+++ b/sdk/typescript/tests-ts/scan-logs.test.ts@@ -1,13 +1,16 @@+import { writeJsonLines } from "./support/json.js";import { mkdir, readFile, rename, writeFile } from "node:fs/promises";import { unlinkSync } from "node:fs";import { join } from "node:path";import { afterEach, describe, expect, spyOn, test } from "bun:test";import { readSavedScanLogs, readScanLogs } from "../src/scan-logs.js";-import { createTemporaryDirectories } from "./support/temporary-directories.js";+import { createApiTestFixtures } from "./support/temporary-directories.js";-const directories = createTemporaryDirectories();+const { temporaryDirectory: temporaryHome, cleanup } = createApiTestFixtures(+ "codex-security-scan-logs-",+);-afterEach(directories.cleanup);+afterEach(cleanup);async function writeSession(home: string,@@ -19,36 +22,26 @@ async function writeSession(): Promise<void> {const directory = join(home, "sessions", "2026", "08", "11");await mkdir(directory, { recursive: true });- await writeFile(- join(directory, `rollout-${threadId}.jsonl`),- [- {- type: "session_meta",- payload: {- id: threadId,- ...(startedAt === undefined ? {} : { timestamp: startedAt }),- ...(workingDirectory === undefined ? {} : { cwd: workingDirectory }),- ...(parentThreadId === undefined- ? {}- : {- source: {- subagent: {- thread_spawn: { parent_thread_id: parentThreadId },- },+ await writeJsonLines(join(directory, `rollout-${threadId}.jsonl`), [+ {+ type: "session_meta",+ payload: {+ id: threadId,+ ...(startedAt === undefined ? {} : { timestamp: startedAt }),+ ...(workingDirectory === undefined ? {} : { cwd: workingDirectory }),+ ...(parentThreadId === undefined+ ? {}+ : {+ source: {+ subagent: {+ thread_spawn: { parent_thread_id: parentThreadId },},- }),- },+ },+ }),},- ...events,- ]- .map((event) => JSON.stringify(event))- .join("\n"),- );-}--async function temporaryHome(): Promise<string> {- const directory = await directories.create("codex-security-scan-logs-");- return directory;+ },+ ...events,+ ]);}function commandEvent(command: string, id: string, timestamp?: string) {diff --git a/sdk/typescript/tests-ts/support/json.ts b/sdk/typescript/tests-ts/support/json.tsindex ed6ab677d..a29ba4b2a 100644--- a/sdk/typescript/tests-ts/support/json.ts+++ b/sdk/typescript/tests-ts/support/json.ts@@ -21,6 +21,9 @@ export function jsonLines(values: readonly unknown[]): string {return values.map((value) => JSON.stringify(value)).join("\n");}+export const writeJsonLines = (path: string, values: readonly unknown[]) =>+ writeFile(path, jsonLines(values));+export const readJsonLines = async <T = ReturnType<typeof JSON.parse>>(path: string,) => parseJsonLines<T>(await readFile(path, "utf8"));