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
feat(deep-scan): add configurable graceful time limits (#369)
Dane Schneider5c262975c29c
diff --git a/README.md b/README.mdindex 0b11ac5ea..353830ea0 100644--- a/README.md+++ b/README.md@@ -19,13 +19,17 @@ npx @openai/codex-security loginnpx @openai/codex-security scan .npx @openai/codex-security scan . --model gpt-5.6-terra --effort highnpx @openai/codex-security scan . --scan-prompt-file scan.md --post-scan-prompt-file follow-up.md-npx @openai/codex-security scan . --mode deep --workers 2 --subagents 0 --stop-after-no-new 3 --max-discovery-runs 10+npx @openai/codex-security scan . --mode deep --workers 2 --subagents 0 --stop-after-no-new 3 --max-discovery-runs 10 --max-time-hours 1.5```For CI, set `OPENAI_API_KEY` or `CODEX_API_KEY` instead of signing in.Environment API keys are passed directly to the current scan and are neverstored in Codex's credential home or system keyring.+Deep-scan discovery stops after 96 hours by default. Set `--max-time-hours` to+any positive number of hours, including fractional hours, up to 96. Completed+findings are preserved and returned when the limit is reached.+To use another inference provider, set its API key and select a model:```bash@@ -106,6 +110,7 @@ await security.run(".", {subagents: 0,stopAfterNoNew: 3,maxDiscoveryRuns: 10,+ maxTimeHours: 1.5,});console.log(result.reportPath);diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex fbc0245f4..c46f521b9 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -83,6 +83,7 @@ Pass scan configuration to `security.run(repository, options)` or| `outputDir` | Choose an artifact directory outside the enclosing Git worktree. || `archiveExisting` | Archive results already in `outputDir` before starting a scan. || `maxCostUsd` | Stop after the estimated model cost exceeds a positive USD amount. |+| `maxTimeHours` | Limit deep-scan discovery to a positive number of hours, up to 96. || `failureSeverity` | Record a finding-severity policy in the saved scan recipe. || `parentScanId` | Link a rerun to an existing parent scan. || `expectedPluginVersion` | Require the original plugin version when replaying a scan. |@@ -212,7 +213,7 @@ npx @openai/codex-security scan /path/to/repository --verbosenpx @openai/codex-security scan /path/to/repository --dry-runnpx @openai/codex-security scan /path/to/repository --fail-on-severity highnpx @openai/codex-security scan /path/to/repository --max-cost 5-npx @openai/codex-security scan /path/to/repository --mode deep --workers 2 --subagents 0 --stop-after-no-new 3 --max-discovery-runs 10+npx @openai/codex-security scan /path/to/repository --mode deep --workers 2 --subagents 0 --stop-after-no-new 3 --max-discovery-runs 10 --max-time-hours 1.5npx @openai/codex-security install-hooknpx @openai/codex-security bulk-scannpx @openai/codex-security bulk-scan --model gpt-5.6-terra --effort high@@ -263,8 +264,9 @@ Markdown, text, PDF, and Word (`.docx`) files.For `scan --mode deep`, `--workers` limits concurrent discovery workers,`--subagents` controls each worker's subagents, `--stop-after-no-new` stops after-that many runs find no new issues, and `--max-discovery-runs` limits total runs.-These options are also available on SDK scans:+that many runs find no new issues, `--max-discovery-runs` limits total runs, and+`--max-time-hours` limits discovery duration. These options are also available+on SDK scans:```tsawait security.run("/path/to/repository", {@@ -273,6 +275,7 @@ await security.run("/path/to/repository", {subagents: 0,stopAfterNoNew: 3,maxDiscoveryRuns: 10,+ maxTimeHours: 1.5,});```@@ -285,8 +288,15 @@ workers = 2subagents = 0stop_after_no_new = 3max_discovery_runs = 10+max_time_hours = 1.5```+The discovery deadline defaults to 96 hours. The configured value may be any+positive number, including fractional hours, up to 96. At the deadline,+in-flight discovery stops and completed findings are reduced and returned.+The 97-hour outer tool-call timeout reserves approximately one hour for final+reduction and result delivery, including at the 96-hour maximum.+`scan --workers` controls discovery workers within one deep scan;`bulk-scan --workers` controls how many repositories are scanned concurrently.@@ -382,22 +392,22 @@ workers = "auto"subagents = 3stop_after_no_new = 6max_discovery_runs = 60+max_time_hours = 96````workers = "auto"` uses half the available parallelism, with a minimum of oneand a maximum of six discovery workers. Set `workers` to a positive integer tochoose an explicit count. `subagents` must be a nonnegative integer;-`stop_after_no_new` and `max_discovery_runs` must be positive integers. Unknown-`[deep_scan]` keys are rejected.+`stop_after_no_new` and `max_discovery_runs` must be positive integers.+`max_time_hours` must be a positive finite number no greater than 96; fractional+hours are supported. Unknown `[deep_scan]` keys are rejected.These settings are separate from Codex's`features.multi_agent_v2.max_concurrent_threads_per_session` and-`bulk-scan --workers`. Importantly, standalone CLI and SDK scans create an-isolated `CODEX_HOME` and do not import the ambient deep-scan configuration-file. Consequently, `scan --mode deep` currently uses the deep engine's-defaults; there are no standalone CLI flags for these four settings. Use-`--codex` to adjust the Codex session thread limit, not to set `[deep_scan]`-values.+`bulk-scan --workers`. Standalone CLI and SDK scans create an isolated+`CODEX_HOME`, import the ambient `[deep_scan]` configuration, and apply explicit+CLI or SDK options on top. Use `--codex` to adjust the Codex session thread+limit, not to set `[deep_scan]` values.### Environment variables@@ -470,8 +480,11 @@ scan history, and bulk-scan receipt. Estimates useincluding cached input and cache writes; fees and surcharges are not included.Use `--max-cost USD` to stop a scan, including its delegated workers, when its-running cost exceeds the limit. Partial results are preserved. Requests-already in progress can finish above the limit.+running cost exceeds the limit. If a Deep Scan has already finished discovery,+it returns a sealed partial report with any completed findings and lists+unvalidated candidates as follow-up work. Requests already in progress can+finish above the limit; preparing the partial report makes no additional model+requests. Incomplete coverage retains its existing exit code.Run `npx @openai/codex-security scan --help` or `npx @openai/codex-security bulk-scan --help`for the complete CLI references.diff --git a/sdk/typescript/_bundled_plugin/.codex-plugin/plugin.json b/sdk/typescript/_bundled_plugin/.codex-plugin/plugin.jsonindex 34e7c8a32..e75b1ff63 100644--- a/sdk/typescript/_bundled_plugin/.codex-plugin/plugin.json+++ b/sdk/typescript/_bundled_plugin/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "codex-security",- "version": "0.1.17",+ "version": "0.1.19","description": "Codex Security workflows for security scans, analysis, and investigation.","author": {"name": "OpenAI"diff --git a/sdk/typescript/_bundled_plugin/.mcp.json b/sdk/typescript/_bundled_plugin/.mcp.jsonindex 41647750f..77967d2c3 100644--- a/sdk/typescript/_bundled_plugin/.mcp.json+++ b/sdk/typescript/_bundled_plugin/.mcp.json@@ -37,7 +37,7 @@"REQUESTS_CA_BUNDLE","NODE_EXTRA_CA_CERTS"],- "tool_timeout_sec": 86400+ "tool_timeout_sec": 349200}}}diff --git a/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-000 b/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-000index 522f3740e..ac3c8bf46 100644Binary files a/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-000 and b/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-000 differdiff --git a/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-001 b/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-001index 5fb8c2f7c..43ce65f86 100644Binary files a/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-001 and b/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-001 differdiff --git a/sdk/typescript/_bundled_plugin/scripts/deep_scan_config.py b/sdk/typescript/_bundled_plugin/scripts/deep_scan_config.pyindex d67b97d58..d500441fe 100644--- a/sdk/typescript/_bundled_plugin/scripts/deep_scan_config.py+++ b/sdk/typescript/_bundled_plugin/scripts/deep_scan_config.py@@ -3,6 +3,7 @@from __future__ import annotationsimport argparse+import mathimport osfrom pathlib import Pathfrom typing import Any@@ -16,6 +17,8 @@ DEFAULT_SUBAGENTS = 3DEFAULT_STOP_AFTER_NO_NEW = 6DEFAULT_STOP_AFTER_CONSECUTIVE_ERRORS = 3DEFAULT_MAX_DISCOVERY_RUNS = 60+DEFAULT_MAX_TIME_HOURS = 96+MAX_TIME_HOURS = 96MAX_AUTOMATIC_WORKERS = 6CONFIG_KEYS = {"workers",@@ -23,6 +26,7 @@ CONFIG_KEYS = {"stop_after_no_new","stop_after_consecutive_errors","max_discovery_runs",+ "max_time_hours",}@@ -34,7 +38,7 @@ def config_path() -> Path:return codex_home() / "codex-security" / "config.toml"-def resolve_deep_scan_config(available_parallelism: int) -> dict[str, int]:+def resolve_deep_scan_config(available_parallelism: int) -> dict[str, int | float]:if isinstance(available_parallelism, bool) or available_parallelism < 1:raise SystemExit("Available parallelism must be a positive integer.")path = config_path()@@ -87,6 +91,10 @@ def resolve_deep_scan_config(available_parallelism: int) -> dict[str, int]:"deep_scan.max_discovery_runs",minimum=1,),+ "maxTimeHours": require_positive_number(+ configured.get("max_time_hours", DEFAULT_MAX_TIME_HOURS),+ "deep_scan.max_time_hours",+ ),}@@ -103,6 +111,18 @@ def require_integer(value: object, label: str, *, minimum: int) -> int:return value+def require_positive_number(value: object, label: str) -> int | float:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise SystemExit(f"{label} must be a positive finite number no greater than 96.")+ try:+ finite = math.isfinite(value)+ except OverflowError:+ finite = False+ if not finite or value <= 0 or value > MAX_TIME_HOURS:+ raise SystemExit(f"{label} must be a positive finite number no greater than 96.")+ return value++def main() -> None:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--available-parallelism", type=int, required=True)diff --git a/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py b/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.pyindex 641eb4dff..f25379624 100644--- a/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py+++ b/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py@@ -217,6 +217,11 @@ def require_deep_scan_run(connection: sqlite3.Connection, scan_id: str) -> sqlitreturn row+def deep_scan_deadline_reached(run: sqlite3.Row) -> bool:+ elapsed = datetime.fromisoformat(now()) - datetime.fromisoformat(str(run["created_at"]))+ return elapsed.total_seconds() / 3600 >= run["max_time_hours"]++def require_deep_scan_ready_for_parent_completion(connection: sqlite3.Connection, scan: sqlite3.Row) -> None:@@ -361,6 +366,23 @@ def deep_scan_state(connection: sqlite3.Connection, scan_id: str) -> dict[str, A""",(run["scan_id"],),).fetchone()+ canonical_artifacts = None+ if run["canonical_inventory_path"] is None:+ if successful_reducer is not None:+ canonical_artifacts = canonical_discovery_artifacts(scan)+ elif (+ run["status"] == "succeeded"+ and run["terminal_reason"] == "capped"+ and run["completion_sequence"] == 0+ and deep_scan_deadline_reached(run)+ ):+ candidate_artifacts = canonical_discovery_artifacts(scan)+ if Path(candidate_artifacts["candidateLedgerPath"]).stat().st_size != 0:+ raise SystemExit(+ "A capped Deep Scan without completed discoveries requires an empty "+ "candidate ledger."+ )+ canonical_artifacts = candidate_artifactsreturn {"scanId": run["scan_id"],"targetPath": scan["target_path"],@@ -378,17 +400,14 @@ def deep_scan_state(connection: sqlite3.Connection, scan_id: str) -> dict[str, A"stopAfterNoNew": run["stop_after_no_new"],"stopAfterConsecutiveErrors": run["stop_after_consecutive_errors"],"maxDiscoveryRuns": run["max_discovery_runs"],+ "maxTimeHours": run["max_time_hours"],},"dispatchedCount": run["discovery_runs_dispatched"],"completionSequence": run["completion_sequence"],"noNewStreak": run["consecutive_no_new"],"consecutiveErrors": run["consecutive_errors"],"cancelRequested": bool(run["cancel_requested"]),- "canonicalArtifacts": (- canonical_discovery_artifacts(scan)- if successful_reducer is not None and run["canonical_inventory_path"] is None- else None- ),+ "canonicalArtifacts": canonical_artifacts,"manifestPath": run["manifest_path"],"terminalReason": run["terminal_reason"],"error": run["error_message"],@@ -466,7 +485,7 @@ def deep_scan_result(return result-def effective_deep_scan_config(args: argparse.Namespace) -> dict[str, int]:+def effective_deep_scan_config(args: argparse.Namespace) -> dict[str, int | float]:available_parallelism = args.available_parallelism or os.cpu_count() or 1return resolve_deep_scan_config(available_parallelism)@@ -474,7 +493,7 @@ def effective_deep_scan_config(args: argparse.Namespace) -> dict[str, int]:def ensure_deep_scan_run(connection: sqlite3.Connection,scan: sqlite3.Row,- config: dict[str, int],+ config: dict[str, int | float],workflow_version: str,timestamp: str,) -> sqlite3.Row:@@ -492,9 +511,9 @@ def ensure_deep_scan_run(INSERT INTO deep_scan_runs (scan_id, schema_version, workflow_version, status, phase,workers, subagents, stop_after_no_new, stop_after_consecutive_errors,- max_discovery_runs,+ max_discovery_runs, max_time_hours,created_at, updated_at- ) VALUES (?, 1, ?, 'running', 'setup', ?, ?, ?, ?, ?, ?, ?)+ ) VALUES (?, 1, ?, 'running', 'setup', ?, ?, ?, ?, ?, ?, ?, ?)""",(scan["id"],@@ -504,6 +523,7 @@ def ensure_deep_scan_run(config["stopAfterNoNew"],config["stopAfterConsecutiveErrors"],config["maxDiscoveryRuns"],+ config["maxTimeHours"],timestamp,timestamp,),@@ -1404,9 +1424,12 @@ def claim_deep_scan_dedup("A Deep Scan dedup worker must claim an ordered prefix of buffered discovery ""results in completion order.")- hard_cap_singleton = (+ capped_singleton = (len(input_ids) == 1- and run["discovery_runs_dispatched"] >= run["max_discovery_runs"]+ and (+ run["discovery_runs_dispatched"] >= run["max_discovery_runs"]+ or deep_scan_deadline_reached(run)+ )and connection.execute("""SELECT 1 FROM deep_scan_workers@@ -1425,7 +1448,7 @@ def claim_deep_scan_dedup(""",(scan_id,),).fetchone()- minimum_inputs = 1 if successful_reducer is not None or hard_cap_singleton else 2+ minimum_inputs = 1 if successful_reducer is not None or capped_singleton else 2if len(input_ids) < minimum_inputs:raise SystemExit("The first Deep Scan dedup requires two buffered discovery results."@@ -1679,12 +1702,13 @@ def finish_deep_scan_locked(if (args.terminal_reason == "capped"and run["discovery_runs_dispatched"] < run["max_discovery_runs"]+ and not deep_scan_deadline_reached(run)):raise SystemExit("Deep Scan cannot finish capped before reaching its configured maximum.")try:- canonical_discovery_artifacts(scan)+ canonical_artifacts = canonical_discovery_artifacts(scan)except SystemExit as exc:raise SystemExit(f"Deep Scan cannot finish without canonical discovery artifacts: {exc}"@@ -1697,7 +1721,13 @@ def finish_deep_scan_locked(""",(scan_id,),).fetchone()- if successful_reducer is None:+ zero_discovery_deadline = (+ args.terminal_reason == "capped"+ and deep_scan_deadline_reached(run)+ and run["completion_sequence"] == 0+ and Path(canonical_artifacts["candidateLedgerPath"]).stat().st_size == 0+ )+ if successful_reducer is None and not zero_discovery_deadline:raise SystemExit("Deep Scan cannot finish without a successful dedup worker.")failed_worker = connection.execute("""diff --git a/sdk/typescript/_bundled_plugin/scripts/report_projection.py b/sdk/typescript/_bundled_plugin/scripts/report_projection.pyindex e1e9f45cb..1a51efa91 100644--- a/sdk/typescript/_bundled_plugin/scripts/report_projection.py+++ b/sdk/typescript/_bundled_plugin/scripts/report_projection.py@@ -739,11 +739,49 @@ def build_report_markdown(else:lines.extend(["", *_finding_section(number, finding)])else:+ deferred = coverage.get("deferred", [])+ no_source_review = (+ coverage.get("completeness") == "partial"+ and isinstance(deferred, list)+ and any(+ isinstance(item, dict)+ and item.get("reason")+ == "The configured discovery time limit elapsed before any source review completed."+ for item in deferred+ )+ )+ budget_exhausted = (+ coverage.get("completeness") == "partial"+ and isinstance(deferred, list)+ and any(+ isinstance(item, dict)+ and isinstance(item.get("reason"), str)+ and (+ item["reason"]+ == "Validation was deferred because the scan reached its cost limit."+ or item["reason"].startswith(+ "Validation was deferred because the scan reached its cost limit: "+ )+ )+ for item in deferred+ )+ )lines.extend(["### No findings","",- "No reportable findings survived the canonical discovery, validation, and reportability gates.",+ (+ "No source review completed before the configured time limit. "+ "No vulnerability conclusion can be drawn."+ if no_source_review+ else (+ "No findings were validated before the scan reached its cost limit. "+ "Review the deferred candidates in Open Questions And Follow Up."+ if budget_exhausted+ else "No reportable findings survived the canonical discovery, validation, "+ "and reportability gates."+ )+ ),])if hardening_portfolio_path is not None:diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.pyindex fe4d7c767..56f8997c7 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py@@ -213,6 +213,11 @@ def parse_args(description: str) -> argparse.Namespace:complete_scan.add_argument("--cost-json")complete_scan.add_argument("--thread-id")+ complete_budget_exhausted_scan = subparsers.add_parser("complete-budget-exhausted-scan")+ complete_budget_exhausted_scan.add_argument("--scan-id", required=True)+ complete_budget_exhausted_scan.add_argument("--cost-json", required=True)+ complete_budget_exhausted_scan.add_argument("--message")+cancel_scan = subparsers.add_parser("cancel-scan")cancel_scan.add_argument("--scan-id", required=True)cancel_scan.add_argument("--thread-id")diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.pyindex 3cb96bb58..2bf473268 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py@@ -1136,6 +1136,285 @@ def complete_scan()+def complete_budget_exhausted_scan(+ connection: sqlite3.Connection, args: argparse.Namespace+) -> dict[str, Any]:+ scan_id = require_uuid(args.scan_id, "scan-id")+ cost_json = parse_scan_cost(args.cost_json)+ if cost_json is None:+ raise SystemExit("Budget-exhausted scan completion requires the measured scan cost.")+ with scan_completion_lock(scan_id):+ scan = require_scan(connection, scan_id)+ if scan["status"] != "running" or scan["mode"] != "deep" or scan["recipe_json"] is None:+ raise SystemExit("Only a running CLI Deep Scan can complete after its cost limit.")+ recipe = json.loads(scan["recipe_json"], parse_constant=reject_non_finite_json)+ if not isinstance(recipe, dict) or recipe.get("mode") != "deep":+ raise SystemExit("Budget-exhausted scan completion requires a Deep Scan launch recipe.")+ cost = json.loads(cost_json)+ measured = cost.get("cost", cost)+ limit = recipe.get("maxCostUsd")+ if (+ not isinstance(limit, (int, float))+ or isinstance(limit, bool)+ or not isinstance(measured, dict)+ or measured.get("estimatedUsd", 0) <= limit+ ):+ raise SystemExit("Deep Scan has not exceeded its configured cost limit.")+ run = connection.execute(+ "SELECT status, terminal_reason, manifest_path FROM deep_scan_runs WHERE scan_id = ?",+ (scan_id,),+ ).fetchone()+ if (+ run is None+ or run["status"] != "succeeded"+ or run["terminal_reason"] not in {"saturated", "capped"}+ or not run["manifest_path"]+ ):+ raise SystemExit(+ "Budget-exhausted scan completion requires successfully completed Deep Scan "+ "discovery."+ )+ scan_dir = require_canonical_scan_directory(Path(scan["scan_dir"]))+ candidates = budget_exhausted_candidates(scan, scan_dir)+ warning = optional_text(args.message, maximum=2400)+ if warning is None:+ warning = (+ f"Deep Scan reached its cost limit after an estimated "+ f"${measured['estimatedUsd']:.6g}; completed discovery was preserved."+ )+ budget_exhausted_draft(scan, scan_dir, candidates, warning)+ warnings = json.loads(scan["completion_warnings_json"])+ if warning not in warnings:+ connection.execute(+ "UPDATE scans SET completion_warnings_json = ? WHERE id = ? AND status = 'running'",+ (json.dumps([*warnings, warning]), scan_id),+ )+ connection.commit()+ return complete_scan_locked(connection, scan_id, None, cost_json)+++def budget_exhausted_candidates(scan: sqlite3.Row, scan_dir: Path) -> list[dict[str, Any]]:+ artifacts = deep_scan.canonical_discovery_artifacts(scan)+ ledger = Path(artifacts["candidateLedgerPath"])+ try:+ inventory = Path(artifacts["inScopeFilesPath"])+ inventory_descriptor = open_scan_local_file_descriptor(+ scan_dir,+ inventory.relative_to(scan_dir).as_posix(),+ "Canonical Deep Scan in-scope inventory",+ )+ with os.fdopen(inventory_descriptor, "rb") as source:+ lines = re.split(r"\r?\n", source.read().decode("utf-8"))+ in_scope = {re.sub(r"^(?:\./)+", "", line) for line in lines if line}+ descriptor = open_scan_local_file_descriptor(+ scan_dir,+ ledger.relative_to(scan_dir).as_posix(),+ "Canonical Deep Scan candidate ledger",+ )+ with os.fdopen(descriptor, "r", encoding="utf-8") as source:+ candidates = [+ json.loads(line, parse_constant=reject_non_finite_json)+ for line in source+ if line.strip()+ ]+ except (ContractError, OSError, UnicodeError, ValueError) as exc:+ raise SystemExit(f"Canonical Deep Scan candidate ledger is invalid: {exc}") from exc++ candidate_ids: set[str] = set()+ for candidate in candidates:+ if not isinstance(candidate, dict):+ raise SystemExit("Canonical Deep Scan candidate ledger rows must be objects.")+ candidate_id = candidate.get("candidate_id")+ locations = candidate.get("locations")+ if (+ not isinstance(candidate_id, str)+ or not candidate_id.strip()+ or candidate_id in {".", ".."}+ or "/" in candidate_id+ or "\\" in candidate_id+ or candidate_id in candidate_ids+ or not isinstance(candidate.get("summary"), str)+ or not candidate["summary"].strip()+ or not isinstance(candidate.get("evidence"), str)+ or not candidate["evidence"].strip()+ or not isinstance(locations, list)+ or not locations+ ):+ raise SystemExit("Canonical Deep Scan candidate ledger contains an invalid candidate.")+ candidate_ids.add(candidate_id)+ for location in locations:+ if not isinstance(location, dict):+ raise SystemExit("Canonical Deep Scan candidate location must be an object.")+ path = location.get("path")+ if (+ not isinstance(path, str)+ or not path+ or "\\" in path+ or "\x00" in path+ or re.match(r"^[A-Za-z]:", path)+ or PurePosixPath(path).is_absolute()+ or any(part in {".", "..", ""} for part in path.split("/"))+ ):+ raise SystemExit(+ "Canonical Deep Scan candidate location must be repository-relative."+ )+ if not any(location["path"] in in_scope for location in locations):+ raise SystemExit(+ "Canonical Deep Scan candidate must include a location in its in-scope inventory."+ )+ return candidates+++def budget_exhausted_draft(+ scan: sqlite3.Row,+ scan_dir: Path,+ candidates: list[dict[str, Any]],+ warning: str,+) -> None:+ documents: dict[str, dict[str, Any]] = {}+ for name in ("scan-manifest.json", "findings.json", "coverage.json"):+ path = artifact_path(scan_dir, name, required=False)+ if path is not None:+ documents[name] = read_json_object(path)+ if documents and len(documents) != 3:+ raise SystemExit("Budget-exhausted scan contains an incomplete canonical scan draft.")++ if documents:+ manifest = documents["scan-manifest.json"]+ findings = documents["findings.json"]+ coverage = documents["coverage.json"]+ if not isinstance(manifest.get("scan"), dict) or not isinstance(+ findings.get("findings"), list+ ):+ raise SystemExit("Budget-exhausted scan contains an invalid canonical scan draft.")+ for key in ("surfaces", "explicitExclusions", "deferred"):+ if not isinstance(coverage.get(key), list):+ raise SystemExit("Budget-exhausted scan contains invalid canonical coverage.")+ if manifest["scan"].get("sealedAt") is not None or manifest["scan"].get("artifacts"):+ raise SystemExit("Budget-exhausted scan cannot replace an already sealed scan draft.")+ else:+ contract = scan_contract(scan)+ target_contract = contract["target"]+ target: dict[str, Any] = {+ "kind": target_contract["allowedKinds"][0],+ "targetId": target_contract["targetId"],+ "displayName": target_contract["displayName"],+ }+ if scan["target_revision"] != "unversioned":+ target["revision"] = scan["target_revision"]+ if "requiredSnapshotDigest" in target_contract:+ target["snapshotDigest"] = target_contract["requiredSnapshotDigest"]+ manifest = {+ "scan": {+ "target": target,+ "scope": {"limitations": [warning], "validationMode": "incomplete"},+ }+ }+ findings = {"findings": []}+ coverage = {+ "completeness": "partial",+ "inventoryStrategy": (+ "scoped_path" if expected_coverage_mode(scan) == "scoped_path" else "repository"+ ),+ "surfaces": [],+ "explicitExclusions": [],+ "deferred": [],+ }++ findings_by_candidate = {+ candidate_id+ for finding in findings["findings"]+ if isinstance(finding, dict)+ and isinstance(candidate_id := finding_candidate_id(finding), str)+ }+ existing_deferred = {+ item.get("candidateId", item.get("id"))+ for item in coverage["deferred"]+ if isinstance(item, dict)+ and isinstance(item.get("candidateId", item.get("id")), str)+ }+ existing_surfaces = {+ item.get("id")+ for item in coverage["surfaces"]+ if isinstance(item, dict) and isinstance(item.get("id"), str)+ }+ for candidate in candidates:+ candidate_id = candidate["candidate_id"]+ if candidate_id in findings_by_candidate or candidate_id in existing_deferred:+ continue+ paths = list(dict.fromkeys(location["path"] for location in candidate["locations"]))+ surface_id = f"candidate-{candidate_id}"+ validation = candidate.get("validation")+ validation = validation.get("disposition") if isinstance(validation, dict) else None+ attack = candidate.get("attack_path")+ attack = attack.get("decision") if isinstance(attack, dict) else None+ disposition = (+ "needs_follow_up"+ if validation == "deferred" or attack == "deferred"+ else "not_applicable"+ if validation == "not_applicable"+ else "rejected"+ if validation == "suppressed" or attack == "ignore"+ else "needs_follow_up"+ )+ if surface_id not in existing_surfaces:+ coverage["surfaces"].append(+ {+ "id": surface_id,+ "label": candidate["summary"],+ "disposition": disposition,+ "notes": candidate["evidence"],+ "receiptRefs": [],+ }+ )+ existing_surfaces.add(surface_id)+ if disposition != "needs_follow_up":+ continue+ coverage["deferred"].append(+ {+ "id": candidate_id,+ "candidateId": candidate_id,+ "reason": (+ "Validation was deferred because the scan reached its cost limit: "+ f"{candidate['summary']}. Evidence: {candidate['evidence']}"+ ),+ "paths": paths,+ "surfaceIds": [surface_id],+ }+ )+ if not any(+ isinstance(item, dict)+ and isinstance(reason := item.get("reason"), str)+ and (+ reason == "Validation was deferred because the scan reached its cost limit."+ or reason.startswith(+ "Validation was deferred because the scan reached its cost limit: "+ )+ )+ for item in coverage["deferred"]+ ):+ coverage["deferred"].append(+ {+ "id": "scan-cost-limit",+ "reason": "Validation was deferred because the scan reached its cost limit.",+ }+ )+ coverage["completeness"] = "partial"+ for name, payload in (+ ("findings.json", findings),+ ("coverage.json", coverage),+ ("scan-manifest.json", manifest),+ ):+ try:+ write_scan_local_bytes(+ scan_dir,+ name,+ (json.dumps(payload, allow_nan=False, indent=2, sort_keys=True) + "\n").encode(),+ )+ except (ContractError, OSError, TypeError, ValueError) as exc:+ raise SystemExit(f"Budget-exhausted scan draft could not be saved: {exc}") from exc++def complete_scan_locked(connection: sqlite3.Connection,scan_id: str,@@ -3400,6 +3679,8 @@ def main() -> None:result = complete_scan(connection, args, prepare_only=args.command == "prepare-scan-completion")+ elif args.command == "complete-budget-exhausted-scan":+ result = complete_budget_exhausted_scan(connection, args)elif args.command == "cancel-scan":result = cancel_scan(connection, args)elif args.command == "fail-scan":diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py b/sdk/typescript/_bundled_plugin/scripts/workbench_schema.pyindex 8bed89cff..a9582f70e 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py@@ -635,6 +635,14 @@ MIGRATIONS = (SET stop_after_consecutive_errors = stop_after_no_new;""",),+ (+ 28,+ "persist deep scan discovery time limit",+ """+ ALTER TABLE deep_scan_runs+ ADD COLUMN max_time_hours REAL NOT NULL DEFAULT 96;+ """,+ ),)@@ -689,6 +697,13 @@ def apply_migrations("completion_warnings_json","TEXT NOT NULL DEFAULT '[]'",)+ elif version == 28:+ add_column_if_missing(+ connection,+ "deep_scan_runs",+ "max_time_hours",+ "REAL NOT NULL DEFAULT 96",+ )continueif version == 6:repair_thread_scoped_workspaces_migration(connection)diff --git a/sdk/typescript/_bundled_plugin/skills/deep-security-scan/SKILL.md b/sdk/typescript/_bundled_plugin/skills/deep-security-scan/SKILL.mdindex 71d464535..89788f789 100644--- a/sdk/typescript/_bundled_plugin/skills/deep-security-scan/SKILL.md+++ b/sdk/typescript/_bundled_plugin/skills/deep-security-scan/SKILL.md@@ -89,7 +89,7 @@ When the existing scan has a `handoffClaimToken`, preserve and pass that same toFor a scoped-path scan, pass the resolved scoped directory as `targetPath` with `scope: "."`; never silently widen it to the repository root.-Make one call and wait for it. The call blocks for up to 24 hours and returns only after discovery completes, fails, or is canceled. The tool owns the transition into the discovery phase, so leave the public scan phase at preflight before calling it. Do not publish discovery progress yourself while the call is pending.+Make one call and wait for it. Discovery stops dispatching new workers after the configured `[deep_scan].max_time_hours` duration, cancels unfinished discovery, merges every completed discovery, and returns the existing `capped` terminal manifest. The default and maximum configured duration are 96 hours, reserving approximately one hour for finalization under the 97-hour tool-call timeout. Then continue immediately with centralized validation, attack-path analysis, and reporting. The call otherwise returns only after discovery completes, fails, or is canceled. The tool owns the transition into the discovery phase, so leave the public scan phase at preflight before calling it. Do not publish discovery progress yourself while the call is pending.Handle the terminal result as follows:@@ -97,7 +97,7 @@ Handle the terminal result as follows:- `status: "canceled"`: stop without starting validation or finalization.- Tool error: report the exact stable MCP error, including its failure-manifest path when present, and stop the current response. This is a terminal failure of that logical scan: do not call `start_codex_security_deep_scan` again in this response; do not call `get_codex_security_scan_context` in this response; do not call `complete_codex_security_scan` in this response; do not call the target form again to create a replacement scan, do not cancel an already terminal failed scan, do not return a final answer, satisfy a structured output schema, do not synthesize no-findings coverage, or emit benchmark JSON.-If the host represents the pending tool call as a running execution cell, keep waiting on that same cell instead of starting another tool call. Stopping the current Codex response or reaching the host's 24-hour timeout detaches only the caller; it does not cancel the scan. Only while the scan is still active may a later desktop turn rejoin with `{ scanId, handoffClaimToken? }`, or a CLI/headless turn repeat the identical target form to rejoin the owning thread's active scan. After an MCP process restart, the new coordinator safely adopts the expired lease and preserves completed discovery receipts. A terminal tool failure is not a detached waiter and must not be replaced. When the user explicitly asks to stop an active scan, call `cancel_codex_security_scan({ scanId })`.+If the host represents the pending tool call as a running execution cell, keep waiting on that same cell instead of starting another tool call. Stopping the current Codex response or reaching the host's tool-call timeout detaches only the caller; it does not cancel the scan. Only while the scan is still active may a later desktop turn rejoin with `{ scanId, handoffClaimToken? }`, or a CLI/headless turn repeat the identical target form to rejoin the owning thread's active scan. After an MCP process restart, the new coordinator safely adopts the expired lease and preserves completed discovery receipts. A terminal tool failure is not a detached waiter and must not be replaced. When the user explicitly asks to stop an active scan, call `cancel_codex_security_scan({ scanId })`.The native Security workbench observes durable discovery progress without another scan-start call.@@ -112,12 +112,14 @@ Treat the returned manifest as the sole discovery-to-parent boundary. Require it- merged, canceled, and intentionally omitted worker IDs- final discovery count and no-new streak-Do not read live worker state, repair worker artifacts, or redo discovery. If a required manifest field or shared discovery artifact is missing or malformed, report the tool failure and stop before validation. An empty compact candidate ledger is the ordinary no-findings discovery result; it still requires a valid terminal manifest.+Do not read live worker state, repair worker artifacts, or redo discovery. If a required manifest field or shared discovery artifact is missing or malformed, report the tool failure and stop before validation. An empty compact candidate ledger with completed discovery workers is the ordinary no-findings discovery result; it still requires a valid terminal manifest. If the manifest is `capped` with `discoveryCount: 0`, no source review completed: treat its empty ledger as incomplete discovery, never as evidence that the repository has no vulnerabilities.## Centralized TailAfter accepting the terminal manifest, continue in the same turn. A discovery manifest is never a final scan result and never authorizes a user-facing or benchmark response:+If the manifest is `capped` with `discoveryCount: 0`, do not invent or synthesize a threat model. Publish the ordinary forward phase transitions and close the empty phases directly with `record_codex_security_candidate_validations({ scanId, validations: [] })` and `record_candidate_attack_paths({ scanId, attackPaths: [] })`. Record `record_codex_security_scan_draft({ scanId, handoffClaimToken?, findings: [], coverage: { completeness: "partial", surfaces: [], explicitExclusions: [], deferred: [{ reason: "The configured discovery time limit elapsed before any source review completed." }] } })` without `threatModel`, then call `complete_codex_security_scan({ scanId, handoffClaimToken? })`. Preserve the actual scan scope and make clear that the report is partial because no source review completed; do not claim the repository is free of vulnerabilities. The usual draft, completion, and error-handling rules below still apply.+1. Read the canonical review items and candidate set with `list_codex_security_review_items({ scanId, handoffClaimToken?, cursor?, limit? })` and `list_codex_security_candidates({ scanId, cursor?, limit? })`. Follow `nextCursor` until all pages are read. If either tool fails or returns malformed records, report the tool failure and stop; do not repair coordinator-owned discovery artifacts, reopen discovery, or silently drop candidates.2. Synthesize one canonical validation threat model from the ordered worker threat models and write it to the per-scan `<context_dir>/threat_model.md` path. Preserve relevant attacker models, trust boundaries, privileged surfaces, contradictions, and risk framings conservatively. This threat model is downstream context, not a retroactive discovery filter.3. Run `$codex-security:validation` once in compact Deep candidate mode over the canonical merged candidates, recording every result with `record_codex_security_candidate_validations`.diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 03476f8fb..209ae6f68 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -153,6 +153,7 @@ export interface DeepScanOptions {subagents?: number;stopAfterNoNew?: number;maxDiscoveryRuns?: number;+ maxTimeHours?: number;}export interface ScanOptions extends DeepScanOptions {@@ -302,6 +303,7 @@ const DEEP_SCAN_SETTINGS = [["subagents", "subagents", 0],["stopAfterNoNew", "stop_after_no_new", 1],["maxDiscoveryRuns", "max_discovery_runs", 1],+ ["maxTimeHours", "max_time_hours", 0],] as const;export class CodexSecurity {@@ -418,6 +420,12 @@ export class CodexSecurity {let releaseCredentialHome: (() => Promise<void>) | null = null;let scanFailure = false;let completionCost: ScanCost | null = null;+ let budgetRecovery: {+ expectation: ScanExpectation;+ pluginRoot: string;+ model: string;+ threadId: string | null;+ } | null = null;let preparedTargetWarnings: string[] = [];let runPostScan: (() => ReturnType<CodexThreadLike["runStreamed"]>) | null =null;@@ -690,6 +698,14 @@ export class CodexSecurity {};const { model } = scanModelConfiguration(effectiveConfig);validateScanCostLimit(options.maxCostUsd, model);+ if (mode === "deep" && options.maxCostUsd !== undefined) {+ budgetRecovery = {+ expectation,+ pluginRoot: runtime.plugin.installedRoot,+ model,+ threadId: null,+ };+ }let scopeFileCount: number | null = null;let reviewedFileCount = 0;const reportProgress = (progress: ScanProgress): void => {@@ -1042,6 +1058,7 @@ export class CodexSecurity {workbenchValidated: true,model,onThreadStarted: async (threadId) => {+ if (budgetRecovery !== null) budgetRecovery.threadId = threadId;tracker.start(threadId);try {await workbench(workbenchOptions, [@@ -1207,6 +1224,81 @@ export class CodexSecurity {signal.reason instanceof ScanCostLimitExceededError? signal.reason: error;+ if (+ failure instanceof ScanCostLimitExceededError &&+ budgetRecovery !== null &&+ budgetRecovery.threadId !== null &&+ activeScan !== null &&+ !this.#abortController.signal.aborted &&+ options.signal?.aborted !== true+ ) {+ try {+ const completion = await workbench(+ { ...activeScan.options, signal: undefined },+ [+ "complete-budget-exhausted-scan",+ "--scan-id",+ activeScan.id,+ "--cost-json",+ JSON.stringify(snapshot?.cost ?? failure.cost),+ "--message",+ failure.message.slice(0, 2400),+ ],+ );+ activeScan = null;+ runPostScan = null;+ const result = await collectResult(+ {+ status: "completed",+ model: budgetRecovery.model,+ usage: snapshot?.usage ?? null,+ },+ budgetRecovery.threadId,+ scanDir,+ budgetRecovery.pluginRoot,+ budgetRecovery.expectation,+ AbortSignal.any([+ this.#abortController.signal,+ ...(options.signal === undefined ? [] : [options.signal]),+ ]),+ true,+ );+ if (result.coverage.completeness !== "partial") {+ throw new IncompleteScanError(+ "Budget-exhausted scan recovery did not report partial coverage.",+ );+ }+ const completedScan = completion["scan"];+ const targetWarnings = new Set(+ Array.isArray(completion["targetWarnings"])+ ? completion["targetWarnings"].filter(+ (warning): warning is string => typeof warning === "string",+ )+ : [],+ );+ const warnings =+ isRecord(completedScan) && Array.isArray(completedScan["warnings"])+ ? completedScan["warnings"].filter(+ (warning): warning is string => typeof warning === "string",+ )+ : [];+ for (const warning of warnings.length > 0+ ? warnings+ : [failure.message]) {+ notifyObserver(+ "onWarning",+ options.onWarning,+ options.onObserverError,+ warning,+ targetWarnings.has(warning)+ ? { kind: "target_changed" }+ : undefined,+ );+ }+ scanFailure = false;+ return result;+ } catch {}+ }if (activeScan !== null) {try {await workbench({ ...activeScan.options, signal: undefined }, [@@ -1714,7 +1806,13 @@ function deepScanOptions(options: ScanOptions): DeepScanOptions {if ((options.mode ?? "standard") !== "deep") {throw new CodexSecurityError("Deep scan settings require deep mode.");}- if (!Number.isSafeInteger(value) || value < minimum) {+ if (name === "maxTimeHours") {+ if (!Number.isFinite(value) || value <= 0 || value > 96) {+ throw new CodexSecurityError(+ "Deep scan maxTimeHours must be a positive number no greater than 96.",+ );+ }+ } else if (!Number.isSafeInteger(value) || value < minimum) {throw new CodexSecurityError(`Deep scan ${name} must be ${minimum === 0 ? "a non-negative" : "a positive"} integer.`,);diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 2b276affa..b626d942c 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -188,6 +188,7 @@ const VALUE_OPTIONS = new Set(["--subagents","--stop-after-no-new","--max-discovery-runs",+ "--max-time-hours","--max-attempts","--export-format","--output",@@ -244,6 +245,12 @@ const DEEP_SCAN_OPTION_SCHEMAS = {.positive().optional().describe("Maximum deep-scan discovery runs."),+ maxTimeHours: z+ .number()+ .positive()+ .max(96)+ .optional()+ .describe("Maximum deep-scan discovery hours (default: 96; maximum: 96)."),};async function readPromptFiles(@@ -1230,7 +1237,8 @@ export async function main((options.workers === undefined &&options.subagents === undefined &&options.stopAfterNoNew === undefined &&- options.maxDiscoveryRuns === undefined),+ options.maxDiscoveryRuns === undefined &&+ options.maxTimeHours === undefined),{ message: "Deep scan settings require --mode deep." },),examples: [@@ -1278,6 +1286,7 @@ export async function main(subagents: options.subagents,stopAfterNoNew: options.stopAfterNoNew,maxDiscoveryRuns: options.maxDiscoveryRuns,+ maxTimeHours: options.maxTimeHours,model: options.model,effort: options.effort,provider: options.provider,@@ -2889,6 +2898,7 @@ async function runScan(subagents: arguments_.subagents,stopAfterNoNew: arguments_.stopAfterNoNew,maxDiscoveryRuns: arguments_.maxDiscoveryRuns,+ maxTimeHours: arguments_.maxTimeHours,outputDir: arguments_.outputDir,archiveExisting: arguments_.archiveExisting,parentScanId: arguments_.parentScanId,diff --git a/sdk/typescript/src/version.ts b/sdk/typescript/src/version.tsindex f2652961f..a17a0fee5 100644--- a/sdk/typescript/src/version.ts+++ b/sdk/typescript/src/version.ts@@ -9,7 +9,7 @@ const PACKAGE_VERSIONS = packageVersions(export const VERSION = PACKAGE_VERSIONS.package;export const CODEX_SDK_VERSION = PACKAGE_VERSIONS.sdk;export const CODEX_EXECUTABLE_VERSION = PACKAGE_VERSIONS.executable;-export const BUNDLED_PLUGIN_VERSION = "0.1.17" as const;+export const BUNDLED_PLUGIN_VERSION = "0.1.19" as const;const PACKAGE_NAME = "@openai/codex-security";const VERSION_PATTERN =diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 7e1a483ee..ff530b689 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -494,6 +494,7 @@ describe("CodexSecurity orchestration", () => {subagents: 0,stopAfterNoNew: 3,maxDiscoveryRuns: 10,+ maxTimeHours: 1.5,}),).resolves.toMatchObject({mode: "deep",@@ -501,10 +502,14 @@ describe("CodexSecurity orchestration", () => {subagents: 0,stopAfterNoNew: 3,maxDiscoveryRuns: 10,+ maxTimeHours: 1.5,});await expect(client.preflight(repository, { workers: 1 })).rejects.toThrow("Deep scan settings require deep mode",);+ await expect(+ client.preflight(repository, { maxTimeHours: 1.5 }),+ ).rejects.toThrow("Deep scan settings require deep mode");for (const invalid of [{ workers: 0 },{ workers: 1.5 },@@ -516,6 +521,20 @@ describe("CodexSecurity orchestration", () => {client.preflight(repository, { mode: "deep", ...invalid }),).rejects.toThrow("integer");}+ for (const maxTimeHours of [+ 0,+ -1,+ Number.NaN,+ Number.POSITIVE_INFINITY,+ 96.5,+ ]) {+ await expect(+ client.preflight(repository, { mode: "deep", maxTimeHours }),+ ).rejects.toThrow("positive number no greater than 96");+ }+ await expect(+ client.preflight(repository, { mode: "deep", maxTimeHours: 96 }),+ ).resolves.toMatchObject({ maxTimeHours: 96 });expect(runtimeStarted).toBe(false);await client.close();});@@ -2025,6 +2044,7 @@ describe("CodexSecurity orchestration", () => {"subagents = 2","stop_after_no_new = 7","max_discovery_runs = 60",+ "max_time_hours = 48","[other]","enabled = true","",@@ -2067,6 +2087,7 @@ describe("CodexSecurity orchestration", () => {workers: 2,subagents: 0,maxDiscoveryRuns: 10,+ maxTimeHours: 1.5,}),).rejects.toThrow("deep scan settings captured");const configuration = await readFile(@@ -2077,11 +2098,17 @@ describe("CodexSecurity orchestration", () => {expect(configuration).toContain("subagents = 0");expect(configuration).toContain("stop_after_no_new = 7");expect(configuration).toContain("max_discovery_runs = 10");+ expect(configuration).toContain("max_time_hours = 1.5");expect(configuration).toContain("[other]");expect(configuration).toContain("enabled = true");expect(recipe).toMatchObject({mode: "deep",- deepScan: { workers: 2, subagents: 0, maxDiscoveryRuns: 10 },+ deepScan: {+ workers: 2,+ subagents: 0,+ maxDiscoveryRuns: 10,+ maxTimeHours: 1.5,+ },});await client.close();});@@ -3341,6 +3368,143 @@ describe("CodexSecurity orchestration", () => {await client.close();});+ test.each(["partial", "invalid", "unavailable"] as const)(+ "recovers exhausted deep-scan budget when completion is %s",+ async (completion) => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "codex-home");+ const scanDir = join(root, "scan");+ await Promise.all([+ mkdir(repository),+ mkdir(codexHome),+ mkdir(scanDir, { mode: 0o700 }),+ ]);+ const commands: Array<readonly string[]> = [];+ const warnings: string[] = [];+ let turns = 0;+ const client = new TestClient(+ {},+ {+ environment: {},+ prepareRuntime: async () => preparedRuntime(codexHome),+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ runWorkbench: async (_options: unknown, args: readonly string[]) => {+ commands.push(args);+ if (args[0] !== "complete-budget-exhausted-scan") {+ return mockWorkbench(args);+ }+ if (completion === "unavailable") {+ throw new Error("Deep Scan discovery has not completed.");+ }+ await copyCompletedScan(root);+ const coveragePath = join(scanDir, "coverage.json");+ const coverage = JSON.parse(await readFile(coveragePath, "utf8"));+ coverage.mode = "deep_repository";+ coverage.completeness =+ completion === "invalid" ? "complete" : "partial";+ if (completion === "partial") {+ coverage.deferred.push({+ id: "budget-exhausted",+ reason: "The scan reached its configured cost limit.",+ });+ }+ const coverageBytes = `${JSON.stringify(coverage)}\n`;+ await writeFile(coveragePath, coverageBytes);+ const manifestPath = join(scanDir, "scan-manifest.json");+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));+ const artifact = manifest.scan.artifacts.find(+ (item: { path: string }) => item.path === "coverage.json",+ );+ artifact.sha256 = createHash("sha256")+ .update(coverageBytes)+ .digest("hex");+ await writeFile(manifestPath, `${JSON.stringify(manifest)}\n`);+ return {+ scan: { warnings: [args[args.indexOf("--message") + 1]] },+ };+ },+ createCodex: () => ({+ startThread: () => ({+ id: null,+ async runStreamed(+ _input: string,+ options: { signal: AbortSignal },+ ) {+ turns += 1;+ async function* events(): AsyncGenerator<ThreadEvent> {+ yield { type: "thread.started", thread_id: "scan-thread" };+ await writeUsageSession(codexHome, "scan-thread", {+ input_tokens: 1_250,+ cached_input_tokens: 200,+ output_tokens: 30,+ });+ await new Promise<void>((resolve) => {+ if (options.signal.aborted) resolve();+ else {+ options.signal.addEventListener(+ "abort",+ () => resolve(),+ {+ once: true,+ },+ );+ }+ });+ throw new DOMException("aborted", "AbortError");+ }+ return { events: events() };+ },+ }),+ }),+ },+ );+ const keepAlive = setTimeout(() => {}, 10_000);+ try {+ const result = client.run(repository, {+ mode: "deep",+ maxCostUsd: 0.005,+ postScanPrompt: "Do not spend another model turn.",+ onWarning: (warning) => warnings.push(warning),+ signal: AbortSignal.timeout(5_000),+ });+ if (completion === "unavailable" || completion === "invalid") {+ await expect(result).rejects.toBeInstanceOf(+ ScanCostLimitExceededError,+ );+ if (completion === "unavailable") {+ expect(commands.at(-1)?.[0]).toBe("fail-scan");+ } else {+ expect(commands.some((args) => args[0] === "fail-scan")).toBe(+ false,+ );+ }+ } else {+ const recovered = await result;+ expect(recovered.coverage.completeness).toBe(completion);+ expect(recovered.findings.findings).toHaveLength(1);+ expect(recovered.threadId).toBe("scan-thread");+ expect(recovered.cost?.estimatedUsd).toBe(0.00625);+ expect(warnings).toEqual([+ `Scan stopped: estimated cost $0.00625 exceeded the $0.005 limit; partial output remains at ${scanDir}.`,+ ]);+ expect(commands.some((args) => args[0] === "fail-scan")).toBe(false);+ }+ expect(turns).toBe(1);+ const recovery = commands.find(+ (args) => args[0] === "complete-budget-exhausted-scan",+ );+ expect(recovery?.includes("--cost-json")).toBe(true);+ expect(recovery?.includes("--message")).toBe(true);+ } finally {+ clearTimeout(keepAlive);+ await client.close();+ }+ },+ );+test("saves a budgeted scan with a warning when token usage is unavailable", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");@@ -4324,7 +4488,7 @@ describe("CodexSecurity orchestration", () => {...Array.from({ length: 1024 },(_, index) =>- `scope-${String(index).padStart(4, "0")}-${"a".repeat(120)}.ts`,+ `scope-${String(index).padStart(4, "0")}-${"a".repeat(115)}.ts`,),);await mkdir(repository);diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.tsindex c4e3b93cd..775bf7de9 100644--- a/sdk/typescript/tests-ts/cli-workbench.test.ts+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts@@ -698,6 +698,7 @@ describe("CLI workbench", () => {subagents: 0,stopAfterNoNew: 3,maxDiscoveryRuns: 10,+ maxTimeHours: 1.5,},config: savedConfig,},@@ -718,6 +719,7 @@ describe("CLI workbench", () => {subagents: 0,stopAfterNoNew: 3,maxDiscoveryRuns: 10,+ maxTimeHours: 1.5,});const references: Array<[JsonObject, ReturnType<typeof DiffTarget.refs>]> =diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex a1b3642b9..6df445e48 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -117,6 +117,7 @@ describe("CLI", () => {subagents: { type: "integer" },stopAfterNoNew: { type: "integer" },maxDiscoveryRuns: { type: "integer" },+ maxTimeHours: { type: "number", maximum: 96 },model: { type: "string" },verbose: { type: "boolean" },effort: { enum: ["minimal", "low", "medium", "high", "xhigh"] },@@ -334,6 +335,7 @@ describe("CLI", () => {"[deep_scan]","stop_after_no_new","max_discovery_runs",+ "max_time_hours",]) {expect(readme).toContain(setting);}@@ -397,6 +399,7 @@ describe("CLI", () => {subagents: number;stopAfterNoNew: number;maxDiscoveryRuns: number;+ maxTimeHours: number;};expect(defaults.workers).toBe(6);expect(readme).toContain('workers = "auto"');@@ -407,6 +410,7 @@ describe("CLI", () => {expect(readme).toContain(`max_discovery_runs = ${defaults.maxDiscoveryRuns}`,);+ expect(readme).toContain(`max_time_hours = ${defaults.maxTimeHours}`);} finally {await rm(root, { recursive: true, force: true });}@@ -1921,6 +1925,7 @@ describe("CLI", () => {expect(help.text()).toContain("--subagents <number>");expect(help.text()).toContain("--stop-after-no-new <number>");expect(help.text()).toContain("--max-discovery-runs <number>");+ expect(help.text()).toContain("--max-time-hours <number>");expect(help.text()).toContain("--headless");expect(help.text()).toContain("Use plain text progress instead of the interactive dashboard.",@@ -2135,6 +2140,8 @@ describe("CLI", () => {"3","--max-discovery-runs","10",+ "--max-time-hours",+ "1.5","--plugin-path","plugin.zip","--python=/managed/python",@@ -2159,6 +2166,7 @@ describe("CLI", () => {subagents: 0,stopAfterNoNew: 3,maxDiscoveryRuns: 10,+ maxTimeHours: 1.5,});expect(pathConfig).toMatchObject({pluginPath: "plugin.zip",@@ -2292,6 +2300,10 @@ describe("CLI", () => {["scan", ".", "--workers", "2"],"Deep scan settings require --mode deep",],+ [+ ["scan", ".", "--max-time-hours", "1.5"],+ "Deep scan settings require --mode deep",+ ],[["scan", ".", "--mode", "deep", "--workers", "0"],"expected number to be >0",@@ -2308,6 +2320,14 @@ describe("CLI", () => {["scan", ".", "--mode", "deep", "--max-discovery-runs", "0"],"expected number to be >0",],+ [+ ["scan", ".", "--mode", "deep", "--max-time-hours", "0"],+ "expected number to be >0",+ ],+ [+ ["scan", ".", "--mode", "deep", "--max-time-hours", "96.5"],+ "expected number to be <=96",+ ],[["scan", ".", "--path="], "--path must not be empty"],[["bulk-scan", "--knowledge-base="],@@ -2337,6 +2357,10 @@ describe("CLI", () => {[["scan", ".", "--effort", "--dry-run"], "Missing value for flag"],[["scan", ".", "--output-dir", "--dry-run"], "Missing value for flag"],[["scan", ".", "--max-cost", "--dry-run"], "Missing value for flag"],+ [+ ["scan", ".", "--max-time-hours", "--dry-run"],+ "Missing value for flag",+ ],[["scan", "repo-a", "repo-b", "--dry-run"], "Unexpected positional"],[["findings", "false-positive"], "occurrenceId"],[["findings", "false-positive", "occurrence-1"], "reason"],diff --git a/sdk/typescript/tests-ts/deep-scan-workbench.test.ts b/sdk/typescript/tests-ts/deep-scan-workbench.test.tsindex 56c399c25..65b6312bd 100644--- a/sdk/typescript/tests-ts/deep-scan-workbench.test.ts+++ b/sdk/typescript/tests-ts/deep-scan-workbench.test.ts@@ -93,6 +93,569 @@ function runOwnershipProbe(probe: OwnershipProbe): Record<string, unknown> {}describe("deep scan workbench ownership", () => {+ test.each([+ [undefined, 96],+ [0.5, 0.5],+ [96, 96],+ ] as const)(+ "resolves the configured discovery deadline %s as %s hours",+ async (configuredHours, expectedHours) => {+ const root = await realpath(+ await mkdtemp(join(tmpdir(), "codex-security-deep-deadline-config-")),+ );+ temporaryDirectories.push(root);+ const codexHome = join(root, "codex-home");+ const configDirectory = join(codexHome, "codex-security");+ await mkdir(configDirectory, { recursive: true });+ await writeFile(+ join(configDirectory, "config.toml"),+ `[deep_scan]\n${configuredHours === undefined ? "" : `max_time_hours = ${configuredHours}\n`}`,+ );++ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const result = Bun.spawnSync(+ [+ python!,+ "-I",+ "-B",+ join(PLUGIN_ROOT, "scripts", "deep_scan_config.py"),+ "--available-parallelism",+ "8",+ ],+ {+ env: { ...process.env, CODEX_HOME: codexHome },+ stdout: "pipe",+ stderr: "pipe",+ },+ );+ expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);+ expect(JSON.parse(new TextDecoder().decode(result.stdout))).toMatchObject(+ {+ maxTimeHours: expectedHours,+ },+ );+ },+ );++ test("rejects invalid discovery deadlines before returning scan configuration", async () => {+ const root = await realpath(+ await mkdtemp(join(tmpdir(), "codex-security-deep-invalid-deadline-")),+ );+ temporaryDirectories.push(root);+ const codexHome = join(root, "codex-home");+ const configDirectory = join(codexHome, "codex-security");+ const configPath = join(configDirectory, "config.toml");+ await mkdir(configDirectory, { recursive: true });+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();++ for (const hours of ["0", "-0.5", "true", '"2"', "nan", "inf", "96.5"]) {+ await writeFile(configPath, `[deep_scan]\nmax_time_hours = ${hours}\n`);+ const result = Bun.spawnSync(+ [+ python!,+ "-I",+ "-B",+ join(PLUGIN_ROOT, "scripts", "deep_scan_config.py"),+ "--available-parallelism",+ "8",+ ],+ {+ env: { ...process.env, CODEX_HOME: codexHome },+ stdout: "pipe",+ stderr: "pipe",+ },+ );+ expect(result.exitCode).not.toBe(0);+ expect(new TextDecoder().decode(result.stderr)).toContain(+ "deep_scan.max_time_hours must be a positive finite number no greater than 96",+ );+ }+ });++ test.each([false, true] as const)(+ "backfills and repairs discovery deadline migration when already recorded: %s",+ (migrationRecorded) => {+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const script = [+ "import json, runpy, sqlite3, sys",+ "from unittest import mock",+ "namespace = runpy.run_path(sys.argv[1], run_name='codex_security_workbench_db')",+ "apply_migrations = namespace['apply_migrations']",+ "connection = sqlite3.connect(':memory:')",+ "connection.row_factory = sqlite3.Row",+ "historical = tuple(item for item in namespace['MIGRATIONS'] if item[0] < 28)",+ "with mock.patch.dict(apply_migrations.__globals__, {'MIGRATIONS': historical}):",+ " apply_migrations(connection)",+ "timestamp = '2026-07-01T00:00:00Z'",+ "connection.execute('INSERT INTO workspaces (id, created_at, updated_at) VALUES (?, ?, ?)', ('legacy-workspace', timestamp, timestamp))",+ "connection.execute(\"INSERT INTO scans (id, workspace_id, target_path, target_revision, scope, mode, scan_dir, status, phase, started_at, created_at, updated_at) VALUES (?, ?, '/legacy/target', 'legacy-revision', '.', 'deep', '/legacy/scan', 'running', 'discovery', ?, ?, ?)\", ('legacy-scan', 'legacy-workspace', timestamp, timestamp, timestamp))",+ "connection.execute(\"INSERT INTO deep_scan_runs (scan_id, schema_version, workflow_version, status, phase, workers, subagents, stop_after_no_new, max_discovery_runs, created_at, updated_at) VALUES (?, 1, 'legacy-workflow', 'running', 'discovery', 1, 0, 3, 10, ?, ?)\", ('legacy-scan', timestamp, timestamp))",+ "if sys.argv[2] == 'true':",+ " connection.execute('INSERT INTO schema_migrations (version, name, applied_at) VALUES (28, ?, ?)', ('persist deep scan discovery time limit', timestamp))",+ "connection.commit()",+ "apply_migrations(connection)",+ "default = connection.execute('SELECT max_time_hours FROM deep_scan_runs').fetchone()[0]",+ "connection.execute('UPDATE deep_scan_runs SET max_time_hours = 2.5')",+ "connection.commit()",+ "apply_migrations(connection)",+ "configured = connection.execute('SELECT max_time_hours FROM deep_scan_runs').fetchone()[0]",+ "migration = connection.execute('SELECT name FROM schema_migrations WHERE version = 28').fetchone()[0]",+ "print(json.dumps({'default': default, 'configured': configured, 'migration': migration}))",+ ].join("\n");+ const result = Bun.spawnSync(+ [+ python!,+ "-I",+ "-B",+ "-c",+ script,+ join(PLUGIN_ROOT, "scripts", "workbench_db.py"),+ String(migrationRecorded),+ ],+ { stdout: "pipe", stderr: "pipe" },+ );+ expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);+ expect(JSON.parse(new TextDecoder().decode(result.stdout))).toEqual({+ default: 96,+ configured: 2.5,+ migration: "persist deep scan discovery time limit",+ });+ },+ );++ test.each([+ ["repository", false],+ ["scoped_path", false],+ ["repository", true],+ ] as const)(+ "returns an honest partial %s report with existing deferred work %s when saturated discovery exceeds its cost limit",+ async (inventoryStrategy, existingDeferred) => {+ const root = await realpath(+ await mkdtemp(join(tmpdir(), "codex-security-deep-budget-recovery-")),+ );+ temporaryDirectories.push(root);+ const repository = join(root, "repository");+ const scanDir = join(root, "scan");+ const stateDir = join(root, "state");+ await mkdir(join(repository, "src"), { recursive: true });+ await mkdir(join(repository, "shared"), { recursive: true });+ await mkdir(scanDir, { mode: 0o700 });+ await writeFile(+ join(repository, "src", "source.py"),+ "# source fixture\n",+ );+ await writeFile(+ join(repository, "shared", "support.py"),+ "# supporting context\n",+ );+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();++ const command = (args: string[]): Record<string, unknown> => {+ const result = Bun.spawnSync(+ [+ python!,+ "-I",+ "-B",+ join(PLUGIN_ROOT, "scripts", "workbench_db.py"),+ ...args,+ ],+ {+ env: { ...process.env, CODEX_SECURITY_STATE_DIR: stateDir },+ stdout: "pipe",+ stderr: "pipe",+ },+ );+ expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(+ 0,+ );+ return JSON.parse(new TextDecoder().decode(result.stdout)) as Record<+ string,+ unknown+ >;+ };+ const scoped = inventoryStrategy === "scoped_path";+ const registration = command([+ "register-cli-scan",+ "--repository",+ repository,+ "--scan-dir",+ scanDir,+ "--recipe-json",+ JSON.stringify({+ config: {},+ mode: "deep",+ repository,+ target: {+ kind: scoped ? "paths" : "repository",+ paths: scoped ? ["src"] : [],+ },+ maxCostUsd: 10,+ }),+ ]);+ const scanId = registration["scanId"] as string;+ const targetId = registration["targetId"] as string;+ command([+ "begin-deep-scan",+ "--scan-id",+ scanId,+ "--thread-id",+ "budget-recovery-thread",+ "--scan-root",+ join(root, "scans"),+ "--available-parallelism",+ "4",+ "--workflow-version",+ "deep-scan-mcp/v1",+ ]);+ const discoveryDir = join(scanDir, "artifacts", "02_discovery");+ await mkdir(discoveryDir, { recursive: true });+ await writeFile(+ join(discoveryDir, "in_scope_files.txt"),+ "src/source.py\n",+ );+ const candidateLocations = [+ { path: "src/source.py", start_line: 1, end_line: 1, role: "sink" },+ ...(scoped+ ? [+ {+ path: "shared/support.py",+ start_line: 1,+ end_line: 1,+ role: "evidence",+ },+ ]+ : []),+ ];+ const candidates = [+ {+ candidate_id: "candidate-001",+ cwe_ids: ["CWE-862"],+ locations: candidateLocations,+ summary: "Possible missing authorization",+ evidence: "The request reaches a protected handler.",+ },+ {+ candidate_id: "candidate-suppressed",+ cwe_ids: ["CWE-862"],+ locations: candidateLocations,+ summary: "Authorization guard already protects the handler",+ evidence: "The request is rejected by the existing policy.",+ validation: { disposition: "suppressed" },+ },+ {+ candidate_id: "candidate-not-applicable",+ cwe_ids: ["CWE-862"],+ locations: candidateLocations,+ summary: "Handler cannot receive external requests",+ evidence: "The handler is only reachable from trusted callers.",+ validation: { disposition: "not_applicable" },+ },+ {+ candidate_id: "candidate-ignored",+ cwe_ids: ["CWE-862"],+ locations: candidateLocations,+ summary: "Attack path does not cross the trust boundary",+ evidence: "An attacker cannot reach the authorization sink.",+ validation: { disposition: "reportable" },+ attack_path: { decision: "ignore" },+ },+ {+ candidate_id: "candidate-deferred",+ cwe_ids: ["CWE-862"],+ locations: candidateLocations,+ summary: "Authorization proof needs runtime evidence",+ evidence: "The runtime permission policy could not be inspected.",+ validation: {+ disposition: "deferred",+ remaining_uncertainty:+ "Runtime policy configuration is unavailable.",+ },+ attack_path: { decision: "ignore" },+ },+ ];+ await writeFile(+ join(discoveryDir, "candidate_ledger.jsonl"),+ `${candidates.map((candidate) => JSON.stringify(candidate)).join("\n")}\n`,+ );+ const terminalManifest = join(scanDir, "coordinator-manifest.json");+ await writeFile(terminalManifest, "{}\n");+ const terminal = Bun.spawnSync(+ [+ python!,+ "-I",+ "-B",+ "-c",+ "import sqlite3,sys; connection=sqlite3.connect(sys.argv[1]); connection.execute(\"UPDATE deep_scan_runs SET status='succeeded', phase='terminal', terminal_reason='saturated', manifest_path=? WHERE scan_id=?\",sys.argv[2:]); connection.commit()",+ join(stateDir, "workbench.sqlite3"),+ terminalManifest,+ scanId,+ ],+ { stdout: "pipe", stderr: "pipe" },+ );+ expect(terminal.exitCode, new TextDecoder().decode(terminal.stderr)).toBe(+ 0,+ );+ if (existingDeferred) {+ await Promise.all([+ writeFile(+ join(scanDir, "scan-manifest.json"),+ JSON.stringify({+ scan: {+ target: {+ kind: "directory_snapshot",+ targetId,+ displayName: "repository",+ },+ scope: { limitations: [], validationMode: "incomplete" },+ },+ }),+ ),+ writeFile(+ join(scanDir, "findings.json"),+ JSON.stringify({ findings: [] }),+ ),+ writeFile(+ join(scanDir, "coverage.json"),+ JSON.stringify({+ completeness: "partial",+ inventoryStrategy,+ surfaces: [],+ explicitExclusions: [],+ deferred: [+ {+ id: "candidate-001",+ candidateId: "candidate-001",+ reason:+ "Existing candidate validation dependency was unavailable.",+ paths: ["src/source.py"],+ },+ {+ id: "candidate-deferred",+ candidateId: "candidate-deferred",+ reason: "Existing runtime policy could not be inspected.",+ paths: ["src/source.py"],+ },+ ],+ }),+ ),+ ]);+ }+ const warning =+ "Scan stopped: estimated cost $10.08 exceeded the $10.00 limit.";+ const completed = command([+ "complete-budget-exhausted-scan",+ "--scan-id",+ scanId,+ "--cost-json",+ JSON.stringify({+ model: "gpt-5.6-sol",+ inputTokens: 1_000,+ cachedInputTokens: 0,+ cacheWriteInputTokens: 0,+ outputTokens: 100,+ estimatedUsd: 10.08,+ }),+ "--message",+ warning,+ ]);+ const scan = completed["scan"] as {+ progress: { status: string };+ warnings: string[];+ };+ expect(scan.progress.status).toBe("complete");+ expect(scan.warnings).toContain(warning);+ const findings = JSON.parse(+ await readFile(join(scanDir, "findings.json"), "utf8"),+ ) as { findings: unknown[] };+ expect(findings.findings).toEqual([]);+ const coverage = JSON.parse(+ await readFile(join(scanDir, "coverage.json"), "utf8"),+ ) as {+ completeness: string;+ inventoryStrategy: string;+ includePaths: string[];+ deferred: Array<{+ id: string;+ candidateId?: string;+ reason: string;+ paths?: string[];+ }>;+ surfaces: Array<{ id: string; disposition: string }>;+ };+ expect(coverage).toMatchObject({+ completeness: "partial",+ inventoryStrategy,+ includePaths: scoped ? ["src"] : ["."],+ });+ if (existingDeferred) {+ expect(coverage.deferred).toEqual([+ {+ id: "candidate-001",+ candidateId: "candidate-001",+ reason: "Existing candidate validation dependency was unavailable.",+ paths: ["src/source.py"],+ },+ {+ id: "candidate-deferred",+ candidateId: "candidate-deferred",+ reason: "Existing runtime policy could not be inspected.",+ paths: ["src/source.py"],+ },+ {+ id: "scan-cost-limit",+ reason:+ "Validation was deferred because the scan reached its cost limit.",+ },+ ]);+ } else {+ expect(coverage.deferred).toEqual([+ expect.objectContaining({+ id: "candidate-001",+ reason: expect.stringContaining("Possible missing authorization"),+ paths: scoped+ ? ["src/source.py", "shared/support.py"]+ : ["src/source.py"],+ }),+ expect.objectContaining({+ id: "candidate-deferred",+ reason: expect.stringContaining(+ "Authorization proof needs runtime evidence",+ ),+ paths: scoped+ ? ["src/source.py", "shared/support.py"]+ : ["src/source.py"],+ }),+ ]);+ }+ expect(coverage.surfaces).toEqual(+ expect.arrayContaining([+ ...(existingDeferred+ ? []+ : [+ expect.objectContaining({+ id: "candidate-candidate-001",+ disposition: "needs_follow_up",+ }),+ ]),+ expect.objectContaining({+ id: "candidate-candidate-suppressed",+ disposition: "rejected",+ }),+ expect.objectContaining({+ id: "candidate-candidate-not-applicable",+ disposition: "not_applicable",+ }),+ expect.objectContaining({+ id: "candidate-candidate-ignored",+ disposition: "rejected",+ }),+ ...(existingDeferred+ ? []+ : [+ expect.objectContaining({+ id: "candidate-candidate-deferred",+ disposition: "needs_follow_up",+ }),+ ]),+ ]),+ );+ const report = await readFile(join(scanDir, "report.md"), "utf8");+ expect(report).toContain(+ "No findings were validated before the scan reached its cost limit.",+ );+ if (existingDeferred) {+ expect(report).toContain(+ "Existing candidate validation dependency was unavailable.",+ );+ expect(report).toContain(+ "Existing runtime policy could not be inspected.",+ );+ } else {+ expect(report).toContain("Possible missing authorization");+ expect(report).toContain("The request reaches a protected handler.");+ }+ expect(report).toContain(+ "Authorization guard already protects the handler",+ );+ expect(report).toContain("Handler cannot receive external requests");+ expect(report).toContain("Attack path does not cross the trust boundary");+ expect(report).not.toContain(+ "No reportable findings survived the canonical discovery, validation",+ );+ },+ );++ test.each([+ [+ "a deferred discovery candidate",+ "Validation was deferred because the scan reached its cost limit: candidate evidence.",+ true,+ ],+ [+ "a cost-limited scan without candidates",+ "Validation was deferred because the scan reached its cost limit.",+ true,+ ],+ [+ "an unrelated retry budget",+ "The retry budget was exhausted while checking the service.",+ false,+ ],+ [+ "an unrelated resource budget",+ "Validation exceeded the container resource budget.",+ false,+ ],+ [+ "an unrelated service cost limit",+ "A dependent service reached its configured cost limit.",+ false,+ ],+ [+ "a similar non-workbench cost limit",+ "Validation was deferred because the scan reached its cost limit elsewhere.",+ false,+ ],+ ] as const)(+ "only describes an exhausted scan cost limit for %s",+ (_description, reason, exhausted) => {+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const script = [+ "import json, pathlib, runpy, sys",+ "plugin = pathlib.Path(sys.argv[1])",+ "examples = plugin / 'examples' / 'completed-scan'",+ "documents = [json.loads((examples / name).read_text()) for name in ('scan-manifest.json', 'findings.json', 'coverage.json')]",+ "manifest, findings, coverage = documents",+ "findings['findings'] = []",+ "coverage['completeness'] = 'partial'",+ "coverage['deferred'] = [{'id': 'candidate-example', 'reason': sys.argv[2]}]",+ "projection = runpy.run_path(str(plugin / 'scripts' / 'report_projection.py'))",+ "print(projection['build_report_markdown'](manifest, findings, coverage))",+ ].join("\n");+ const result = Bun.spawnSync(+ [python!, "-I", "-B", "-c", script, PLUGIN_ROOT, reason],+ { stdout: "pipe", stderr: "pipe" },+ );+ expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);+ const report = new TextDecoder().decode(result.stdout);+ expect(+ report.includes(+ "No findings were validated before the scan reached its cost limit.",+ ),+ ).toBe(exhausted);+ expect(+ report.includes(+ "No reportable findings survived the canonical discovery, validation, and reportability gates.",+ ),+ ).toBe(!exhausted);+ },+ );+test.each([["a malformed continuation token", null, "not-a-valid-token"],["an unexpected token for a legacy delivery", null, originalClaimToken],@@ -353,7 +916,199 @@ describe("deep scan workbench ownership", () => {expect(staleProgress["stderr"]).toContain("newer generation");});- test("requeues a failed reducer's inputs and completes without losing findings", async () => {+ test("completes an expired discovery deadline with no workers as honest partial coverage", async () => {+ const root = await realpath(+ await mkdtemp(join(tmpdir(), "codex-security-deep-empty-deadline-")),+ );+ temporaryDirectories.push(root);+ const repository = join(root, "repository");+ const scanDir = join(root, "scan");+ const stateDir = join(root, "state");+ const codexHome = join(root, "codex-home");+ const configDir = join(codexHome, "codex-security");+ await Promise.all([+ mkdir(repository),+ mkdir(scanDir, { mode: 0o700 }),+ mkdir(configDir, { recursive: true }),+ ]);+ await Promise.all([+ writeFile(join(repository, "source.py"), "# source fixture\n"),+ writeFile(+ join(configDir, "config.toml"),+ "[deep_scan]\nworkers = 1\nmax_discovery_runs = 3\nmax_time_hours = 0.5\n",+ ),+ ]);++ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const command = (args: string[]): Record<string, unknown> => {+ const result = Bun.spawnSync(+ [+ python!,+ "-I",+ "-B",+ join(PLUGIN_ROOT, "scripts", "workbench_db.py"),+ ...args,+ ],+ {+ env: {+ ...process.env,+ CODEX_SECURITY_STATE_DIR: stateDir,+ CODEX_HOME: codexHome,+ },+ stdout: "pipe",+ stderr: "pipe",+ },+ );+ expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);+ return JSON.parse(new TextDecoder().decode(result.stdout)) as Record<+ string,+ unknown+ >;+ };+ const registration = command([+ "register-cli-scan",+ "--repository",+ repository,+ "--scan-dir",+ scanDir,+ "--recipe-json",+ JSON.stringify({+ config: {},+ mode: "deep",+ repository,+ target: { kind: "repository", paths: [] },+ }),+ ]);+ const scanId = registration["scanId"] as string;+ const targetId = registration["targetId"] as string;+ const begun = command([+ "begin-deep-scan",+ "--scan-id",+ scanId,+ "--thread-id",+ "empty-deadline-thread",+ "--scan-root",+ join(root, "scans"),+ "--available-parallelism",+ "4",+ "--workflow-version",+ "deep-scan-mcp/v1",+ ])["deepScan"] as Record<string, unknown>;+ expect(begun).toMatchObject({+ status: "running",+ completionSequence: 0,+ canonicalArtifacts: null,+ config: { maxTimeHours: 0.5 },+ });++ const discoveryDir = join(scanDir, "artifacts", "02_discovery");+ await mkdir(discoveryDir, { recursive: true });+ const ledgerPath = join(discoveryDir, "candidate_ledger.jsonl");+ const inventoryPath = join(discoveryDir, "in_scope_files.txt");+ const manifestPath = join(scanDir, "coordinator-manifest.json");+ await Promise.all([+ writeFile(ledgerPath, ""),+ writeFile(inventoryPath, "source.py\n"),+ writeFile(manifestPath, "{}\n"),+ ]);+ const expired = Bun.spawnSync(+ [+ python!,+ "-I",+ "-B",+ "-c",+ [+ "import sqlite3, sys",+ "connection = sqlite3.connect(sys.argv[1])",+ "connection.execute('UPDATE deep_scan_runs SET created_at = ? WHERE scan_id = ?', ('2000-01-01T00:00:00+00:00', sys.argv[2]))",+ "connection.commit()",+ ].join("\n"),+ join(stateDir, "workbench.sqlite3"),+ scanId,+ ],+ { stdout: "pipe", stderr: "pipe" },+ );+ expect(expired.exitCode, new TextDecoder().decode(expired.stderr)).toBe(0);++ const capped = command([+ "finish-deep-scan",+ "--scan-id",+ scanId,+ "--terminal-reason",+ "capped",+ "--manifest-path",+ manifestPath,+ ])["deepScan"] as Record<string, unknown>;+ expect(capped).toMatchObject({+ status: "succeeded",+ terminalReason: "capped",+ completionSequence: 0,+ workers: [],+ canonicalArtifacts: {+ candidateLedgerPath: ledgerPath,+ inScopeFilesPath: inventoryPath,+ },+ });+ expect(await readFile(ledgerPath, "utf8")).toBe("");++ const reason =+ "The configured discovery time limit elapsed before any source review completed.";+ await Promise.all([+ writeFile(+ join(scanDir, "scan-manifest.json"),+ JSON.stringify({+ scan: {+ target: {+ kind: "directory_snapshot",+ targetId,+ displayName: "repository",+ },+ scope: { limitations: [], validationMode: "incomplete" },+ },+ }),+ ),+ writeFile(+ join(scanDir, "findings.json"),+ JSON.stringify({ findings: [] }),+ ),+ writeFile(+ join(scanDir, "coverage.json"),+ JSON.stringify({+ completeness: "partial",+ inventoryStrategy: "repository",+ surfaces: [],+ explicitExclusions: [],+ deferred: [{ id: "source-review", reason }],+ }),+ ),+ ]);+ const completed = command(["complete-scan", "--scan-id", scanId])[+ "scan"+ ] as {+ progress: { status: string };+ findings: unknown[];+ };+ expect(completed.progress.status).toBe("complete");+ expect(completed.findings).toEqual([]);+ const coverage = JSON.parse(+ await readFile(join(scanDir, "coverage.json"), "utf8"),+ );+ expect(coverage).toMatchObject({+ completeness: "partial",+ mode: "deep_repository",+ deferred: [{ id: "source-review", reason }],+ });+ const report = await readFile(join(scanDir, "report.md"), "utf8");+ expect(report).toContain(+ "No source review completed before the configured time limit. " ++ "No vulnerability conclusion can be drawn.",+ );+ expect(report).not.toContain("No reportable findings survived");+ expect(report).not.toContain("No findings were validated before");+ });++ test("requeues a failed reducer's inputs and preserves findings at the discovery deadline", async () => {const root = await realpath(await mkdtemp(join(tmpdir(), "codex-security-deep-reducer-recovery-")),);@@ -367,7 +1122,7 @@ describe("deep scan workbench ownership", () => {await writeFile(join(repository, "source.py"), "# source fixture\n");await writeFile(join(configDir, "config.toml"),- "[deep_scan]\nworkers = 3\nmax_discovery_runs = 5\n",+ "[deep_scan]\nworkers = 3\nmax_discovery_runs = 6\nmax_time_hours = 0.5\n",);const python = Bun.which("python3") ?? Bun.which("python");@@ -416,6 +1171,10 @@ describe("deep scan workbench ownership", () => {);const scanId = initial["scanId"] as string;const scanDir = initial["scanDir"] as string;+ expect(initial["config"]).toMatchObject({+ maxDiscoveryRuns: 6,+ maxTimeHours: 0.5,+ });const discoveryDir = join(scanDir, "artifacts", "02_discovery");const ledgerPath = join(discoveryDir, "candidate_ledger.jsonl");const existingFinding = '{"candidate":"previously committed"}\n';@@ -604,6 +1363,55 @@ describe("deep scan workbench ownership", () => {const manifestPath = join(scanDir, "coordinator-manifest.json");await writeFile(manifestPath, "{}\n");+ const premature = Bun.spawnSync(+ [+ python!,+ "-I",+ "-B",+ join(PLUGIN_ROOT, "scripts", "workbench_db.py"),+ "finish-deep-scan",+ "--scan-id",+ scanId,+ "--terminal-reason",+ "capped",+ "--manifest-path",+ manifestPath,+ ],+ {+ env: {+ ...process.env,+ CODEX_SECURITY_STATE_DIR: stateDir,+ CODEX_HOME: codexHome,+ },+ stdout: "pipe",+ stderr: "pipe",+ },+ );+ expect(premature.exitCode).not.toBe(0);+ expect(new TextDecoder().decode(premature.stderr)).toContain(+ "before reaching its configured maximum",+ );+ expect(await readFile(ledgerPath, "utf8")).toBe(existingFinding);++ const expire = Bun.spawnSync(+ [+ python!,+ "-I",+ "-B",+ "-c",+ [+ "import sqlite3, sys",+ "connection = sqlite3.connect(sys.argv[1])",+ "connection.execute('UPDATE deep_scan_runs SET created_at = ? WHERE scan_id = ?', ('2000-01-01T00:00:00+00:00', sys.argv[2]))",+ "connection.commit()",+ ].join("\n"),+ join(stateDir, "workbench.sqlite3"),+ scanId,+ ],+ { stdout: "pipe", stderr: "pipe" },+ );+ expect(expire.exitCode, new TextDecoder().decode(expire.stderr)).toBe(0);+const completed = state(command(["finish-deep-scan",