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: add CLI shortcuts for saved scans (#443)

ianw-oaia7411bc12845
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 5c2cf0698..e60c3590b 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -200,6 +200,7 @@ Trusted Access for Cyber. To apply or check your access, visit
## CLI
```bash
+npx @openai/codex-security scan
npx @openai/codex-security scan /path/to/repository
npx @openai/codex-security scan /path/to/repository --headless
npx @openai/codex-security scan /path/to/repository --model gpt-5.6-terra
@@ -223,14 +224,21 @@ npx @openai/codex-security bulk-scan repositories.csv --output-dir /path/outside
npx @openai/codex-security bulk-scan repositories.csv --output-dir /path/outside/repositories/security-scans --scan-prompt-file scan.md --post-scan-prompt-file follow-up.md
npx @openai/codex-security scans list /path/to/repository
npx @openai/codex-security scans list --scan-root /path/outside/repository/results
+npx @openai/codex-security scans show
npx @openai/codex-security scans show SCAN_ID
+npx @openai/codex-security scans logs
npx @openai/codex-security scans logs SCAN_ID
+npx @openai/codex-security scans rerun
npx @openai/codex-security scans rerun SCAN_ID
npx @openai/codex-security scans match PREVIOUS_SCAN_ID CURRENT_SCAN_ID
npx @openai/codex-security scans match --all
+npx @openai/codex-security scans compare
+npx @openai/codex-security scans compare PREVIOUS_SCAN_ID
npx @openai/codex-security scans compare PREVIOUS_SCAN_ID CURRENT_SCAN_ID
+npx @openai/codex-security findings
npx @openai/codex-security findings list /path/to/repository
npx @openai/codex-security findings false-positive OCCURRENCE_ID --reason "The route already checks permissions"
+npx @openai/codex-security export
npx @openai/codex-security export /path/outside/repository/results --export-format sarif --output /path/outside/repository/results.sarif
npx @openai/codex-security export /path/outside/repository/results --export-format csv --output /path/outside/repository/findings.csv
npx @openai/codex-security export /path/outside/repository/results --export-format json --output /path/outside/repository/findings.json
@@ -538,14 +546,15 @@ same command to resume.
### Scan history and reruns
-`npx @openai/codex-security scans list` lists scans for the current repository. Pass a
-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. Add
+`scans` or `scans list` lists scans for the current repository. Pass a repository
+path to inspect another checkout, or `--scan-root DIR` to list scans whose
+artifacts are under a particular root. `scans show` opens the latest completed
+scan for the current repository. Pass `SCAN_ID` to inspect another scan. Scan
+details include the configuration, results, coverage, and artifact locations. Add
`--show-linked-findings` to include finding links from previous scans.
-`scans logs SCAN_ID` shows complete session events from the scan and its
-workers, which can include source code and credentials.
+`scans logs` shows session events from the latest scan, including an active scan.
+Pass `SCAN_ID` to select another scan. Logs can contain source code and credentials.
Every scan history command accepts a full scan ID or a unique prefix of at
least eight characters.
@@ -565,22 +574,25 @@ default directory, select a writable directory outside the scanned repository:
export CODEX_SECURITY_STATE_DIR=/path/to/writable/codex-security-state
```
-Use `findings false-positive OCCURRENCE_ID --reason TEXT` to mark a finding as
-a false positive and explain why. Later scans dismiss a matching finding only
-when the same reason still applies.
+`findings` or `findings list` lists open findings for the current repository.
+Use `findings false-positive OCCURRENCE_ID --reason TEXT` to mark a finding as a
+false positive and explain why. Later scans dismiss a matching finding only when
+the same reason still applies.
-`scans rerun SCAN_ID` repeats the original configuration against the current
-checkout so a fixed vulnerability can be checked again.
+`scans rerun` repeats the latest completed scan against the current checkout.
+Pass `SCAN_ID` to rerun another scan.
`scans match BEFORE_SCAN_ID AFTER_SCAN_ID` links findings with the same root
cause; `scans match --all` matches all completed scans of the current repository,
including other worktrees and clones. Saved matches appear in `scans show` and
are reused unless `--force` is passed. Scans without sealed artifacts are skipped.
-`scans compare BEFORE_SCAN_ID AFTER_SCAN_ID` automatically matches findings by
-root cause, reuses saved matches, and reports findings as new, persisting,
-reopened, resolved, or unknown. Missing findings are not treated as resolved when
-the later scan is incomplete or does not cover their original scope.
+`scans compare` compares the two latest completed scans. Pass one scan ID to
+compare it with the latest completed scan, or two IDs to select both scans. It
+matches findings by root cause, reuses saved matches, and reports findings as
+new, persisting, reopened, resolved, or unknown. Missing findings are not
+treated as resolved when the later scan is incomplete or does not cover their
+original scope.
The CLI uses [Incur](https://github.com/wevm/incur) for agent-friendly discovery
and structured output. Inspect the command manifest with `--llms`, inspect a
@@ -612,7 +624,8 @@ they do not produce structured CLI output. Sign-in commands remain interactive.
CSV exports cannot be written to stdout while JSON output is requested.
Use `export` to create CSV, JSON, or SARIF from a completed, sealed scan without
-starting Codex or loading credentials. JSON preserves the sealed findings
+starting Codex or loading credentials. Without a scan directory, it exports the
+latest completed scan for the current repository. JSON preserves the sealed findings
document. CSV uses the portable findings columns, marks findings as open, and
does not include local workbench triage state. The exporter validates the seal
before writing, accepts `--output -` for stdout, and can use
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 7d5a77c60..8b949e52e 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -143,6 +143,7 @@ type Writable = Pick<NodeJS.WriteStream, "write"> & {
};
type SignalName = "SIGINT" | "SIGTERM";
type FailureSeverity = Exclude<SeverityLevel, "informational">;
+type SavedScan = JsonObject & { scanId: string; scanDir: string };
const REPORTABLE_SEVERITIES: readonly FailureSeverity[] = [
"critical",
@@ -759,7 +760,7 @@ export async function main(
errorOutput: Writable = process.stderr,
dependencies: CliDependencies = DEFAULT_DEPENDENCIES,
): Promise<number> {
- argv = defaultScansList(argv);
+ argv = defaultListCommand(argv);
const positionals: string[] = [];
const argumentError = validateCliArguments(argv, positionals);
if (argumentError !== undefined) {
@@ -804,6 +805,33 @@ export async function main(
return undefined;
}
};
+ const latestScans = async (
+ count = 1,
+ status: "complete" | "any" = "complete",
+ ): Promise<SavedScan[] | undefined> => {
+ const result = await history(
+ [
+ "list-scans",
+ "--repository",
+ dependencies.currentDirectory(),
+ ...(status === "complete" ? ["--status", "complete"] : []),
+ "--limit",
+ String(count),
+ ],
+ (value) => {
+ if ((value["scans"] as SavedScan[]).length < count) {
+ const kind = status === "complete" ? "completed" : "saved";
+ throw new CodexSecurityError(
+ count === 1
+ ? `No ${kind} scans found for the current repository.`
+ : `At least ${count} ${kind} scans are required for the current repository.`,
+ );
+ }
+ return value;
+ },
+ );
+ return result?.["scans"] as SavedScan[] | undefined;
+ };
const matchScanPair = async (
beforeId: string,
afterId: string,
@@ -993,7 +1021,8 @@ export async function main(
scanId: z
.string()
.min(1)
- .describe("Saved scan identifier or unique prefix."),
+ .optional()
+ .describe("Scan ID or unique prefix (default: latest completed)."),
}),
options: z.object({
showLinkedFindings: z
@@ -1003,8 +1032,10 @@ 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;
+ if (scanId === undefined) return;
return presentHistory(
- await history(["get-scan", "--scan-id", args.scanId], (value) => {
+ await history(["get-scan", "--scan-id", scanId], (value) => {
const { scan, recipe, parentScanId } = value;
return {
...(scan as JsonObject),
@@ -1025,12 +1056,16 @@ export async function main(
scanId: z
.string()
.min(1)
- .describe("Saved scan identifier or unique prefix."),
+ .optional()
+ .describe("Scan identifier or unique prefix (default: latest)."),
}),
output: z.record(z.string(), z.unknown()).optional(),
async run({ args }) {
+ const scanId =
+ args.scanId ?? (await latestScans(1, "any"))?.[0]?.scanId;
+ if (scanId === undefined) return;
return await history(
- ["get-scan", "--scan-id", args.scanId],
+ ["get-scan", "--scan-id", scanId],
async (value) => {
const scan = value["scan"] as {
scanId: string;
@@ -1068,7 +1103,11 @@ export async function main(
destructive: true,
mcp: false,
args: z.object({
- scanId: z.string().min(1).describe("Saved scan identifier."),
+ scanId: z
+ .string()
+ .min(1)
+ .optional()
+ .describe("Saved scan identifier (default: latest completed scan)."),
}),
options: z.object({
verbose: z
@@ -1078,14 +1117,16 @@ export async function main(
}),
output: z.record(z.string(), z.unknown()).optional(),
async run({ args, error: incurError, options }) {
+ const scanId = args.scanId ?? (await latestScans())?.[0]?.scanId;
+ if (scanId === undefined) return;
let scanArguments: ScanArguments;
try {
const { recipe } = await dependencies.runWorkbench([
"get-scan-recipe",
"--scan-id",
- args.scanId,
+ scanId,
]);
- scanArguments = scanArgumentsFromRecipe(recipe, args.scanId);
+ scanArguments = scanArgumentsFromRecipe(recipe, scanId);
scanArguments.verbose = options.verbose;
} catch (error) {
const message = errorMessage(error);
@@ -1162,13 +1203,31 @@ export async function main(
destructive: true,
mcp: false,
args: z.object({
- beforeId: z.string().min(1).describe("Earlier saved scan identifier."),
- afterId: z.string().min(1).describe("Later saved scan identifier."),
+ beforeId: z
+ .string()
+ .min(1)
+ .optional()
+ .describe("Earlier saved scan identifier."),
+ afterId: z
+ .string()
+ .min(1)
+ .optional()
+ .describe("Later saved scan identifier (default: latest completed)."),
}),
output: z.record(z.string(), z.unknown()).optional(),
async run({ args, format }) {
+ let { beforeId, afterId } = args;
+ if (beforeId === undefined) {
+ const scans = await latestScans(2);
+ if (scans === undefined) return;
+ beforeId = scans[1]!.scanId;
+ afterId = scans[0]!.scanId;
+ } else if (afterId === undefined) {
+ afterId = (await latestScans())?.[0]?.scanId;
+ if (afterId === undefined) return;
+ }
return presentHistory(
- await matchScanPair(args.beforeId, args.afterId),
+ await matchScanPair(beforeId, afterId),
"compare",
format,
);
@@ -1668,7 +1727,8 @@ export async function main(
args: z.object({
scanDir: z
.string()
- .describe("Completed Codex Security scan directory."),
+ .optional()
+ .describe("Completed scan directory (default: latest completed)."),
}),
options: z
.object({
@@ -1701,9 +1761,11 @@ export async function main(
),
async run({ args, options }) {
const currentDirectory = dependencies.currentDirectory();
+ const scanDir = args.scanDir ?? (await latestScans())?.[0]?.scanDir;
+ if (scanDir === undefined) return;
exitCode = await runExport(
{
- scanDir: resolve(currentDirectory, args.scanDir),
+ scanDir: resolve(currentDirectory, scanDir),
format: options.exportFormat,
output:
options.output === "-"
@@ -2001,14 +2063,14 @@ export async function main(
}
}
-function defaultScansList(argv: readonly string[]): readonly string[] {
+function defaultListCommand(argv: readonly string[]): readonly string[] {
const commandIndex = argv.findIndex((value, index) => {
if (value.startsWith("-")) return false;
return index === 0 || !VALUE_OPTIONS.has(argv[index - 1]!);
});
if (
commandIndex < 0 ||
- argv[commandIndex] !== "scans" ||
+ !["scans", "findings"].includes(argv[commandIndex]!) ||
argv.includes("--help") ||
argv.includes("-h")
) {
diff --git a/sdk/typescript/tests-ts/cli-export.test.ts b/sdk/typescript/tests-ts/cli-export.test.ts
index 12b0d7b73..923e247c0 100644
--- a/sdk/typescript/tests-ts/cli-export.test.ts
+++ b/sdk/typescript/tests-ts/cli-export.test.ts
@@ -77,6 +77,28 @@ describe("CLI", () => {
}
});
+ test("exports the latest completed scan when no directory is provided", async () => {
+ const scanDir = join(tmpdir(), "codex-security-latest-scan");
+ const deps = dependencies({
+ onWorkbench: () => ({ scans: [{ scanId: "latest-scan", scanDir }] }),
+ });
+ let exportedScanDir = "";
+ deps.exportFindings = async (arguments_) => {
+ exportedScanDir = arguments_.scanDir;
+ return new Uint8Array();
+ };
+
+ expect(
+ await main(
+ ["export", "--output", "-"],
+ capture().stream,
+ capture().stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(exportedScanDir).toBe(scanDir);
+ });
+
test("waits for delayed stdout writes without closing the destination", async () => {
let contents = "";
const stdout = new Writable({
diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.ts
index 9766a2615..591630e7a 100644
--- a/sdk/typescript/tests-ts/cli-workbench.test.ts
+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts
@@ -50,6 +50,14 @@ describe("CLI workbench", () => {
repository,
findings: [{ title: "Finding 1" }, { title: "Finding 2" }],
});
+ expect(
+ await main(
+ ["findings", "--json"],
+ capture().stream,
+ capture().stream,
+ dependencies({ onWorkbench: () => ({ repositories: [] }) }),
+ ),
+ ).toBe(0);
for (const confirmed of [[true, false], []]) {
const result = fakeResult(["high"]);
Object.assign(result, {
@@ -314,8 +322,11 @@ describe("CLI workbench", () => {
const stdout = capture();
const deps = dependencies({
environment: { CODEX_SECURITY_STATE_DIR: state },
- onWorkbench: (args) => {
+ onWorkbench: (args): JsonObject => {
calls.push(args);
+ if (args[0] === "list-scans") {
+ return { scans: [{ scanId: "scan-1" }] };
+ }
return {
scan: {
scanId: "scan-1",
@@ -345,6 +356,22 @@ describe("CLI workbench", () => {
expect(stdout.text()).toContain("SYNTHETIC_KEY");
expect(stdout.text()).toContain("independent worker");
expect(stdout.text()).not.toContain("PRIVATE LATER SESSION");
+
+ calls.length = 0;
+ const latest = capture();
+ expect(
+ await main(
+ ["scans", "logs", "--json"],
+ latest.stream,
+ capture().stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(calls).toEqual([
+ ["list-scans", "--repository", "/current/repository", "--limit", "1"],
+ ["get-scan", "--scan-id", "scan-1"],
+ ]);
+ expect(latest.text()).toContain("SYNTHETIC_KEY");
} finally {
await rm(state, { recursive: true, force: true });
}
@@ -384,18 +411,28 @@ describe("CLI workbench", () => {
uncertain: [],
};
- for (const command of ["match", "compare"]) {
+ for (const [command, scanIds, expectedBefore, expectedAfter] of [
+ ["match", ["before", "after"], "before", "after"],
+ ["compare", ["before", "after"], "before", "after"],
+ ["compare", [], "older-scan", "latest-scan"],
+ ["compare", ["baseline-scan"], "baseline-scan", "latest-scan"],
+ ] as const) {
const calls: Array<readonly string[]> = [];
const stdout = capture();
expect(
await main(
- ["scans", command, "before", "after", "--json"],
+ ["scans", command, ...scanIds, "--json"],
stdout.stream,
capture().stream,
dependencies({
onWorkbench: (args): JsonObject => {
calls.push(args);
+ if (args[0] === "list-scans") {
+ return {
+ scans: [{ scanId: "latest-scan" }, { scanId: "older-scan" }],
+ };
+ }
return args[0] === "compare-scans"
? { matchingCached: false, matchingInputs: { before, after } }
: { summary: { persisting: 1 } };
@@ -408,14 +445,37 @@ describe("CLI workbench", () => {
),
).toBe(0);
expect(calls.map((args) => args[0])).toEqual([
+ ...(scanIds.length < 2 ? ["list-scans"] : []),
"compare-scans",
"save-scan-comparison",
]);
- expect(JSON.parse(calls[1]![6]!)).toEqual(matching);
+ const comparison = calls.find((args) => args[0] === "compare-scans")!;
+ expect(comparison[2]).toBe(expectedBefore);
+ expect(comparison[4]).toBe(expectedAfter);
+ expect(JSON.parse(calls.at(-1)![6]!)).toEqual(matching);
expect(JSON.parse(stdout.text())).toEqual({ summary: { persisting: 1 } });
}
});
+ test("requires two completed scans for a default comparison", async () => {
+ const stderr = capture();
+ expect(
+ await main(
+ ["scans", "compare"],
+ capture().stream,
+ stderr.stream,
+ dependencies({
+ onWorkbench: () => ({
+ scans: [{ scanId: "scan-1" }],
+ }),
+ }),
+ ),
+ ).toBe(2);
+ expect(stderr.text()).toContain(
+ "At least 2 completed scans are required for the current repository.",
+ );
+ });
+
test("reports automatic matching failures without saving a comparison", async () => {
const calls: string[] = [];
const stderr = capture();
@@ -715,6 +775,35 @@ describe("CLI workbench", () => {
}
});
+ test("reruns the latest completed scan by default", async () => {
+ let parentScanId: unknown;
+
+ expect(
+ await main(
+ ["scans", "rerun"],
+ capture().stream,
+ capture().stream,
+ dependencies({
+ onTurn: (_repository, options) => {
+ parentScanId = (options as { parentScanId?: string }).parentScanId;
+ },
+ onWorkbench: (args): JsonObject =>
+ args[0] === "list-scans"
+ ? { scans: [{ scanId: "latest-scan" }] }
+ : {
+ recipe: {
+ repository: "/current/repository",
+ target: { kind: "repository", paths: [] },
+ mode: "standard",
+ config: {},
+ },
+ },
+ }),
+ ),
+ ).toBe(0);
+ expect(parentScanId).toBe("latest-scan");
+ });
+
test("reruns canonical recipes with exact config, policy, plugin, and lineage", async () => {
let config: CodexSecurityConfig | undefined;
let repository: string | undefined;
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index 15e801ee8..b84013345 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -192,20 +192,20 @@ describe("CLI", () => {
"codex-security install-hook [repository]",
);
expect(manifest.text()).toContain("codex-security bulk-scan [input]");
- expect(manifest.text()).toContain("codex-security export <scanDir>");
+ expect(manifest.text()).toContain("codex-security export [scanDir]");
expect(manifest.text()).toContain("codex-security validate <findings...>");
expect(manifest.text()).toContain("codex-security patch <issues...>");
expect(manifest.text()).toContain(
"codex-security findings false-positive <occurrenceId>",
);
expect(manifest.text()).toContain("codex-security scans list [repository]");
- expect(manifest.text()).toContain("codex-security scans show <scanId>");
- expect(manifest.text()).toContain("codex-security scans rerun <scanId>");
+ expect(manifest.text()).toContain("codex-security scans show [scanId]");
+ expect(manifest.text()).toContain("codex-security scans rerun [scanId]");
expect(manifest.text()).toContain(
"codex-security scans match [beforeId] [afterId]",
);
expect(manifest.text()).toContain(
- "codex-security scans compare <beforeId> <afterId>",
+ "codex-security scans compare [beforeId] [afterId]",
);
expect(manifest.text()).toContain("codex-security info");
@@ -1114,6 +1114,55 @@ describe("CLI", () => {
expect(text).not.toContain("target-internal-id");
});
+ test("shows the latest completed scan for the current repository by default", async () => {
+ const stdout = capture();
+ const calls: Array<readonly string[]> = [];
+ const responses: JsonObject[] = [
+ { scans: [{ scanId: "latest-scan" }] },
+ { scan: { scanId: "latest-scan" } },
+ ];
+
+ expect(
+ await main(
+ ["scans", "show", "--json"],
+ stdout.stream,
+ capture().stream,
+ dependencies({
+ onWorkbench: (args) => responses[calls.push(args) - 1]!,
+ }),
+ ),
+ ).toBe(0);
+ expect(JSON.parse(stdout.text())).toEqual({ scanId: "latest-scan" });
+ expect(calls).toEqual([
+ [
+ "list-scans",
+ "--repository",
+ "/current/repository",
+ "--status",
+ "complete",
+ "--limit",
+ "1",
+ ],
+ ["get-scan", "--scan-id", "latest-scan"],
+ ]);
+ });
+
+ test("reports when the current repository has no saved scans", async () => {
+ const stderr = capture();
+
+ expect(
+ await main(
+ ["scans", "show"],
+ capture().stream,
+ stderr.stream,
+ dependencies(),
+ ),
+ ).toBe(2);
+ expect(stderr.text()).toContain(
+ "No completed scans found for the current repository.",
+ );
+ });
+
test("shows finding history and optionally reveals linked findings", async () => {
const findings: JsonObject[] = [
{
@@ -2097,7 +2146,7 @@ describe("CLI", () => {
expect(
await main(["export", "--help"], stdout.stream, stderr.stream, deps),
).toBe(0);
- expect(stdout.text()).toContain("Usage: codex-security export <scanDir>");
+ expect(stdout.text()).toContain("Usage: codex-security export [scanDir]");
expect(stdout.text()).toContain("--export-format <csv|json|sarif>");
expect(stdout.text()).toContain("--source-root <string>");
expect(stdout.text()).not.toContain("--format {sarif}");
@@ -2633,7 +2682,6 @@ describe("CLI", () => {
],
"--effort conflicts with --codex model_reasoning_effort",
],
- [["export"], "scanDir"],
[["export", "scan", "--unknown"], "Unknown flag: --unknown"],
[["export", "scan", "--format", "sarif"], "Invalid format"],
[["export", "scan", "--export-format", "xml"], "Invalid option"],