OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(cli): resolve saved scans in the current worktree (#2590)
Michael D'Angelo301141f4b6e6
diff --git a/plugins/codex-security/scripts/workbench_cli.py b/plugins/codex-security/scripts/workbench_cli.pyindex 636e904df..7dad25c9a 100644--- a/plugins/codex-security/scripts/workbench_cli.py+++ b/plugins/codex-security/scripts/workbench_cli.py@@ -222,6 +222,9 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.Nlist_scans.add_argument("--status", choices=("running", "complete", "failed", "canceled"))list_scans.add_argument("--mode", choices=MODES)list_scans.add_argument("--repository")+ list_scans.add_argument(+ "--prefer-worktree", action="store_true", help="List scans from this checkout first."+ )list_scans.add_argument("--scan-root")list_scans.add_argument("--offset", type=non_negative_int, default=0)list_scans.add_argument("--limit", type=positive_int)diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.pyindex 024ec6228..ee4ff6259 100644--- a/plugins/codex-security/scripts/workbench_db.py+++ b/plugins/codex-security/scripts/workbench_db.py@@ -254,7 +254,10 @@ def release_completion_file_lock(descriptor: int) -> None:def connect(- *, deferred: bool = False, discovery_roots: tuple[Path, ...] = ()+ *,+ deferred: bool = False,+ discovery_roots: tuple[Path, ...] = (),+ in_memory: bool = False,) -> sqlite3.Connection:"""Open the workbench SQLite database and bring its schema up to date.@@ -263,6 +266,7 @@ def connect(Retries after lock contention use an immediate transaction.discovery_roots: Additional local paths for bounded target discovery.+ in_memory: Keep a fresh profile read entirely in memory.Returns:sqlite3.Connection: A caller-owned connection with named rows, foreign@@ -279,13 +283,14 @@ def connect("the scanned repository.")try:- create_private_directory(path.parent)+ if not in_memory:+ create_private_directory(path.parent)except OSError:print(guidance, file=sys.stderr)raisefor attempt in range(SQLITE_RETRY_ATTEMPTS):try:- connection = sqlite3.connect(path, timeout=5)+ connection = sqlite3.connect(":memory:" if in_memory else path, timeout=5)except sqlite3.OperationalError:print(guidance, file=sys.stderr)raise@@ -298,7 +303,8 @@ def connect(connection, immediate=not deferred or attempt > 0, discovery_roots=discovery_roots)connection.execute("PRAGMA journal_mode = WAL")- path.chmod(0o600)+ if not in_memory:+ path.chmod(0o600)return connectionexcept sqlite3.OperationalError as exc:connection.close()@@ -3385,6 +3391,7 @@ def main(*, before_archive: Callable[[], None] | None = None) -> None:"update-progress",},discovery_roots=command_targets,+ in_memory=scan_history.reads_missing_history(args, database_path()),)) as connection,scoped_git_discovery(diff --git a/plugins/codex-security/scripts/workbench_native_indexes.py b/plugins/codex-security/scripts/workbench_native_indexes.pyindex 32a628d95..f485e3480 100644--- a/plugins/codex-security/scripts/workbench_native_indexes.py+++ b/plugins/codex-security/scripts/workbench_native_indexes.py@@ -38,7 +38,7 @@ def list_global_findings(repository = getattr(args, "repository", None)requested = Noneif repository is not None:- repository = str(Path(repository).expanduser().absolute())+ repository = identities.history_path(str(Path(repository).expanduser().absolute()))requested = identities.for_path(repository)scan_scope = identities.scope_for_path(repository)else:diff --git a/plugins/codex-security/scripts/workbench_scan_history.py b/plugins/codex-security/scripts/workbench_scan_history.pyindex 1fdeef87b..54dd0409d 100644--- a/plugins/codex-security/scripts/workbench_scan_history.py+++ b/plugins/codex-security/scripts/workbench_scan_history.py@@ -9,6 +9,7 @@ import sqlite3import sysfrom collections.abc import Iterable, Iteratorfrom fractions import Fraction+from functools import cachefrom itertools import chainfrom pathlib import Path, PurePosixPathfrom typing import Any, Callable@@ -42,6 +43,22 @@ from workbench_target_state import (from workbench_validation import timestamp_key+def reads_missing_history(args: argparse.Namespace, path: Path) -> bool:+ """Select an in-memory database only for history reads on a fresh profile."""+ if args.command not in {"list-scans", "list-repositories", "list-global-findings"} and not (+ args.command == "get-scan" and not (args.request_id or args.action_token)+ ):+ return False+ try:+ path.lstat()+ except FileNotFoundError:+ return True+ except OSError:+ # The ordinary connection reports inaccessible storage.+ pass+ return False++def rename_scan(connection: sqlite3.Connection, scan: sqlite3.Row, name: str) -> dict[str, Any]:name = name.strip()if not name:@@ -443,14 +460,27 @@ def list_scans(connection.create_function("codex_security_path_key", 1, _windows_path_key)clauses: list[str] = []values: list[Any] = []+ worktree_order = ""if args is not None and args.repository:repository = Path(args.repository).expanduser().absolute()identities = RepositoryIdentityCache(connection)+ repository = Path(identities.history_path(str(repository)))clause, scope_values = identities.scope_for_path(str(repository)).sql(supports_generation=identities.supports_generation)clauses.append(clause)values.extend(scope_values)+ if getattr(args, "prefer_worktree", False):++ @cache+ def in_worktree(target_path: str) -> bool:+ try:+ return repository.samefile(target_path)+ except OSError:+ return False++ connection.create_function("in_worktree", 1, in_worktree)+ worktree_order = "in_worktree(scans.target_path) DESC,"if args is not None and args.scan_root:scan_root = str(Path(args.scan_root).expanduser().resolve())prefix = scan_root.rstrip(os.sep) + os.sep@@ -497,7 +527,7 @@ def list_scans(f"""{SCAN_SUMMARY_QUERY}{where}- ORDER BY+ ORDER BY {worktree_order}CASE WHEN scans.status = 'running' AND scans.canceled_at IS NULL THEN 0 ELSE 1 END,MAX(julianday(upper(scans.updated_at)), julianday(upper(progress.updated_at))) DESC,julianday(upper(scans.started_at)) DESC,@@ -506,7 +536,11 @@ def list_scans(""",values,).fetchall()- result = {"scans": [scan_summary(row) for row in rows[:limit]]}+ scans = [scan_summary(row) for row in rows[:limit]]+ if worktree_order:+ for scan in scans:+ scan["inCurrentWorktree"] = in_worktree(scan["targetPath"])+ result = {"scans": scans}if limit is not None:result.update({@@ -775,7 +809,7 @@ def compare_scans(f"'codex-security scans compare {after['id']} {before['id']}'.")raise SystemExit(- "No saved matches for these scans. Run 'codex-security scans match BEFORE AFTER' first."+ "No saved matches for these scans. Run 'codex-security scans compare BEFORE AFTER' first.")if include_matching_inputs and backfill_finding_details is not None:backfill_finding_details(connection, before)diff --git a/plugins/codex-security/scripts/workbench_target_state.py b/plugins/codex-security/scripts/workbench_target_state.pyindex ebe087466..db6a09cec 100644--- a/plugins/codex-security/scripts/workbench_target_state.py+++ b/plugins/codex-security/scripts/workbench_target_state.py@@ -713,6 +713,27 @@ class RepositoryIdentityCache:else RepositoryScanScope(target_id=target_id))+ def history_path(self, target_path: str) -> str:+ """Use the worktree root when a subdirectory has no saved history of its own."""+ requested = self.for_path(target_path)+ if (+ not requested.ownership_matches+ or requested.target_id+ or requested.repository is None+ or requested.repository.relative_path == "."+ ):+ return target_path+ if (+ self.supports_generation+ and self.connection.execute(+ "SELECT 1 FROM scans WHERE repository_generation = ? LIMIT 1",+ (requested.live_identity,),+ ).fetchone()+ ):+ return target_path+ worktree = _repository_worktree(Path(target_path))+ return str(worktree[0]) if worktree is not None else target_path+def scope_for_path(self, target_path: str) -> RepositoryScanScope:return self._scope_for_state(self.for_path(target_path))diff --git a/plugins/codex-security/tests/test_windows_workbench_output_permissions.py b/plugins/codex-security/tests/test_windows_workbench_output_permissions.pyindex e34a5de21..a35841306 100644--- a/plugins/codex-security/tests/test_windows_workbench_output_permissions.py+++ b/plugins/codex-security/tests/test_windows_workbench_output_permissions.py@@ -501,7 +501,7 @@ def test_legacy_windows_resume_keeps_populated_output_and_rejects_unbound_empty_def test_deep_registration_rolls_back_the_retained_child(deep_registration) -> None:state, output, register = deep_registration- run_workbench(state, "list-scans")+ run_workbench(state, "database-info")with closing(sqlite3.connect(state / "workbench.sqlite3")) as connection, connection:connection.execute("CREATE TRIGGER fail_binding BEFORE UPDATE OF windows_resume_output_identity ON scans "@@ -599,7 +599,7 @@ def test_resume_cleanup_cannot_remove_an_existing_or_substituted_child(tmp_path:def test_post_commit_interrupt_keeps_the_registered_resume_directory(deep_registration) -> None:state, output, register = deep_registration- run_workbench(state, "list-scans")+ run_workbench(state, "database-info")class InterruptedCommit(sqlite3.Connection):def commit(self):diff --git a/plugins/codex-security/tests/test_workbench_scan_history.py b/plugins/codex-security/tests/test_workbench_scan_history.pyindex 31f5476f7..9f3f4921a 100644--- a/plugins/codex-security/tests/test_workbench_scan_history.py+++ b/plugins/codex-security/tests/test_workbench_scan_history.py@@ -893,6 +893,34 @@ def test_scan_history_resolves_unique_prefixes_and_rejects_ambiguity(tmp_path: Passert get_scan(state_dir, scan["scanId"])["scan"]["scanId"] == scan["scanId"]+def test_reading_empty_history_leaves_state_uninitialized(tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ initialized = tmp_path / "initialized"+ run_workbench(initialized, "database-info")+ for command, key in (+ ("list-scans", "scans"),+ ("list-repositories", "repositories"),+ ("list-global-findings", "findings"),+ ):+ args = (command, "--limit", "2", "--offset", "1")+ empty = run_workbench(state_dir, *args)+ assert empty == run_workbench(initialized, *args)+ assert empty == {+ key: [],+ "nextOffset": None,+ "limit": 2,+ "offset": 1,+ **({"projectionAvailable": True} if command == "list-global-findings" else {}),+ }+ for target in (str(tmp_path), str(tmp_path / "missing" / "..")):+ args = ("list-global-findings", "--repository", target)+ assert run_workbench(state_dir, *args) == run_workbench(initialized, *args)+ for scan_id, message in (("short", "eight characters"), (str(uuid.uuid4()), "scan not found")):+ missing = run_workbench(state_dir, "get-scan", "--scan-id", scan_id, check=False)+ assert missing["returncode"] != 0 and message in missing["stderr"]+ assert not state_dir.exists()++def test_scan_list_shares_worktree_history_without_including_clones(tmp_path: Path) -> None:state_dir = tmp_path / "state"repository = tmp_path / "repository"@@ -926,6 +954,21 @@ def test_scan_list_shares_worktree_history_without_including_clones(tmp_path: Paoriginal_scan["scanId"],]+ for target, expected in (+ (repository, original_scan),+ (worktree, worktree_scan),+ (clone, clone_scan),+ ):+ nested = target / "nested"+ nested.mkdir()+ local = run_workbench(+ state_dir, "list-scans", "--repository", str(nested), "--prefer-worktree"+ )+ assert local["scans"][0]["scanId"] == expected["scanId"]+ assert [scan["inCurrentWorktree"] for scan in local["scans"]] == (+ [True] if target == clone else [True, False]+ )+for offset, expected in enumerate((worktree_scan, original_scan)):page = run_workbench(state_dir,@@ -960,6 +1003,24 @@ def test_scan_list_shares_worktree_history_without_including_clones(tmp_path: Paassert [scan["scanId"] for scan in other] == [unrelated_scan["scanId"]]+def test_nested_finding_history_uses_saved_scope_before_worktree_root(tmp_path: Path) -> None:+ repository = tmp_path / "repository"+ revision = initialize_git_repository(repository)+ nested = repository / "src"+ nested.mkdir()+ state = tmp_path / "state"+ root_scan = create_cli_scan(state, tmp_path / "results", repository, target_revision=revision)+ findings = run_workbench(state, "list-global-findings", "--repository", str(nested))["findings"]+ assert [finding["scanId"] for finding in findings] == [root_scan["scanId"]]++ nested_scan = create_cli_scan(state, tmp_path / "results", nested, complete=False)+ assert (+ run_workbench(state, "list-global-findings", "--repository", str(nested))["findings"] == []+ )+ saved = run_workbench(state, "list-scans", "--repository", str(nested), "--prefer-worktree")+ assert [scan["scanId"] for scan in saved["scans"]] == [nested_scan["scanId"]]++def test_cli_scan_comparison_tracks_stable_findings_without_copying_triage(tmp_path: Path) -> None:state_dir, repository = empty_history_paths(tmp_path)root = tmp_path / "results"@@ -1075,7 +1136,7 @@ def test_scan_comparison_requires_saved_matches_and_remains_read_only(tmp_path:rejected = compare_scan_pair(state_dir, before, after, "--require-matches", check=False)assert rejected["returncode"] != 0- assert "Run 'codex-security scans match BEFORE AFTER' first" in rejected["stderr"]+ assert "Run 'codex-security scans compare BEFORE AFTER' first" in rejected["stderr"]with sqlite3.connect(database) as connection:assert connection.execute("SELECT COUNT(*) FROM scan_comparisons").fetchone() == (0,)assert connection.execute("SELECT COUNT(*) FROM scan_comparison_matches").fetchone() == (0,)@@ -2593,7 +2654,7 @@ def test_portable_identity_decodes_git_line_protocol_without_changing_path_bytes@pytest.mark.parametrize("reopen", (False, True))def test_portable_identity_history_lookup_uses_indexes(tmp_path: Path, reopen: bool) -> None:state = tmp_path / "state"- run_workbench(state, "list-repositories")+ run_workbench(state, "database-info")if reopen:with sqlite3.connect(state / "workbench.sqlite3") as connection:connection.execute("DROP INDEX IF EXISTS scans_by_target_path")diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex 0fcf06c44..dd3599c3b 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -2107,7 +2107,7 @@ attach only their owner's session. Unrecorded earlier retry sessions may be abse## Scan history and rerunsCommands default to the current repository. IDs accept unique prefixes of at-least eight characters.+least eight characters. Reading empty history leaves the workbench database uninitialized.Linked Git worktrees share scans, findings, and reviewer decisions when theirscans record the same repository generation in the selected state database.@@ -2125,8 +2125,7 @@ in the workbench, without changing sealed report timestamps.| `scans show [SCAN_ID]` | Show a scan; defaults to latest completed. || `scans logs [SCAN_ID]` | Show session events; defaults to latest, including active. || `scans resume SCAN_ID` | Continue an interrupted Deep Scan. |-| `scans rerun [SCAN_ID]` | Repeat on the current checkout. |-| `scans match BEFORE AFTER` | Link findings with the same root cause. |+| `scans rerun [SCAN_ID]` | Rerun a saved recipe in its checkout. || `scans match --all` | Match completed scans in this repository generation, including linked worktrees. || `scans compare [BEFORE] [AFTER]` | Compare scans; defaults to latest two completed. || `findings list [REPOSITORY]` | List open findings. |@@ -2138,9 +2137,11 @@ Copy that ID into `findings false-positive` with your reason. Subsequent scans cuse the explanation while it applies. In `scans show SCAN_ID --json`, eachdisplayed occurrence has its saved rationale in `triage.note` after dismissal. The list identifiesa repository with no saved scan history separately from one with zero open findings.+From an unregistered Git subdirectory with no scan history of its own, it uses the worktree root.-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+With an omitted ID or the literal `latest`, `scans show` selects the latest completed scan, while `scans logs`+selects the latest scan of any status. Both prefer a scan in the current+worktree when one qualifies. After a successful scan followed by afailed or active scan, these defaults refer to different runs. Human outputidentifies the selected run, labels its saved update time, and gives matchingcommands with its full scan ID:@@ -2158,7 +2159,10 @@ history. Inspect its saved status before choosing resume or rerun, and supplythe original custom prompt files for reruns. Structured history and log outputand command selection defaults are unchanged.-Reruns use the current checkout/context files and do not reload project files.+Without an ID, rerun selects the latest completed scan in the current worktree.+If only a related checkout has a completed scan, rerun shows its ID, path, and+revision. Pass that ID to run the saved recipe using the files currently at its+saved checkout and context paths. Reruns do not reload project files.The readable scan recipe records your authentication choice. A separate privatereplay profile stores explicit `openai_base_url`, `chatgpt_base_url`, and custom`model_providers` settings, including any credentials written directly in@@ -2262,7 +2266,10 @@ to update campaign receipts. Individual resume does not update `results.jsonl`.### Matching saved scans-Matching uses sealed artifacts and cached decisions unless `--force` is supplied.+Use `scans compare BEFORE AFTER` to compare a pair. A cache miss can use the model+and save its matching decisions. Pass `--force` to recompute saved matches.+The older `scans match BEFORE AFTER` spelling is also supported.+Use `scans match --all` to match completed scans in this repository generation, including linked worktrees.Comparisons classify findings as new, persisting, reopened, not observed, resolved,or unknown. An absent finding in the later scope is not observed; absence alonedoes not verify remediation. A finding is resolved only after it was explicitlydiff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex db663b8b3..f8d12b39a 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -485,10 +485,15 @@ const DEFAULT_SCAN_MODEL_CONFIGURATION =scanModelConfiguration(DEFAULT_CODEX_CONFIG);const MODEL_OPTIONS = modelOptions();type ModelCliOptions = z.infer<typeof MODEL_OPTIONS>;-const MATCHING_MODEL_OPTIONS = modelOptions(+const MATCHING_OPTIONS = modelOptions("Model for finding matching (default: Codex's configured model).","Matching reasoning effort (default: medium).",-);+).extend({+ force: z+ .boolean()+ .default(false)+ .describe("Recompute saved finding matches."),+});const SKILL_CODEX_OVERRIDE_DESCRIPTION ='Repeat TOML model="gpt-5.6-terra", model_reasoning_effort="high", model_provider="gateway", model_providers.<name>.<key>=VALUE, daybreak=true, or analytics.enabled=false.';const SKILL_CONFIG_OPTIONS = MODEL_OPTIONS.extend({@@ -2660,12 +2665,16 @@ export async function main(const latestScans = async (count = 1,status: "complete" | "any" = "complete",- pythonPath?: string,- protectedRoot?: PluginPythonOptions["protectedRoot"],+ options: {+ pythonPath?: string;+ protectedRoot?: PluginPythonOptions["protectedRoot"];+ preferWorktree?: boolean;+ } = {},): Promise<SavedScan[] | undefined> => {const result = await history(workbenchArgs("list-scans", {repository: dependencies.currentDirectory(),+ preferWorktree: options.preferWorktree,status: status === "complete" ? "complete" : undefined,limit: String(count),}),@@ -2680,11 +2689,31 @@ export async function main(}return value;},- pythonPath,- protectedRoot,+ options.pythonPath,+ options.protectedRoot,);return result?.["scans"] as SavedScan[] | undefined;};+ type WorktreeScan = SavedScan & {+ targetPath: string;+ inCurrentWorktree: boolean;+ };+ const preferredScan = async (repository: string, status?: "complete") => {+ const result = await dependencies.runWorkbench(+ workbenchArgs("list-scans", {+ repository,+ preferWorktree: true,+ status,+ limit: 1,+ }),+ );+ return (result["scans"] as WorktreeScan[])[0];+ };+ const historyId = z.string().min(1).optional();+ const resolveHistoryId = async (id: string, status: "complete" | "any") =>+ id === "latest"+ ? (await latestScans(1, status, { preferWorktree: true }))?.[0]?.scanId+ : id;type MatchingCliOptions = ModelCliOptions & { force?: boolean };const runMatching = async (operation: (options: ScanComparisonOptions) => Promise<JsonObject>,@@ -3033,11 +3062,9 @@ export async function main(description: "Show the results and saved configuration for a scan.",hint: "Without an ID, show selects the latest completed scan; logs selects the latest scan of any status. Pass the same ID to inspect one run.",args: z.object({- scanId: z- .string()- .min(1)- .optional()- .describe("Scan ID or unique prefix (default: latest completed)."),+ scanId: historyId.describe(+ "Scan ID, unique prefix, or latest (default: latest completed).",+ ),}),options: z.object({showLinkedFindings: z@@ -3053,19 +3080,17 @@ export async function main(},],output: z.record(z.string(), z.unknown()).optional(),- async run({ args, format, options }) {- let scanId = args.scanId;- if (scanId === undefined) {- try {- scanId = (await latestScans())?.[0]?.scanId;- } catch (error) {- if (useDefaultOutput(format)) {- errorOutput.write(- "Use codex-security scans list to find failed or active scans, then pass a scan ID to scans show and scans logs.\n",- );- }- throw error;+ async run({ args: { scanId: requestedId = "latest" }, format, options }) {+ let scanId;+ try {+ scanId = await resolveHistoryId(requestedId, "complete");+ } catch (error) {+ if (useDefaultOutput(format)) {+ errorOutput.write(+ "Use codex-security scans list to find failed or active scans, then pass a scan ID to scans show and scans logs.\n",+ );}+ throw error;}if (scanId === undefined) return;return presentHistory(@@ -3074,7 +3099,7 @@ export async function main(await showHistoryNavigation(scan as ScanLogSource,format,- args.scanId === undefined ? "latest completed scan" : undefined,+ requestedId === "latest" ? "latest completed scan" : undefined,);return {...(scan as JsonObject),@@ -3092,13 +3117,9 @@ export async function main(description: "Show saved activity for a scan and its workers.",hint: "Without an ID, logs selects the latest scan, including failed and active runs; show selects the latest completed scan. Pass the same ID to inspect one run.",args: z.object({- scanId: z- .string()- .min(1)- .optional()- .describe(- "Scan identifier or unique prefix (default: latest, any status).",- ),+ scanId: historyId.describe(+ "Scan ID, unique prefix, or latest (default: latest, any status).",+ ),}),examples: [{ args: {}, description: "Show activity from the latest scan." },@@ -3108,9 +3129,8 @@ export async function main(},],output: z.record(z.string(), z.unknown()).optional(),- async run({ args, format }) {- const scanId =- args.scanId ?? (await latestScans(1, "any"))?.[0]?.scanId;+ async run({ args: { scanId: requestedId = "latest" }, format }) {+ const scanId = await resolveHistoryId(requestedId, "any");if (scanId === undefined) return;const result = await history(["get-scan", "--scan-id", scanId],@@ -3119,7 +3139,7 @@ export async function main(await showHistoryNavigation(scan,format,- args.scanId === undefined+ requestedId === "latest"? "latest scan, including failed and active runs": undefined,);@@ -3229,7 +3249,7 @@ export async function main(}).command("rerun", {description:- "Start a new scan using saved settings and current checkout/context files.",+ "Start a new scan using saved settings and the current files at its saved checkout.",examples: [{ args: { scanId: "SCAN_ID" } }],hint: "Execution failures keep available scan results under data in failed full-output JSON, JSONL, YAML, or TOON envelopes.",destructive: true,@@ -3238,7 +3258,9 @@ export async function main(.string().min(1).optional()- .describe("Saved scan identifier (default: latest completed scan)."),+ .describe(+ "Saved scan identifier (default: latest completed in this worktree).",+ ),}),options: z.object({showCost: SHOW_COST_OPTION,@@ -3271,23 +3293,25 @@ export async function main(exitCode = 2;throw error;}- let scanId: string | undefined;- try {- scanId = args.scanId ?? (await latestScans())?.[0]?.scanId;- } catch (error) {- const message = errorMessage(error);- if (exitCode === 0)- errorOutput.write(`codex-security: ${diagnosticLines(message)}\n`);- return finishScanCommand(- { exitCode: 2, error: message },- format,- incurError,- "SCAN_REPLAY_UNAVAILABLE",- );- }- if (scanId === undefined) return;let scanArguments: ScanArguments;try {+ let scanId = args.scanId;+ let localScan: WorktreeScan | undefined;+ if (scanId === undefined) {+ localScan = await preferredScan(+ dependencies.currentDirectory(),+ "complete",+ );+ if (!localScan)+ throw new CodexSecurityError(+ "No completed scans found for the current repository.",+ );+ scanId = localScan.scanId;+ if (!localScan.inCurrentWorktree)+ throw new CodexSecurityError(+ `No completed scan in this worktree. Scan ${scanId} used ${localScan.targetPath} (revision ${localScan["targetRevision"] ?? "unknown"}). To rerun there, use codex-security scans rerun ${scanId}.`,+ );+ }const saved = await dependencies.runWorkbench(workbenchArgs("get-scan-recipe", { scanId }),);@@ -3334,12 +3358,12 @@ export async function main();}const replay =- args.scanId === undefined && isJsonObject(recipe)+ localScan && isJsonObject(recipe)? {...saved,recipe: {...recipe,- repository: dependencies.currentDirectory(),+ repository: localScan.targetPath,},}: saved;@@ -3368,13 +3392,11 @@ export async function main(},}).command("match", {- description: "Match findings by root cause across saved scans.",- usage: [- { suffix: "BEFORE AFTER [options]" },- { suffix: "--all [options]" },- ],+ description:+ "Match findings across completed scans. Uncached matches can use the model and save decisions.",+ usage: [{ suffix: "--all [options]" }],examples: [{ options: { all: true } }],- hint: "Use scans compare for a pair. Match all completed scans with --all; --force recomputes saved matches.",+ hint: "For a pair, use scans compare BEFORE AFTER. The older scans match BEFORE AFTER spelling also works.",destructive: true,args: z.object({beforeId: z@@ -3393,15 +3415,16 @@ export async function main(.boolean().default(false).describe("Match all completed scans of the current repository."),- force: z- .boolean()- .default(false)- .describe("Recompute an existing semantic finding comparison."),- ...MATCHING_MODEL_OPTIONS.shape,+ ...MATCHING_OPTIONS.shape,}),output: z.record(z.string(), z.unknown()).optional(),async run({ args, format, options }) {if (options.all) {+ if (args.beforeId !== undefined || args.afterId !== undefined) {+ throw new CodexSecurityError(+ "scans match --all does not accept scan identifiers.",+ );+ }return presentHistory(await runMatching((matchingOptions) =>@@ -3412,8 +3435,13 @@ export async function main(format,);}+ if (args.beforeId === undefined || args.afterId === undefined) {+ throw new CodexSecurityError(+ "scans match requires two scan identifiers or --all.",+ );+ }return presentHistory(- await matchScanPair(args.beforeId!, args.afterId!, options),+ await matchScanPair(args.beforeId, args.afterId, options),"compare",format,);@@ -3423,6 +3451,11 @@ export async function main(description:"Compare findings from two scans. Uncached matches can use the model and save matching decisions.",examples: [+ {+ args: { beforeId: "BEFORE", afterId: "AFTER" },+ description:+ "Compare two scans, using the model and saving decisions on a cache miss.",+ },{ args: {}, description: "Compare the latest two completed scans." },],destructive: true,@@ -3438,7 +3471,7 @@ export async function main(.optional().describe("Later saved scan identifier (default: latest completed)."),}),- options: MATCHING_MODEL_OPTIONS,+ options: MATCHING_OPTIONS,output: z.record(z.string(), z.unknown()).optional(),async run({ args, format, options }) {let { beforeId, afterId } = args;@@ -6943,12 +6976,10 @@ export async function main(if (scanDir === undefined) {let scanId = options.scan;if (!scanId || scanId === "latest") {- const scans = await latestScans(- 1,- "complete",- options.python,+ const scans = await latestScans(1, "complete", {+ pythonPath: options.python,protectedRoot,- );+ });scanId = scans?.[0]?.scanId;}if (scanId === undefined) return;@@ -8241,19 +8272,6 @@ export async function main() {return "Use login to sign in or login status to inspect authentication.";}- if (- subcommand === "match" &&- !argv.some((value) =>- ["--schema", "--llms", "--llms-full"].includes(value),- )- ) {- if (argv.includes("--all") && positionals.length > 0) {- return "scans match --all does not accept scan identifiers.";- }- if (!argv.includes("--all") && positionals.length !== 2) {- return "scans match requires two scan identifiers or --all.";- }- }if (command !== "validate" &&command !== "verify-fix" &&diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.tsindex 079e68a87..ee476b68f 100644--- a/sdk/typescript/tests-ts/cli-authentication.test.ts+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts@@ -969,6 +969,7 @@ describe("CLI authentication", () => {});test("never prompts during automation, explicit selection, or unavailable credentials", async () => {+ const repository = "/original/repository";for (const scenario of [{ argv: ["scan", "--json"], terminal: true, stored: true, key: true },{@@ -1042,16 +1043,26 @@ describe("CLI authentication", () => {let prompts = 0;const hasStoredChatGPTSignIn = mock(resolving(scenario.stored));const deps = dependencies({+ currentDirectory: repository,environment: scenario.key? { OPENAI_API_KEY: "synthetic-private-key" }: {},onTurn,onWorkbench: (args): JsonObject =>args[0] === "list-scans"- ? { scans: [{ scanId: "scan-original" }] }+ ? {+ scans: [+ {+ scanId: "scan-original",+ targetPath: repository,+ inCurrentWorktree: true,+ },+ ],+ }: {+ scanId: "scan-original",recipe: {- repository: "/original/repository",+ repository,target: { kind: "repository", paths: [] },mode: "standard",...(scenario.recipeAuth === undefineddiff --git a/sdk/typescript/tests-ts/cli-scan-navigation.test.ts b/sdk/typescript/tests-ts/cli-scan-navigation.test.tsindex 2c21dc3c2..cdb0f9b4c 100644--- a/sdk/typescript/tests-ts/cli-scan-navigation.test.ts+++ b/sdk/typescript/tests-ts/cli-scan-navigation.test.ts@@ -59,20 +59,26 @@ describe("scan navigation", () => {environment: { CODEX_HOME: home, CODEX_SECURITY_STATE_DIR: root },onWorkbench: (args): JsonObject => {calls.push([...args]);- if (args[0] === "list-scans")+ if (args[0] === "list-scans") {+ if (!args.includes("--prefer-worktree"))+ return { scans: [{ scanId: "newer-sibling-scan" }] };return {scans: args.includes("complete")? [completed]: [latest, completed],};+ }return {scan: completedId.startsWith(args[2]!) ? completed : latest,};},});for (const interactive of [false, true]) {+ const selection = interactive ? ["latest"] : [];const show = createCliTest(main, { stdout: interactive });- expect(await show.runCli(["scans", "show"], deps)).toBe(0);+ expect(await show.runCli(["scans", "show", ...selection], deps)).toBe(+ 0,+ );expect(show.stderr.text()).toContain(`Scan ${completedId} · complete`,);@@ -86,7 +92,9 @@ describe("scan navigation", () => {expect(show.stderr.text()).not.toContain(latestId);const logs = createCliTest(main, { stdout: interactive });- expect(await logs.runCli(["scans", "logs"], deps)).toBe(0);+ expect(await logs.runCli(["scans", "logs", ...selection], deps)).toBe(+ 0,+ );expect(logs.stderr.text()).toContain(`Scan ${latestId} · ${status}`);expect(logs.stderr.text()).toContain("including failed and active runs",diff --git a/sdk/typescript/tests-ts/cli-scan-prompts.test.ts b/sdk/typescript/tests-ts/cli-scan-prompts.test.tsindex 9c1e426d7..82b7e3083 100644--- a/sdk/typescript/tests-ts/cli-scan-prompts.test.ts+++ b/sdk/typescript/tests-ts/cli-scan-prompts.test.ts@@ -279,7 +279,11 @@ test("history repair loads implicit rerun prompts from the current checkout", asonTurn,onWorkbench: (args): JsonObject =>args[0] === "list-scans"- ? { scans: [{ scanId: "saved" }] }+ ? {+ scans: [+ { scanId: "saved", inCurrentWorktree: true, targetPath: root },+ ],+ }: {scanId: "saved",recipe: {diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.tsindex b4f176e51..485ea9503 100644--- a/sdk/typescript/tests-ts/cli-workbench.test.ts+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts@@ -621,7 +621,14 @@ describe("CLI workbench", () => {const latest = captureCli(main, "stdout");expect(await latest.run(["scans", "logs", "--json"], deps)).toBe(0);expect(calls).toEqual([- ["list-scans", "--repository", "/current/repository", "--limit", "1"],+ [+ "list-scans",+ "--repository",+ "/current/repository",+ "--prefer-worktree",+ "--limit",+ "1",+ ],["get-scan", "--scan-id", "scan-1"],]);expect(latest.text()).toContain("SYNTHETIC_KEY");@@ -1078,7 +1085,7 @@ describe("CLI workbench", () => {expect(await stdout.run(- ["scans", "match", "--all", "--force", "--json"],+ ["scans", "match", "--all=true", "--force", "--json"],dependencies({onWorkbench: (args, input): JsonObject => {calls.push(args);@@ -1411,7 +1418,12 @@ describe("CLI workbench", () => {expect(await runCapturedCli(main,- ["scans", "match", "before", "after", ...(force ? ["--force"] : [])],+ [+ "scans",+ ...(force+ ? ["compare", "before", "after", "--force"]+ : ["match", "before", "after", "--all=false"]),+ ],dependencies({onWorkbench: (args, input): JsonObject => {calls.push(args);@@ -1458,7 +1470,8 @@ describe("CLI workbench", () => {["scans", "match", "before"],["scans", "match", "--all", "before"],["scans", "match", "before", "after", "--all"],- ["scans", "compare", "before", "after", "--force"],+ ["scans", "match", "before", "after", "--all=true"],+ ["scans", "match", "--all=false"],]) {const onWorkbench = mock<() => {}>().mockReturnValue({});expect(@@ -1503,6 +1516,31 @@ describe("CLI workbench", () => {},);+ test("requires an explicit ID before rerunning another worktree's recipe", async () => {+ const cli = createCliTest(main);+ const onWorkbench = mock((args: readonly string[]): JsonObject => {+ expect(args[0]).toBe("list-scans");+ return {+ scans: [+ {+ scanId: "sibling-id",+ targetPath: "/sibling",+ targetRevision: "abc123",+ inCurrentWorktree: false,+ },+ ],+ };+ });+ expect(+ await cli.runCli(["scans", "rerun"], dependencies({ onWorkbench })),+ ).toBe(2);+ expect(onWorkbench).toHaveBeenCalledTimes(1);+ expect(cli.stderr.text()).toContain("/sibling (revision abc123)");+ expect(cli.stderr.text()).toContain(+ "codex-security scans rerun sibling-id",+ );+ });+test("reruns the latest completed scan by default", async () => {let parentScanId: unknown;let rerunRepository: string | undefined;@@ -1513,14 +1551,23 @@ describe("CLI workbench", () => {main,["scans", "rerun"],dependencies({+ currentDirectory: "/current/repository/src",onTurn: (repository, options) => {rerunRepository = repository;parentScanId = options.parentScanId;maxTimeMinutes = options.maxTimeMinutes;},onWorkbench: (args): JsonObject =>- args[0] === "list-scans"- ? { scans: [{ scanId: "latest-scan" }] }+ args.includes("--prefer-worktree")+ ? {+ scans: [+ {+ scanId: "latest-scan",+ targetPath: "/current/repository",+ inCurrentWorktree: true,+ },+ ],+ }: {scanId: "latest-scan",recipe: {diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex ec4694f15..118991a48 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -2084,6 +2084,7 @@ describe("CLI", () => {"list-scans","--repository","/current/repository",+ "--prefer-worktree","--status","complete","--limit",