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(cli): keep scan identity visible in results and failures (#1554)

mldangelo-oaia2917cace2b0
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 076a54f3c..f54fa6b98 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1067,6 +1067,25 @@ least eight characters.
| `findings list [REPOSITORY]` | List open findings. |
| `findings false-positive OCCURRENCE_ID --reason TEXT` | Dismiss a finding while the reason applies. |
+Without an ID, `scans show` selects the latest completed scan, while `scans logs`
+selects the latest scan of any status. After a successful scan followed by a
+failed or active scan, these defaults refer to different runs. Human output
+identifies the selected run, labels its saved update time, and gives matching
+commands with its full scan ID:
+
+```bash
+codex-security scans show SCAN_ID
+codex-security scans logs SCAN_ID
+```
+
+Completion summaries include that ID and the saved results directory. Failure
+summaries include the same navigation when the current run was registered, plus
+the last observed phase when available. A failure before registration has no
+scan ID. The handoff uses that run's registration receipt without querying scan
+history. Inspect its saved status before choosing resume or rerun, and supply
+the original custom prompt files for reruns. Structured history and log output
+and command selection defaults are unchanged.
+
Recipes save settings and authentication choice, not credentials. Reruns use the
current checkout/context files and do not reload project files. Supply replacement
scan and custom-validation prompts when the original used them:
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index f85efa5c7..9a76f340b 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -316,6 +316,12 @@ export interface ScanOptions extends ScanSettings {
) => number | undefined | Promise<number | undefined>;
onOutputArchived?: (archiveDir: string) => void;
onOutputDirReady?: (scanDir: string) => void;
+ /** @internal Authoritative registration receipt for CLI scan navigation. */
+ onScanRegistered?: (scan: {
+ scanId: string;
+ scanDir: string;
+ startedAt?: string;
+ }) => void;
onAuthentication?: (authentication: ScanAuthentication) => void;
onTrustedAccessStatus?: (status: ScanTrustedAccessStatus) => void;
onScanStarted?: () => void;
@@ -418,6 +424,7 @@ type ScanObserverName =
| "onCost"
| "onOutputArchived"
| "onOutputDirReady"
+ | "onScanRegistered"
| "onScanStarted"
| "onTrustedAccessStatus"
| "onReconnect"
@@ -1785,6 +1792,16 @@ export class CodexSecurity {
});
}
activeScan = { id: scanId, options: workbenchOptions };
+ notifyObserver(
+ options,
+ "onScanRegistered",
+ )({
+ scanId,
+ scanDir,
+ ...(typeof registration["startedAt"] === "string"
+ ? { startedAt: registration["startedAt"] }
+ : {}),
+ });
if (typeof registration["archivedScanDir"] === "string") {
notifyObserver(
options,
@@ -3312,6 +3329,16 @@ export class CodexSecurity {
);
}
activeScan = { id: scanId, options: workbenchOptions };
+ notifyObserver(
+ options,
+ "onScanRegistered",
+ )({
+ scanId,
+ scanDir,
+ ...(typeof registration["startedAt"] === "string"
+ ? { startedAt: registration["startedAt"] }
+ : {}),
+ });
if (typeof registration["archivedScanDir"] === "string") {
notifyObserver(
options,
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 04b3c61a2..28f7dfc67 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -1950,6 +1950,24 @@ export async function main(
});
return result;
};
+ const showHistoryNavigation = async (
+ scan: JsonObject,
+ format: string,
+ selection?: string,
+ ): Promise<void> => {
+ if (
+ format !== "toon" ||
+ argv.some((argument) => OUTPUT_OPTION.test(argument))
+ )
+ return;
+ await withTerminalErrorsHandled(errorOutput, async () => {
+ try {
+ printScanReference(scan, errorOutput, selection);
+ } catch {
+ // Optional navigation must not prevent reading saved results or logs.
+ }
+ });
+ };
const findingFeedback = Cli.create("findings", {
description: "Review saved findings (default: list).",
}).command("false-positive", {
@@ -2100,6 +2118,7 @@ export async function main(
})
.command("show", {
description: "Show the results and saved configuration for a scan.",
+ hint: "Without an ID, show selects the latest completed scan; logs selects the latest scan of any status. Pass the same ID to inspect one run.",
mcp: false,
args: z.object({
scanId: z
@@ -2123,11 +2142,31 @@ export async function main(
],
output: z.record(z.string(), z.unknown()).optional(),
async run({ args, format, options }) {
- const scanId = args.scanId ?? (await latestScans())?.[0]?.scanId;
+ let scanId = args.scanId;
+ if (scanId === undefined) {
+ try {
+ scanId = (await latestScans())?.[0]?.scanId;
+ } catch (error) {
+ if (
+ format === "toon" &&
+ !argv.some((argument) => OUTPUT_OPTION.test(argument))
+ ) {
+ errorOutput.write(
+ "Use codex-security scans list to find failed or active scans, then pass a scan ID to scans show and scans logs.\n",
+ );
+ }
+ throw error;
+ }
+ }
if (scanId === undefined) return;
return presentHistory(
- await history(["get-scan", "--scan-id", scanId], (value) => {
+ await history(["get-scan", "--scan-id", scanId], async (value) => {
const { scan, recipe, parentScanId } = value;
+ await showHistoryNavigation(
+ scan as JsonObject,
+ format,
+ args.scanId === undefined ? "latest completed scan" : undefined,
+ );
return {
...(scan as JsonObject),
...(recipe === undefined ? {} : { recipe }),
@@ -2142,13 +2181,16 @@ export async function main(
})
.command("logs", {
description: "Show saved activity for a scan and its workers.",
+ hint: "Without an ID, logs selects the latest scan, including failed and active runs; show selects the latest completed scan. Pass the same ID to inspect one run.",
mcp: false,
args: z.object({
scanId: z
.string()
.min(1)
.optional()
- .describe("Scan identifier or unique prefix (default: latest)."),
+ .describe(
+ "Scan identifier or unique prefix (default: latest, any status).",
+ ),
}),
examples: [
{ args: {}, description: "Show activity from the latest scan." },
@@ -2166,6 +2208,13 @@ export async function main(
["get-scan", "--scan-id", scanId],
async (value) => {
const scan = value["scan"] as ScanLogSource;
+ await showHistoryNavigation(
+ scan,
+ format,
+ args.scanId === undefined
+ ? "latest scan, including failed and active runs"
+ : undefined,
+ );
const logs = await readSavedScanLogs(
scan,
[
@@ -8118,6 +8167,7 @@ async function executeScan(
dependencies: CliDependencies,
interactive = true,
): Promise<ScanOutcome> {
+ let registeredScan: JsonObject | undefined;
let scanDir: string | null = null;
const scanInput = dependencies.scanInput ?? process.stdin;
let requestedSignal: SignalName | null = null;
@@ -8448,6 +8498,10 @@ async function executeScan(
);
},
signal: preparationAbortController.signal,
+ onScanRegistered: (scan) => {
+ registeredScan = scan;
+ scanDir = scan.scanDir;
+ },
onOutputDirReady: (path) => {
scanDir = path;
diagnostic("scan.output_ready", { scan_dir: path });
@@ -8701,8 +8755,10 @@ async function executeScan(
signal: requestedSignal,
partial_output: scanDir !== null,
});
+ const exitCode = interruptedExit(requestedSignal, scanDir, errorOutput);
+ printFailedScanReference(registeredScan, phase, arguments_, errorOutput);
return {
- exitCode: interruptedExit(requestedSignal, scanDir, errorOutput),
+ exitCode,
error:
requestedSignal === "SIGINT"
? "Scan canceled by Ctrl-C."
@@ -8737,6 +8793,7 @@ async function executeScan(
});
errorOutput.write(`${message}\n`);
if (failure instanceof ScanInterruptedError) {
+ printFailedScanReference(registeredScan, phase, arguments_, errorOutput);
return { exitCode: 2, error: message };
}
if (scanDir !== null) {
@@ -8744,6 +8801,7 @@ async function executeScan(
`Partial output was kept at ${errorMessage(scanDir)}.\n`,
);
}
+ printFailedScanReference(registeredScan, phase, arguments_, errorOutput);
return { exitCode: 2, error: message };
}
if (preflight !== null) {
@@ -8792,6 +8850,7 @@ async function executeScan(
message: "Scan completed without a result.",
});
errorOutput.write("scan completed without a result\n");
+ printFailedScanReference(registeredScan, phase, arguments_, errorOutput);
return { exitCode: 2, error: "Scan completed without a result." };
}
const threshold = arguments_.failureSeverity;
@@ -9237,6 +9296,72 @@ async function readDeepScanStop(
};
}
+function printScanReference(
+ scan: JsonObject,
+ output: Writable,
+ selection?: string,
+): void {
+ const scanId = scan["scanId"];
+ if (typeof scanId !== "string") return;
+ const progress = scan["progress"] as JsonObject | undefined;
+ const detail = [
+ `Scan ${diagnosticValue(scanId)}`,
+ ...(typeof progress?.["status"] === "string"
+ ? [diagnosticValue(progress["status"])]
+ : []),
+ ...(typeof progress?.["phase"] === "string"
+ ? [diagnosticValue(progress["phase"])]
+ : []),
+ ...(typeof scan["startedAt"] === "string"
+ ? [`started ${diagnosticValue(scan["startedAt"])}`]
+ : typeof scan["updatedAt"] === "string"
+ ? [`updated ${diagnosticValue(scan["updatedAt"])}`]
+ : []),
+ ];
+ const argument = quoteCliPath(diagnosticValue(scanId));
+ output.write(
+ `\n${detail.join(" · ")}\n` +
+ (selection === undefined ? "" : `Selected ${selection}.\n`) +
+ `Inspect: codex-security scans show ${argument}\n` +
+ `Logs: codex-security scans logs ${argument}\n`,
+ );
+}
+
+function printFailedScanReference(
+ scan: JsonObject | undefined,
+ phase: string | null,
+ arguments_: ScanArguments,
+ output: Writable,
+): void {
+ if (scan === undefined) return;
+ try {
+ printScanReference(scan, output);
+ if (phase !== null)
+ output.write(`Last observed phase: ${diagnosticValue(phase)}\n`);
+ output.write(
+ `Retained results: ${diagnosticValue(scan["scanDir"])}\n` +
+ "Inspect the saved scan status before choosing resume or rerun.\n",
+ );
+ const prompts = [
+ ...(arguments_.scanPromptFile !== undefined ||
+ arguments_.scanPrompt !== undefined
+ ? ["--scan-prompt-file"]
+ : []),
+ ...(arguments_.validationPromptFile !== undefined ||
+ arguments_.validationPrompt !== undefined
+ ? ["--validation-prompt-file"]
+ : []),
+ ];
+ if (prompts.length > 0) {
+ output.write(
+ `A rerun requires the original instructions via ${prompts.join(" and ")}.\n`,
+ );
+ }
+ } catch {
+ // Optional navigation must not replace the scan's original failure.
+ }
+}
+
function printScanSummary(
result: ScanResult,
progress: Progress | null,
@@ -9315,6 +9440,14 @@ function printScanSummary(
errorOutput.write(
` ${paint("RESULTS", 1)} ${errorMessage(result.scanDir)}\n`,
);
+ printScanReference(
+ {
+ scanId: result.manifest.scan.id,
+ progress: { status: "complete" },
+ startedAt: result.manifest.scan.startedAt,
+ },
+ errorOutput,
+ );
if (deepScanStop?.nextStep !== undefined) {
errorOutput.write(`\n ${deepScanStop.nextStep}\n`);
}
diff --git a/sdk/typescript/src/scan-history-renderer.ts b/sdk/typescript/src/scan-history-renderer.ts
index 410d47530..305152274 100644
--- a/sdk/typescript/src/scan-history-renderer.ts
+++ b/sdk/typescript/src/scan-history-renderer.ts
@@ -260,6 +260,11 @@ export function renderScanHistory(
` ${strong(clean(basename(result["targetPath"] as string)))} ${accent("·")} ${clean(result["scanId"])}`,
` ${paint(`${status === "complete" ? "✓" : "●"} ${status.toUpperCase()}`, statusColor)} ${accent("·")} ${clean(result["mode"])}`,
);
+ if (typeof result["startedAt"] === "string") {
+ lines.push(` ${strong("STARTED")} ${clean(result["startedAt"])}`);
+ } else if (typeof result["updatedAt"] === "string") {
+ lines.push(` ${strong("UPDATED")} ${clean(result["updatedAt"])}`);
+ }
if (result["failureMessage"]) {
wrap(String(result["failureMessage"]), 11, ` ${paint("ERROR", 31)} `);
}
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 75f1a1820..b85439344 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -947,12 +947,15 @@ describe("CodexSecurity orchestration", () => {
pythonPath: "/definitely/missing/python",
});
const onScanStarted = mock();
+ const onScanRegistered = mock();
await expect(
client.run("/definitely/missing/repository", {
onScanStarted,
+ onScanRegistered,
}),
).rejects.toBeInstanceOf(InvalidTargetError);
expect(onScanStarted).not.toHaveBeenCalled();
+ expect(onScanRegistered).not.toHaveBeenCalled();
await client.close();
});
@@ -2065,26 +2068,52 @@ describe("CodexSecurity orchestration", () => {
await client.close();
});
- test("isolates authentication observer failures from scan startup", async () => {
+ test.each(["onAuthentication", "onScanRegistered"] as const)(
+ "isolates %s observer failures from scan startup",
+ async (observer) => {
+ const { root, repository, codexHome } = await runtimeDirectories();
+ const observerErrors: Array<[ScanObserverName, string]> = [];
+ const client = TestClient.withDependencies({
+ prepareRuntime: async () => preparedRuntime(codexHome),
+ resolvePluginPython: async () => "/managed/python",
+ repositoryRevision: async () => null,
+ createCodex: codexFactory(scanDidNotStart),
+ });
+
+ await expect(
+ client.run(repository, {
+ outputDir: join(root, "scan"),
+ [observer]: () => fail("observer exploded"),
+ onObserverError: collectObserverErrors(observerErrors),
+ }),
+ ).rejects.toThrow("scan did not start");
+ expect(observerErrors).toEqual([[observer, "observer exploded"]]);
+ await client.close();
+ },
+ );
+
+ test("does not announce a scan when its output directory registration fails", async () => {
const { root, repository, codexHome } = await runtimeDirectories();
- const observerErrors: Array<[ScanObserverName, string]> = [];
+ const onOutputDirReady = mock();
+ const onScanRegistered = mock();
const client = TestClient.withDependencies({
prepareRuntime: async () => preparedRuntime(codexHome),
resolvePluginPython: async () => "/managed/python",
repositoryRevision: async () => null,
+ runWorkbench: async () => {
+ throw new Error("Output directory already registered");
+ },
createCodex: codexFactory(scanDidNotStart),
});
-
await expect(
client.run(repository, {
outputDir: join(root, "scan"),
- onAuthentication: () => fail("authentication observer exploded"),
- onObserverError: collectObserverErrors(observerErrors),
+ onOutputDirReady,
+ onScanRegistered,
}),
- ).rejects.toThrow("scan did not start");
- expect(observerErrors).toEqual([
- ["onAuthentication", "authentication observer exploded"],
- ]);
+ ).rejects.toThrow("Output directory already registered");
+ expect(onOutputDirReady).toHaveBeenCalled();
+ expect(onScanRegistered).not.toHaveBeenCalled();
await client.close();
});
diff --git a/sdk/typescript/tests-ts/cli-scan-logs.test.ts b/sdk/typescript/tests-ts/cli-scan-logs.test.ts
index 64227ca42..817d711cc 100644
--- a/sdk/typescript/tests-ts/cli-scan-logs.test.ts
+++ b/sdk/typescript/tests-ts/cli-scan-logs.test.ts
@@ -218,7 +218,12 @@ describe("saved logs JSON output", () => {
} else {
expect(stdout.text()).toBe(expected);
}
- expect(stderr.text()).toBe("");
+ if (args.length === 0) {
+ expect(stderr.text()).toContain("scans show scan-1");
+ expect(stderr.text()).toContain("scans logs scan-1");
+ } else {
+ expect(stderr.text()).toBe("");
+ }
} finally {
await rm(f.state, { recursive: true, force: true });
}
diff --git a/sdk/typescript/tests-ts/cli-scan-navigation.test.ts b/sdk/typescript/tests-ts/cli-scan-navigation.test.ts
new file mode 100644
index 000000000..42c109b4e
--- /dev/null
+++ b/sdk/typescript/tests-ts/cli-scan-navigation.test.ts
@@ -0,0 +1,250 @@
+import { mkdir, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { describe, expect, test } from "bun:test";
+import { main } from "../src/cli.js";
+import type { JsonObject } from "../src/config.js";
+import { dependencies, fakeResult } from "./cli-fixtures.js";
+import { createCliTest } from "./support/cli-run.js";
+import { writeJsonLines } from "./support/json.js";
+import { temporaryDirectory } from "./support/temporary-directories.js";
+import { runCommand } from "./support/shell.js";
+
+const completedId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
+const latestId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
+const startedAt = "2026-01-02T12:00:00Z";
+
+describe("scan navigation", () => {
+ test.each(["show", "logs"])(
+ "%s keeps saved output when optional navigation fails",
+ async (command) => {
+ for (const failure of ["sync", "EPIPE", "ENOSPC"]) {
+ const result = await runCommand(process.execPath, [
+ join(import.meta.dir, "fixtures", "scan-navigation-output.mts"),
+ command,
+ failure,
+ ]);
+ expect(result.status, result.stderr).toBe(0);
+ expect(JSON.parse(result.stdout)).toMatchObject({ status: 0 });
+ expect(JSON.parse(result.stdout).output).toContain(completedId);
+ expect(result.stderr).toBe("");
+ }
+ },
+ );
+
+ test.each(["failed", "running"])(
+ "identifies different default result and log selections when the latest scan is %s",
+ async (status) => {
+ const root = await temporaryDirectory("scan-navigation-");
+ try {
+ const home = join(root, "codex-home");
+ await mkdir(join(home, "sessions"), { recursive: true });
+ await writeJsonLines(join(home, "sessions", "rollout.jsonl"), [
+ { type: "session_meta", payload: { id: "latest-thread" } },
+ { type: "event_msg", payload: { message: "Saved scan activity" } },
+ ]);
+ const completed = {
+ scanId: completedId,
+ targetPath: join(root, "repository"),
+ mode: "deep",
+ updatedAt: "2026-01-01T12:00:00Z",
+ progress: { status: "complete" },
+ findings: [],
+ };
+ const latest = {
+ ...completed,
+ scanId: latestId,
+ continuationThreadId: "latest-thread",
+ updatedAt: startedAt,
+ progress: { status },
+ };
+ const calls: string[][] = [];
+ const deps = dependencies({
+ environment: { CODEX_HOME: home, CODEX_SECURITY_STATE_DIR: root },
+ onWorkbench: (args): JsonObject => {
+ calls.push([...args]);
+ if (args[0] === "list-scans")
+ return {
+ scans: args.includes("complete")
+ ? [completed]
+ : [latest, completed],
+ };
+ return {
+ scan: completedId.startsWith(args[2]!) ? completed : latest,
+ };
+ },
+ });
+ for (const interactive of [false, true]) {
+ const show = createCliTest(main, { stdout: interactive });
+ expect(await show.runCli(["scans", "show"], deps)).toBe(0);
+ expect(show.stderr.text()).toContain(
+ `Scan ${completedId} · complete`,
+ );
+ expect(show.stderr.text()).toContain(
+ "Selected latest completed scan",
+ );
+ expect(show.stderr.text()).toContain(
+ `updated ${completed.updatedAt}`,
+ );
+ expect(show.stderr.text()).toContain(`scans logs ${completedId}`);
+ expect(show.stderr.text()).not.toContain(latestId);
+
+ const logs = createCliTest(main, { stdout: interactive });
+ expect(await logs.runCli(["scans", "logs"], deps)).toBe(0);
+ expect(logs.stderr.text()).toContain(`Scan ${latestId} · ${status}`);
+ expect(logs.stderr.text()).toContain(
+ "including failed and active runs",
+ );
+ expect(logs.stderr.text()).toContain(`updated ${latest.updatedAt}`);
+ expect(logs.stderr.text()).toContain(`scans show ${latestId}`);
+ expect(logs.stderr.text()).not.toContain(completedId);
+ }
+ expect(
+ calls.filter((args) => args[0] === "get-scan").map((args) => args[2]),
+ ).toEqual([completedId, latestId, completedId, latestId]);
+
+ for (const command of ["show", "logs"]) {
+ const explicit = createCliTest(main);
+ expect(
+ await explicit.runCli(
+ ["scans", command, latestId.slice(0, 8)],
+ deps,
+ ),
+ ).toBe(0);
+ expect(explicit.stderr.text()).toContain(`scans show ${latestId}`);
+ expect(explicit.stderr.text()).toContain(`scans logs ${latestId}`);
+ expect(explicit.stderr.text()).not.toContain("Selected latest");
+ }
+ const json = createCliTest(main);
+ expect(await json.runCli(["scans", "show", "--json"], deps)).toBe(0);
+ expect(JSON.parse(json.stdout.text())).toEqual(completed);
+ expect(json.stderr.text()).toBe("");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
+
+ test("points to saved history when there are no completed scans", async () => {
+ const cli = createCliTest(main);
+ expect(await cli.runCli(["scans", "show"], dependencies())).toBe(2);
+ expect(cli.stderr.text()).toContain("No completed scans");
+ expect(cli.stderr.text()).toContain("codex-security scans list");
+ expect(cli.stderr.text()).toContain("failed or active scans");
+ });
+
+ test("completion navigation uses the complete scan ID without changing JSON", async () => {
+ const result = fakeResult(["high"], "partial");
+ result.manifest.scan.id = completedId;
+ const cli = createCliTest(main);
+ expect(await cli.runCli(["scan", "--json"], dependencies({ result }))).toBe(
+ 2,
+ );
+ expect(JSON.parse(cli.stdout.text())).toEqual(result.toJSON());
+ expect(cli.stderr.text()).toContain(`Scan ${completedId} · complete`);
+ expect(cli.stderr.text()).toContain(
+ `started ${result.manifest.scan.startedAt}`,
+ );
+ expect(cli.stderr.text()).toContain(`scans show ${completedId}`);
+ expect(cli.stderr.text()).toContain(`scans logs ${completedId}`);
+ expect(cli.stderr.text()).toContain(result.scanDir);
+ });
+
+ test.each([false, true])(
+ "identifies only the registered scan without a history lookup (custom prompts: %p)",
+ async (customPrompts) => {
+ const root = await temporaryDirectory("failed-scan-navigation-");
+ try {
+ const scanDir = join(root, "results");
+ const repository = join(root, "repository");
+ await mkdir(repository);
+ const promptFile = join(root, "instructions.md");
+ await writeFile(promptFile, "Review the authorized source.");
+ const failure = "Reducer could not record its result";
+ const cli = createCliTest(main);
+ let lookups = 0;
+ const deps = dependencies({
+ currentDirectory: repository,
+ onTurn: (_repository, options) => {
+ options.onOutputDirReady?.(scanDir);
+ options.onScanRegistered?.({
+ scanId: latestId,
+ scanDir,
+ startedAt,
+ });
+ options.onProgress?.({
+ phase: "discovery",
+ filesCompleted: 1,
+ filesTotal: 2,
+ });
+ throw new Error(failure);
+ },
+ onWorkbench: () => {
+ lookups += 1;
+ throw new Error("History unavailable");
+ },
+ });
+ expect(
+ await cli.runCli(
+ [
+ "scan",
+ "--json",
+ ...(customPrompts
+ ? [
+ "--scan-prompt-file",
+ promptFile,
+ "--validation-prompt-file",
+ promptFile,
+ ]
+ : []),
+ ],
+ deps,
+ ),
+ ).toBe(2);
+ expect(lookups).toBe(0);
+ expect(cli.stderr.text()).toContain(failure);
+ expect(cli.stderr.text()).toContain(`Scan ${latestId}`);
+ expect(cli.stderr.text()).toContain(startedAt);
+ expect(cli.stderr.text()).toContain(
+ "Last observed phase: reviewing files",
+ );
+ expect(cli.stderr.text()).toContain(`Retained results: ${scanDir}`);
+ expect(cli.stderr.text()).toContain(`scans show ${latestId}`);
+ expect(cli.stderr.text()).toContain(`scans logs ${latestId}`);
+ expect(cli.stderr.text()).toContain("Inspect the saved scan status");
+ expect(cli.stderr.text()).not.toContain("scans rerun");
+ expect(cli.stderr.text()).not.toContain("scans resume");
+ if (customPrompts) {
+ expect(cli.stderr.text()).toContain(
+ "original instructions via --scan-prompt-file and --validation-prompt-file",
+ );
+ }
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
+
+ test.each([false, true])(
+ "does not adopt another scan before registration (output ready: %p)",
+ async (outputReady) => {
+ const scanDir = join("/tmp", "shared-output-directory");
+ const cli = createCliTest(main);
+ let lookups = 0;
+ const deps = dependencies({
+ onTurn: (_repository, options) => {
+ if (outputReady) options.onOutputDirReady?.(scanDir);
+ throw new Error("Original scan registration failed");
+ },
+ onWorkbench: () => {
+ lookups += 1;
+ return { scans: [{ scanId: completedId, scanDir, startedAt }] };
+ },
+ });
+ expect(await cli.runCli(["scan", "--json"], deps)).toBe(2);
+ expect(cli.stderr.text()).toContain("Original scan registration failed");
+ expect(cli.stderr.text()).not.toContain("scans show");
+ expect(cli.stderr.text()).not.toContain(completedId);
+ expect(lookups).toBe(0);
+ },
+ );
+});
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index f14dbc2de..e1f353726 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -4154,7 +4154,8 @@ describe("CLI", () => {
expect(await runCli(["scan"], dependencies({ result }))).toBe(0);
expect(stdout.text()).toBe("");
expect(stderr.text()).toContain("Scan complete · 12345678");
- expect(stderr.text()).not.toContain(result.manifest.scan.id);
+ expect(stderr.text()).toContain(`scans show ${result.manifest.scan.id}`);
+ expect(stderr.text()).toContain(`scans logs ${result.manifest.scan.id}`);
expect(stderr.text()).toContain(
[
` REPORT ${result.reportPath}`,
diff --git a/sdk/typescript/tests-ts/fixtures/scan-navigation-output.mts b/sdk/typescript/tests-ts/fixtures/scan-navigation-output.mts
new file mode 100644
index 000000000..15ab1bb9d
--- /dev/null
+++ b/sdk/typescript/tests-ts/fixtures/scan-navigation-output.mts
@@ -0,0 +1,70 @@
+import assert from "node:assert/strict";
+import { mkdir, rm } from "node:fs/promises";
+import { join } from "node:path";
+import { Writable } from "node:stream";
+import { main } from "../../src/cli.js";
+import { capture, dependencies } from "../cli-fixtures.js";
+import { writeJsonLines } from "../support/json.js";
+import { temporaryDirectory } from "../support/temporary-directories.js";
+
+const command = process.argv[2]!;
+const failure = process.argv[3]!;
+const root = await temporaryDirectory("scan-navigation-output-");
+try {
+ process.env["XDG_DATA_HOME"] = root;
+ const home = join(root, "codex-home");
+ await mkdir(join(home, "sessions"), { recursive: true });
+ await writeJsonLines(join(home, "sessions", "rollout.jsonl"), [
+ { type: "session_meta", payload: { id: "saved-thread" } },
+ { type: "event_msg", payload: { message: "Saved activity" } },
+ ]);
+ const scan = {
+ scanId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ targetPath: join(root, "repository"),
+ mode: "standard",
+ updatedAt: "2026-01-01T12:00:00Z",
+ continuationThreadId: "saved-thread",
+ progress: { status: "complete" },
+ findings: [],
+ };
+ const stdout = capture();
+ const error = Object.assign(new Error("Diagnostic output failed"), {
+ code: failure,
+ });
+ let writes = 0;
+ const stderr =
+ failure === "sync"
+ ? {
+ write(): boolean {
+ writes += 1;
+ throw error;
+ },
+ }
+ : new Writable({
+ autoDestroy: false,
+ write(_chunk, _encoding, callback) {
+ writes += 1;
+ setImmediate(() => callback(error));
+ },
+ });
+ const status = await main(
+ ["scans", command, scan.scanId],
+ stdout.stream,
+ stderr,
+ dependencies({
+ environment: { CODEX_HOME: home, CODEX_SECURITY_STATE_DIR: root },
+ onWorkbench: () => ({ scan }),
+ }),
+ );
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ assert.equal(status, 0);
+ assert.ok(writes > 0);
+ assert.ok(stdout.text().includes(scan.scanId));
+ if (stderr instanceof Writable) {
+ assert.equal(stderr.errored, error);
+ assert.equal(stderr.listenerCount("error"), 0);
+ }
+ process.stdout.write(JSON.stringify({ status, output: stdout.text() }));
+} finally {
+ await rm(root, { recursive: true, force: true });
+}
diff --git a/sdk/typescript/tests-ts/mock-scan.test.ts b/sdk/typescript/tests-ts/mock-scan.test.ts
index fdf961566..4426e87be 100644
--- a/sdk/typescript/tests-ts/mock-scan.test.ts
+++ b/sdk/typescript/tests-ts/mock-scan.test.ts
@@ -1,4 +1,4 @@
-import type { ScanOptions } from "../src/index.js";
+import type { JsonObject, ScanOptions } from "../src/index.js";
import {
mkdir,
mkdtemp,
@@ -57,6 +57,9 @@ async function fixture() {
test("mock scans seal real artifacts and index shared and unique findings without Codex", async () => {
const { repository, client, environment, python } = await fixture();
const callbacks: string[] = [];
+ const registrations: Array<
+ Parameters<NonNullable<ScanOptions["onScanRegistered"]>>[0]
+ > = [];
try {
const first = await client.run(repository, {
mock: true,
@@ -64,10 +67,20 @@ test("mock scans seal real artifacts and index shared and unique findings withou
maxCostUsd: 0.01,
failureSeverity: "informational",
onAuthentication: () => callbacks.push("authentication"),
+ onScanRegistered: (scan) => {
+ callbacks.push("registered");
+ registrations.push(scan);
+ },
onScanStarted: () => callbacks.push("started"),
});
const second = await client.run(repository, { mock: true });
- expect(callbacks).toEqual(["started"]);
+ expect(callbacks).toEqual(["registered", "started"]);
+ expect(registrations).toEqual([
+ {
+ scanId: first.manifest.scan.id,
+ scanDir: first.scanDir,
+ },
+ ]);
expect(first.findings.findings).toHaveLength(12);
expect(first.coverage.completeness).toBe("complete");
expect(first.manifest.scan.status).toBe("completed");
@@ -127,6 +140,27 @@ test("mock scans seal real artifacts and index shared and unique findings withou
["list-scans", "--repository", repository],
);
expect(history["scans"]).toHaveLength(2);
+ const saved = await runWorkbench(
+ { python, pluginRoot: PLUGIN_ROOT, environment },
+ ["get-scan", "--scan-id", first.manifest.scan.id],
+ );
+ const savedScan = saved["scan"] as JsonObject;
+ expect(typeof savedScan["updatedAt"]).toBe("string");
+ const showOutput = capture(true);
+ const showDiagnostics = capture();
+ expect(
+ await main(
+ ["scans", "show", first.manifest.scan.id],
+ showOutput.stream,
+ showDiagnostics.stream,
+ dependencies({ onWorkbench: async () => saved }),
+ ),
+ ).toBe(0);
+ expect(showDiagnostics.text()).toContain(
+ `updated ${savedScan["updatedAt"]}`,
+ );
+ expect(showOutput.text()).toContain("UPDATED");
+ expect(showOutput.text()).toContain(savedScan["updatedAt"] as string);
const recipe = await runWorkbench(
{ python, pluginRoot: PLUGIN_ROOT, environment },
["get-scan-recipe", "--scan-id", first.manifest.scan.id],
diff --git a/sdk/typescript/tests-ts/scan-history-renderer.test.ts b/sdk/typescript/tests-ts/scan-history-renderer.test.ts
index da6264837..df7714380 100644
--- a/sdk/typescript/tests-ts/scan-history-renderer.test.ts
+++ b/sdk/typescript/tests-ts/scan-history-renderer.test.ts
@@ -262,6 +262,7 @@ describe("scan history renderer", () => {
test("shows bounded findings, saved configuration, and failure reasons", () => {
const scan = {
scanId: "12345678-abcd-4567-abcd-1234567890ab",
+ updatedAt: "2026-01-01T12:00:00Z",
parentScanId: "87654321-abcd-4567-abcd-1234567890ab",
targetPath: "/demo/juice-shop",
mode: "standard",
@@ -288,6 +289,7 @@ describe("scan history renderer", () => {
};
const output = stripVTControlCharacters(renderScanHistory(scan, "show"));
for (const expected of [
+ `UPDATED ${scan.updatedAt}`,
"FINDINGS 20 of 75",
"PARENT SCAN 87654321",
"CONFIGURATION",
diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.ts
index b033d52df..072f5b7ab 100644
--- a/sdk/typescript/tests-ts/scan-resume.test.ts
+++ b/sdk/typescript/tests-ts/scan-resume.test.ts
@@ -410,6 +410,8 @@ test("CLI resumes the owning Codex thread and preserves running state on a trans
}),
});
expect(stderr.text()).toContain("Synthetic transport disconnected");
+ expect(stderr.text()).toContain(`scans show ${f.scanId}`);
+ expect(stderr.text()).toContain(`scans logs ${f.scanId}`);
expect(code).not.toBe(0);
expect(resumedThread).toBe(f.threadId);
expect(