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-oaif107d772737d
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 2efd387f7..0aab93a82 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -60,6 +60,7 @@ npx codex-security scan /path/to/repository --output-dir /path/outside/repositor
npx codex-security scan /path/to/repository --output-dir /path/outside/repository/results --archive-existing
npx codex-security scan /path/to/repository --dry-run
npx codex-security scan /path/to/repository --fail-on-severity high
+npx codex-security scan-csv repositories.csv --output-dir /tmp/security-scans --workers 4
npx codex-security export /path/outside/repository/results --export-format sarif --output results.sarif
npx codex-security export /path/outside/repository/results --export-format csv --output findings.csv
npx codex-security export /path/outside/repository/results --export-format json --output findings.json
@@ -93,7 +94,20 @@ Scans use `gpt-5.6-sol` with extra-high reasoning effort by default. Override
either setting with repeatable `--codex KEY=VALUE` options, for example
`--codex 'model="gpt-5.6-sol"' --codex 'model_reasoning_effort="high"'`.
-Run `npx codex-security scan --help` for the complete CLI reference.
+Run `npx codex-security scan --help` or `npx codex-security scan-csv --help`
+for the complete CLI references.
+
+Use `scan-csv` to scan repositories from a CSV manifest with required `id`,
+`repository`, and `revision` columns. Revisions must be full commit hashes;
+optional `scope` and `mode` columns narrow individual scans:
+
+```csv
+id,repository,revision,scope,mode
+service,https://github.com/acme/service.git,0123456789abcdef0123456789abcdef01234567,src,standard
+```
+
+`--workers` limits concurrent scans and `--max-attempts` retries failures.
+Results remain under `--output-dir`; rerun the same command to resume.
The CLI uses [Incur](https://github.com/wevm/incur) for agent-friendly discovery
and structured output. Inspect the command manifest with `--llms`, inspect a
@@ -102,8 +116,9 @@ server with `mcp add`, sync agent skills with `skills add`, or generate shell
completions with `completions bash|zsh|fish`. Scan results support
`--format toon|json|yaml|jsonl` and `--full-output`.
Use `info --json` for SDK and bundled-plugin metadata. MCP exposes only this
-read-only metadata command; scans, authentication, exports, validation, and
-patching remain CLI-only because the MCP transport cannot cancel active scans.
+read-only metadata command; scans, CSV-based multi-repository scans,
+authentication, exports, validation, and patching remain CLI-only because the
+MCP transport cannot cancel active scans.
For CI, keep machine-readable output on stdout and apply a severity policy;
incomplete coverage and runtime errors still exit nonzero:
diff --git a/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py b/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py
index 7a971283f..0a8f1f141 100644
--- a/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py
+++ b/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py
@@ -18,7 +18,7 @@ import secrets
import stat
import sys
from collections.abc import Iterator
-from datetime import datetime
+from datetime import datetime, timezone
from pathlib import Path, PurePosixPath
from typing import Any, BinaryIO, TextIO
from urllib.parse import quote, urlsplit
@@ -797,6 +797,11 @@ def _populate_unsealed_manifest_envelope(
scan["coverageRef"] = "coverage.json"
scan["findingsRef"] = "findings.json"
if completion_binding is None:
+ started_at = os.environ.get("CODEX_SECURITY_STARTED_AT")
+ if started_at is not None:
+ _validate_date_time(started_at, "CODEX_SECURITY_STARTED_AT")
+ scan["startedAt"] = started_at
+ scan["completedAt"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
return
scan["id"] = completion_binding["scanId"]
diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json
index 87234549b..c63e09be7 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/cli.test.ts tests-ts/config.test.ts tests-ts/contract.test.ts tests-ts/result.test.ts tests-ts/runtime.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/cli.test.ts tests-ts/config.test.ts tests-ts/contract.test.ts tests-ts/multiscan.test.ts tests-ts/result.test.ts tests-ts/runtime.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": {
@@ -55,11 +55,13 @@
"ajv": "8.20.0",
"extract-zip": "2.0.1",
"incur": "0.4.13",
+ "papaparse": "5.5.3",
"smol-toml": "1.6.1"
},
"devDependencies": {
"@types/bun": "1.3.13",
"@types/node": "22.19.17",
+ "@types/papaparse": "5.3.15",
"fflate": "0.8.2",
"json-schema-to-typescript": "15.0.4",
"prettier": "3.2.5",
diff --git a/sdk/typescript/pnpm-lock.yaml b/sdk/typescript/pnpm-lock.yaml
index 2bbd36286..22cca3fa0 100644
--- a/sdk/typescript/pnpm-lock.yaml
+++ b/sdk/typescript/pnpm-lock.yaml
@@ -23,6 +23,9 @@ importers:
incur:
specifier: 0.4.13
version: 0.4.13
+ papaparse:
+ specifier: 5.5.3
+ version: 5.5.3
smol-toml:
specifier: 1.6.1
version: 1.6.1
@@ -33,6 +36,9 @@ importers:
'@types/node':
specifier: 22.19.17
version: 22.19.17
+ '@types/papaparse':
+ specifier: 5.3.15
+ version: 5.3.15
fflate:
specifier: 0.8.2
version: 0.8.2
@@ -130,6 +136,9 @@ packages:
resolution: {integrity: sha512-wGdMcf+vPYM6jikpS/qhg6WiqSV/OhG+jeeHT/KlVqxYfD40iYJf9/AE1uQxVWFvU7MipKRkRv8NSHiCGgPr8Q==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-JHe6vF6x/8Z85nCX4yFdDslN11d+1pr12E526X8WAfhadOeaOTx5AuIkvDKIBopfvlzpzkdMx4YyvSKCM9oqtw==}
+
resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==}
@@ -224,6 +233,9 @@ packages:
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
+ resolution: {integrity: sha512-5QvjGxYVjxO59MGU2lHVYpRWBBtKHnlIAcSe1uNFCkkptUh63NFRj0FJQm7nR67puEruUci/ZkjmEFrjCAyP4A==}
+
resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}
@@ -344,6 +356,10 @@ snapshots:
dependencies:
undici-types: 6.21.0
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.19.17
+
dependencies:
'@types/node': 22.19.17
@@ -444,6 +460,8 @@ snapshots:
dependencies:
wrappy: 1.0.2
+
diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjs
index 0fd2ed4d4..f99ef1232 100644
--- a/sdk/typescript/scripts/check-package.mjs
+++ b/sdk/typescript/scripts/check-package.mjs
@@ -136,6 +136,7 @@ const distFiles = new Set(
"errors",
"index",
"models",
+ "multiscan",
"result",
"runtime",
"targets",
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index da671d63e..46db830ea 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -344,6 +344,7 @@ export class CodexSecurity {
: null;
const runtimePaths = {
PYTHON: python,
+ CODEX_SECURITY_STARTED_AT: new Date().toISOString(),
CODEX_SECURITY_REPOSITORY: repo,
CODEX_SECURITY_SCAN_DIR: scanDir,
CODEX_SECURITY_PLUGIN_ROOT: shellPluginRoot,
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 11c680c2e..791aa874f 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -34,6 +34,7 @@ import {
ScanInterruptedError,
} from "./errors.js";
import type { SeverityLevel } from "./models.js";
+import { runMultiscan } from "./multiscan.js";
import type { ScanResult } from "./result.js";
import {
bundledPluginRoot,
@@ -81,6 +82,8 @@ const VALUE_OPTIONS = new Set([
"--python",
"--codex",
"--fail-on-severity",
+ "--workers",
+ "--max-attempts",
"--export-format",
"--output",
"--source-root",
@@ -480,6 +483,75 @@ export async function main(
return outcome.data;
},
})
+ .command("scan-csv", {
+ description: "Run resumable repository scans from a CSV inventory.",
+ destructive: true,
+ mcp: false,
+ args: z.object({
+ input: z.string().min(1).describe("CSV repository inventory."),
+ }),
+ options: z.object({
+ outputDir: z
+ .string()
+ .min(1, "--output-dir must not be empty.")
+ .describe("Directory for scan artifacts and resumable results."),
+ workers: z.number().int().positive().default(4),
+ mode: z.enum(["standard", "deep"]).default("standard"),
+ maxAttempts: z
+ .number()
+ .int()
+ .positive()
+ .default(1)
+ .describe("Maximum scan attempts per repository."),
+ pluginPath: z.string().min(1).optional(),
+ python: z.string().min(1).optional(),
+ codex: z.array(z.string().min(1)).default([]),
+ }),
+ output: z.record(z.string(), z.unknown()).optional(),
+ async run({ args, options }) {
+ const controller = new AbortController();
+ const onInterrupt = (): void => controller.abort("SIGINT");
+ const onTerminate = (): void => controller.abort("SIGTERM");
+ const interruptedExitCode = (): number | undefined =>
+ controller.signal.reason === "SIGINT"
+ ? 130
+ : controller.signal.reason === "SIGTERM"
+ ? 143
+ : undefined;
+ dependencies.addSignalListener("SIGINT", onInterrupt);
+ dependencies.addSignalListener("SIGTERM", onTerminate);
+ try {
+ const currentDirectory = dependencies.currentDirectory();
+ const result = await runMultiscan({
+ inputPath: resolve(currentDirectory, args.input),
+ outputDir: resolve(currentDirectory, options.outputDir),
+ workers: options.workers,
+ mode: options.mode,
+ maxAttempts: options.maxAttempts,
+ config: {
+ pluginPath: options.pluginPath,
+ pythonPath: options.python,
+ codexOverrides: parseCodexOverrides(options.codex),
+ },
+ createSecurity: dependencies.createSecurity,
+ signal: controller.signal,
+ onProgress: ({ repository, status, attempt, error }) => {
+ errorOutput.write(
+ `codex-security: ${repository} ${status} (attempt ${attempt})${error === undefined ? "" : `: ${cliErrorMessage(error)}`}\n`,
+ );
+ },
+ });
+ exitCode = interruptedExitCode() ?? (result.failed > 0 ? 2 : 0);
+ return { ...result };
+ } catch (error) {
+ exitCode = interruptedExitCode() ?? 2;
+ errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
+ } finally {
+ dependencies.removeSignalListener("SIGINT", onInterrupt);
+ dependencies.removeSignalListener("SIGTERM", onTerminate);
+ }
+ },
+ })
.command("export", {
description:
"Export findings from a completed scan as CSV, JSON, or SARIF.",
@@ -668,9 +740,16 @@ function validateCliArguments(
): string | undefined {
if (argv.includes("--help") || argv.includes("-h")) return undefined;
const commandIndex = argv.findIndex((value) =>
- ["scan", "export", "validate", "patch", "login", "logout", "info"].includes(
- value,
- ),
+ [
+ "scan",
+ "scan-csv",
+ "export",
+ "validate",
+ "patch",
+ "login",
+ "logout",
+ "info",
+ ].includes(value),
);
if (commandIndex < 0) return undefined;
const command = argv[commandIndex];
diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.ts
new file mode 100644
index 000000000..905debf33
--- /dev/null
+++ b/sdk/typescript/src/multiscan.ts
@@ -0,0 +1,495 @@
+import { execFile as execFileCallback } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import {
+ lstat,
+ mkdir,
+ open,
+ readFile,
+ realpath,
+ rename,
+ rm,
+ truncate,
+ writeFile,
+} from "node:fs/promises";
+import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+import { promisify } from "node:util";
+import Papa from "papaparse";
+import type { CodexSecurity } from "./api.js";
+import type { CodexSecurityConfig } from "./config.js";
+import type { ScanMode } from "./targets.js";
+import { resolveTrustedExecutable } from "./trusted-executable.js";
+
+const execFile = promisify(execFileCallback);
+const REQUIRED_ARTIFACTS = [
+ "scan-manifest.json",
+ "findings.json",
+ "coverage.json",
+ "report.md",
+];
+
+interface MultiscanTask {
+ id: string;
+ repository: string;
+ revision: string;
+ mode: ScanMode;
+ scope?: string;
+}
+
+interface MultiscanReceipt extends MultiscanTask {
+ status: "completed" | "failed";
+ attempt: number;
+ outputDir: string;
+ error?: string;
+}
+
+export interface MultiscanOptions {
+ inputPath: string;
+ outputDir: string;
+ workers: number;
+ mode: ScanMode;
+ maxAttempts: number;
+ config: CodexSecurityConfig;
+ createSecurity(
+ config: CodexSecurityConfig,
+ ): Pick<CodexSecurity, "run" | "close">;
+ signal?: AbortSignal;
+ onProgress?(event: {
+ repository: string;
+ status: "started" | "completed" | "failed";
+ attempt: number;
+ error?: string;
+ }): void;
+}
+
+export interface MultiscanResult {
+ total: number;
+ completed: number;
+ failed: number;
+ skipped: number;
+ resultsPath: string;
+}
+
+export async function runMultiscan(
+ options: MultiscanOptions,
+): Promise<MultiscanResult> {
+ options.signal?.throwIfAborted();
+ if (!Number.isSafeInteger(options.workers) || options.workers < 1) {
+ throw new Error("Multiscan workers must be a positive integer.");
+ }
+ if (!Number.isSafeInteger(options.maxAttempts) || options.maxAttempts < 1) {
+ throw new Error("Multiscan max attempts must be a positive integer.");
+ }
+ const tasks = parseInventory(
+ await readFile(options.inputPath, "utf8"),
+ dirname(resolve(options.inputPath)),
+ options.mode,
+ );
+ const output = resolve(options.outputDir);
+ await ensureOutputDirectory(output);
+ const unlock = await acquireLock(output);
+ try {
+ return await runCampaign(options, tasks, output);
+ } finally {
+ await unlock();
+ }
+}
+
+async function runCampaign(
+ options: MultiscanOptions,
+ tasks: MultiscanTask[],
+ output: string,
+): Promise<MultiscanResult> {
+ const ledger = join(output, "results.jsonl");
+ await ensureOutputDirectory(join(output, "checkouts"));
+ await ensureOutputDirectory(join(output, "artifacts"));
+ await ensureManifest(join(output, "manifest.json"), tasks);
+ const receipts = await readReceipts(ledger);
+ const pending: MultiscanTask[] = [];
+ let completed = 0;
+ for (const task of tasks) {
+ const receipt = receipts.get(task.id.toLowerCase());
+ if (
+ receipt?.status === "completed" &&
+ receipt.outputDir ===
+ join(output, "artifacts", task.id, `attempt-${receipt.attempt}`) &&
+ (await hasArtifacts(receipt.outputDir))
+ ) {
+ completed += 1;
+ } else {
+ pending.push(task);
+ }
+ }
+ const skipped = completed;
+ if (pending.length === 0) {
+ return {
+ total: tasks.length,
+ completed,
+ failed: 0,
+ skipped,
+ resultsPath: ledger,
+ };
+ }
+
+ let next = 0;
+ let failed = 0;
+ const worker = async (
+ security: Pick<CodexSecurity, "run" | "close">,
+ ): Promise<void> => {
+ for (;;) {
+ options.signal?.throwIfAborted();
+ const task = pending[next++];
+ if (task === undefined) return;
+ let attempt = receipts.get(task.id.toLowerCase())?.attempt ?? 0;
+ for (let retry = 0; retry < options.maxAttempts; retry += 1) {
+ options.signal?.throwIfAborted();
+ attempt += 1;
+ const checkout = join(output, "checkouts", task.id);
+ const scanDir = join(
+ output,
+ "artifacts",
+ task.id,
+ `attempt-${attempt}`,
+ );
+ const progress = { repository: task.id, attempt };
+ options.onProgress?.({ ...progress, status: "started" });
+ let failure: string | undefined;
+ try {
+ await mkdir(dirname(scanDir), { recursive: true, mode: 0o700 });
+ await rm(checkout, { recursive: true, force: true });
+ await mkdir(checkout, { mode: 0o700 });
+ await checkoutRevision(task, checkout, options.signal);
+ if (task.scope !== undefined) {
+ const scoped = await realpath(join(checkout, task.scope));
+ const outside = relative(await realpath(checkout), scoped);
+ if (
+ outside === ".." ||
+ outside.startsWith(`..${sep}`) ||
+ isAbsolute(outside)
+ ) {
+ throw new Error("Multiscan scope escapes its repository.");
+ }
+ }
+ const result = await security.run(checkout, {
+ ...(task.scope === undefined ? {} : { target: [task.scope] }),
+ mode: task.mode,
+ outputDir: scanDir,
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
+ });
+ if (result.coverage.completeness !== "complete") {
+ throw new Error("Multiscan repository coverage is incomplete.");
+ }
+ } catch (error) {
+ if (options.signal?.aborted === true) options.signal.throwIfAborted();
+ failure = redactError(error);
+ } finally {
+ await rm(checkout, { recursive: true, force: true });
+ }
+ const status = failure === undefined ? "completed" : "failed";
+ await appendReceipt(
+ ledger,
+ `${JSON.stringify({
+ ...task,
+ status,
+ attempt,
+ outputDir: scanDir,
+ ...(failure === undefined ? {} : { error: failure }),
+ })}\n`,
+ );
+ options.onProgress?.({
+ ...progress,
+ status,
+ ...(failure === undefined ? {} : { error: failure }),
+ });
+ if (failure === undefined) {
+ completed += 1;
+ break;
+ }
+ if (retry === options.maxAttempts - 1) failed += 1;
+ }
+ }
+ };
+ const results = await Promise.allSettled(
+ Array.from(
+ { length: Math.min(options.workers, pending.length) },
+ async () => {
+ const security = options.createSecurity(options.config);
+ try {
+ await worker(security);
+ } finally {
+ await security.close();
+ }
+ },
+ ),
+ );
+ const rejection = results.find((result) => result.status === "rejected");
+ if (rejection?.status === "rejected") throw rejection.reason;
+ return {
+ total: tasks.length,
+ completed,
+ failed,
+ skipped,
+ resultsPath: ledger,
+ };
+}
+
+async function ensureOutputDirectory(path: string): Promise<void> {
+ const metadata = await lstat(path).catch((error: NodeJS.ErrnoException) => {
+ if (error.code !== "ENOENT") throw error;
+ return undefined;
+ });
+ if (metadata?.isSymbolicLink()) {
+ throw new Error("Multiscan output directories must not be symbolic links.");
+ }
+ await mkdir(path, { recursive: true, mode: 0o700 });
+}
+
+async function appendReceipt(path: string, receipt: string): Promise<void> {
+ const file = await open(path, "a", 0o600);
+ try {
+ await file.writeFile(receipt, "utf8");
+ await file.sync();
+ } finally {
+ await file.close();
+ }
+}
+
+async function acquireLock(output: string): Promise<() => Promise<void>> {
+ const path = join(output, ".lock");
+ const ownerPath = join(path, "owner.json");
+ try {
+ await mkdir(path, { mode: 0o700 });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ const { pid } = JSON.parse(await readFile(ownerPath, "utf8")) as {
+ pid: number;
+ };
+ try {
+ process.kill(pid, 0);
+ throw new Error("A multiscan supervisor is already running.");
+ } catch (failure) {
+ if ((failure as NodeJS.ErrnoException).code !== "ESRCH") throw failure;
+ }
+ const stale = join(output, `.lock.stale-${randomUUID()}`);
+ await rename(path, stale);
+ await rm(stale, { recursive: true });
+ return await acquireLock(output);
+ }
+ await writeFile(ownerPath, `${JSON.stringify({ pid: process.pid })}\n`, {
+ flag: "wx",
+ mode: 0o600,
+ });
+ return async () => rm(path, { recursive: true });
+}
+
+async function ensureManifest(
+ path: string,
+ tasks: MultiscanTask[],
+): Promise<void> {
+ const expected = `${JSON.stringify({ version: 1, tasks }, null, 2)}\n`;
+ try {
+ await writeFile(path, expected, { flag: "wx", mode: 0o600 });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ if ((await readFile(path, "utf8")) !== expected) {
+ throw new Error(
+ "Multiscan manifest does not match existing output directory.",
+ );
+ }
+ }
+}
+
+async function readReceipts(
+ path: string,
+): Promise<Map<string, MultiscanReceipt>> {
+ let contents: string;
+ try {
+ contents = await readFile(path, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return new Map();
+ throw error;
+ }
+ const lines = contents.split("\n");
+ if (!contents.endsWith("\n")) {
+ const partial = lines.pop()!;
+ await truncate(
+ path,
+ Buffer.byteLength(contents) - Buffer.byteLength(partial),
+ );
+ }
+ return new Map(
+ lines.filter(Boolean).map((line): [string, MultiscanReceipt] => {
+ const receipt = JSON.parse(line) as MultiscanReceipt;
+ return [receipt.id.toLowerCase(), receipt];
+ }),
+ );
+}
+
+async function hasArtifacts(path: string): Promise<boolean> {
+ try {
+ if (!(await lstat(path)).isDirectory()) return false;
+ for (const artifact of REQUIRED_ARTIFACTS) {
+ if (!(await lstat(join(path, artifact))).isFile()) return false;
+ }
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function parseInventory(
+ source: string,
+ directory: string,
+ defaultMode: ScanMode,
+): MultiscanTask[] {
+ const { data: rows, errors } = Papa.parse<string[]>(source, {
+ delimiter: ",",
+ skipEmptyLines: "greedy",
+ });
+ if (errors.length > 0) {
+ throw new Error(`Multiscan CSV could not be parsed: ${errors[0]!.message}`);
+ }
+ const headers = rows.shift();
+ if (
+ headers === undefined ||
+ !["id", "repository", "revision"].every((name) => headers.includes(name)) ||
+ new Set(headers).size !== headers.length
+ ) {
+ throw new Error(
+ "Multiscan CSV requires id, repository, and revision columns.",
+ );
+ }
+ if (rows.length === 0)
+ throw new Error("Multiscan CSV must contain at least one repository.");
+ const seen = new Set<string>();
+ return rows.map((fields) => {
+ if (fields.length !== headers.length) {
+ throw new Error("Multiscan CSV rows must match their header columns.");
+ }
+ const get = (name: string): string =>
+ fields[headers.indexOf(name)]?.trim() ?? "";
+ const id = get("id");
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(id)) {
+ throw new Error("Multiscan task IDs must be safe, unique path names.");
+ }
+ if (seen.has(id.toLowerCase()))
+ throw new Error("Multiscan task IDs must be unique.");
+ seen.add(id.toLowerCase());
+ const revision = get("revision").toLowerCase();
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(revision)) {
+ throw new Error("Multiscan revisions must be full immutable Git SHAs.");
+ }
+ const mode = get("mode") || defaultMode;
+ if (mode !== "standard" && mode !== "deep") {
+ throw new Error("Multiscan mode must be standard or deep.");
+ }
+ const scope = get("scope");
+ if (
+ scope &&
+ (isAbsolute(scope) ||
+ scope.includes("\\") ||
+ scope.split("/").includes("..") ||
+ scope.includes("\0"))
+ ) {
+ throw new Error("Multiscan scope must stay inside its repository.");
+ }
+ return {
+ id,
+ repository: normalizeRepository(get("repository"), directory),
+ revision,
+ mode,
+ ...(scope ? { scope } : {}),
+ };
+ });
+}
+
+function normalizeRepository(repository: string, directory: string): string {
+ if (!repository || repository.length > 4096 || repository.includes("\0")) {
+ throw new Error(
+ "Multiscan repositories must be safe local paths or Git URLs.",
+ );
+ }
+ if (/^[^@\s/:]+@[^:\s/]+:.+$/u.test(repository)) return repository;
+ if (!repository.includes("://")) return resolve(directory, repository);
+ let url: URL;
+ try {
+ url = new URL(repository);
+ } catch {
+ throw new Error("Multiscan repository URL is invalid.");
+ }
+ if (url.protocol !== "https:" && url.protocol !== "ssh:") {
+ throw new Error("Multiscan repository URL protocol is unsupported.");
+ }
+ if (
+ url.password ||
+ (url.protocol === "https:" && url.username) ||
+ url.search ||
+ url.hash
+ ) {
+ throw new Error(
+ "Repository URLs must not contain embedded credentials, query strings, or fragments.",
+ );
+ }
+ return repository;
+}
+
+async function checkoutRevision(
+ task: MultiscanTask,
+ path: string,
+ signal?: AbortSignal,
+): Promise<void> {
+ const environment = { ...process.env };
+ for (const name of [
+ "GIT_DIR",
+ "GIT_WORK_TREE",
+ "GIT_INDEX_FILE",
+ "GIT_OBJECT_DIRECTORY",
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
+ ]) {
+ delete environment[name];
+ }
+ environment["GIT_TERMINAL_PROMPT"] = "0";
+ environment["GIT_LFS_SKIP_SMUDGE"] = "1";
+ const command = await resolveTrustedExecutable(
+ "git",
+ environment,
+ resolve(process.cwd()),
+ );
+ if (command === null) {
+ throw new Error("Git is not available on a trusted PATH.");
+ }
+ const git = async (...args: string[]): Promise<string> => {
+ const result = await execFile(
+ "git",
+ ["-c", "core.hooksPath=/dev/null", "-C", path, ...args],
+ { env: command.environment, signal },
+ );
+ return result.stdout.trim();
+ };
+ await git("init", "--quiet");
+ await git(
+ "fetch",
+ "--quiet",
+ "--no-tags",
+ "--depth=1",
+ "--",
+ task.repository,
+ task.revision,
+ );
+ await git("checkout", "--quiet", "--detach", "FETCH_HEAD");
+ if ((await git("rev-parse", "HEAD")).toLowerCase() !== task.revision) {
+ throw new Error("Git checkout revision did not match the pinned SHA.");
+ }
+}
+
+function redactError(error: unknown): string {
+ return (error instanceof Error ? error.message : String(error))
+ .replaceAll(
+ /((?:api[_-]?key|token|secret|credential|password)[A-Za-z0-9_-]*\s*[:=]\s*)[^\s,;]+/giu,
+ "$1[redacted]",
+ )
+ .replaceAll(
+ /\b(?:sk-(?:proj-)?|gh[pousr]_|github_pat_|npm_)[A-Za-z0-9_*=-]{8,}/gu,
+ "[redacted]",
+ )
+ .replaceAll(/\b(Bearer|Basic|Token)\s+[^\s,;]+/giu, "$1 [redacted]");
+}
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 4d537a5d1..ba835e9f2 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -1203,6 +1203,7 @@ describe("CodexSecurity orchestration", () => {
},
);
+ const scanStartedAt = Date.now();
const result = await client.run(repository, {
onScanStarted: () => {
scanStarted = true;
@@ -1214,9 +1215,18 @@ describe("CodexSecurity orchestration", () => {
expect(result.threadId).toBe("thread-1");
expect(scanStarted).toBe(true);
expect(reconnects).toEqual([[2, 5]]);
+ const startedAt = (codexOptions as CodexOptions | null)?.env?.[
+ "CODEX_SECURITY_STARTED_AT"
+ ];
+ if (typeof startedAt !== "string") throw new Error("missing scan start");
+ expect(new Date(startedAt).toISOString()).toBe(startedAt);
+ expect(startedAt.endsWith("Z")).toBe(true);
+ expect(Date.parse(startedAt)).toBeGreaterThanOrEqual(scanStartedAt);
+ expect(Date.parse(startedAt)).toBeLessThanOrEqual(Date.now());
expect((codexOptions as CodexOptions | null)?.env).toMatchObject({
CODEX_HOME: codexHome,
PYTHON: "/managed/python",
+ CODEX_SECURITY_STARTED_AT: startedAt,
CODEX_SECURITY_REPOSITORY: repository,
CODEX_SECURITY_SCAN_DIR: scanDir,
CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,
@@ -1242,12 +1252,14 @@ describe("CodexSecurity orchestration", () => {
"LANG",
"LC_*",
"PYTHON",
+ "CODEX_SECURITY_STARTED_AT",
"CODEX_SECURITY_REPOSITORY",
"CODEX_SECURITY_SCAN_DIR",
"CODEX_SECURITY_PLUGIN_ROOT",
],
set: {
PYTHON: "/managed/python",
+ CODEX_SECURITY_STARTED_AT: startedAt,
CODEX_SECURITY_REPOSITORY: repository,
CODEX_SECURITY_SCAN_DIR: scanDir,
CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,
@@ -1582,11 +1594,13 @@ describe("CodexSecurity orchestration", () => {
expect(environment).toMatchObject({
PYTHON: python,
CODEX_HOME: codexHome,
+ CODEX_SECURITY_STARTED_AT: expect.any(String),
CODEX_SECURITY_REPOSITORY: repository,
CODEX_SECURITY_SCAN_DIR: scanDir,
CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,
});
expect(environment).not.toHaveProperty("CODEX_SECURITY_TARGET_PATHS_JSON");
+ const startedAt = environment?.["CODEX_SECURITY_STARTED_AT"];
const targetPathsFile = environment?.["CODEX_SECURITY_TARGET_PATHS_FILE"];
expect(typeof targetPathsFile).toBe("string");
if (typeof targetPathsFile !== "string")
@@ -1648,6 +1662,7 @@ describe("CodexSecurity orchestration", () => {
set: {
CUSTOM_REQUIRED: "top-level",
PYTHON: python,
+ CODEX_SECURITY_STARTED_AT: startedAt,
CODEX_SECURITY_REPOSITORY: repository,
CODEX_SECURITY_SCAN_DIR: scanDir,
CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,
@@ -1657,6 +1672,7 @@ describe("CodexSecurity orchestration", () => {
"PATH",
"HOME",
"PYTHON",
+ "CODEX_SECURITY_STARTED_AT",
"CODEX_SECURITY_REPOSITORY",
"CODEX_SECURITY_SCAN_DIR",
"CODEX_SECURITY_PLUGIN_ROOT",
@@ -1696,6 +1712,7 @@ describe("CodexSecurity orchestration", () => {
set: {
PROFILE_REQUIRED: "profile-level",
PYTHON: python,
+ CODEX_SECURITY_STARTED_AT: startedAt,
CODEX_SECURITY_REPOSITORY: repository,
CODEX_SECURITY_SCAN_DIR: scanDir,
CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,
@@ -1703,6 +1720,7 @@ describe("CodexSecurity orchestration", () => {
},
include_only: [
"PYTHON",
+ "CODEX_SECURITY_STARTED_AT",
"CODEX_SECURITY_REPOSITORY",
"CODEX_SECURITY_SCAN_DIR",
"CODEX_SECURITY_PLUGIN_ROOT",
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index b3c36cdf4..3028091da 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -231,6 +231,36 @@ function fakeResult(
});
}
+async function multiscanInventory(root: string): Promise<void> {
+ const repository = join(root, "repository");
+ for (const args of [
+ ["init", "-q", repository],
+ [
+ "-C",
+ repository,
+ "-c",
+ "-c",
+ "user.name=Test",
+ "-c",
+ "commit.gpgsign=false",
+ "commit",
+ "--allow-empty",
+ "-qm",
+ "initial",
+ ],
+ ]) {
+ expect(spawnSync("git", args, { encoding: "utf8" }).status).toBe(0);
+ }
+ const revision = spawnSync("git", ["-C", repository, "rev-parse", "HEAD"], {
+ encoding: "utf8",
+ }).stdout.trim();
+ await writeFile(
+ join(root, "repositories.csv"),
+ `id,repository,revision\nsample,${repository},${revision}\n`,
+ );
+}
+
class FakeSignals {
readonly listeners = new Map<string, Set<() => void>>();
@@ -336,6 +366,8 @@ describe("CLI", () => {
const stderr = capture();
expect(await main([], root.stream, stderr.stream, dependencies())).toBe(0);
expect(root.text()).toContain("Usage: codex-security <command>");
+ expect(root.text()).toContain("scan-csv");
+ expect(root.text()).not.toContain("multiscan");
expect(root.text()).toContain("Integrations:");
expect(root.text()).toContain("completions");
expect(root.text()).toContain("--llms, --llms-full");
@@ -366,6 +398,7 @@ describe("CLI", () => {
await main(["--llms"], manifest.stream, capture().stream, dependencies()),
).toBe(0);
expect(manifest.text()).toContain("codex-security scan [repository]");
+ expect(manifest.text()).toContain("codex-security scan-csv <input>");
expect(manifest.text()).toContain("codex-security export <scanDir>");
expect(manifest.text()).toContain("codex-security validate <findings...>");
expect(manifest.text()).toContain("codex-security patch <issues...>");
@@ -383,6 +416,89 @@ describe("CLI", () => {
expect(completions.text()).toContain('export COMPLETE="bash"');
});
+ test("runs scan-csv and keeps structured output on stdout", async () => {
+ const root = await mkdtemp(join(tmpdir(), "codex-security-cli-multiscan-"));
+ try {
+ await multiscanInventory(root);
+ const stdout = capture();
+ const stderr = capture();
+ let config: CodexSecurityConfig | undefined;
+ let scanOptions: unknown;
+ expect(
+ await main(
+ [
+ "scan-csv",
+ "repositories.csv",
+ "--output-dir",
+ "results",
+ "--mode",
+ "deep",
+ "--codex",
+ "features.goals=true",
+ "--json",
+ ],
+ stdout.stream,
+ stderr.stream,
+ dependencies({
+ currentDirectory: root,
+ onConfig: (value) => (config = value),
+ onTurn: (_repository, options) => (scanOptions = options),
+ }),
+ ),
+ ).toBe(0);
+ expect(JSON.parse(stdout.text())).toMatchObject({
+ total: 1,
+ completed: 1,
+ failed: 0,
+ skipped: 0,
+ resultsPath: join(root, "results", "results.jsonl"),
+ });
+ expect(config).toMatchObject({
+ codexOverrides: { features: { goals: true } },
+ });
+ expect(scanOptions).toMatchObject({ mode: "deep" });
+ expect(stderr.text()).toContain("sample started (attempt 1)");
+ expect(stderr.text()).toContain("sample completed (attempt 1)");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ test("preserves the scan-csv failure summary and redacts progress errors", async () => {
+ const root = await mkdtemp(join(tmpdir(), "codex-security-cli-multiscan-"));
+ try {
+ await multiscanInventory(root);
+ const stdout = capture();
+ const stderr = capture();
+ expect(
+ await main(
+ ["scan-csv", "repositories.csv", "--output-dir", "results", "--json"],
+ stdout.stream,
+ stderr.stream,
+ dependencies({
+ currentDirectory: root,
+ onRun: () => {
+ throw new CodexSecurityError(
+ "scan failed sk-proj-SYNTHETIC_KEY_123",
+ );
+ },
+ }),
+ ),
+ ).toBe(2);
+ expect(JSON.parse(stdout.text())).toMatchObject({
+ total: 1,
+ completed: 0,
+ failed: 1,
+ skipped: 0,
+ });
+ expect(stderr.text()).toContain("sample failed (attempt 1)");
+ expect(stderr.text()).toContain("[redacted]");
+ expect(stderr.text()).not.toContain("SYNTHETIC_KEY_123");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
test("exposes only typed, read-only SDK metadata over MCP", () => {
const child = spawnSync(
process.execPath,
diff --git a/sdk/typescript/tests-ts/multiscan.test.ts b/sdk/typescript/tests-ts/multiscan.test.ts
new file mode 100644
index 000000000..b8cfbed65
--- /dev/null
+++ b/sdk/typescript/tests-ts/multiscan.test.ts
@@ -0,0 +1,602 @@
+import { execFileSync } from "node:child_process";
+import {
+ access,
+ appendFile,
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, test } from "bun:test";
+import type { ScanResult } from "../src/result.js";
+import { runMultiscan } from "../src/multiscan.js";
+
+type MultiscanOptions = Parameters<typeof runMultiscan>[0];
+type SecurityClient = ReturnType<MultiscanOptions["createSecurity"]>;
+
+const temporaryDirectories: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryDirectories
+ .splice(0)
+ .map((path) => rm(path, { recursive: true, force: true })),
+ );
+});
+
+async function fixture(): Promise<{
+ root: string;
+ input: string;
+ output: string;
+}> {
+ const root = await mkdtemp(join(tmpdir(), "codex-security-multiscan-"));
+ temporaryDirectories.push(root);
+ return {
+ root,
+ input: join(root, "repositories.csv"),
+ output: join(root, "results"),
+ };
+}
+
+function git(repository: string, ...args: string[]): string {
+ return execFileSync("git", ["-C", repository, ...args], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"],
+ }).trim();
+}
+
+async function repository(
+ root: string,
+ name: string,
+): Promise<{ path: string; revision: string }> {
+ const path = join(root, name);
+ await mkdir(join(path, "src"), { recursive: true });
+ await writeFile(
+ join(path, "src", "app.ts"),
+ `export const name = "${name}";\n`,
+ );
+ git(path, "init", "-q");
+ git(path, "add", ".");
+ git(
+ path,
+ "-c",
+ "user.name=Multiscan Test",
+ "-c",
+ "commit",
+ "-qm",
+ "initial",
+ );
+ return { path, revision: git(path, "rev-parse", "HEAD") };
+}
+
+async function completedScan(
+ outputDir: string,
+ completeness: "complete" | "partial" = "complete",
+): Promise<ScanResult> {
+ await mkdir(outputDir, { recursive: true });
+ await Promise.all(
+ ["scan-manifest.json", "findings.json", "coverage.json", "report.md"].map(
+ (name) => writeFile(join(outputDir, name), "{}\n"),
+ ),
+ );
+ return { coverage: { completeness } } as ScanResult;
+}
+
+function client(
+ run: SecurityClient["run"],
+ close: SecurityClient["close"] = async () => {},
+): SecurityClient {
+ return { run, close };
+}
+
+function options(
+ paths: { input: string; output: string },
+ security: SecurityClient,
+ overrides: Partial<MultiscanOptions> = {},
+): MultiscanOptions {
+ return {
+ inputPath: paths.input,
+ outputDir: paths.output,
+ workers: 1,
+ mode: "standard",
+ maxAttempts: 2,
+ config: {},
+ createSecurity: () => security,
+ ...overrides,
+ };
+}
+
+async function results(path: string): Promise<Record<string, unknown>[]> {
+ return (await readFile(path, "utf8"))
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line) as Record<string, unknown>);
+}
+
+describe("multiscan", () => {
+ test("parses quoted CSV fields, embedded delimiters, and Windows line endings", async () => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "comma, quoted");
+ await writeFile(
+ paths.input,
+ `\uFEFF"id","repository","revision","scope","mode","notes"\r\n"payments","${source.path}","${source.revision}","src","deep","contains ""quotes"""\r\n\r\n`,
+ );
+
+ const summary = await runMultiscan(
+ options(
+ paths,
+ client(async (_repository, scanOptions = {}) => {
+ expect(scanOptions.target).toEqual(["src"]);
+ expect(scanOptions.mode).toBe("deep");
+ return await completedScan(scanOptions.outputDir!);
+ }),
+ ),
+ );
+
+ expect(summary).toMatchObject({ total: 1, completed: 1, failed: 0 });
+ expect(await results(summary.resultsPath)).toMatchObject([
+ { id: "payments", repository: source.path },
+ ]);
+ });
+
+ test("rejects malformed CSV and duplicate headers before starting scans", async () => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "csv");
+ const invalid = [
+ `id,repository,revision\npayments,"${source.path},${source.revision}\n`,
+ `id,repository,revision,id\npayments,${source.path},${source.revision},again\n`,
+ `id,repository,revision\npayments,${source.path}\n`,
+ ];
+ let scans = 0;
+
+ for (const input of invalid) {
+ await writeFile(paths.input, input);
+ await expect(
+ runMultiscan(
+ options(
+ paths,
+ client(async (_repository, scanOptions = {}) => {
+ scans += 1;
+ return await completedScan(scanOptions.outputDir!);
+ }),
+ ),
+ ),
+ ).rejects.toThrow(/CSV/);
+ }
+
+ expect(scans).toBe(0);
+ });
+
+ test("materializes the pinned commit, applies row options, and removes its checkout", async () => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "payments");
+ await writeFile(
+ join(source.path, "src", "app.ts"),
+ "export const changed = true;\n",
+ );
+ git(source.path, "add", ".");
+ git(
+ source.path,
+ "-c",
+ "user.name=Multiscan Test",
+ "-c",
+ "commit",
+ "-qm",
+ "later",
+ );
+ await writeFile(
+ paths.input,
+ `id,repository,revision,scope,mode\npayments,${source.path},${source.revision},src,deep\n`,
+ );
+
+ let checkout = "";
+ let closed = 0;
+ const summary = await runMultiscan(
+ options(
+ paths,
+ client(
+ async (path, scanOptions = {}) => {
+ checkout = path;
+ expect(git(path, "rev-parse", "HEAD")).toBe(source.revision);
+ expect(
+ await readFile(join(path, "src", "app.ts"), "utf8"),
+ ).toContain('name = "payments"');
+ expect(scanOptions.target).toEqual(["src"]);
+ expect(scanOptions.mode).toBe("deep");
+ expect(scanOptions.outputDir).toBe(
+ join(paths.output, "artifacts", "payments", "attempt-1"),
+ );
+ return await completedScan(scanOptions.outputDir!);
+ },
+ async () => {
+ closed += 1;
+ },
+ ),
+ ),
+ );
+
+ expect(summary).toMatchObject({ completed: 1, failed: 0, skipped: 0 });
+ expect(closed).toBe(1);
+ await expect(access(checkout)).rejects.toThrow();
+ expect(await readdir(join(paths.output, "checkouts"))).toEqual([]);
+ expect(await results(summary.resultsPath)).toMatchObject([
+ {
+ id: "payments",
+ repository: source.path,
+ revision: source.revision,
+ scope: "src",
+ mode: "deep",
+ status: "completed",
+ attempt: 1,
+ },
+ ]);
+ });
+
+ test("limits simultaneous checkouts to the requested worker count", async () => {
+ const paths = await fixture();
+ const sources = await Promise.all(
+ ["one", "two", "three"].map((name) => repository(paths.root, name)),
+ );
+ await writeFile(
+ paths.input,
+ `id,repository,revision\n${sources
+ .map(
+ (source, index) => `${index + 1},${source.path},${source.revision}`,
+ )
+ .join("\n")}\n`,
+ );
+
+ let active = 0;
+ let maximum = 0;
+ let created = 0;
+ let closed = 0;
+ let release!: () => void;
+ const simultaneous = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const security = client(async (_repository, scanOptions = {}) => {
+ active += 1;
+ maximum = Math.max(maximum, active);
+ if (active === 2) release();
+ await simultaneous;
+ active -= 1;
+ return await completedScan(scanOptions.outputDir!);
+ });
+ const summary = await runMultiscan(
+ options(paths, security, {
+ workers: 2,
+ createSecurity: () => {
+ created += 1;
+ let running = false;
+ return client(
+ async (repository, scanOptions) => {
+ if (running) {
+ throw new Error("A scan is already running for this client.");
+ }
+ running = true;
+ try {
+ return await security.run(repository, scanOptions);
+ } finally {
+ running = false;
+ }
+ },
+ async () => {
+ closed += 1;
+ },
+ );
+ },
+ }),
+ );
+
+ expect(maximum).toBe(2);
+ expect(created).toBe(2);
+ expect(closed).toBe(2);
+ expect(summary).toMatchObject({ total: 3, completed: 3, failed: 0 });
+ expect(await results(summary.resultsPath)).toHaveLength(3);
+ });
+
+ test("rejects another supervisor and recovers a crashed owner's checkout", async () => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "exclusive");
+ await writeFile(
+ paths.input,
+ `id,repository,revision\nexclusive,${source.path},${source.revision}\n`,
+ );
+ let started!: () => void;
+ let release!: () => void;
+ const running = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const finish = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const security = client(async (_repository, scanOptions = {}) => {
+ started();
+ await finish;
+ return await completedScan(scanOptions.outputDir!);
+ });
+ const first = runMultiscan(options(paths, security));
+ await running;
+ try {
+ await expect(runMultiscan(options(paths, security))).rejects.toThrow(
+ /running|locked|supervisor/iu,
+ );
+ } finally {
+ release();
+ await first;
+ }
+
+ const [receipt] = await results(join(paths.output, "results.jsonl"));
+ await rm(join(receipt!["outputDir"] as string, "report.md"));
+ const lock = join(paths.output, ".lock");
+ await mkdir(lock);
+ await writeFile(
+ join(lock, "owner.json"),
+ JSON.stringify({ pid: 999_999_999 }),
+ );
+ const checkout = join(paths.output, "checkouts", "exclusive");
+ await mkdir(checkout);
+
+ const recovered = await runMultiscan(options(paths, security));
+ expect(recovered).toMatchObject({ completed: 1, failed: 0, skipped: 0 });
+ expect(await readdir(join(paths.output, "checkouts"))).toEqual([]);
+ await expect(access(lock)).rejects.toThrow();
+ });
+
+ test("retries a failed attempt and records both durable receipts", async () => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "retry");
+ const secret = "sk-proj-SYNTHETIC_MULTISCAN_SECRET_123";
+ await writeFile(
+ paths.input,
+ `id,repository,revision\nretry,${source.path},${source.revision}\n`,
+ );
+
+ let attempts = 0;
+ const summary = await runMultiscan(
+ options(
+ paths,
+ client(async (_repository, scanOptions = {}) => {
+ attempts += 1;
+ if (attempts === 1) throw new Error(`temporary failure ${secret}`);
+ return await completedScan(scanOptions.outputDir!);
+ }),
+ ),
+ );
+
+ expect(attempts).toBe(2);
+ expect(summary).toMatchObject({ completed: 1, failed: 0 });
+ expect(await results(summary.resultsPath)).toMatchObject([
+ { id: "retry", status: "failed", attempt: 1 },
+ { id: "retry", status: "completed", attempt: 2 },
+ ]);
+ expect(await readFile(summary.resultsPath, "utf8")).not.toContain(secret);
+ });
+
+ test("resumes complete bundles, repairs missing output, and rejects manifest drift", async () => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "resume");
+ const csv = `id,repository,revision\nresume,${source.path},${source.revision}\n`;
+ await writeFile(paths.input, csv);
+ let calls = 0;
+ const security = client(async (_repository, scanOptions = {}) => {
+ calls += 1;
+ return await completedScan(scanOptions.outputDir!);
+ });
+
+ const initial = await runMultiscan(options(paths, security));
+ await appendFile(initial.resultsPath, '{"id":"interrupted"');
+ const resumed = await runMultiscan(options(paths, security));
+ expect(resumed).toMatchObject({ completed: 1, failed: 0, skipped: 1 });
+ expect(calls).toBe(1);
+
+ const [receipt] = await results(initial.resultsPath);
+ await rm(join(receipt!["outputDir"] as string, "report.md"));
+ const repaired = await runMultiscan(options(paths, security));
+ expect(repaired).toMatchObject({ completed: 1, failed: 0, skipped: 0 });
+ expect(calls).toBe(2);
+ expect((await results(repaired.resultsPath)).at(-1)?.["outputDir"]).toBe(
+ join(paths.output, "artifacts", "resume", "attempt-2"),
+ );
+
+ await writeFile(paths.input, csv.replace("resume,", "changed,"));
+ await expect(runMultiscan(options(paths, security))).rejects.toThrow(
+ "manifest does not match",
+ );
+ expect(calls).toBe(2);
+ });
+
+ test("ignores repository-local Git shims while preserving credential configuration", async () => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "private");
+ await writeFile(
+ paths.input,
+ `id,repository,revision\nprivate,${source.path},${source.revision}\n`,
+ );
+ const shimDirectory = join(paths.root, "node_modules", ".bin");
+ const leakedCredential = join(paths.root, "leaked-credential");
+ await mkdir(shimDirectory, { recursive: true });
+ await writeFile(
+ join(shimDirectory, "git"),
+ `#!/bin/sh\nprintf '%s' "$GIT_CONFIG_VALUE_0" > "${leakedCredential}"\nexit 1\n`,
+ { mode: 0o700 },
+ );
+ const previousDirectory = process.cwd();
+ const environment = new Map(
+ [
+ "PATH",
+ "GIT_CONFIG_COUNT",
+ "GIT_CONFIG_KEY_0",
+ "GIT_CONFIG_VALUE_0",
+ ].map((name) => [name, process.env[name]] as const),
+ );
+
+ try {
+ process.chdir(paths.root);
+ process.env["PATH"] =
+ `${shimDirectory}${process.platform === "win32" ? ";" : ":"}${environment.get("PATH") ?? ""}`;
+ process.env["GIT_CONFIG_COUNT"] = "1";
+ process.env["GIT_CONFIG_KEY_0"] = "multiscan.credential";
+ process.env["GIT_CONFIG_VALUE_0"] = "SYNTHETIC_GIT_CREDENTIAL";
+
+ const summary = await runMultiscan(
+ options(
+ paths,
+ client(async (checkout, scanOptions = {}) => {
+ const credential = execFileSync(
+ "git",
+ ["-C", checkout, "config", "--get", "multiscan.credential"],
+ {
+ encoding: "utf8",
+ env: { ...process.env, PATH: environment.get("PATH") ?? "" },
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ ).trim();
+ expect(credential).toBe("SYNTHETIC_GIT_CREDENTIAL");
+ return await completedScan(scanOptions.outputDir!);
+ }),
+ ),
+ );
+
+ expect(summary).toMatchObject({ completed: 1, failed: 0 });
+ await expect(access(leakedCredential)).rejects.toThrow();
+ } finally {
+ process.chdir(previousDirectory);
+ for (const [name, value] of environment) {
+ if (value === undefined) delete process.env[name];
+ else process.env[name] = value;
+ }
+ }
+ });
+
+ test("rejects output-directory symlinks before deleting external checkouts", async () => {
+ for (const directory of ["", "checkouts", "artifacts"]) {
+ const paths = await fixture();
+ const source = await repository(paths.root, "victim");
+ await writeFile(
+ paths.input,
+ `id,repository,revision\nvictim,${source.path},${source.revision}\n`,
+ );
+ const external = join(paths.root, "external");
+ const preserved = join(external, "victim", "keep.txt");
+ await mkdir(join(external, "victim"), { recursive: true });
+ await writeFile(preserved, "preserved\n");
+ if (directory) await mkdir(paths.output);
+ await symlink(
+ external,
+ directory ? join(paths.output, directory) : paths.output,
+ );
+
+ let scans = 0;
+ await expect(
+ runMultiscan(
+ options(
+ paths,
+ client(async (_repository, scanOptions = {}) => {
+ scans += 1;
+ return await completedScan(scanOptions.outputDir!);
+ }),
+ ),
+ ),
+ ).rejects.toThrow("symbolic links");
+ expect(scans).toBe(0);
+ expect(await readFile(preserved, "utf8")).toBe("preserved\n");
+ }
+ });
+
+ test("rejects unsafe input without starting scans or exposing URL credentials", async () => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "safe");
+ const secret = "MULTISCAN_CREDENTIAL_SHOULD_NOT_APPEAR";
+ const invalid = [
+ {
+ name: "task-id",
+ row: `../escape,${source.path},${source.revision},.`,
+ },
+ {
+ name: "scope",
+ row: `safe,${source.path},${source.revision},../outside`,
+ },
+ {
+ name: "revision",
+ row: `safe,${source.path},HEAD,.`,
+ },
+ {
+ name: "duplicate-id",
+ row: `safe,${source.path},${source.revision},.\nsafe,${source.path},${source.revision},.`,
+ },
+ {
+ name: "credentials",
+ row: `safe,https://user:${secret}@example.test/private.git,${source.revision},.`,
+ },
+ ];
+ let scans = 0;
+ const security = client(async (_repository, scanOptions = {}) => {
+ scans += 1;
+ return await completedScan(scanOptions.outputDir!);
+ });
+
+ for (const entry of invalid) {
+ await writeFile(
+ paths.input,
+ `id,repository,revision,scope\n${entry.row}\n`,
+ );
+ const output = join(paths.root, entry.name);
+ const error = await runMultiscan(
+ options(paths, security, { outputDir: output }),
+ ).then(
+ () => null,
+ (reason: unknown) => reason,
+ );
+ expect(error).toBeInstanceOf(Error);
+ expect(String(error)).not.toContain(secret);
+ }
+
+ expect(scans).toBe(0);
+ });
+
+ test("treats incomplete coverage as a failure and still finishes other repositories", async () => {
+ const paths = await fixture();
+ const incomplete = await repository(paths.root, "incomplete");
+ const complete = await repository(paths.root, "complete");
+ await writeFile(
+ paths.input,
+ [
+ "id,repository,revision",
+ `incomplete,${incomplete.path},${incomplete.revision}`,
+ `complete,${complete.path},${complete.revision}`,
+ "",
+ ].join("\n"),
+ );
+
+ const summary = await runMultiscan(
+ options(
+ paths,
+ client(async (checkout, scanOptions = {}) =>
+ completedScan(
+ scanOptions.outputDir!,
+ (await readFile(join(checkout, "src", "app.ts"), "utf8")).includes(
+ 'name = "incomplete"',
+ )
+ ? "partial"
+ : "complete",
+ ),
+ ),
+ { maxAttempts: 1 },
+ ),
+ );
+
+ expect(summary).toMatchObject({ total: 2, completed: 1, failed: 1 });
+ expect(await results(summary.resultsPath)).toMatchObject([
+ { id: "incomplete", status: "failed", attempt: 1 },
+ { id: "complete", status: "completed", attempt: 1 },
+ ]);
+ });
+});