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

chore(codex-security): sync public projection

ianw-oaif180f4e5904e
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index ceac26803..c16b1f0bd 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -190,6 +190,9 @@ repository path to inspect another checkout, `--scan-root DIR` to list scans
whose artifacts are under a particular root. `scans show SCAN_ID` includes the
scan configuration, results, coverage, and artifact locations.
+Every scan history command accepts a full scan ID or a unique prefix of at
+least eight characters.
+
Scan history uses the existing Codex Security workbench database at
`$CODEX_HOME/state/plugins/codex-security/workbench.sqlite3`. Set
`CODEX_SECURITY_STATE_DIR` to place the database elsewhere. Scan credentials
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
index 42285efb0..d66cb81a5 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
@@ -774,13 +774,32 @@ def require_workspace(connection: sqlite3.Connection, workspace_id: str) -> sqli
def require_scan(connection: sqlite3.Connection, scan_id: str) -> sqlite3.Row:
- scan_id = require_uuid(scan_id, "scan-id")
+ scan_id = resolve_scan_id(connection, scan_id)
row = connection.execute("SELECT * FROM scans WHERE id = ?", (scan_id,)).fetchone()
if row is None:
raise SystemExit("Codex Security scan not found.")
return row
+def resolve_scan_id(connection: sqlite3.Connection, scan_id: str) -> str:
+ try:
+ return str(uuid.UUID(scan_id))
+ except ValueError:
+ if len(scan_id) < 8:
+ raise SystemExit("Scan ID prefixes must be at least eight characters.") from None
+ matches = connection.execute(
+ "SELECT id FROM scans WHERE substr(id, 1, ?) = ? LIMIT 2",
+ (len(scan_id), scan_id.lower()),
+ ).fetchall()
+ if not matches:
+ raise SystemExit("Codex Security scan not found.") from None
+ if len(matches) > 1:
+ raise SystemExit(
+ f'Scan ID prefix "{scan_id}" matches multiple scans; use a longer prefix.'
+ ) from None
+ return matches[0]["id"]
+
+
def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:
workspace_id = require_uuid(args.workspace_id, "workspace-id")
timestamp = now()
@@ -3208,9 +3227,13 @@ def finding_result(
"title": bounded_output_text(occurrence["title"], FINDING_TITLE_BYTES),
"triage": finding_triage_result(connection, occurrence["id"]),
}
- matches = scan_history.finding_matches(connection, occurrence["id"])
+ matches, known_since, known_scan_ids = scan_history.finding_matches(
+ connection, occurrence["id"], scan["id"], scan["started_at"]
+ )
if matches:
result["matches"] = matches
+ result["knownSince"] = known_since
+ result["knownScanIds"] = known_scan_ids
result.pop("artifactPaths", None)
source_excerpt = finding_source_excerpt(scan, target, locations)
if source_excerpt:
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py
index ae49fc7eb..e73d5ee41 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py
@@ -14,7 +14,12 @@ from workbench_constants import FINDINGS_PAGE_MAX
from workbench_target import git_output
-def _same_repository(before: sqlite3.Row, after: sqlite3.Row) -> bool:
+def _same_repository(
+ before: sqlite3.Row,
+ after: sqlite3.Row,
+ *,
+ after_identity: tuple[str | None, tuple[str, str] | None] | None = None,
+) -> bool:
if before["target_id"] == after["target_id"]:
return True
before_target = Path(before["target_path"])
@@ -22,8 +27,10 @@ def _same_repository(before: sqlite3.Row, after: sqlite3.Row) -> bool:
before_git_dir = git_output(
before_target, "rev-parse", "--path-format=absolute", "--git-common-dir"
)
- after_git_dir = git_output(
- after_target, "rev-parse", "--path-format=absolute", "--git-common-dir"
+ after_git_dir = (
+ git_output(after_target, "rev-parse", "--path-format=absolute", "--git-common-dir")
+ if after_identity is None
+ else after_identity[0]
)
if (
before_git_dir is not None
@@ -32,7 +39,9 @@ def _same_repository(before: sqlite3.Row, after: sqlite3.Row) -> bool:
):
return True
before_origin = _repository_origin(before_target)
- return before_origin is not None and before_origin == _repository_origin(after_target)
+ return before_origin is not None and before_origin == (
+ _repository_origin(after_target) if after_identity is None else after_identity[1]
+ )
def _repository_origin(target: Path) -> tuple[str, str] | None:
@@ -117,12 +126,32 @@ def list_scans(
clauses: list[str] = []
values: list[Any] = []
if args is not None and args.repository:
- repository = str(Path(args.repository).expanduser().resolve())
- clauses.append(
- "(scans.target_path = ? OR scans.target_id IN "
- "(SELECT id FROM security_targets WHERE current_path = ?))"
+ repository = Path(args.repository).expanduser().resolve()
+ requested_repository = connection.execute(
+ """
+ SELECT COALESCE((SELECT id FROM security_targets WHERE current_path = ?), '') AS target_id,
+ ? AS target_path
+ """,
+ (str(repository), str(repository)),
+ ).fetchone()
+ requested_identity = (
+ git_output(repository, "rev-parse", "--path-format=absolute", "--git-common-dir"),
+ _repository_origin(repository),
)
- values.extend((repository, repository))
+ related_target_ids = [
+ target["target_id"]
+ for target in connection.execute(
+ "SELECT id AS target_id, current_path AS target_path FROM security_targets"
+ )
+ if _same_repository(target, requested_repository, after_identity=requested_identity)
+ ]
+ repository_clauses = ["scans.target_path = ?"]
+ values.append(str(repository))
+ if related_target_ids:
+ placeholders = ", ".join("?" for _ in related_target_ids)
+ repository_clauses.append(f"scans.target_id IN ({placeholders})")
+ values.extend(related_target_ids)
+ clauses.append(f"({' OR '.join(repository_clauses)})")
if args is not None and args.scan_root:
scan_root = str(Path(args.scan_root).expanduser().resolve())
prefix = scan_root.rstrip(os.sep) + os.sep
@@ -328,7 +357,18 @@ def compare_scans(
(before["id"], after["id"]),
).fetchone()
if cached is None and require_matches:
- raise SystemExit("No saved matches for these scans. Run 'scans match BEFORE AFTER' first.")
+ reversed_comparison = connection.execute(
+ "SELECT 1 FROM scan_comparisons WHERE before_scan_id = ? AND after_scan_id = ?",
+ (after["id"], before["id"]),
+ ).fetchone()
+ if reversed_comparison is not None:
+ raise SystemExit(
+ "These scans are in the wrong order. Run "
+ f"'codex-security scans compare {after['id']} {before['id']}'."
+ )
+ raise SystemExit(
+ "No saved matches for these scans. Run 'codex-security scans match BEFORE AFTER' first."
+ )
if include_matching_inputs and backfill_finding_details is not None:
backfill_finding_details(connection, before)
backfill_finding_details(connection, after)
@@ -424,6 +464,7 @@ def compare_scans(
"comparable": comparable,
"coverage": {"afterCompleteness": after_coverage.get("completeness")},
"findings": findings,
+ "repository": before["target_path"],
"summary": summary,
}
if include_matching_inputs:
@@ -526,34 +567,71 @@ def save_scan_comparison(
return compare_scans(connection, args, require_scan=require_scan, read_coverage=read_coverage)
-def finding_matches(connection: sqlite3.Connection, occurrence_id: str) -> list[dict[str, Any]]:
+def finding_matches(
+ connection: sqlite3.Connection, occurrence_id: str, scan_id: str, started_at: str
+) -> tuple[list[dict[str, Any]], str, list[str]]:
rows = connection.execute(
"""
- SELECT matches.after_scan_id AS scan_id, occurrences.id, occurrences.finding_id,
+ SELECT matches.after_scan_id AS scan_id, occurrences.id AS occurrence_id, occurrences.finding_id,
occurrences.title, matches.reason
FROM scan_comparison_matches AS matches
JOIN finding_occurrences AS occurrences ON occurrences.id = matches.after_occurrence_id
WHERE matches.before_occurrence_id = ?
UNION
- SELECT matches.before_scan_id AS scan_id, occurrences.id, occurrences.finding_id,
+ SELECT matches.before_scan_id AS scan_id, occurrences.id AS occurrence_id, occurrences.finding_id,
occurrences.title, matches.reason
FROM scan_comparison_matches AS matches
JOIN finding_occurrences AS occurrences ON occurrences.id = matches.before_occurrence_id
WHERE matches.after_occurrence_id = ?
- ORDER BY scan_id, id
+ ORDER BY scan_id, occurrence_id
""",
(occurrence_id, occurrence_id),
).fetchall()
- return [
- {
- "findingId": row["finding_id"],
- "occurrenceId": row["id"],
- "reason": row["reason"],
- "scanId": row["scan_id"],
- "title": row["title"],
- }
- for row in rows
- ]
+ known_scans = [(started_at, scan_id)]
+ if rows:
+ known_scans = [
+ (row["started_at"], row["scan_id"])
+ for row in connection.execute(
+ """
+ WITH RECURSIVE linked_occurrences(occurrence_id) AS (
+ SELECT ?
+ UNION
+ SELECT CASE
+ WHEN matches.before_occurrence_id = linked.occurrence_id
+ THEN matches.after_occurrence_id
+ ELSE matches.before_occurrence_id
+ END
+ FROM scan_comparison_matches AS matches
+ JOIN linked_occurrences AS linked
+ ON matches.before_occurrence_id = linked.occurrence_id
+ OR matches.after_occurrence_id = linked.occurrence_id
+ )
+ SELECT DISTINCT scans.started_at, scans.id AS scan_id
+ FROM linked_occurrences AS linked
+ JOIN finding_occurrences AS occurrences ON occurrences.id = linked.occurrence_id
+ JOIN scans ON scans.id = occurrences.scan_id
+ ORDER BY scans.started_at, scans.id
+ """,
+ (occurrence_id,),
+ )
+ ]
+ known_scan_ids = [known_scans[0][1]]
+ if len(known_scans) > 1:
+ known_scan_ids.append(known_scans[-1][1])
+ return (
+ [
+ {
+ "findingId": row["finding_id"],
+ "occurrenceId": row["occurrence_id"],
+ "reason": row["reason"],
+ "scanId": row["scan_id"],
+ "title": row["title"],
+ }
+ for row in rows
+ ],
+ known_scans[0][0],
+ known_scan_ids,
+ )
def _finding_groups(
diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json
index 4913eaf57..d530ee5a7 100644
--- a/sdk/typescript/package.json
+++ b/sdk/typescript/package.json
@@ -46,7 +46,7 @@
"generate:models": "node scripts/generate-models.cjs",
"generate:models:check": "node scripts/generate-models.cjs --check",
"lint": "tsc --noEmit",
- "test": "bun test --timeout 30000 tests-ts/api.test.ts tests-ts/auth.test.ts tests-ts/bulk-scan-discovery.test.ts tests-ts/cli.test.ts tests-ts/config.test.ts tests-ts/contract.test.ts tests-ts/knowledge-base.test.ts tests-ts/multiscan.test.ts tests-ts/result.test.ts tests-ts/runtime.test.ts tests-ts/scan-comparison.test.ts tests-ts/skeleton.test.ts tests-ts/targets.test.ts tests-ts/trusted-executable.test.ts tests-ts/worker-progress.test.ts",
+ "test": "bun test --timeout 30000 tests-ts/api.test.ts tests-ts/auth.test.ts tests-ts/bulk-scan-discovery.test.ts tests-ts/cli.test.ts tests-ts/config.test.ts tests-ts/contract.test.ts tests-ts/knowledge-base.test.ts tests-ts/multiscan.test.ts tests-ts/result.test.ts tests-ts/runtime.test.ts tests-ts/scan-comparison.test.ts tests-ts/scan-history-renderer.test.ts tests-ts/skeleton.test.ts tests-ts/targets.test.ts tests-ts/trusted-executable.test.ts tests-ts/worker-progress.test.ts",
"types": "pnpm run generate:models:check && tsc --noEmit"
},
"dependencies": {
diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjs
index 059cb7584..e731c0143 100644
--- a/sdk/typescript/scripts/check-package.mjs
+++ b/sdk/typescript/scripts/check-package.mjs
@@ -148,6 +148,7 @@ const distFiles = new Set(
"result",
"runtime",
"scan-comparison",
+ "scan-history-renderer",
"targets",
"trusted-executable",
"version",
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 77d805371..9df1335ee 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -68,6 +68,10 @@ import {
matchScanFindings,
type ScanComparisonInput,
} from "./scan-comparison.js";
+import {
+ renderScanHistory,
+ type HistoryCommand,
+} from "./scan-history-renderer.js";
import type { ScanWorkerPhase, ScanWorkerStatus } from "./worker-progress.js";
import { DiffTarget, type ScanMode, type ScanTarget } from "./targets.js";
import {
@@ -86,12 +90,15 @@ const MAX_SKILL_INPUT_COUNT = 64;
const WINDOWS_NETWORK_PATH = /^[\\/]{2}/u;
const WINDOWS_LOCAL_DEVICE_ROOT =
/^[\\/]{2}[?.][\\/](?:[A-Za-z]:|Volume\{[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\}|GLOBALROOT[\\/]Device[\\/]HarddiskVolume[0-9]+)(?=[\\/]|$)/iu;
+const SCAN_HISTORY_OUTPUT_OPTION =
+ /^--(?:format|filter-output|full-output|token-count|token-limit|token-offset)(?:=|$)/u;
const HIDE_CURSOR = "\u001B[?25l";
const SHOW_CURSOR = "\u001B[?25h";
type Writable = Pick<NodeJS.WriteStream, "write"> & {
readonly isTTY?: boolean;
readonly fd?: number;
+ readonly columns?: number;
};
type SignalName = "SIGINT" | "SIGTERM";
type FailureSeverity = Exclude<SeverityLevel, "informational">;
@@ -102,6 +109,10 @@ const REPORTABLE_SEVERITIES: readonly FailureSeverity[] = [
"medium",
"low",
];
+const DISPLAY_SEVERITIES: readonly SeverityLevel[] = [
+ ...REPORTABLE_SEVERITIES,
+ "informational",
+];
const EXPORT_DEFAULT_OUTPUTS = {
csv: "findings.csv",
json: "findings.json",
@@ -482,6 +493,7 @@ export async function main(
let exitCode = 0;
let frameworkExit: number | undefined;
let frameworkOutput = "";
+ let renderedHistory: string | undefined;
const history = async (
args: readonly string[],
select: (value: JsonObject) => JsonObject = (value) => value,
@@ -494,6 +506,36 @@ export async function main(
return undefined;
}
};
+ const presentHistory = (
+ result: JsonObject | undefined,
+ command: HistoryCommand,
+ format: string,
+ settings: {
+ repository?: string;
+ scanRoot?: string;
+ showLinkedFindings?: boolean;
+ } = {},
+ ): JsonObject | undefined => {
+ if (
+ result === undefined ||
+ format !== "toon" ||
+ output.isTTY !== true ||
+ argv.some((argument) => SCAN_HISTORY_OUTPUT_OPTION.test(argument))
+ ) {
+ return result;
+ }
+ renderedHistory = renderScanHistory(result, command, {
+ columns: output.columns,
+ color:
+ dependencies.environment["NO_COLOR"] === undefined &&
+ dependencies.environment["TERM"] !== "dumb",
+ now: dependencies.now(),
+ repository: settings.repository,
+ scanRoot: settings.scanRoot,
+ showLinkedFindings: settings.showLinkedFindings,
+ });
+ return result;
+ };
const scanHistory = Cli.create("scans", {
description:
"List, inspect, rerun, match, and compare saved Codex Security scans.",
@@ -514,40 +556,61 @@ export async function main(
.describe("Include scans whose output is under ROOT."),
}),
output: z.record(z.string(), z.unknown()).optional(),
- async run({ args, options }) {
+ async run({ args, format, options }) {
const directory = dependencies.currentDirectory();
- return await history([
- "list-scans",
- ...(options.scanRoot !== undefined && args.repository === undefined
- ? []
- : [
- "--repository",
- resolve(directory, args.repository ?? directory),
- ]),
- ...(options.scanRoot === undefined
- ? []
- : ["--scan-root", resolve(directory, options.scanRoot)]),
- ]);
+ const repository =
+ options.scanRoot !== undefined && args.repository === undefined
+ ? undefined
+ : resolve(directory, args.repository ?? directory);
+ return presentHistory(
+ await history([
+ "list-scans",
+ ...(repository === undefined ? [] : ["--repository", repository]),
+ ...(options.scanRoot === undefined
+ ? []
+ : ["--scan-root", resolve(directory, options.scanRoot)]),
+ ]),
+ "list",
+ format,
+ {
+ repository,
+ scanRoot:
+ options.scanRoot === undefined
+ ? undefined
+ : resolve(directory, options.scanRoot),
+ },
+ );
},
})
.command("show", {
description: "Show the results and saved configuration for a scan.",
mcp: false,
args: z.object({
- scanId: z.string().min(1).describe("Saved scan identifier."),
+ scanId: z
+ .string()
+ .min(1)
+ .describe("Saved scan identifier or unique prefix."),
+ }),
+ options: z.object({
+ showLinkedFindings: z
+ .boolean()
+ .default(false)
+ .describe("Show findings linked across previous scans."),
}),
output: z.record(z.string(), z.unknown()).optional(),
- async run({ args }) {
- return await history(
- ["get-scan", "--scan-id", args.scanId],
- (value) => {
+ async run({ args, format, options }) {
+ return presentHistory(
+ await history(["get-scan", "--scan-id", args.scanId], (value) => {
const { scan, recipe, parentScanId } = value;
return {
...(scan as JsonObject),
...(recipe === undefined ? {} : { recipe }),
...(parentScanId === undefined ? {} : { parentScanId }),
};
- },
+ }),
+ "show",
+ format,
+ { showLinkedFindings: options.showLinkedFindings },
);
},
})
@@ -617,10 +680,14 @@ export async function main(
.describe("Recompute an existing semantic finding comparison."),
}),
output: z.record(z.string(), z.unknown()).optional(),
- async run({ args, options }) {
+ async run({ args, format, options }) {
try {
if (options.all) {
- return await matchAllScans(dependencies, options.force);
+ return presentHistory(
+ await matchAllScans(dependencies, options.force),
+ "match-all",
+ format,
+ );
}
const comparison = await history([
"compare-scans",
@@ -633,20 +700,26 @@ export async function main(
if (comparison === undefined) return undefined;
const { matchingCached, matchingInputs, ...visibleComparison } =
comparison;
- if (matchingCached && !options.force) return visibleComparison;
+ if (matchingCached && !options.force) {
+ return presentHistory(visibleComparison, "compare", format);
+ }
const matching = await dependencies.matchFindings(
matchingInputs as JsonObject & ScanComparisonInput,
);
- return await history([
- "save-scan-comparison",
- "--before-scan-id",
- args.beforeId!,
- "--after-scan-id",
- args.afterId!,
- "--matches-json",
- JSON.stringify(matching),
- ]);
+ return presentHistory(
+ await history([
+ "save-scan-comparison",
+ "--before-scan-id",
+ args.beforeId!,
+ "--after-scan-id",
+ args.afterId!,
+ "--matches-json",
+ JSON.stringify(matching),
+ ]),
+ "compare",
+ format,
+ );
} catch (error) {
errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
exitCode = 2;
@@ -662,15 +735,19 @@ export async function main(
afterId: z.string().min(1).describe("Later saved scan identifier."),
}),
output: z.record(z.string(), z.unknown()).optional(),
- async run({ args }) {
- return await history([
- "compare-scans",
- "--before-scan-id",
- args.beforeId,
- "--after-scan-id",
- args.afterId,
- "--require-matches",
- ]);
+ async run({ args, format }) {
+ return presentHistory(
+ await history([
+ "compare-scans",
+ "--before-scan-id",
+ args.beforeId,
+ "--after-scan-id",
+ args.afterId,
+ "--require-matches",
+ ]),
+ "compare",
+ format,
+ );
},
});
const cli = Cli.create("codex-security", {
@@ -1174,7 +1251,7 @@ export async function main(
}
if (frameworkOutput.length === 0) return exitCode;
try {
- await writeCliOutput(output, frameworkOutput);
+ await writeCliOutput(output, renderedHistory ?? frameworkOutput);
return exitCode;
} catch (error) {
errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
@@ -2183,11 +2260,10 @@ function printScanSummary(
(severities.get(finding.severity.level) ?? 0) + 1,
);
}
- const severitySummary = [...REPORTABLE_SEVERITIES, "informational" as const]
- .map((severity) => {
- const count = severities.get(severity);
- return count === undefined ? null : `${count} ${severity}`;
- })
+ 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(", ");
errorOutput.write(
diff --git a/sdk/typescript/src/scan-history-renderer.ts b/sdk/typescript/src/scan-history-renderer.ts
new file mode 100644
index 000000000..c0696df09
--- /dev/null
+++ b/sdk/typescript/src/scan-history-renderer.ts
@@ -0,0 +1,397 @@
+import { basename, relative } from "node:path";
+import type { JsonObject } from "./config.js";
+
+export type HistoryCommand = "list" | "show" | "compare" | "match-all";
+type RendererOptions = {
+ columns?: number;
+ color?: boolean;
+ now?: number;
+ repository?: string;
+ scanRoot?: string;
+ showLinkedFindings?: boolean;
+};
+
+const STALE_SCAN_MILLISECONDS = 24 * 60 * 60 * 1_000;
+
+const STATUS_STYLES: Record<string, { color: number; icon: string }> = {
+ resolved: { color: 32, icon: "✓" },
+ reopened: { color: 31, icon: "↻" },
+ new: { color: 31, icon: "+" },
+ persisting: { color: 33, icon: "●" },
+ not_rescanned: { color: 36, icon: "○" },
+ unknown: { color: 35, icon: "?" },
+};
+
+const SEVERITY_COLORS: Record<string, number> = {
+ CRITICAL: 31,
+ HIGH: 31,
+ MEDIUM: 33,
+ LOW: 36,
+ INFORMATIONAL: 37,
+};
+
+const KNOWN_SINCE_DATE = new Intl.DateTimeFormat("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ timeZone: "UTC",
+});
+
+function clean(value: unknown): string {
+ return String(value)
+ .replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, "")
+ .replace(/[\u0000-\u001F\u007F-\u009F]/g, " ");
+}
+
+function findingSeverity(finding: JsonObject): string {
+ const severity = finding["severity"];
+ return clean(
+ typeof severity === "string" ? severity : (severity as JsonObject)["level"],
+ ).toUpperCase();
+}
+
+export function renderScanHistory(
+ result: JsonObject,
+ command: HistoryCommand,
+ options: RendererOptions = {},
+): string {
+ const color = options.color ?? true;
+ const width = Math.max(48, Math.min(options.columns ?? 96, 120));
+ const paint = (value: string, code: number): string =>
+ color ? `\u001B[${code}m${value}\u001B[0m` : value;
+ const dim = (value: string): string => paint(value, 90);
+ const strong = (value: string): string => paint(value, 1);
+ const accent = (value: string): string => paint(value, 36);
+ const labels: Record<HistoryCommand, string> = {
+ list: "SCAN HISTORY",
+ show: "SCAN DETAILS",
+ compare: "SCAN COMPARISON",
+ "match-all": "MATCH RESULTS",
+ };
+ const lines = [
+ "",
+ ` ${accent("◆")} ${strong("CODEX SECURITY")} ${accent("/")} ${strong(labels[command])}`,
+ ` ${accent("━".repeat(width - 4))}`,
+ ];
+
+ const wrap = (value: string, indent: number, prefix?: string): void => {
+ const available = width - indent - 2;
+ let line = "";
+ let first = true;
+ for (const word of clean(value).split(/\s+/)) {
+ if (line.length > 0 && line.length + word.length + 1 > available) {
+ lines.push(`${first && prefix ? prefix : " ".repeat(indent)}${line}`);
+ first = false;
+ line = word;
+ } else {
+ line = line.length > 0 ? `${line} ${word}` : word;
+ }
+ }
+ if (line.length > 0) {
+ lines.push(`${first && prefix ? prefix : " ".repeat(indent)}${line}`);
+ }
+ };
+
+ const finding = (entry: JsonObject, includeReason = true): void => {
+ const severity = findingSeverity(entry);
+ const title = clean(entry["title"]);
+ const badge = paint(severity.padEnd(8), SEVERITY_COLORS[severity] ?? 37);
+ wrap(title, 14, ` ${badge} `);
+ const before = entry["beforeOccurrenceIds"] as string[] | undefined;
+ const after = entry["afterOccurrenceIds"] as string[] | undefined;
+ const grouped =
+ before?.length || after?.length
+ ? ` ${accent("·")} ${before?.length ?? 1} → ${after?.length ?? 1}`
+ : "";
+ const matches = entry["matches"] as JsonObject[] | undefined;
+ const knownScanIds = entry["knownScanIds"] as string[] | undefined;
+ const knownScans = knownScanIds?.length
+ ? ` in ${clean(knownScanIds[0]).slice(0, 8)}${knownScanIds.length > 1 ? ` … ${clean(knownScanIds[knownScanIds.length - 1]).slice(0, 8)}` : ""}`
+ : "";
+ const knownSince =
+ command === "show" && matches?.length && entry["knownSince"]
+ ? ` ${accent("·")} ${strong(`Known since ${KNOWN_SINCE_DATE.format(new Date(clean(entry["knownSince"])))}`)}${knownScans}`
+ : "";
+ const location = (entry["locations"] as JsonObject[] | undefined)?.[0];
+ const path =
+ entry["path"] ??
+ `${location?.["path"]}${location?.["startLine"] ? `:${location["startLine"]}` : ""}`;
+ lines.push(` ${dim(clean(path))}${grouped}${knownSince}`);
+ const showLinkedFindings = command !== "show" || options.showLinkedFindings;
+ if (matches?.length && showLinkedFindings) {
+ lines.push(` ${accent("↔")} ${strong("LINKED FINDINGS")}`);
+ for (const match of matches) {
+ lines.push(
+ ` ${strong("MATCHED SCAN")} ${accent(clean(match["scanId"]).slice(0, 8))}`,
+ );
+ wrap(`↳ ${clean(match["title"])}`, 18);
+ }
+ }
+ const reason =
+ entry["matchReason"] ??
+ entry["reason"] ??
+ (matches?.length
+ ? [...new Set(matches.map((match) => clean(match["reason"])))].join(
+ "; ",
+ )
+ : undefined);
+ if (includeReason && reason && (!matches?.length || showLinkedFindings)) {
+ if (matches?.length) {
+ lines.push(` ${strong("SAME ROOT CAUSE")}`);
+ wrap(clean(reason), 18);
+ } else {
+ wrap(`↳ ${clean(reason)}`, 14);
+ }
+ }
+ };
+
+ if (command === "list") {
+ const scans = (result["scans"] as JsonObject[]).filter((scan) => {
+ if ((scan["progress"] as JsonObject)["status"] !== "running") {
+ return true;
+ }
+ const updated = Date.parse(scan["updatedAt"] as string);
+ return (
+ !Number.isFinite(updated) ||
+ (options.now ?? Date.now()) - updated < STALE_SCAN_MILLISECONDS
+ );
+ });
+ const repository = basename(
+ String(
+ options.scanRoot ??
+ options.repository ??
+ scans[0]?.["targetPath"] ??
+ "",
+ ),
+ );
+ const latest = scans.find(
+ (scan) => (scan["progress"] as JsonObject)["status"] === "complete",
+ )?.["findingCount"];
+ const multipleRepositories =
+ options.repository === undefined &&
+ new Set(scans.map((scan) => scan["targetPath"])).size > 1;
+ const wide = width >= (multipleRepositories ? 96 : 80);
+ lines.push(
+ ` ${strong(clean(repository))} ${accent("·")} ${scans.length} ${scans.length === 1 ? "scan" : "scans"}${latest === undefined ? "" : ` ${accent("·")} latest: ${clean(latest)} findings`}`,
+ "",
+ );
+ if (wide) {
+ lines.push(
+ ` ${strong("SCAN".padEnd(36))} ${strong("DATE".padEnd(10))} ${strong("MODE".padEnd(8))}${multipleRepositories ? ` ${strong("REPOSITORY".padEnd(18))}` : ""} ${strong("FINDINGS")} ${strong("STATUS")}`,
+ );
+ }
+ for (const scan of scans) {
+ const status = clean((scan["progress"] as JsonObject)["status"]);
+ const complete = status === "complete";
+ const statusColor = complete ? 32 : status === "running" ? 36 : 31;
+ const statusLabel = paint(
+ `${complete ? "✓" : "●"} ${status.toUpperCase()}`,
+ statusColor,
+ );
+ const started = clean(scan["startedAt"]).slice(0, 10);
+ const findings = clean(scan["findingCount"]);
+ const scanRepository = basename(clean(scan["targetPath"]));
+ if (wide) {
+ lines.push(
+ ` ${clean(scan["scanId"]).padEnd(36)} ${started.padEnd(10)} ${clean(scan["mode"]).padEnd(8)}${multipleRepositories ? ` ${scanRepository.slice(0, 18).padEnd(18)}` : ""} ${findings.padEnd(8)} ${statusLabel}`,
+ );
+ } else {
+ lines.push(
+ ` ${clean(scan["scanId"])}`,
+ ` ${started}${multipleRepositories ? ` ${accent("·")} ${clean(scanRepository)}` : ""} ${accent("·")} ${findings} findings ${accent("·")} ${statusLabel}`,
+ );
+ }
+ }
+ } else if (command === "show") {
+ const status = clean((result["progress"] as JsonObject)["status"]);
+ const statusColor =
+ status === "complete" ? 32 : status === "running" ? 36 : 31;
+ lines.push(
+ ` ${strong(clean(basename(result["targetPath"] as string)))} ${accent("·")} ${clean(result["scanId"])}`,
+ ` ${paint(`${status === "complete" ? "✓" : "●"} ${status.toUpperCase()}`, statusColor)} ${accent("·")} ${clean(result["mode"])}`,
+ );
+ if (result["failureMessage"]) {
+ wrap(String(result["failureMessage"]), 11, ` ${paint("ERROR", 31)} `);
+ }
+ if (result["parentScanId"]) {
+ lines.push(
+ ` ${strong("PARENT SCAN")} ${clean(result["parentScanId"]).slice(0, 8)}`,
+ );
+ }
+ const summary = result["severityCounts"] as JsonObject | undefined;
+ if (summary) {
+ lines.push(
+ ` ${Object.entries(summary)
+ .filter(([, count]) => count)
+ .map(([severity, count]) => {
+ const label = severity.toUpperCase();
+ return paint(
+ `${clean(count)} ${label}`,
+ SEVERITY_COLORS[label] ?? 37,
+ );
+ })
+ .join(` ${accent("·")} `)}`,
+ );
+ }
+ const recipe = result["recipe"] as JsonObject | undefined;
+ const config = recipe?.["config"] as JsonObject | undefined;
+ if (config && Object.keys(config).length > 0) {
+ lines.push(
+ ` ${strong("CONFIGURATION")} ${Object.entries(config)
+ .map(([key, value]) => `${clean(key)}=${clean(value)}`)
+ .join(` ${accent("·")} `)}`,
+ );
+ }
+ const coverage = (result["progress"] as JsonObject)["coverage"] as
+ | JsonObject
+ | undefined;
+ if (coverage) {
+ const parts = [
+ ...(coverage["worklistRows"] == null
+ ? []
+ : [
+ `${clean(coverage["closedRows"])} of ${clean(coverage["worklistRows"])} reviewed`,
+ ]),
+ ...(coverage["filesTotal"] == null
+ ? []
+ : [`${clean(coverage["filesTotal"])} files`]),
+ ];
+ if (parts.length > 0) {
+ lines.push(
+ ` ${strong("COVERAGE")} ${parts.join(` ${accent("·")} `)}`,
+ );
+ }
+ }
+ const knowledgeBase = recipe?.["knowledgeBasePaths"] as
+ | string[]
+ | undefined;
+ if (knowledgeBase?.length) {
+ lines.push(
+ ` ${strong("KNOWLEDGE BASE")} ${knowledgeBase.map((path) => dim(clean(path))).join(", ")}`,
+ );
+ }
+ const artifacts = result["artifacts"] as JsonObject | undefined;
+ if (artifacts && Object.keys(artifacts).length > 0) {
+ lines.push(` ${strong("ARTIFACTS")}`);
+ const scanDirectory = result["scanDir"] as string | undefined;
+ if (scanDirectory) lines.push(` ${dim(clean(scanDirectory))}`);
+ for (const [kind, path] of Object.entries(artifacts)) {
+ const label = kind.replace(/([a-z])([A-Z])/g, "$1 $2").toUpperCase();
+ const artifactPath = scanDirectory
+ ? relative(scanDirectory, String(path))
+ : String(path);
+ lines.push(
+ ` ${strong(clean(label).padEnd(15))} ${dim(clean(artifactPath))}`,
+ );
+ }
+ }
+ const findings = result["findings"] as JsonObject[];
+ if (findings.length > 0) {
+ const count =
+ typeof result["findingCount"] === "number"
+ ? result["findingCount"]
+ : findings.length;
+ lines.push(
+ "",
+ ` ${strong("FINDINGS")} ${strong(
+ result["findingsTruncated"] || count > findings.length
+ ? `${findings.length} of ${count}`
+ : String(count),
+ )}`,
+ );
+ for (const entry of findings) {
+ lines.push("");
+ finding(entry);
+ }
+ }
+ } else if (command === "compare") {
+ if (result["repository"]) {
+ lines.push(
+ ` ${strong(clean(basename(result["repository"] as string)))}`,
+ );
+ }
+ lines.push(
+ ` ${clean(result["beforeScanId"]).slice(0, 8)} → ${clean(result["afterScanId"]).slice(0, 8)}`,
+ );
+ const coverage = (result["coverage"] as JsonObject)["afterCompleteness"];
+ if (coverage !== "complete") {
+ lines.push(
+ ` ${paint(`⚠ Follow-up coverage is ${clean(coverage)}; resolved findings cannot be confirmed.`, 33)}`,
+ );
+ }
+ const findings = (result["findings"] as JsonObject[]).map((entry) =>
+ entry["status"] === "unknown" &&
+ entry["reason"] ===
+ "The affected path was excluded or outside the later scope."
+ ? { ...entry, status: "not_rescanned" }
+ : entry,
+ );
+ const notRescanned = findings.filter(
+ (entry) => entry["status"] === "not_rescanned",
+ ).length;
+ const summary: JsonObject = {
+ ...(result["summary"] as JsonObject),
+ ...(notRescanned
+ ? {
+ unknown:
+ Number((result["summary"] as JsonObject)["unknown"] ?? 0) -
+ notRescanned,
+ not_rescanned: notRescanned,
+ }
+ : {}),
+ };
+ lines.push("");
+ let summaryLine = " ";
+ let summaryLength = 2;
+ for (const [status, style] of Object.entries(STATUS_STYLES)) {
+ const value = summary[status];
+ if (!value) continue;
+ const label = `${style.icon} ${clean(value)} ${status.replaceAll("_", " ")}`;
+ if (summaryLength > 2 && summaryLength + label.length + 4 > width - 2) {
+ lines.push(summaryLine);
+ summaryLine = " ";
+ summaryLength = 2;
+ }
+ summaryLine += `${summaryLength > 2 ? " " : ""}${paint(label, style.color)}`;
+ summaryLength += label.length + (summaryLength > 2 ? 4 : 0);
+ }
+ if (summaryLength > 2) lines.push(summaryLine);
+
+ for (const status of Object.keys(STATUS_STYLES)) {
+ const group = findings.filter(
+ (entry) => String(entry["status"]).toLowerCase() === status,
+ );
+ if (group.length === 0) continue;
+ group.sort(
+ (first, second) =>
+ Object.keys(SEVERITY_COLORS).indexOf(findingSeverity(first)) -
+ Object.keys(SEVERITY_COLORS).indexOf(findingSeverity(second)),
+ );
+ const style = STATUS_STYLES[status]!;
+ const title = `${style.icon} ${status[0]!.toUpperCase()}${status.slice(1).replaceAll("_", " ")}`;
+ const heading = `${title} (${group.length} finding${group.length === 1 ? "" : "s"})`;
+ const rule = "━".repeat(Math.max(2, width - heading.length - 8));
+ lines.push("", ` ${paint(`━━ ${heading} ${rule}`, style.color)}`);
+ if (status === "not_rescanned") {
+ lines.push(` ${accent("Outside follow-up scan coverage")}`);
+ }
+ for (const entry of group) {
+ lines.push("");
+ finding(entry, status !== "not_rescanned");
+ }
+ }
+ } else {
+ lines.push(
+ ` ${strong(clean(basename(result["repository"] as string)))}`,
+ "",
+ ` ${paint("●", 36)} ${clean(result["scanCount"])} scans ${paint("↔", 36)} ${clean(result["matchedPairs"])} comparisons ${paint("◆", 32)} ${clean(result["findingMatches"])} root-cause matches`,
+ );
+ if (result["unavailableScans"]) {
+ lines.push(
+ ` ${paint(`${clean(result["unavailableScans"])} scans unavailable`, 33)}`,
+ );
+ }
+ }
+
+ return `${lines.join("\n")}\n\n`;
+}
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index c7315240a..a701e41ec 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -15,6 +15,7 @@ import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { Writable } from "node:stream";
import { pathToFileURL } from "node:url";
+import { stripVTControlCharacters } from "node:util";
import { describe, expect, test } from "bun:test";
import type {
CodexSecurity,
@@ -685,6 +686,279 @@ describe("CLI", () => {
expect(JSON.parse(stdout.text())).toMatchObject({ repository: "scans" });
});
+ test("presents interactive scan history and hides abandoned running scans", async () => {
+ const stdout = capture(true);
+ const scan = {
+ mode: "standard",
+ targetPath: "/demo/juice-shop",
+ scanDir: "/private/tmp/results",
+ targetId: "target-internal-id",
+ };
+ const deps = dependencies({
+ currentDirectory: "/demo/juice-shop",
+ onWorkbench: () => ({
+ scans: [
+ {
+ ...scan,
+ scanId: "failed-scan",
+ progress: { status: "failed" },
+ findingCount: 0,
+ startedAt: "2026-07-24T12:00:00Z",
+ updatedAt: "2026-07-24T12:00:00Z",
+ },
+ {
+ ...scan,
+ scanId: "abandoned-scan",
+ progress: { status: "running" },
+ findingCount: 0,
+ startedAt: "2026-07-20T12:00:00Z",
+ updatedAt: "2026-07-20T12:00:00Z",
+ },
+ {
+ ...scan,
+ scanId: "active-scan",
+ progress: { status: "running" },
+ findingCount: 2,
+ startedAt: "2026-07-24T11:00:00Z",
+ updatedAt: "2026-07-24T11:00:00Z",
+ },
+ {
+ ...scan,
+ scanId: "completed-scan",
+ progress: { status: "complete" },
+ findingCount: 8,
+ targetPath: "/demo/juice-shop-remediated",
+ startedAt: "2026-07-23T12:00:00Z",
+ updatedAt: "2026-07-23T12:00:00Z",
+ },
+ ],
+ }),
+ });
+ deps.now = () => Date.parse("2026-07-24T12:00:00Z");
+
+ expect(
+ await main(
+ ["scans", "list", "/demo/juice-shop"],
+ stdout.stream,
+ capture().stream,
+ deps,
+ ),
+ ).toBe(0);
+ const text = stdout.text();
+ expect(text).toContain("CODEX SECURITY");
+ expect(text).toContain("SCAN HISTORY");
+ expect(text).toContain("juice-shop");
+ for (const heading of ["DATE", "STATUS", "FINDINGS", "MODE", "SCAN"]) {
+ expect(text).toContain(heading);
+ }
+ expect(text).toContain("failed-scan");
+ expect(text).toContain("FAILED");
+ expect(text).toContain("latest: 8 findings");
+ expect(text).not.toContain("latest: 0 findings");
+ expect(text).toContain("active-scan");
+ expect(text).toContain("completed-scan");
+ expect(text).not.toContain("abandoned-scan");
+ expect(text).not.toContain("juice-shop-remediated");
+ expect(text).not.toContain("/private/tmp");
+ expect(text).not.toContain("target-internal-id");
+ });
+
+ test("shows finding history and optionally reveals linked findings", async () => {
+ const findings: JsonObject[] = [
+ {
+ findingId: "internal-finding-id",
+ occurrenceId: "internal-occurrence-id",
+ severity: { level: "critical" },
+ title: "Login SQL injection bypasses authentication",
+ locations: [{ path: "routes/login.ts", startLine: 34 }],
+ knownSince: "2026-06-15T12:00:00Z",
+ knownScanIds: [
+ "12345678-abcd-4567-abcd-1234567890ab",
+ "87654321-abcd-4567-abcd-1234567890ab",
+ ],
+ matches: [
+ {
+ scanId: "12345678-abcd-4567-abcd-1234567890ab",
+ title:
+ "Earlier authentication bypass; deadbeef: forged linked finding",
+ reason: "The same login query interpolates email.",
+ },
+ {
+ scanId: "87654321-abcd-4567-abcd-1234567890ab",
+ title: "Historic login injection",
+ reason: "The same login query interpolates email.",
+ },
+ ],
+ },
+ {
+ severity: { level: "high" },
+ title: "New basket authorization bypass",
+ locations: [{ path: "routes/basket.ts", startLine: 19 }],
+ },
+ ];
+
+ for (const showLinkedFindings of [false, true]) {
+ const stdout = capture(true);
+ expect(
+ await main(
+ [
+ "scans",
+ "show",
+ "scan-1",
+ ...(showLinkedFindings ? ["--show-linked-findings"] : []),
+ ],
+ stdout.stream,
+ capture().stream,
+ dependencies({
+ onWorkbench: () => ({
+ scan: {
+ scanId: "scan-1",
+ targetPath: "/demo/juice-shop",
+ mode: "standard",
+ progress: { status: "complete" },
+ severityCounts: { critical: 1, high: 1 },
+ findings,
+ },
+ recipe: { knowledgeBasePaths: ["/demo/threat-models"] },
+ }),
+ }),
+ ),
+ ).toBe(0);
+ const text = stripVTControlCharacters(stdout.text());
+ expect(text).toContain("CODEX SECURITY");
+ expect(text).toContain("SCAN DETAILS");
+ expect(text).toContain("juice-shop");
+ expect(text).toContain("scan-1");
+ expect(text).toContain("CRITICAL");
+ expect(text).toContain("routes/login.ts:34");
+ expect(text).toContain("Known since Jun 15, 2026 in 12345678 … 87654321");
+ expect(text.match(/Known since/g)).toHaveLength(1);
+ expect(text).toContain("New basket authorization bypass");
+ expect(text).toContain("/demo/threat-models");
+ expect(text).not.toContain("internal-finding-id");
+ expect(text).not.toContain("internal-occurrence-id");
+ if (showLinkedFindings) {
+ expect(text).toContain("LINKED FINDINGS");
+ expect(text).toContain("MATCHED SCAN");
+ expect(text).toContain("12345678");
+ expect(text).toContain("Earlier authentication bypass");
+ expect(text).toContain("87654321");
+ expect(text).toContain("Historic login injection");
+ expect(text).toContain("SAME ROOT CAUSE");
+ expect(text).toContain("The same login query interpolates email.");
+ expect(text.match(/MATCHED SCAN/g)).toHaveLength(2);
+ expect(text).not.toContain("MATCHED SCAN deadbeef");
+ } else {
+ expect(text).not.toContain("LINKED FINDINGS");
+ expect(text).not.toContain("MATCHED SCAN");
+ expect(text).not.toContain("SAME ROOT CAUSE");
+ }
+ }
+ });
+
+ test("sanitizes interactive finding text and respects NO_COLOR", async () => {
+ const stdout = capture(true);
+ expect(
+ await main(
+ ["scans", "show", "scan-1"],
+ stdout.stream,
+ capture().stream,
+ dependencies({
+ environment: { NO_COLOR: "1" },
+ onWorkbench: () => ({
+ scan: {
+ scanId: "scan-1",
+ targetPath: "/demo/juice-shop",
+ mode: "standard",
+ progress: { status: "complete" },
+ findings: [
+ {
+ severity: { level: "high" },
+ title: "Safe title\u001b[31mINJECTED\nFORGED ROW",
+ locations: [{ path: "routes/login.ts", startLine: 34 }],
+ },
+ ],
+ },
+ }),
+ }),
+ ),
+ ).toBe(0);
+ expect(stdout.text()).toContain("Safe titleINJECTED FORGED ROW");
+ expect(stdout.text()).not.toContain("\u001b");
+ expect(stdout.text()).not.toContain("\nFORGED ROW");
+ });
+
+ test("preserves structured and noninteractive scan-history output", async () => {
+ const response: JsonObject = {
+ beforeScanId: "before-scan",
+ afterScanId: "after-scan",
+ coverage: { afterCompleteness: "complete" },
+ summary: { persisting: 1, resolved: 0, unknown: 1 },
+ findings: [
+ {
+ findingId: "internal-finding-id",
+ beforeOccurrenceId: "internal-occurrence-id",
+ status: "persisting",
+ severity: "high",
+ title: "Basket ownership check is missing",
+ path: "routes/basket.ts",
+ },
+ {
+ status: "unknown",
+ severity: "high",
+ title: "Complaint upload can overwrite trusted files",
+ path: "routes/fileUpload.ts",
+ reason: "The affected path was excluded or outside the later scope.",
+ },
+ ],
+ };
+ for (const argv of [
+ ["scans", "compare", "before", "after", "--json"],
+ ["scans", "compare", "before", "after", "--format", "yaml"],
+ ]) {
+ const stdout = capture(true);
+ expect(
+ await main(
+ argv,
+ stdout.stream,
+ capture().stream,
+ dependencies({ onWorkbench: () => response }),
+ ),
+ ).toBe(0);
+ expect(stdout.text()).toContain("internal-finding-id");
+ expect(stdout.text()).toContain("internal-occurrence-id");
+ if (argv.includes("--json")) {
+ expect(JSON.parse(stdout.text())).toEqual(response);
+ }
+ }
+
+ const redirected = capture();
+ expect(
+ await main(
+ ["scans", "compare", "before", "after"],
+ redirected.stream,
+ capture().stream,
+ dependencies({ onWorkbench: () => response }),
+ ),
+ ).toBe(0);
+ expect(redirected.text()).toContain("internal-finding-id");
+ expect(redirected.text()).toContain("status: unknown");
+ expect(redirected.text()).not.toContain("CODEX SECURITY");
+
+ const filtered = capture(true);
+ expect(
+ await main(
+ ["scans", "compare", "before", "after", "--filter-output", "summary"],
+ filtered.stream,
+ capture().stream,
+ dependencies({ onWorkbench: () => response }),
+ ),
+ ).toBe(0);
+ expect(filtered.text()).toContain("persisting: 1");
+ expect(filtered.text()).not.toContain("internal-finding-id");
+ expect(filtered.text()).not.toContain("CODEX SECURITY");
+ });
+
test("shows scans and returns cached comparisons with one workbench call", async () => {
const cases: Array<[string[], string[], JsonObject, JsonObject]> = [
[
@@ -703,6 +977,38 @@ describe("CLI", () => {
parentScanId: "scan-0",
},
],
+ [
+ ["scans", "show", "14b85b21", "--json"],
+ ["get-scan", "--scan-id", "14b85b21"],
+ { scan: { scanId: "14b85b21-a276-48d7-9f0d-1ebd048fe2a3" } },
+ { scanId: "14b85b21-a276-48d7-9f0d-1ebd048fe2a3" },
+ ],
+ [
+ ["scans", "show", "scan-1", "--show-linked-findings", "--json"],
+ ["get-scan", "--scan-id", "scan-1"],
+ {
+ scan: {
+ scanId: "scan-1",
+ findings: [
+ {
+ knownSince: "2026-06-15T12:00:00Z",
+ knownScanIds: ["12345678-abcd-4567-abcd-1234567890ab"],
+ matches: [{ scanId: "scan-0" }],
+ },
+ ],
+ },
+ },
+ {
+ scanId: "scan-1",
+ findings: [
+ {
+ knownSince: "2026-06-15T12:00:00Z",
+ knownScanIds: ["12345678-abcd-4567-abcd-1234567890ab"],
+ matches: [{ scanId: "scan-0" }],
+ },
+ ],
+ },
+ ],
[
["scans", "show", "legacy", "--json"],
["get-scan", "--scan-id", "legacy"],
diff --git a/sdk/typescript/tests-ts/scan-history-renderer.test.ts b/sdk/typescript/tests-ts/scan-history-renderer.test.ts
new file mode 100644
index 000000000..4c7a0aafc
--- /dev/null
+++ b/sdk/typescript/tests-ts/scan-history-renderer.test.ts
@@ -0,0 +1,268 @@
+import { stripVTControlCharacters } from "node:util";
+import { describe, expect, test } from "bun:test";
+import { renderScanHistory } from "../src/scan-history-renderer.js";
+
+describe("scan history renderer", () => {
+ test("leads comparisons with the outcome and groups root causes", () => {
+ const text = stripVTControlCharacters(
+ renderScanHistory(
+ {
+ repository: "/demo/juice-shop",
+ beforeScanId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
+ afterScanId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
+ comparable: true,
+ coverage: { afterCompleteness: "complete" },
+ summary: {
+ new: 1,
+ persisting: 2,
+ resolved: 2,
+ reopened: 0,
+ unknown: 2,
+ },
+ findings: [
+ {
+ findingId: "internal-persisting-id",
+ status: "persisting",
+ severity: "high",
+ title: "Basket ownership check is missing",
+ path: "routes/basket.ts",
+ beforeOccurrenceIds: ["before-one", "before-two"],
+ afterOccurrenceIds: ["after-one"],
+ matchReason:
+ "Both routes share the same unchecked basket lookup.",
+ },
+ {
+ status: "persisting",
+ severity: "high",
+ title: "Basket modification omits the ownership check",
+ path: "routes/basket.ts",
+ },
+ {
+ status: "new",
+ severity: "medium",
+ title: "Order input is evaluated",
+ path: "routes/b2bOrder.ts",
+ },
+ {
+ status: "resolved",
+ severity: "informational",
+ title: "Informational cookie observation",
+ path: "routes/session.ts",
+ },
+ {
+ status: "resolved",
+ severity: "critical",
+ title: "Login SQL injection bypasses authentication",
+ path: "routes/login.ts",
+ beforeOccurrenceId: "before-resolved",
+ },
+ {
+ status: "unknown",
+ severity: "high",
+ title: "Complaint upload can overwrite trusted files",
+ path: "routes/fileUpload.ts",
+ reason:
+ "The affected path was excluded or outside the later scope.",
+ },
+ {
+ status: "unknown",
+ severity: "medium",
+ title: "Session handling might match an earlier finding",
+ path: "routes/session.ts",
+ reason: "The two findings describe different session flows.",
+ },
+ ],
+ },
+ "compare",
+ ),
+ );
+
+ expect(text).toContain("CODEX SECURITY");
+ expect(text).toMatch(
+ /SCAN COMPARISON[\s\S]*━━ ✓ Resolved \(2 findings\) ━+[\s\S]*━━ \+ New \(1 finding\) ━+[\s\S]*━━ ● Persisting \(2 findings\) ━+[\s\S]*━━ ○ Not rescanned \(1 finding\) ━+[\s\S]*━━ \? Unknown \(1 finding\) ━+/,
+ );
+ expect(
+ text.indexOf("Login SQL injection bypasses authentication"),
+ ).toBeLessThan(text.indexOf("Informational cookie observation"));
+ for (const expected of [
+ "Complaint upload can overwrite trusted files",
+ "Outside follow-up scan coverage",
+ "Session handling might match an earlier finding",
+ "The two findings describe different session flows.",
+ "juice-shop",
+ "aaaaaaaa → bbbbbbbb",
+ "CRITICAL",
+ "2 → 1",
+ "Both routes share the same unchecked basket lookup.",
+ ]) {
+ expect(text).toContain(expected);
+ }
+ for (const hidden of [
+ "follow-up scope",
+ "internal-persisting-id",
+ "before-resolved",
+ "NOT_RESCANNED",
+ "REOPENED",
+ ]) {
+ expect(text).not.toContain(hidden);
+ }
+ });
+
+ test("reserves dim styling for finding and knowledge-base paths", () => {
+ const output = renderScanHistory(
+ {
+ targetPath: "/demo/juice-shop",
+ scanId: "scan-1",
+ progress: { status: "complete" },
+ mode: "standard",
+ recipe: { knowledgeBasePaths: ["/demo/threat-model.md"] },
+ findings: [
+ {
+ severity: "HIGH",
+ title: "Missing auth",
+ path: "routes/login.ts",
+ },
+ ],
+ },
+ "show",
+ );
+ expect(output).toContain("\u001B[1mKNOWLEDGE BASE\u001B[0m");
+ expect(
+ [...output.matchAll(/\u001B\[90m([^\u001B]*)\u001B\[0m/g)].map(
+ ([, value]) => value,
+ ),
+ ).toEqual(["/demo/threat-model.md", "routes/login.ts"]);
+ for (const coverage of ["partial", "unknown", "complete"]) {
+ const comparison = renderScanHistory(
+ {
+ beforeScanId: "before-scan",
+ afterScanId: "after-scan",
+ coverage: { afterCompleteness: coverage },
+ summary: {},
+ findings: [],
+ },
+ "compare",
+ { color: false },
+ );
+ if (coverage === "complete") {
+ expect(comparison).not.toContain("Follow-up coverage");
+ } else {
+ expect(comparison).toContain(
+ `⚠ Follow-up coverage is ${coverage}; resolved findings cannot be confirmed.`,
+ );
+ }
+ }
+ });
+
+ test("keeps repositories visible at narrow and wide terminal widths", () => {
+ const scans = [
+ {
+ scanId: "11111111-1111-4111-8111-111111111111",
+ targetPath: "/demo/juice-shop",
+ mode: "standard",
+ progress: { status: "complete" },
+ findingCount: 8,
+ startedAt: "2026-07-24T12:00:00Z",
+ },
+ {
+ scanId: "22222222-2222-4222-8222-222222222222",
+ targetPath: "/demo/payment-service",
+ mode: "deep",
+ progress: { status: "complete" },
+ findingCount: 2,
+ startedAt: "2026-07-23T12:00:00Z",
+ },
+ ];
+
+ for (const columns of [72, 100]) {
+ const output = stripVTControlCharacters(
+ renderScanHistory({ scans }, "list", {
+ columns,
+ scanRoot: "/demo/results",
+ }),
+ );
+ expect(output).toContain("results");
+ expect(output).toContain("juice-shop");
+ expect(output).toContain("payment-service");
+ expect(output).toContain(scans[0]!.scanId);
+ expect(output).toContain(scans[1]!.scanId);
+ if (columns >= 96) expect(output).toContain("REPOSITORY");
+ }
+ });
+
+ test("shows bounded findings, saved configuration, and failure reasons", () => {
+ const scan = {
+ scanId: "12345678-abcd-4567-abcd-1234567890ab",
+ parentScanId: "87654321-abcd-4567-abcd-1234567890ab",
+ targetPath: "/demo/juice-shop",
+ mode: "standard",
+ progress: {
+ status: "complete",
+ coverage: { closedRows: 12, worklistRows: 15, filesTotal: 9 },
+ },
+ findingCount: 75,
+ findingsTruncated: true,
+ artifacts: { markdownReport: "/demo/results/report.md" },
+ recipe: {
+ config: { model: "gpt-5.6-sol", model_reasoning_effort: "high" },
+ },
+ findings: Array.from({ length: 20 }, (_, index) => ({
+ severity: { level: "high" },
+ title: `Finding ${index + 1}`,
+ locations: [{ path: "routes/login.ts", startLine: index + 1 }],
+ })),
+ };
+ const output = stripVTControlCharacters(renderScanHistory(scan, "show"));
+ for (const expected of [
+ "FINDINGS 20 of 75",
+ "PARENT SCAN 87654321",
+ "CONFIGURATION",
+ "model=gpt-5.6-sol",
+ "COVERAGE",
+ "12 of 15 reviewed",
+ "9 files",
+ "ARTIFACTS",
+ "/demo/results/report.md",
+ ]) {
+ expect(output).toContain(expected);
+ }
+
+ const failed = stripVTControlCharacters(
+ renderScanHistory(
+ {
+ ...scan,
+ progress: { status: "failed" },
+ failureMessage: "Repository checkout became unavailable.",
+ findings: [],
+ },
+ "show",
+ ),
+ );
+ expect(failed).toContain("ERROR Repository checkout became unavailable.");
+ });
+
+ test("renders match-all results from the original workbench data", () => {
+ const output = stripVTControlCharacters(
+ renderScanHistory(
+ {
+ repository: "/demo/juice-shop",
+ scanCount: 5,
+ unavailableScans: 2,
+ matchedPairs: 0,
+ findingMatches: 0,
+ },
+ "match-all",
+ ),
+ );
+ for (const expected of [
+ "MATCH RESULTS",
+ "juice-shop",
+ "5 scans",
+ "0 comparisons",
+ "0 root-cause matches",
+ "2 scans unavailable",
+ ]) {
+ expect(output).toContain(expected);
+ }
+ });
+});