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

feat(cli): expose identifiers for saved scan follow-up (#2577)

Michael D'Angelofacaa9e07d54
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 949ae8438..f3779b5fb 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1886,15 +1886,17 @@ or effort. A successful
run also writes `severity-classification.json`, but publication reads the database. Original findings and sealed artifacts remain
unchanged.
-Repeat `--finding-id ID` for a subset from the selected scan. Dedupe's
-`uniqueFindingIds` can represent findings from another scan; replace an outside-scan
-representative with a member of its `duplicateGroups` entry from this scan.
+Repeat `--finding-id ID` for a subset from the selected scan. Dedupe returns
+`scanRepresentativeFindingIds` for this selection, in the same order as its
+corpus-wide `uniqueFindingIds`.
Linear publication defaults to saved classification selection, omits exclusions,
and uses assessed severity for title and priority. Descriptions retain original
severity and add the classification rationale. Publication rejects incomplete or
stale assessments. It never reclassifies or rereads the rubric at publication time.
```bash
+# List the IDs you can pass to --finding-id.
+codex-security dedupe --scan SCAN_ID --json | jq -r '.scanRepresentativeFindingIds[]'
codex-security classify-severity --scan SCAN_ID --rubric /path/to/policy.md \
--finding-id FINDING_ID
codex-security publish scan --scan SCAN_ID --to linear --linear-team TEAM_ID --dry-run
@@ -1909,46 +1911,32 @@ import {
classifySeverity,
classifyScanSeverity,
classifyScanDirectorySeverity,
+ deduplicateScanDirectory,
publishScan,
- type FindingsDocument,
} from "@openai/codex-security";
-import { readFile } from "node:fs/promises";
-import { join } from "node:path";
// Assess supplied reports in memory.
-const classification = await classifySeverity(findings, {
+await classifySeverity(findings, {
rubricPath: "/path/to/policy.md",
knowledgeBasePaths: ["/path/to/context.md"],
});
// Save assessments for a scan ID or sealed directory.
await classifyScanSeverity("SCAN_ID", { rubricPath: "/path/to/policy.md" });
-const scanFindings = (
- JSON.parse(
- await readFile(join(scanDirectory, "findings.json"), "utf8"),
- ) as FindingsDocument
-).findings;
-const scanFindingIds = new Set(
- scanFindings.map((finding) => finding.findingId),
-);
-// dedupeResult was produced by deduplicating this same scan.
-const selectedIds = dedupeResult.uniqueFindingIds.map((representative) => {
- if (scanFindingIds.has(representative)) return representative;
- return dedupeResult.duplicateGroups
- .find((group) => group.includes(representative))!
- .find((member) => scanFindingIds.has(member))!;
+const dedupeResult = await deduplicateScanDirectory(scanDirectory, {
+ repository: "/path/to/repository",
});
-await classifyScanDirectorySeverity(scanDirectory, {
+const classification = await classifyScanDirectorySeverity(scanDirectory, {
rubricPath: "/path/to/policy.md",
- findingIds: selectedIds,
+ findingIds: dedupeResult.scanRepresentativeFindingIds,
});
-// Or supply an in-memory assessment directly to publication.
+// Preview Linear publication for those same findings using their assessments.
await publishScan(scanDirectory, {
destination: "linear",
teamId: "TEAM_ID",
classification,
- findingIds: classification.assessments.map(({ findingId }) => findingId),
+ findingIds: dedupeResult.scanRepresentativeFindingIds,
dryRun: true,
});
```
@@ -2071,6 +2059,12 @@ least eight characters.
| `findings imported [REPOSITORY]` | Read locally imported, unassessed vendor evidence. |
| `findings false-positive OCCURRENCE_ID --reason TEXT` | Dismiss a finding while the reason applies. |
+In the terminal, `findings list` shows the occurrence ID for each open finding.
+Copy that ID into `findings false-positive` with your reason. Subsequent scans can
+use the explanation while it applies. In `scans show SCAN_ID --json`, each
+displayed occurrence has its saved rationale in `triage.note` after dismissal. The list identifies
+a repository with no saved scan history separately from one with zero open findings.
+
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
@@ -2144,6 +2138,10 @@ codex-security scans list --scan-root /path/to/security-scans
codex-security scans resume SCAN_ID
```
+The terminal list shows the full scan ID and labels the last activity of a
+`running` scan after 24 hours without an update. For a Deep Scan with a saved
+launch recipe and its original session, it also shows the resume command to use after interruption.
+
The scan must still be `running`, with its original checkout, output directory,
and Codex session in the same state directory. Checkout identity, revision, and
contents must match. Completed, failed, and canceled scans need a rerun instead.
diff --git a/sdk/typescript/docs/findings-service.md b/sdk/typescript/docs/findings-service.md
index 9fb6c2081..4c2460d96 100644
--- a/sdk/typescript/docs/findings-service.md
+++ b/sdk/typescript/docs/findings-service.md
@@ -132,6 +132,7 @@ The CLI and SDK return the same result:
{
"scanId": "scan_example_001",
"uniqueFindingIds": ["csf_852f90d6e1177502ff113d4a"],
+ "scanRepresentativeFindingIds": ["csf_852f90d6e1177502ff113d4a"],
"duplicateGroups": [],
"deduplicationStatus": "completed"
}
@@ -140,8 +141,12 @@ The CLI and SDK return the same result:
`uniqueFindingIds` contains one representative for each selected finding after
accepted groups are collapsed. A representative can come from outside the scan.
Each group lists its canonical finding first: highest reported severity, then
-finding ID to break ties. Group associations are saved before returning success;
-the original findings and scan artifacts remain unchanged.
+finding ID to break ties. `scanRepresentativeFindingIds` gives the highest-ranked
+member from the selected scan for each canonical ID in the same order, including
+ungrouped findings. Pass these IDs to severity classification or Linear publication
+for that scan. The SDK also returns them when resuming older saved workflows.
+Dedupe saves the group associations separately from the original findings and
+scan artifacts before returning success.
If a model refuses a review, the result uses `completed_with_refusals` and adds
`refusals`. Each entry contains `decision: "NO_DECISION"`, `stage`, `model`,
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index c3cefbaf7..75fa06a19 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -10,6 +10,7 @@ const distModules = [
"auth",
"bulk-scan-discovery",
"cli",
+ "cli-argument",
"cli-daybreak",
"cli-help",
"cli-scan-logs-json",
diff --git a/sdk/typescript/src/classify-scan-severity.ts b/sdk/typescript/src/classify-scan-severity.ts
index f6d869149..ac4d90d18 100644
--- a/sdk/typescript/src/classify-scan-severity.ts
+++ b/sdk/typescript/src/classify-scan-severity.ts
@@ -24,7 +24,7 @@ export interface ScanSeverityClassification extends SeverityClassification {
}
export interface ClassifyScanSeverityOptions extends ClassifySeverityOptions {
- /** Exact selection, such as dedupe's uniqueFindingIds. Omit to classify all findings. */
+ /** Exact selection, such as dedupe's scanRepresentativeFindingIds. Omit to classify all findings. */
findingIds?: readonly string[];
/** Reclassify selected findings even when their saved assessment matches the inputs. */
reprocess?: boolean;
diff --git a/sdk/typescript/src/cli-argument.ts b/sdk/typescript/src/cli-argument.ts
new file mode 100644
index 000000000..c9e12b597
--- /dev/null
+++ b/sdk/typescript/src/cli-argument.ts
@@ -0,0 +1,17 @@
+/** Quote a literal argument for the user's shell (PowerShell on Windows). */
+export function quoteCliPath(value: string): string {
+ if (/^[A-Za-z0-9_./:-]+$/u.test(value)) return value;
+ if (process.platform === "win32" && /^[A-Za-z0-9_./:\\-]+$/u.test(value))
+ return value;
+ const escaped =
+ process.platform === "win32"
+ ? value.replace(/['\u2018\u2019\u201a\u201b]/gu, (quote) => quote + quote)
+ : value.replaceAll("'", `'"'"'`);
+ return `'${escaped}'`;
+}
+
+export function cliShellLabel(quotedArgument: string): string {
+ return process.platform === "win32" && quotedArgument.startsWith("'")
+ ? " (PowerShell)"
+ : "";
+}
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 8016dc431..be7d72a48 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -371,6 +371,7 @@ import {
type PolicyPrompt,
type PolicySecurity,
} from "./security-policy-cli.js";
+import { cliShellLabel, quoteCliPath } from "./cli-argument.js";
import { formatSecurityPolicyText as escapeTerminalText } from "./security-policy.js";
import { commandGitProtectionRoots } from "./local-git-metadata.js";
import type { PatchSelection } from "./patch-tui.js";
@@ -2611,16 +2612,17 @@ export async function main(
}, selection);
const useInteractiveHistory = (format: string) =>
useDefaultOutput(format) && output.isTTY === true;
- const presentHistory = (
- result: JsonObject | undefined,
+ const presentHistory = <T extends JsonObject | undefined>(
+ result: T,
command: HistoryCommand,
format: string,
settings: {
repository?: string;
scanRoot?: string;
showLinkedFindings?: boolean;
+ missingRepositoryHistory?: boolean;
} = {},
- ): JsonObject | undefined => {
+ ): T => {
if (result === undefined || !useInteractiveHistory(format)) {
return result;
}
@@ -2630,9 +2632,7 @@ export async function main(
dependencies.environment["NO_COLOR"] === undefined &&
dependencies.environment["TERM"] !== "dumb",
now: dependencies.now(),
- repository: settings.repository,
- scanRoot: settings.scanRoot,
- showLinkedFindings: settings.showLinkedFindings,
+ ...settings,
});
return result;
};
@@ -2663,6 +2663,15 @@ export async function main(
description: "Review saved findings (default: list).",
}).command("false-positive", {
description: "Mark a finding as a false positive for future scans.",
+ examples: [
+ {
+ args: { occurrenceId: "occurrence_abc123" },
+ options: { reason: "unreachable" },
+ description:
+ "Use the occurrence ID from findings list and explain why it does not apply.",
+ },
+ ],
+ hint: "Future scans of the repository can reuse the reason while it applies. Read the occurrence’s triage.note in codex-security scans show SCAN_ID --json.",
destructive: true,
args: z.object({
occurrenceId: z
@@ -2711,52 +2720,49 @@ export async function main(
const repository = await realpath(requestedRepository).catch(
() => requestedRepository,
);
- return presentHistory(
- await history(
- ["list-repositories", "--status", "scanned"],
- async (value): Promise<JsonObject> => {
- const repositories = value["repositories"] as JsonObject[];
- let target = repositories.find(
- (entry) => entry["targetPath"] === requestedRepository,
- );
- const canonicalTarget = repositories.find(
- (entry) => entry["targetPath"] === repository,
- );
- if (
- target === undefined &&
- canonicalTarget !== undefined &&
- (await sameFile(
- canonicalTarget["targetPath"] as string,
- requestedRepository,
- ))
- ) {
- target = canonicalTarget;
- }
- if (target === undefined) {
- for (const entry of repositories) {
- const storedPath = entry["targetPath"] as string;
- if (await sameFile(storedPath, requestedRepository)) {
- target = entry;
- break;
- }
+ return await history(
+ ["list-repositories", "--status", "scanned"],
+ async (value): Promise<JsonObject> => {
+ const repositories = value["repositories"] as JsonObject[];
+ let target = repositories.find(
+ (entry) => entry["targetPath"] === requestedRepository,
+ );
+ const canonicalTarget = repositories.find(
+ (entry) => entry["targetPath"] === repository,
+ );
+ if (
+ target === undefined &&
+ canonicalTarget !== undefined &&
+ (await sameFile(
+ canonicalTarget["targetPath"] as string,
+ requestedRepository,
+ ))
+ ) {
+ target = canonicalTarget;
+ }
+ if (target === undefined) {
+ for (const entry of repositories) {
+ const storedPath = entry["targetPath"] as string;
+ if (await sameFile(storedPath, requestedRepository)) {
+ target = entry;
+ break;
}
}
- const findings =
- target === undefined
- ? []
- : await listRepositoryFindings(
- dependencies.runWorkbench,
- target["targetId"] as string,
- );
- return {
- repository: requestedRepository,
- findings: findings ?? [],
- };
- },
- ),
- "findings",
- format,
- { repository: requestedRepository },
+ }
+ const findings =
+ target === undefined
+ ? []
+ : await listRepositoryFindings(
+ dependencies.runWorkbench,
+ target["targetId"] as string,
+ );
+ return presentHistory(
+ { repository: requestedRepository, findings: findings ?? [] },
+ "findings",
+ format,
+ { missingRepositoryHistory: target === undefined },
+ );
+ },
);
},
});
@@ -4126,7 +4132,7 @@ export async function main(
const summary =
disposition === "empty"
? "The report contains no findings. Nothing was stored.\n"
- : `Local import complete.\nCreated: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Excluded: ${result.excluded.length}\nImported evidence remains not assessed by Codex.\nRead stored evidence with codex-security findings imported REPOSITORY.\n`;
+ : `Local import complete.\nCreated: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Excluded: ${result.excluded.length}\nImported evidence remains not assessed by Codex.\n${importedFindingsCommand(preview.repository)}\n`;
if (humanSummary) renderedOutput = summary;
else if (!structured) writeDiagnostic(summary);
return { ...result };
@@ -4825,7 +4831,7 @@ export async function main(
);
if (humanSummary) {
const { created, updated, unchanged } = result.local.counts;
- renderedOutput = `Local import: ${created} created, ${updated} updated, ${unchanged} unchanged.\n`;
+ renderedOutput = `Local import: ${created} created, ${updated} updated, ${unchanged} unchanged.\n${importedFindingsCommand(info.repository)}\n`;
if (result.cloud)
renderedOutput += renderExternalPublicationSummary(
result.cloud,
@@ -5630,6 +5636,7 @@ export async function main(
.object({
scanId: z.string(),
uniqueFindingIds: z.array(z.string()),
+ scanRepresentativeFindingIds: z.array(z.string()),
duplicateGroups: z.array(z.array(z.string())),
deduplicationStatus: z.enum(["completed", "completed_with_refusals"]),
refusals: z
@@ -11290,7 +11297,7 @@ async function executeScan(
if (result !== null && arguments_.validate) {
const exitCode = requestedSignal === "SIGINT" ? 130 : 143;
const scanId = quoteCliPath(diagnosticValue(result.manifest.scan.id));
- const message = `Validation interrupted. Original output directory: ${errorMessage(result.scanDir)}. Run codex-security scans show ${scanId} to inspect the completed scan.`;
+ const message = `Validation interrupted. Original output directory: ${errorMessage(result.scanDir)}. Run${cliShellLabel(scanId)} codex-security scans show ${scanId} to inspect the completed scan.`;
errorOutput.write(`codex-security: ${message}\n`);
return {
exitCode,
@@ -11923,8 +11930,10 @@ function printScanReference(
output.write(
`\n${detail.join(" · ")}\n` +
(selection === undefined ? "" : `Selected ${selection}.\n`) +
- `Inspect: codex-security scans show ${argument}\n` +
- (showLogs ? `Logs: codex-security scans logs ${argument}\n` : ""),
+ `Inspect${cliShellLabel(argument)}: codex-security scans show ${argument}\n` +
+ (showLogs
+ ? `Logs${cliShellLabel(argument)}: codex-security scans logs ${argument}\n`
+ : ""),
);
}
@@ -12125,7 +12134,7 @@ function protectedRootErrorMessage(
error.pathKind === "output"
? "Scan artifacts cannot be written inside the protected scan root."
: "Temporary and runtime files cannot be created inside the protected scan root.";
- const suggestion = suggestedOutputDirectory(error.protectedRoot);
+ const suggestion = suggestedOutputArgument(error.protectedRoot);
return [
`${description} must be outside the scanned directory and any enclosing Git worktree.`,
` Resolved path: ${error.outputDirectory}`,
@@ -12134,14 +12143,14 @@ function protectedRootErrorMessage(
error.pathKind === "output"
? suggestion === undefined
? "Choose an output directory outside the protected root."
- : `Re-run with --output-dir ${quoteCliPath(suggestion)}.`
+ : `Re-run${cliShellLabel(suggestion)} with --output-dir ${suggestion}.`
: suggestion === undefined
? "Set TMPDIR (or TEMP on Windows) to a writable directory outside the protected root."
- : `Set TMPDIR (or TEMP on Windows) to ${quoteCliPath(suggestion)} after creating that directory.`,
+ : `Set TMPDIR (or TEMP on Windows) to ${suggestion} after creating that directory.`,
].join("\n");
}
-function suggestedOutputDirectory(protectedRoot: string): string | undefined {
+function suggestedOutputArgument(protectedRoot: string): string | undefined {
const parent = dirname(protectedRoot);
if (parent === protectedRoot) return undefined;
try {
@@ -12164,7 +12173,7 @@ function suggestedOutputDirectory(protectedRoot: string): string | undefined {
"code" in error &&
error.code === "ENOENT"
) {
- return candidate;
+ return quoteCliPath(candidate);
}
return undefined;
}
@@ -12172,11 +12181,11 @@ function suggestedOutputDirectory(protectedRoot: string): string | undefined {
return undefined;
}
-function quoteCliPath(path: string): string {
- if (/^[A-Za-z0-9_./:\\-]+$/u.test(path)) return path;
- return process.platform === "win32"
- ? `"${path}"`
- : `'${path.replaceAll("'", `'"'"'`)}'`;
+function importedFindingsCommand(repository: string): string {
+ if (diagnosticValue(repository) !== repository)
+ return "From the repository directory, run codex-security findings imported.";
+ const path = quoteCliPath(repository);
+ return `Stored evidence${cliShellLabel(path)}: codex-security findings imported ${path}`;
}
async function selectedProjectConfig(
diff --git a/sdk/typescript/src/deduplication/scan.ts b/sdk/typescript/src/deduplication/scan.ts
index 0c3d38bcd..ccb782534 100644
--- a/sdk/typescript/src/deduplication/scan.ts
+++ b/sdk/typescript/src/deduplication/scan.ts
@@ -84,6 +84,8 @@ export interface DeduplicateScanDirectoryOptions extends DeduplicateScanOptions
export interface DeduplicateScanResult extends DeduplicationResult {
scanId: string;
+ /** One finding from this scan for each entry in uniqueFindingIds, in the same order. */
+ scanRepresentativeFindingIds: string[];
}
/** Review a saved scan against embedding candidates and persist accepted duplicate groups. */
@@ -260,6 +262,25 @@ async function deduplicateResolvedScan(
},
);
}
+ const selectedFindingIds = new Set(
+ contract.findings.findings.map((finding) => finding.findingId),
+ );
+ function scanResult(result: DeduplicationResult): DeduplicateScanResult {
+ // Groups are already ranked by severity and then by finding ID.
+ const representatives = new Map<string, string>();
+ for (const group of result.duplicateGroups) {
+ const representative = group.find((id) => selectedFindingIds.has(id));
+ if (representative !== undefined)
+ representatives.set(group[0]!, representative);
+ }
+ return {
+ ...result,
+ scanId,
+ scanRepresentativeFindingIds: result.uniqueFindingIds.map(
+ (id) => representatives.get(id) ?? id,
+ ),
+ };
+ }
const dedupe = async (): Promise<DeduplicateScanResult> => {
if (local) {
await (
@@ -348,9 +369,6 @@ async function deduplicateResolvedScan(
options.onDiagnostic,
)
: undefined;
- const selectedFindingIds = new Set(
- contract.findings.findings.map((finding) => finding.findingId),
- );
const sourceRepositories = new Map<Finding, readonly string[]>();
const sourceSnapshots = new Map<Finding, FindingSourceSnapshot>();
const deduplicator = new FindingDeduplicator(
@@ -408,7 +426,7 @@ async function deduplicateResolvedScan(
const reviewed = await deduplicator.run([...selectedFindingIds]);
await checkpoints?.assertSourceUnchanged();
options.signal?.throwIfAborted();
- const result: DeduplicateScanResult = { scanId, ...reviewed };
+ const result = scanResult(reviewed);
await workflow?.prepareDedupe(result, {
groups: result.duplicateGroups,
...(local
@@ -429,7 +447,10 @@ async function deduplicateResolvedScan(
? await workflow.run("dedupe", dedupe)
: await dedupe();
options.signal?.throwIfAborted();
- return result;
+ // Completed workflows and pending receipts from older releases omit this field.
+ return result.scanRepresentativeFindingIds === undefined
+ ? scanResult(result)
+ : result;
}
async function modelConfigurationForReview(
diff --git a/sdk/typescript/src/publication.ts b/sdk/typescript/src/publication.ts
index e62814c8d..da5f3bd0c 100644
--- a/sdk/typescript/src/publication.ts
+++ b/sdk/typescript/src/publication.ts
@@ -40,7 +40,7 @@ export interface PrepareScanPublicationOptions {
environment?: NodeJS.ProcessEnv;
signal?: AbortSignal;
expectedScanId?: string;
- /** Publish only these finding IDs from the supplied scan; dedupe representatives may belong to other scans. */
+ /** Publish only these finding IDs from the supplied scan. Use scanRepresentativeFindingIds from saved-scan dedupe. */
findingIds?: readonly string[];
/** Use this assessment; otherwise use the scan's saved classification when present. */
classification?: SeverityClassification | ScanSeverityClassification;
diff --git a/sdk/typescript/src/scan-history-renderer.ts b/sdk/typescript/src/scan-history-renderer.ts
index 5cdf5387f..c7abf6c1a 100644
--- a/sdk/typescript/src/scan-history-renderer.ts
+++ b/sdk/typescript/src/scan-history-renderer.ts
@@ -1,5 +1,6 @@
import { basename, relative } from "node:path";
import stringWidth from "string-width";
+import { cliShellLabel, quoteCliPath } from "./cli-argument.js";
import { fitCell, graphemes } from "./terminal-columns.js";
import type { JsonObject } from "./config.js";
import {
@@ -16,6 +17,7 @@ type RendererOptions = {
repository?: string;
scanRoot?: string;
showLinkedFindings?: boolean;
+ missingRepositoryHistory?: boolean;
};
const STALE_SCAN_MILLISECONDS = 24 * 60 * 60 * 1_000;
@@ -194,16 +196,7 @@ export function renderScanHistory(
};
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 scans = result["scans"] as JsonObject[];
const repository = basename(
String(
options.scanRoot ??
@@ -258,18 +251,47 @@ export function renderScanHistory(
lines.push(line);
}
}
+ const updatedAt = scan["updatedAt"];
+ if (
+ status === "running" &&
+ typeof updatedAt === "string" &&
+ (options.now ?? Date.now()) - Date.parse(updatedAt) >=
+ STALE_SCAN_MILLISECONDS
+ ) {
+ lines.push(` ${dim(`Last activity: ${clean(updatedAt)}`)}`);
+ if (
+ scan["mode"] === "deep" &&
+ scan["recipeAvailable"] === true &&
+ scan["handoffStatus"] === "delivered" &&
+ scan["continuationThreadId"]
+ ) {
+ const id = quoteCliPath(clean(scan["scanId"]));
+ lines.push(
+ ` If interrupted${cliShellLabel(id)}: codex-security scans resume ${id}`,
+ );
+ }
+ }
}
} else if (command === "findings") {
const findings = result["findings"] as JsonObject[];
- lines.push(
- ` ${strong(clean(basename(result["repository"] as string)))} ${accent("·")} ${findings.length} open finding${findings.length === 1 ? "" : "s"}`,
- );
+ const repository = clean(result["repository"]);
+ if (options.missingRepositoryHistory) {
+ lines.push(` No saved scan for ${repository}`);
+ } else {
+ lines.push(
+ ` ${strong(basename(repository))} ${accent("·")} ${findings.length} open finding${findings.length === 1 ? "" : "s"}`,
+ );
+ }
for (const entry of findings) {
lines.push(
"",
` ${strong(entry["confirmedInLatestScan"] ? "Seen this scan" : "Not confirmed in latest scan")}`,
);
finding(entry);
+ if (typeof entry["occurrenceId"] === "string")
+ lines.push(
+ ` ${dim("Occurrence")} ${clean(entry["occurrenceId"])}`,
+ );
}
} else if (command === "show") {
const status = clean((result["progress"] as JsonObject)["status"]);
diff --git a/sdk/typescript/tests-ts/cli-dedupe.test.ts b/sdk/typescript/tests-ts/cli-dedupe.test.ts
index 923374292..21d24010a 100644
--- a/sdk/typescript/tests-ts/cli-dedupe.test.ts
+++ b/sdk/typescript/tests-ts/cli-dedupe.test.ts
@@ -20,14 +20,19 @@ const args = [
"--json",
];
-test("asynchronous stderr failures do not discard successful dedupe results", async () => {
- const deps = dependencies();
- const result = {
- scanId: "scan-example",
+function emptyDedupeResult(scanId: string) {
+ return {
+ scanId,
uniqueFindingIds: [],
+ scanRepresentativeFindingIds: [],
duplicateGroups: [],
deduplicationStatus: "completed" as const,
};
+}
+
+test("asynchronous stderr failures do not discard successful dedupe results", async () => {
+ const deps = dependencies();
+ const result = emptyDedupeResult("scan-example");
deps.deduplicateScan = async (_scan, options) => {
options.onDiagnostic?.({
event: "review.started",
@@ -56,12 +61,7 @@ test.each([false, true])(
async (debug) => {
const deps = dependencies();
if (debug) deps.environment["CODEX_SECURITY_LOG_LEVEL"] = "debug";
- const result = {
- scanId: "scan-example",
- uniqueFindingIds: [],
- duplicateGroups: [],
- deduplicationStatus: "completed" as const,
- };
+ const result = emptyDedupeResult("scan-example");
deps.deduplicateScan = async (_id, options) => {
options.onDiagnostic?.({
event: "review.started",
@@ -112,6 +112,7 @@ test.each([false, true])(
const result = {
scanId: "scan-example",
uniqueFindingIds: ["finding-one", "finding-two"],
+ scanRepresentativeFindingIds: ["finding-one", "finding-two"],
duplicateGroups: [],
deduplicationStatus: "completed_with_refusals" as const,
refusals: [
@@ -161,12 +162,7 @@ test.each([
deps.deduplicateScan = async (scanId, options) => {
expect(scanId).toBe("exact-scan");
expect(options.workflowId).toBe("workflow-example");
- return {
- scanId,
- uniqueFindingIds: [],
- duplicateGroups: [],
- deduplicationStatus: "completed",
- };
+ return emptyDedupeResult(scanId);
};
const stdout = captureCli(main, "stdout");
expect(
@@ -182,12 +178,7 @@ test.each([
deps,
),
).toBe(0);
- expect(JSON.parse(stdout.text())).toEqual({
- scanId: "exact-scan",
- uniqueFindingIds: [],
- duplicateGroups: [],
- deduplicationStatus: "completed",
- });
+ expect(JSON.parse(stdout.text())).toEqual(emptyDedupeResult("exact-scan"));
});
test.each([false, true])(
@@ -199,6 +190,7 @@ test.each([false, true])(
const result = {
scanId: "scan-example",
uniqueFindingIds: ["finding-example"],
+ scanRepresentativeFindingIds: ["finding-example"],
duplicateGroups: [],
deduplicationStatus: "completed" as const,
};
@@ -236,12 +228,7 @@ test.each([
deps.deduplicateScan = async (scanId, options) => {
called = true;
expect(options.concurrency).toBe(expected);
- return {
- scanId,
- uniqueFindingIds: [],
- duplicateGroups: [],
- deduplicationStatus: "completed",
- };
+ return emptyDedupeResult(scanId);
};
expect(await runCapturedCli(main, [...args, ...flags], deps)).toBe(0);
expect(called).toBe(true);
@@ -310,12 +297,7 @@ test("dedupe defaults to local storage without a findings URL", async () => {
expect(scanId).toBe("latest");
expect(options.findingsUrl).toBeUndefined();
expect(dependencies?.surface).toBe("cli");
- return {
- scanId,
- uniqueFindingIds: [],
- duplicateGroups: [],
- deduplicationStatus: "completed",
- };
+ return emptyDedupeResult(scanId);
};
expect(
await runCapturedCli(main, ["dedupe", "--scan", "latest", "--json"], deps),
diff --git a/sdk/typescript/tests-ts/cli-local-import.test.ts b/sdk/typescript/tests-ts/cli-local-import.test.ts
index 9651764e8..fd4c05a70 100644
--- a/sdk/typescript/tests-ts/cli-local-import.test.ts
+++ b/sdk/typescript/tests-ts/cli-local-import.test.ts
@@ -204,6 +204,14 @@ test("CLI imports a vendor report, reads local evidence, and updates the same so
assessment: { state: "not_assessed" },
evidence: { severity: "high", source_data: f.record },
});
+ const terminal = createCliTest(main, { stdout: true });
+ expect(
+ await terminal.runCli([...f.command.slice(0, -2), "--yes"], f.deps),
+ ).toBe(0);
+ expect(terminal.stdout.text()).toContain(
+ `Stored evidence${process.platform === "win32" ? " (PowerShell)" : ""}: codex-security findings imported '${f.repository}'`,
+ );
+
const repeated = createCliTest(main);
expect(await repeated.runCli([...f.command, "--yes"], f.deps)).toBe(0);
expect(JSON.parse(repeated.stdout.text()).counts).toEqual({
diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.ts
index 386b49a6c..d18f488c3 100644
--- a/sdk/typescript/tests-ts/cli-workbench.test.ts
+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts
@@ -317,6 +317,7 @@ describe("CLI workbench", () => {
findings: [
{
title: "Saved finding",
+ occurrenceId: "occ_sample_copyable",
severity: "high",
path: "source.ts:1",
},
@@ -332,6 +333,7 @@ describe("CLI workbench", () => {
findings: [
{
title: "Saved finding",
+ occurrenceId: "occ_sample_copyable",
severity: "high",
path: "source.ts:1",
},
@@ -340,11 +342,37 @@ describe("CLI workbench", () => {
} else {
expect(stdout.text()).toContain(basename(requested!));
expect(stdout.text()).toContain("Saved finding");
+ expect(stdout.text()).toContain("occ_sample_copyable");
}
}
}
},
);
+ test.each([false, true])(
+ "distinguishes missing repository history from an empty finding list in the terminal (scanned=%j)",
+ async (scanned) => {
+ const repository = resolve("/sample/repository");
+ const deps = dependencies({
+ currentDirectory: repository,
+ onWorkbench: (args): JsonObject =>
+ args[0] === "list-repositories"
+ ? {
+ repositories: scanned
+ ? [{ targetId: "repo", targetPath: repository }]
+ : [],
+ }
+ : { findings: [], nextOffset: null },
+ });
+ const tty = captureCli(main, "stdout", true);
+ expect(await tty.run(["findings", "list"], deps)).toBe(0);
+ expect(tty.text()).toContain(
+ scanned ? "0 open findings" : `No saved scan for ${repository}`,
+ );
+ const json = captureCli(main, "stdout");
+ expect(await json.run(["findings", "list", "--json"], deps)).toBe(0);
+ expect(JSON.parse(json.text())).toEqual({ repository, findings: [] });
+ },
+ );
test("lists and summarizes open findings for the current repository", async () => {
const repository = resolve("/current/repository");
const stdout = captureCli(main, "stdout");
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index c8872c4e1..ead2b1add 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -1874,7 +1874,7 @@ describe("CLI", () => {
});
}, 30_000);
- test("presents interactive scan history and hides abandoned running scans", async () => {
+ test("keeps inactive running scans visible with their last activity in interactive history", async () => {
const stdout = captureCli(main, "stdout", true);
const scan = {
mode: "standard",
@@ -1897,6 +1897,22 @@ describe("CLI", () => {
{
...scan,
scanId: "abandoned-scan",
+ mode: "deep",
+ continuationThreadId: "thread-for-deep",
+ handoffStatus: "delivered",
+ recipeAvailable: true,
+ progress: { status: "running" },
+ findingCount: 0,
+ startedAt: "2026-07-20T12:00:00Z",
+ updatedAt: "2026-07-20T12:00:00Z",
+ },
+ {
+ ...scan,
+ scanId: "recipe-less-scan",
+ mode: "deep",
+ continuationThreadId: "retained-thread",
+ handoffStatus: "delivered",
+ recipeAvailable: false,
progress: { status: "running" },
findingCount: 0,
startedAt: "2026-07-20T12:00:00Z",
@@ -1940,7 +1956,13 @@ describe("CLI", () => {
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).toContain("abandoned-scan");
+ expect(text).toContain("Last activity: 2026-07-20T12:00:00Z");
+ expect(text).toContain("codex-security scans resume abandoned-scan");
+ expect(text).not.toContain("scans resume active-scan");
+ expect(text).toContain("recipe-less-scan");
+ expect(text).not.toContain("scans resume recipe-less-scan");
+ expect(text).toContain("5 scans");
expect(text).not.toContain("juice-shop-remediated");
expect(text).not.toContain("/private/tmp");
expect(text).not.toContain("target-internal-id");
@@ -6149,7 +6171,7 @@ describe("CLI", () => {
);
expect(stderr.text()).toContain(
process.platform === "win32"
- ? `Re-run with --output-dir "${suggestion}".`
+ ? `Re-run (PowerShell) with --output-dir '${suggestion.replaceAll("'", "''")}'.`
: `Re-run with --output-dir '${suggestion.replaceAll("'", `'"'"'`)}'.`,
);
} finally {
diff --git a/sdk/typescript/tests-ts/finding-deduplication.test.ts b/sdk/typescript/tests-ts/finding-deduplication.test.ts
index 85526b4d6..4f036fcc2 100644
--- a/sdk/typescript/tests-ts/finding-deduplication.test.ts
+++ b/sdk/typescript/tests-ts/finding-deduplication.test.ts
@@ -1381,6 +1381,7 @@ test.each(
expect(await pending).toEqual({
scanId: manifest.scan.id,
uniqueFindingIds: [group[0]],
+ scanRepresentativeFindingIds: [group[0]],
duplicateGroups: [group],
deduplicationStatus: "completed",
});
@@ -1515,6 +1516,9 @@ test("resolves a saved scan and retrieves its IDs without uploading or modifying
expect(result).toEqual({
scanId: "scan_example_001",
uniqueFindingIds: document.findings.map((finding) => finding.findingId),
+ scanRepresentativeFindingIds: document.findings.map(
+ (finding) => finding.findingId,
+ ),
duplicateGroups: [],
deduplicationStatus: "completed",
});
@@ -1593,6 +1597,9 @@ test("deduplicates an explicit sealed scan directory without reading scan histor
expect(result).toEqual({
scanId: "scan_example_001",
uniqueFindingIds: document.findings.map((finding) => finding.findingId),
+ scanRepresentativeFindingIds: document.findings.map(
+ (finding) => finding.findingId,
+ ),
duplicateGroups: [],
deduplicationStatus: "completed",
});
diff --git a/sdk/typescript/tests-ts/finding-workflow-integration.test.ts b/sdk/typescript/tests-ts/finding-workflow-integration.test.ts
index 0be701d18..fc9e6b8f2 100644
--- a/sdk/typescript/tests-ts/finding-workflow-integration.test.ts
+++ b/sdk/typescript/tests-ts/finding-workflow-integration.test.ts
@@ -146,6 +146,9 @@ test("completed workflows preserve refusal outcomes without caching a false verd
deduplicationStatus: "completed_with_refusals",
duplicateGroups: [],
uniqueFindingIds: document.findings.map((finding) => finding.findingId),
+ scanRepresentativeFindingIds: document.findings.map(
+ (finding) => finding.findingId,
+ ),
refusals: [{ decision: "NO_DECISION", stage: "pair-review" }],
});
expect(reviews).toBe(3);
@@ -383,6 +386,9 @@ test("reuses publication after dedupe failure and persists a successful empty du
expect(result).toEqual({
scanId: document.scanId,
uniqueFindingIds: document.findings.map((finding) => finding.findingId),
+ scanRepresentativeFindingIds: document.findings.map(
+ (finding) => finding.findingId,
+ ),
duplicateGroups: [],
deduplicationStatus: "completed",
});
@@ -411,6 +417,7 @@ test("an empty workflow preserves its result across cancellation at completion a
const result = {
scanId: document.scanId,
uniqueFindingIds: [],
+ scanRepresentativeFindingIds: [],
duplicateGroups: [],
deduplicationStatus: "completed" as const,
};
diff --git a/sdk/typescript/tests-ts/finding-workflow-publication.test.ts b/sdk/typescript/tests-ts/finding-workflow-publication.test.ts
index 0d891d97c..f498a74ac 100644
--- a/sdk/typescript/tests-ts/finding-workflow-publication.test.ts
+++ b/sdk/typescript/tests-ts/finding-workflow-publication.test.ts
@@ -12,6 +12,7 @@ import {
import type { DeduplicationReviewer } from "../src/deduplication/deduplication-reviewer.js";
import type { ScanManifest } from "../src/models.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
+import { prepareScanPublication } from "../src/publication.js";
import { scriptedWorkbench } from "./support/workbench-fakes.js";
import { workflowFixture } from "./support/workflow-fixture.js";
import { rejecting } from "./support/errors.js";
@@ -54,6 +55,9 @@ test("deduplicates an external scan through its bound workflow without reading s
const result: DeduplicateScanResult = {
scanId: document.scanId,
uniqueFindingIds: document.findings.map((finding) => finding.findingId),
+ scanRepresentativeFindingIds: document.findings.map(
+ (finding) => finding.findingId,
+ ),
duplicateGroups: [],
deduplicationStatus: "completed",
};
@@ -245,14 +249,15 @@ test.each(["before-post", "before-write", "lost-ack", "lost-completion"])(
const { scanDir, repository, environment, document } = fixture;
const originals = [
document.findings[0]!,
- { ...document.findings[0]!, findingId: `csf_${"f".repeat(24)}` },
+ { ...document.findings[0]!, findingId: `csf_${"0".repeat(24)}` },
];
const id = `write-${failure}`;
const options = { workflowId: id, findingsUrl: "http://synthetic.test" };
- const groups = [originals.map((finding) => finding.findingId)];
+ const groups = [[originals[1]!.findingId, originals[0]!.findingId]];
const result: DeduplicateScanResult = {
scanId: document.scanId,
- uniqueFindingIds: [originals[0]!.findingId],
+ uniqueFindingIds: [originals[1]!.findingId],
+ scanRepresentativeFindingIds: [originals[0]!.findingId],
duplicateGroups: groups,
deduplicationStatus: "completed",
};
@@ -341,6 +346,25 @@ test.each(["before-post", "before-write", "lost-ack", "lost-completion"])(
},
},
complete,
+ ...prefix.slice(0, -1),
+ {
+ request: { id, action: "begin", stage: "dedupe" },
+ response: {
+ workflow: {
+ stages: {
+ dedupe: {
+ status: "completed",
+ result: {
+ scanId: document.scanId,
+ uniqueFindingIds: result.uniqueFindingIds,
+ duplicateGroups: groups,
+ deduplicationStatus: "completed",
+ },
+ },
+ },
+ },
+ },
+ },
]);
const history = async (args: readonly string[], input?: string) => {
if (args[0] === "get-scan") {
@@ -419,6 +443,20 @@ test.each(["before-post", "before-write", "lost-ack", "lost-completion"])(
expect(
await deduplicateScanInternal(document.scanId, options, dependencies),
).toEqual(result);
+ const cached = await deduplicateScanInternal(document.scanId, options, {
+ ...dependencies,
+ fetch: rejecting("Reading a completed workflow made an HTTP request"),
+ });
+ expect(cached).toEqual(result);
+ const publication = await prepareScanPublication(scanDir, {
+ destination: "linear",
+ teamId: "fixture-team",
+ findingIds: cached.scanRepresentativeFindingIds,
+ environment,
+ });
+ expect(publication.issues.map((issue) => issue.findingId)).toEqual(
+ cached.scanRepresentativeFindingIds,
+ );
expect(bodies).toHaveLength(
failure === "before-post"
? 1