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
fix(logs): prefer complete saved rollout copies (#933)
mldangelo-oai289f9d2052ad
diff --git a/sdk/typescript/src/scan-logs.ts b/sdk/typescript/src/scan-logs.tsindex 851a8f2da..a2c3cb4f6 100644--- a/sdk/typescript/src/scan-logs.ts+++ b/sdk/typescript/src/scan-logs.ts@@ -1,6 +1,7 @@import { createReadStream } from "node:fs";import { basename, dirname, join, relative } from "node:path";import { createInterface } from "node:readline";+import { isDeepStrictEqual } from "node:util";import { sessionFiles } from "./cost.js";import { CodexSecurityError } from "./errors.js";import type { JsonObject } from "./config.js";@@ -105,7 +106,7 @@ export async function findScanSession(}export async function readScanLogs(options: ScanLogOptions) {- const logs = new Map<string, SessionLog>();+ const logs = new Map<string, [SessionLog, ...SessionLog[]]>();const homes = new Set(typeof options.codexHome === "string"? [options.codexHome]@@ -114,12 +115,14 @@ export async function readScanLogs(options: ScanLogOptions) {for (const directory of ["sessions", "archived_sessions"]) {for (const home of homes) {for await (const session of scanSessions(home, directory)) {- if (!logs.has(session.threadId)) logs.set(session.threadId, session);+ const copies = logs.get(session.threadId);+ if (copies === undefined) logs.set(session.threadId, [session]);+ else copies.push(session);}}}- const root = options.threadId ? logs.get(options.threadId) : undefined;+ const root = options.threadId ? logs.get(options.threadId)?.[0] : undefined;if (root === undefined && !options.allowMissingRoot) {throw new CodexSecurityError(`No saved session logs are available for scan ${options.scanId}.`,@@ -136,8 +139,8 @@ export async function readScanLogs(options: ScanLogOptions) {const traversed = new Set(options.executionThreadIds ?? included);const pending = [...traversed];for (const parentId of pending) {- const parent = logs.get(parentId);- for (const session of logs.values()) {+ const parent = logs.get(parentId)?.[0];+ for (const [session] of logs.values()) {if (!traversed.has(session.threadId) &&(session.parentThreadId === parentId ||@@ -154,8 +157,13 @@ export async function readScanLogs(options: ScanLogOptions) {}const sessions: SessionLog[] = [];for (const threadId of included) {- const session = logs.get(threadId);- if (session !== undefined) sessions.push(session);+ const copies = logs.get(threadId);+ if (copies === undefined) continue;+ let session = copies[0];+ for (const copy of copies.slice(1)) {+ if (await extendsSessionLog(session.path, copy.path)) session = copy;+ }+ sessions.push(session);}const events: Record<string, unknown>[] = [];for (const session of sessions) {@@ -238,6 +246,24 @@ function belongsToScan(return false;}+// Prefer a longer copy only when it preserves every event in the earlier copy.+// Identical or divergent copies keep the existing home/archive precedence.+async function extendsSessionLog(+ previousPath: string,+ path: string,+): Promise<boolean> {+ const events = sessionEvents(path);+ try {+ for await (const previous of sessionEvents(previousPath)) {+ const next = await events.next();+ if (next.done || !isDeepStrictEqual(previous, next.value)) return false;+ }+ return !(await events.next()).done;+ } finally {+ await events.return(undefined);+ }+}+async function* sessionEvents(path: string,): AsyncGenerator<Record<string, unknown>> {diff --git a/sdk/typescript/tests-ts/scan-logs.test.ts b/sdk/typescript/tests-ts/scan-logs.test.tsindex 059e0e42f..972637477 100644--- a/sdk/typescript/tests-ts/scan-logs.test.ts+++ b/sdk/typescript/tests-ts/scan-logs.test.ts@@ -82,6 +82,91 @@ function commandEvent(command: string, id: string, timestamp?: string) {}describe("saved scan logs", () => {+ test.each([+ ["prefix first", [0], [0, 1, 1, 2], 1, false],+ ["complete first", [0, 1, 1, 2], [0], 0, false],+ ["identical copies", [0, 1, 1, 2], [0, 1, 1, 2], 0, false],+ ["longer divergent copy", [0, 2], [0, 1, 1, 2], 0, false],+ ["shorter divergent copy", [0, 1, 1, 2], [0, 2], 0, false],+ ["equal-length divergent copy", [0, 1], [0, 2], 0, false],+ ["complete archived copy", [0], [0, 1, 1, 2], 1, true],+ ["prefix archived copy", [0, 1, 1, 2], [0], 0, true],+ ["identical archived copy", [0, 1, 1, 2], [0, 1, 1, 2], 0, true],+ ["divergent archived copy", [0, 2], [0, 1, 1, 2], 0, true],+ ] as const)(+ "retains complete copied rollout events and precedence: %s",+ async (_label, first, second, selected, archived) => {+ const homes = [await temporaryHome(), await temporaryHome()];+ const activity = [+ commandEvent("first", "first-call", "2026-08-11T12:00:03Z"),+ commandEvent("repeated", "repeat-call", "2026-08-11T12:00:01Z"),+ commandEvent("last", "last-call", "2026-08-11T12:00:02Z"),+ ];+ const copies = [first, second];+ for (const [index, home] of homes.entries()) {+ await writeSession(home, "parent", []);+ await writeSession(+ home,+ "worker",+ copies[index]!.map((event) => activity[event]!),+ "parent",+ );+ }+ if (archived) {+ await rename(+ join(homes[1]!, "sessions"),+ join(homes[1]!, "archived_sessions"),+ );+ }+ const result = await readSavedScanLogs(+ {+ scanId: "scan-1",+ continuationThreadId: "parent",+ executionThreadIds: ["parent"],+ },+ archived ? [...homes].reverse() : homes,+ );+ expect(result.sessions.map(({ threadId }) => threadId)).toEqual([+ "parent",+ "worker",+ ]);+ expect(result.sessions[1]!.path).toBe(+ join(+ homes[selected]!,+ archived && selected === 1 ? "archived_sessions" : "sessions",+ "2026",+ "08",+ "11",+ "rollout-worker.jsonl",+ ),+ );+ expect(+ result.events+ .filter(({ threadId }) => threadId === "worker")+ .slice(1)+ .map(({ event }) => event),+ ).toEqual(copies[selected]!.map((event) => activity[event]!));+ },+ );++ test("keeps first-copy ownership when a longer copy has different session metadata", async () => {+ const first = await temporaryHome();+ const second = await temporaryHome();+ const event = commandEvent("scan work", "scan-call");+ await writeSession(first, "parent", []);+ await writeSession(first, "worker", [event], "unrelated");+ await writeSession(second, "worker", [event, event], "parent");+ const result = await readSavedScanLogs(+ {+ scanId: "scan-1",+ continuationThreadId: "parent",+ executionThreadIds: ["parent"],+ },+ [first, second],+ );+ expect(result.sessions.map(({ threadId }) => threadId)).toEqual(["parent"]);+ });+test("collects known desktop and CLI threads across active and archived homes without duplicates", async () => {const desktop = await temporaryHome();const cli = await temporaryHome();@@ -523,37 +608,48 @@ describe("saved scan logs", () => {);});- test("does not parse event bodies from unrelated saved sessions", async () => {- const home = await temporaryHome();- await writeSession(home, "parent", [- commandEvent("included", "parent-call"),- ]);- await writeSession(home, "unrelated", [- commandEvent("UNRELATED_PRIVATE_EVENT_BODY", "unrelated-call"),- ]);- const originalParse = JSON.parse;- let unrelatedBodies = 0;- const parseSpy = spyOn(JSON, "parse").mockImplementation(- (text, reviver) => {- if (text.includes("UNRELATED_PRIVATE_EVENT_BODY")) unrelatedBodies++;- return originalParse(text, reviver);- },- );-- try {- const result = await readScanLogs({- scanId: "scan-1",- threadId: "parent",- codexHome: home,- });- expect(result.sessions.map(({ threadId }) => threadId)).toEqual([- "parent",+ test.each([false, true])(+ "does not parse event bodies from unrelated saved sessions (copied: %p)",+ async (copied) => {+ const home = await temporaryHome();+ await writeSession(home, "parent", [+ commandEvent("included", "parent-call"),]);- expect(unrelatedBodies).toBe(0);- } finally {- parseSpy.mockRestore();- }- });+ const unrelated = commandEvent(+ "UNRELATED_PRIVATE_EVENT_BODY",+ "unrelated-call",+ );+ await writeSession(home, "unrelated", [unrelated]);+ const homes = [home];+ if (copied) {+ const copyHome = await temporaryHome();+ await writeSession(copyHome, "unrelated", [unrelated, unrelated]);+ homes.push(copyHome);+ }+ const originalParse = JSON.parse;+ let unrelatedBodies = 0;+ const parseSpy = spyOn(JSON, "parse").mockImplementation(+ (text, reviver) => {+ if (text.includes("UNRELATED_PRIVATE_EVENT_BODY")) unrelatedBodies++;+ return originalParse(text, reviver);+ },+ );++ try {+ const result = await readScanLogs({+ scanId: "scan-1",+ threadId: "parent",+ codexHome: homes,+ });+ expect(result.sessions.map(({ threadId }) => threadId)).toEqual([+ "parent",+ ]);+ expect(unrelatedBodies).toBe(0);+ } finally {+ parseSpy.mockRestore();+ }+ },+ );test("preserves large selected events and skips malformed metadata prefixes", async () => {const home = await temporaryHome();