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(cli): recover interrupted Deep Scans and bulk campaigns (#835)
Soyeon Park9c06032fa79b
diff --git a/plugins/codex-security/scripts/workbench_cli.py b/plugins/codex-security/scripts/workbench_cli.pyindex 63b457d66..5c43d8899 100644--- a/plugins/codex-security/scripts/workbench_cli.py+++ b/plugins/codex-security/scripts/workbench_cli.py@@ -167,6 +167,10 @@ def parse_args(description: str) -> argparse.Namespace:get_scan_recipe = subparsers.add_parser("get-scan-recipe")get_scan_recipe.add_argument("--scan-id", required=True)+ get_cli_scan_resume = subparsers.add_parser("get-cli-scan-resume")+ get_cli_scan_resume.add_argument("--scan-id", required=True)+ get_cli_scan_resume.add_argument("--allow-unavailable", action="store_true")+compare_scans = subparsers.add_parser("compare-scans")compare_scans.add_argument("--before-scan-id", required=True)compare_scans.add_argument("--after-scan-id", required=True)diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.pyindex 22f113211..7decf27c7 100644--- a/plugins/codex-security/scripts/workbench_db.py+++ b/plugins/codex-security/scripts/workbench_db.py@@ -138,6 +138,7 @@ from workbench_validation import (optional_text,parse_scan_cost,path_within_scope,+ reject_non_finite_json,require_close_note,require_occurrence,require_uuid,@@ -503,7 +504,9 @@ def expected_coverage_mode(scan: sqlite3.Row) -> str:return "deep_repository" if scan["mode"] == "deep" else "repository"-def workbench_completion_binding(scan: sqlite3.Row, completed_at: str) -> dict[str, Any]:+def workbench_completion_binding(+ scan: sqlite3.Row, completed_at: str, manifest: dict[str, Any] | None = None+) -> dict[str, Any]:contract = scan_contract(scan)target_contract = contract["target"]plugin_manifest = read_json_object(@@ -532,7 +535,7 @@ def workbench_completion_binding(scan: sqlite3.Row, completed_at: str) -> dict[s"excludePaths": contract["scope"]["requiredExcludePaths"],}- return {+ binding: dict[str, Any] = {"scanId": scan["id"],"startedAt": scan["started_at"],"completedAt": completed_at,@@ -542,6 +545,7 @@ def workbench_completion_binding(scan: sqlite3.Row, completed_at: str) -> dict[s"scope": scope,"coverageMode": expected_coverage_mode(scan),}+ return scan_history.preserve_sealed_completion(binding, manifest)def verify_manifest_binding(scan: sqlite3.Row, manifest: dict[str, Any]) -> None:@@ -1484,8 +1488,8 @@ def complete_scan_locked(add_warning()scan_dir = require_canonical_scan_directory(Path(scan["scan_dir"]))completion_timestamp = now()- completion_binding = workbench_completion_binding(scan, completion_timestamp)current_manifest_path = artifact_path(scan_dir, ARTIFACTS["manifest"], required=False)+ current_manifest = Noneif current_manifest_path is not None:current_manifest = read_json_object(current_manifest_path)if (@@ -1503,8 +1507,8 @@ def complete_scan_locked(or current_manifest["scan"].get("artifacts") is not None))+ completion_binding = workbench_completion_binding(scan, completion_timestamp, current_manifest)if scan["recipe_json"] is not None:- draft_artifacts: dict[str, Path] = {}missing_drafts = []for file_name in (ARTIFACTS["manifest"],@@ -1516,20 +1520,13 @@ def complete_scan_locked(except FileNotFoundError:missing_drafts.append(file_name)continue- draft_path = artifact_path(scan_dir, file_name, required=True)- if draft_path is not None:- draft_artifacts[file_name] = draft_path+ artifact_path(scan_dir, file_name, required=True)if missing_drafts:raise SystemExit("Scan agent did not create required draft artifacts: "f"{', '.join(missing_drafts)}. Check that the scan agent can run shell ""commands and write to the scan directory before retrying.")- manifest = read_json_object(draft_artifacts[ARTIFACTS["manifest"]])- manifest_scan = manifest.get("scan")- if isinstance(manifest_scan, dict) and manifest_scan.get("sealedAt") is not None:- completion_binding["startedAt"] = manifest_scan.get("startedAt")- completion_binding["completedAt"] = manifest_scan.get("completedAt")wrote = Falsetry:prepared = _prepare_scan_finalization(@@ -1558,7 +1555,11 @@ def complete_scan_locked(wrote = Truemanifest, findings, _ = _write_prepared_scan_finalization(prepared)except ContractError as exc:- if wrote or (scan["mode"] == "deep" and not isinstance(exc, RecoverableContractError)):+ if wrote or (+ scan["mode"] == "deep"+ and not already_sealed+ and not isinstance(exc, RecoverableContractError)+ ):args = argparse.Namespace(claim_token=claim_token, cost_json=cost_json)args.message, args.scan_id = str(exc), scan_idfail_scan_locked(connection, args)@@ -1869,17 +1870,6 @@ def parse_scan_recipe(value: str, repository: Path) -> dict[str, Any]:return recipe-def get_scan_recipe(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:- scan = require_scan(connection, args.scan_id)- if scan["recipe_json"] is None:- raise SystemExit("This scan does not have a saved launch recipe.")- return {- "parentScanId": scan["parent_scan_id"],- "recipe": json.loads(scan["recipe_json"], parse_constant=reject_non_finite_json),- "scanId": scan["id"],- }--_WORKBENCH_DB_CONTEXT: saved_results.WorkbenchDbContext@@ -3376,10 +3366,6 @@ def read_json_object(path: Path) -> dict[str, Any]:return payload-def reject_non_finite_json(value: str) -> None:- raise ValueError(f"non-finite JSON number {value!r} is not supported")--_WORKBENCH_PUBLICATION_CONTEXT = publication.WorkbenchPublicationContext(ARTIFACTS=ARTIFACTS,artifact_path=artifact_path,@@ -3518,7 +3504,25 @@ def main() -> None:elif args.command == "set-scan-cost-limit":result = set_scan_cost_limit(connection, args)elif args.command == "get-scan-recipe":- result = get_scan_recipe(connection, args)+ result = scan_history.scan_recipe(require_scan(connection, args.scan_id))+ elif args.command == "get-cli-scan-resume":+ scan = require_scan(connection, args.scan_id)+ try:+ result = scan_history.cli_scan_resume(+ connection,+ scan,+ require_workspace(connection, scan["workspace_id"]),+ parse_scan_recipe=parse_scan_recipe,+ scan_contract=scan_contract,+ require_scan_directory=require_canonical_scan_directory,+ artifact_path=artifact_path,+ read_json_object=read_json_object,+ workbench_completion_binding=workbench_completion_binding,+ )+ except SystemExit as exc:+ if not args.allow_unavailable:+ raise+ result = {"unavailable": str(exc)}elif args.command == "compare-scans":result = scan_history.compare_scans(connection,diff --git a/plugins/codex-security/scripts/workbench_scan_history.py b/plugins/codex-security/scripts/workbench_scan_history.pyindex 14a40f5c0..fc145bc04 100644--- a/plugins/codex-security/scripts/workbench_scan_history.py+++ b/plugins/codex-security/scripts/workbench_scan_history.py@@ -14,10 +14,125 @@ from urllib.parse import urlsplit# Some plugin hosts launch Python with safe-path isolation enabled.sys.path.insert(0, str(Path(__file__).resolve().parent))+from finalize_scan_contract import ContractError, _prepare_scan_finalizationfrom report_projection import SEVERITY_ORDER-from workbench_constants import FINDINGS_PAGE_MAX+from workbench_constants import ARTIFACTS, FINDINGS_PAGE_MAX+from workbench_scan_start import scan_target_identityfrom workbench_scan_usage import stored_scan_cost_fields-from workbench_target import git_output+from workbench_target import git_output, require_scan_target_identity+from workbench_validation import reject_non_finite_json+++def scan_recipe(scan: sqlite3.Row) -> dict[str, Any]:+ if scan["recipe_json"] is None:+ raise SystemExit("This scan does not have a saved launch recipe.")+ return {+ "parentScanId": scan["parent_scan_id"],+ "recipe": json.loads(scan["recipe_json"], parse_constant=reject_non_finite_json),+ "scanId": scan["id"],+ }+++def preserve_sealed_completion(+ binding: dict[str, Any], manifest: dict[str, Any] | None+) -> dict[str, Any]:+ manifest_scan = manifest.get("scan") if manifest is not None else None+ if isinstance(manifest_scan, dict) and manifest_scan.get("sealedAt") is not None:+ # Keep the original producer; finalization still validates schema, seal and owner.+ binding["startedAt"] = manifest_scan.get("startedAt")+ binding["completedAt"] = manifest_scan.get("completedAt")+ producer = manifest_scan.get("producer")+ if isinstance(producer, dict):+ binding["producer"]["version"] = producer.get("version")+ return binding+++def cli_scan_resume(+ connection: sqlite3.Connection,+ scan: sqlite3.Row,+ workspace: sqlite3.Row,+ *,+ parse_scan_recipe: Callable[[str, Path], dict[str, Any]],+ scan_contract: Callable[[sqlite3.Row], dict[str, Any]],+ require_scan_directory: Callable[[Path], Path],+ artifact_path: Callable[..., Path | None],+ read_json_object: Callable[[Path], dict[str, Any]],+ workbench_completion_binding: Callable[..., dict[str, Any]],+) -> dict[str, Any]:+ if scan["mode"] != "deep" or scan["recipe_json"] is None:+ raise SystemExit("Resume requires a Deep Scan with a saved CLI launch recipe.")+ if scan["status"] != "running" or scan["canceled_at"] is not None:+ raise SystemExit(+ "Resume requires a running scan; completed, failed, and canceled scans cannot resume."+ )+ thread_id = scan["continuation_thread_id"]+ owner = scan["deep_scan_owner_thread_id"] or workspace["thread_id"]+ if (+ not thread_id+ or (owner is not None and owner != thread_id)+ or scan["handoff_status"] != "delivered"+ or scan["handoff_claim_token"] is not None+ ):+ raise SystemExit("Resume requires the original owning CLI session.")+ run = connection.execute(+ "SELECT status, cancel_requested FROM deep_scan_runs WHERE scan_id = ?", (scan["id"],)+ ).fetchone()+ if run is not None and (+ run["status"] not in {"running", "succeeded"} or run["cancel_requested"]+ ):+ raise SystemExit("This Deep Scan has stopped and cannot resume.")+ try:+ repository = require_scan_target_identity(scan)+ except SystemExit as exc:+ raise SystemExit(+ "Cannot resume: the original checkout is missing or was replaced."+ ) from exc+ if scan_target_identity(repository, None) != (+ scan["target_revision"],+ scan["target_snapshot_digest"],+ scan["target_device"],+ scan["target_inode"],+ ):+ raise SystemExit("Cannot resume: the original checkout revision or contents changed.")+ recipe = parse_scan_recipe(scan["recipe_json"], repository)+ scan_dir = require_scan_directory(Path(scan["scan_dir"]))+ progress = connection.execute(+ "SELECT scope_file_count FROM scan_progress WHERE scan_id = ?", (scan["id"],)+ ).fetchone()+ result = {+ "contract": scan_contract(scan),+ "recipe": recipe,+ "scanDir": str(scan_dir),+ "scanId": scan["id"],+ "scopeFileCount": progress["scope_file_count"],+ "startedAt": scan["started_at"],+ "targetId": scan["target_id"],+ "targetRevision": scan["target_revision"],+ "threadId": thread_id,+ "userContext": scan["user_context"],+ }+ # Active coordinators may still be writing drafts. Validate sealed results+ # before attaching to a coordinator that has finished.+ if run is not None and run["status"] == "succeeded":+ manifest_path = artifact_path(scan_dir, ARTIFACTS["manifest"], required=False)+ if manifest_path is not None:+ manifest = read_json_object(manifest_path)+ manifest_scan = manifest.get("scan")+ if isinstance(manifest_scan, dict) and (+ manifest_scan.get("sealedAt") is not None+ or manifest_scan.get("artifacts") is not None+ ):+ try:+ binding = workbench_completion_binding(scan, scan["started_at"], manifest)+ _prepare_scan_finalization(+ scan_dir,+ expected_coverage_mode=binding["coverageMode"],+ completion_binding=binding,+ )+ result["sealedProducerVersion"] = manifest_scan["producer"]["version"]+ except ContractError as exc:+ raise SystemExit(f"Cannot resume sealed scan: {exc}") from exc+ return resultdef _windows_path_key(value: str) -> str:diff --git a/plugins/codex-security/scripts/workbench_validation.py b/plugins/codex-security/scripts/workbench_validation.pyindex 1d8681c97..a65aff1e7 100644--- a/plugins/codex-security/scripts/workbench_validation.py+++ b/plugins/codex-security/scripts/workbench_validation.py@@ -16,6 +16,10 @@ from typing import Anysys.path.insert(0, str(Path(__file__).resolve().parent))+def reject_non_finite_json(value: str) -> None:+ raise ValueError(f"non-finite JSON number {value!r} is not supported")++def require_uuid(value: str, label: str) -> str:try:return str(uuid.UUID(value))diff --git a/plugins/codex-security/tests/test_workbench_completion_binding.py b/plugins/codex-security/tests/test_workbench_completion_binding.pyindex 5eed724c6..dbcdafd9f 100644--- a/plugins/codex-security/tests/test_workbench_completion_binding.py+++ b/plugins/codex-security/tests/test_workbench_completion_binding.py@@ -152,6 +152,31 @@ def test_prepared_completion_does_not_publish_scan_before_acceptance(tmp_path: P).fetchone() == ("complete", manifest["scan"]["completedAt"])+def test_incompatible_sealed_deep_scan_remains_recoverable(tmp_path: Path) -> None:+ state_dir, scan_id, scan_dir = _start_deep_scan_with_draft_findings(tmp_path)+ run_workbench(state_dir, "prepare-scan-completion", "--scan-id", scan_id)+ manifest_path = scan_dir / "scan-manifest.json"+ manifest = json.loads(manifest_path.read_text())+ manifest["schemaVersion"] = "999.0"+ manifest_path.write_text(json.dumps(manifest))+ artifacts = {+ name: (scan_dir / name).read_bytes()+ for name in ("scan-manifest.json", "findings.json", "coverage.json", "report.md")+ }+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:+ before = connection.execute("SELECT * FROM scans WHERE id = ?", (scan_id,)).fetchone()++ rejected = run_workbench(state_dir, "complete-scan", "--scan-id", scan_id, check=False)++ assert rejected["returncode"] != 0+ assert "schemaVersion" in str(rejected["stderr"])+ assert {name: (scan_dir / name).read_bytes() for name in artifacts} == artifacts+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:+ assert (+ connection.execute("SELECT * FROM scans WHERE id = ?", (scan_id,)).fetchone() == before+ )++def test_rejected_prepared_completion_can_be_marked_failed(tmp_path: Path) -> None:state_dir = tmp_path / "state"target = tmp_path / "target"diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex cca9016a7..7baaf1932 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -842,8 +842,45 @@ even after a failed or incomplete scan, but not after cancellation or acost-limit stop.`--workers` defaults to `4`. `--max-attempts` defaults to `1` attempt per pending-repository per invocation. Rerun the command to resume; `bulk-scan --help`-lists all options.+repository per invocation. Rerunning the command continues the campaign, skips+completed results, and starts new attempts for pending repositories. If an+attempt directory is occupied, that repository stops before replacing its+checkout and the command recommends `--recover`.++#### Recovering failed or interrupted bulk scans++Use the original CSV, output directory, and campaign options with `--recover`:++```bash+npx @openai/codex-security bulk-scan repositories.csv \+ --output-dir /path/outside/repositories/security-scans --recover+```++Recovery requires an existing campaign with a matching manifest. It skips+completed results, including partial coverage, and repositories never started.+For each failed or interrupted repository, it checks the latest attempt:++- A sealed scan is recorded in `results.jsonl` without scanning again.+- An eligible running Deep Scan resumes its original session, keeping its scan+ ID, completed workers, artifacts, saved settings, and accumulated cost.+- A failed, canceled, or otherwise unavailable scan starts a new attempt at the+ CSV's pinned revision. Attempt numbers account for both receipts and existing+ directories. Old artifacts and checkouts are preserved; new attempts use+ `recovery-checkouts/<id>/attempt-<n>`.++`--workers` still defaults to `4`; `--max-attempts` defaults to one recovery or+new attempt per repository. A resume connection failure stops that repository+for this invocation instead of starting another scan. Other repositories+continue. Failed and interrupted recovery checkouts remain available for a later+`--recover`; fresh completed checkouts are removed after recording the result.+If a reboot interrupted a receipt write, its unfinished tail is saved beside+`results.jsonl` as `results.jsonl.interrupted-<id>` before appending valid records.++Same-scan resume requires the original checkout, session logs, and Codex Security+state directory. Recovery does not reconstruct deleted checkpoints or fix the+underlying cause of execution failures. New attempts incur new scan costs.+Any remaining failures or partial coverage keep exit code `2`.+`bulk-scan --help` lists all options.### Custom validation@@ -1212,6 +1249,7 @@ unique prefix of at least eight characters.| `scans list [REPOSITORY]` | List scans. Filter by artifact root with `--scan-root DIR`. || `scans show [SCAN_ID]` | Show a scan; defaults to the latest completed one. `--show-linked-findings` includes earlier finding links. || `scans logs [SCAN_ID]` | Show session events; defaults to the latest scan, including active scans. |+| `scans resume SCAN_ID` | Resume an interrupted Deep Scan in its original session and output directory. || `scans rerun [SCAN_ID]` | Repeat a scan on the current checkout; defaults to the latest completed scan. || `scans match BEFORE AFTER` | Link findings with the same root cause. || `scans match --all` | Match completed scans across the repository's worktrees and clones. |@@ -1219,6 +1257,43 @@ unique prefix of at least eight characters.| `findings list [REPOSITORY]` | List open findings. `findings` is an alias. || `findings false-positive OCCURRENCE_ID --reason TEXT` | Mark a false positive. Later scans dismiss matches only while the reason applies. |+#### Resuming an interrupted Deep Scan++After the CLI process or host stops unexpectedly, find the scan and rejoin it:++```bash+npx @openai/codex-security scans list --scan-root /path/to/security-scans+npx @openai/codex-security scans resume SCAN_ID+```++The scan must still be `running`, with its original checkout, output directory,+and owning Codex session available in the same Codex Security state directory.+The checkout's identity, revision, and contents must match the saved target.+Completed, failed, and canceled scans cannot resume; `scans rerun` starts a new scan.++Resume uses the saved configuration and instructions with the installed plugin.+New scans save the explicit safety identifier and post-scan prompt contents.+Single-scan resume restores them even if the prompt file changes or disappears.+Older records that did not save these values cannot reconstruct them. Bulk+recovery still requires matching campaign inputs and options; it uses the supplied+post-scan prompt when the scan has no saved prompt.+It keeps the scan ID, completed workers, artifacts, and accumulated session cost.+The existing coordinator recovers interrupted workers after its lease expires.+If discovery finished before the interruption, resume completes and seals the+same scan. No archiving or new attempt directory is needed. A failed connection+leaves the existing scan available for another resume attempt.++Compatible saved scans can resume after a plugin update. Already-sealed results+keep their original producer version and contents when completion is recorded.+Unsupported or invalid sealed artifacts are rejected before resuming, preserving+the saved scan state and files.++For bulk campaigns, use [`bulk-scan --recover`](#recovering-failed-or-interrupted-bulk-scans)+to recover eligible attempts and update `results.jsonl`. Individual `scans resume`+does not update campaign receipts.++#### Matching saved scans+Matching requires sealed artifacts and reuses saved matches unless you pass`--force`. Comparisons classify findings as new, persisting, reopened, resolved,or unknown. Missing findings aren't resolved if the later scan is incompletediff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 68e094705..075b2f014 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -75,6 +75,7 @@ import {DeepScanProgressTracker,type DeepScanProgress,} from "./deep-progress.js";+import { findScanSession } from "./scan-logs.js";import {loadContract,readScanFile,@@ -214,6 +215,7 @@ interface ScanEvent {interface CodexClientLike {startThread(options: ThreadOptions): CodexThreadLike;+ resumeThread?(threadId: string, options: ThreadOptions): CodexThreadLike;}interface PreparedRuntime {@@ -259,6 +261,8 @@ export interface DeepScanOptions {}export interface ScanOptions extends DeepScanOptions {+ /** @internal Resume a CLI Deep Scan with its saved launch recipe. */+ resumeScanId?: string;/** Save synthetic Standard scan results without calling Codex or a model. */mock?: boolean;/** Opt into a durable scan -> custom publication -> dedupe workflow. */@@ -1299,22 +1303,25 @@ export class CodexSecurity {scanOutputRoot === temporaryRoot ? "temporary" : "output",);}- scanDir = await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(- requestedOutput ?? undefined,- basename(repo),- scanOutputRoot,- (path) => requireOutputOutsideRepository(protectedRoot, path),- options.archiveExisting,- (archiveDir) => {- archivedScanDir = archiveDir;- notifyObserver(- "onOutputArchived",- options.onOutputArchived,- options.onObserverError,- archiveDir,- );- },- );+ scanDir =+ options.resumeScanId !== undefined+ ? requestedOutput!+ : await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(+ requestedOutput ?? undefined,+ basename(repo),+ scanOutputRoot,+ (path) => requireOutputOutsideRepository(protectedRoot, path),+ options.archiveExisting,+ (archiveDir) => {+ archivedScanDir = archiveDir;+ notifyObserver(+ "onOutputArchived",+ options.onOutputArchived,+ options.onObserverError,+ archiveDir,+ );+ },+ );requireOutputOutsideRepository(protectedRoot, scanDir);requireModelSafeOutputDir(scanDir);notifyObserver(@@ -1543,6 +1550,10 @@ export class CodexSecurity {options.maxCostUsd,deepScanOptions(options),);+ if (options.safetyIdentifier !== undefined)+ recipe["safetyIdentifier"] = options.safetyIdentifier;+ if (options.postScanPrompt !== undefined)+ recipe["postScanPrompt"] = options.postScanPrompt;if (options.validationPrompt !== undefined)recipe["validationMode"] = "custom";const workbenchOptions: WorkbenchCommandOptions = {@@ -1559,32 +1570,76 @@ export class CodexSecurity {signal,failureMessage: "Could not save the Codex Security scan",};- const registration = await workbench(- workbenchOptions,- [- "register-cli-scan",- "--repository",- repo,- "--scan-dir",- scanDir,- "--registration-json-stdin",- ...(options.archiveExisting === true ? ["--archive-existing"] : []),- ...(archivedScanDir === null- ? []- : ["--archived-scan-dir", archivedScanDir]),- ...(options.parentScanId === undefined- ? []- : ["--parent-scan-id", options.parentScanId]),- ],- JSON.stringify({- recipe,- userContext: options.scanPrompt,- ...(options.workflowId === undefined- ? {}- : { workflowId: options.workflowId }),- }),- );+ const registration =+ options.resumeScanId !== undefined+ ? await workbench(workbenchOptions, [+ "get-cli-scan-resume",+ "--scan-id",+ options.resumeScanId,+ ])+ : await workbench(+ workbenchOptions,+ [+ "register-cli-scan",+ "--repository",+ repo,+ "--scan-dir",+ scanDir,+ "--registration-json-stdin",+ ...(options.archiveExisting === true+ ? ["--archive-existing"]+ : []),+ ...(archivedScanDir === null+ ? []+ : ["--archived-scan-dir", archivedScanDir]),+ ...(options.parentScanId === undefined+ ? []+ : ["--parent-scan-id", options.parentScanId]),+ ],+ JSON.stringify({+ recipe,+ userContext: options.scanPrompt,+ ...(options.workflowId === undefined+ ? {}+ : { workflowId: options.workflowId }),+ }),+ );const scanId = registration["scanId"];+ const resumeThreadId =+ options.resumeScanId === undefined+ ? undefined+ : registration["threadId"];+ if (options.resumeScanId !== undefined) {+ const savedRecipe = registration["recipe"];+ if (+ scanId !== options.resumeScanId ||+ !isRecord(savedRecipe) ||+ savedRecipe["repository"] !== repo ||+ typeof resumeThreadId !== "string" ||+ !resumeThreadId ||+ JSON.stringify(savedRecipe["target"]) !==+ JSON.stringify(recipe["target"])+ ) {+ throw new CodexSecurityError(+ "The workbench returned mismatched scan resume context.",+ );+ }+ const savedSession = await findScanSession(+ runtime.codexHome,+ resumeThreadId,+ );+ if (+ savedSession === null ||+ savedSession.workingDirectory !== scanDir+ ) {+ throw new CodexSecurityError(+ `The original Codex session for scan ${scanId} is unavailable. Restore its session logs in the original Codex Security state directory before resuming.`,+ );+ }+ if (typeof registration["sealedProducerVersion"] === "string") {+ expectation.pluginVersion = registration["sealedProducerVersion"];+ }+ }const targetId = registration["targetId"];const contract = registration["contract"];const contractTarget = isRecord(contract)@@ -1697,7 +1752,10 @@ export class CodexSecurity {scanId,runtime.configPath !== undefined,knowledgeBase !== null,- options.scanPrompt,+ options.resumeScanId !== undefined &&+ typeof registration["userContext"] === "string"+ ? registration["userContext"]+ : options.scanPrompt,options.maxCostUsd !== undefined,discoveryPrompt,);@@ -1732,7 +1790,14 @@ export class CodexSecurity {scopeFileCount === null? basePrompt: `${basePrompt}\nThe SDK's current in-scope file-count estimate is ${scopeFileCount}; use it for scan progress unless exact scoped-source enumeration establishes a different total before review begins.`;- if (falsePositiveExamples.length > 0) {+ if (options.resumeScanId !== undefined) {+ prompt +=+ "\nResume the existing Deep Scan through its coordinator. Preserve completed workers and saved artifacts; do not recreate the scan directory or restart completed analysis. If the coordinator already finished, continue with completion of this same scan.";+ }+ if (+ falsePositiveExamples.length > 0 &&+ options.resumeScanId === undefined+ ) {const feedbackPath = join(scanDir,"artifacts",@@ -1761,7 +1826,11 @@ export class CodexSecurity {: null;const runtimePaths = {PYTHON: python,- CODEX_SECURITY_STARTED_AT: new Date().toISOString(),+ CODEX_SECURITY_STARTED_AT:+ options.resumeScanId !== undefined &&+ typeof registration["startedAt"] === "string"+ ? registration["startedAt"]+ : new Date().toISOString(),CODEX_SECURITY_REPOSITORY: repo,CODEX_SECURITY_SCAN_DIR: scanDir,CODEX_SECURITY_PLUGIN_ROOT: shellPluginRoot,@@ -1797,12 +1866,27 @@ export class CodexSecurity {runtimePaths,options.auth,);- const thread = codex.startThread({+ const threadOptions: ThreadOptions = {threadSource: CODEX_SECURITY_THREAD_SOURCES.scan,workingDirectory: scanDir,skipGitRepoCheck: true,approvalPolicy,- });+ };+ let thread: CodexThreadLike;+ if (typeof resumeThreadId === "string") {+ if (codex.resumeThread === undefined) {+ throw new CodexSecurityError(+ "The configured Codex client does not support resuming sessions.",+ );+ }+ thread = codex.resumeThread(resumeThreadId, threadOptions);+ tracker.start(resumeThreadId);+ if (budgetRecovery !== null) budgetRecovery.threadId = resumeThreadId;+ await tracker.refresh().catch(reportTrackingError);+ checkOpen();+ } else {+ thread = codex.startThread(threadOptions);+ }const serializedPaths =normalized.kind === "paths" ? jsonForPrompt(normalized.paths) : null;checkOpen();@@ -1835,6 +1919,14 @@ export class CodexSecurity {workbenchValidated: true,model,onThreadStarted: async (threadId) => {+ if (resumeThreadId !== undefined) {+ if (threadId !== resumeThreadId) {+ throw new CodexSecurityError(+ "Codex did not resume the original scan session.",+ );+ }+ return;+ }if (budgetRecovery !== null) budgetRecovery.threadId = threadId;tracker.start(threadId);try {@@ -2235,7 +2327,9 @@ export class CodexSecurity {return result;} catch {}}- if (activeScan !== null) {+ // A failed attachment must not turn a resumable coordinator into a terminal failure.+ // Deep Scan orchestration persists its own terminal failures and cancellations.+ if (activeScan !== null && options.resumeScanId === undefined) {if (options.validationPrompt !== undefined &&!customValidationComplete@@ -3182,6 +3276,19 @@ export class CodexSecurity {signal?: AbortSignal,protectedRoots?: readonly string[],): Promise<LocalScanInputs> {+ if (+ options.resumeScanId !== undefined &&+ (options.mode !== "deep" ||+ !options.outputDir ||+ options.archiveExisting ||+ options.parentScanId !== undefined ||+ options.workflowId !== undefined ||+ options.mock)+ ) {+ throw new CodexSecurityError(+ "Resume requires the original Deep Scan output directory without archive, rerun, or workflow options.",+ );+ }if (options.mock &&(options.mode === "deep" ||@@ -3245,7 +3352,7 @@ export class CodexSecurity {protectedRoots ??= [protectedRoot];const requestedOutput = await validateOutputDir(options.outputDir,- options.archiveExisting,+ options.resumeScanId !== undefined || options.archiveExisting,);if (requestedOutput !== null) {requireOutputOutsideRepositories(protectedRoots, requestedOutput);diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 303f29bed..c0e2d6caa 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -64,6 +64,7 @@ import {type ScanPreflight,} from "./api.js";import { accountStatus } from "./auth.js";+import { loadContract } from "./contract.js";import { publishScanToCustom } from "./custom-publish.js";import { deduplicateScanInternal } from "./deduplication/scan.js";import {@@ -170,7 +171,11 @@ import {CODEX_SECURITY_THREAD_SOURCES,type CodexSecurityThreadSource,} from "./thread-source.js";-import { readSavedScanLogs, type ScanLogSource } from "./scan-logs.js";+import {+ findScanSession,+ readSavedScanLogs,+ type ScanLogSource,+} from "./scan-logs.js";import { sendFeedback } from "./feedback.js";import {renderScanHistory,@@ -1001,6 +1006,7 @@ export function resolveCliPath(directory: string, value: string): string {}interface ScanArguments extends DeepScanOptions {+ resumeScanId?: string;mock?: boolean;workflowId?: string;auth?: ScanAuthMode;@@ -1012,6 +1018,7 @@ interface ScanArguments extends DeepScanOptions {scanPromptFile?: string;validationPromptFile?: string;postScanPromptFile?: string;+ postScanPrompt?: string;diff?: string;workingTree: boolean;head?: string;@@ -1999,6 +2006,67 @@ export async function main();},})+ .command("resume", {+ description: "Resume an interrupted Deep Scan in its original session.",+ mcp: false,+ args: z.object({+ scanId: z.string().min(1).describe("Interrupted Deep Scan identifier."),+ }),+ options: z.object({+ verbose: z+ .boolean()+ .default(false)+ .describe("Print scan diagnostics to stderr."),+ }),+ output: z.record(z.string(), z.unknown()).optional(),+ async run({ args, error: incurError, options }) {+ let scanArguments: ScanArguments;+ try {+ const saved = await dependencies.runWorkbench([+ "get-cli-scan-resume",+ "--scan-id",+ args.scanId,+ ]);+ if (+ typeof saved["scanId"] !== "string" ||+ typeof saved["scanDir"] !== "string"+ ) {+ throw new CodexSecurityError(+ "The workbench returned invalid scan resume context.",+ );+ }+ scanArguments = scanArgumentsFromRecipe(+ saved["recipe"],+ saved["scanId"],+ );+ scanArguments.resumeScanId = saved["scanId"];+ scanArguments.outputDir = saved["scanDir"];+ scanArguments.parentScanId = undefined;+ // Resume uses the installed engine with the saved recipe and checkpoints.+ scanArguments.expectedPluginVersion = undefined;+ scanArguments.verbose = options.verbose;+ } catch (error) {+ const message = errorMessage(error);+ errorOutput.write(`codex-security: ${message}\n`);+ exitCode = 2;+ return incurError({+ code: "SCAN_RESUME_UNAVAILABLE",+ message,+ exitCode,+ });+ }+ const outcome = await runScan(scanArguments, errorOutput, dependencies);+ exitCode = outcome.exitCode;+ if (outcome.error !== undefined) {+ return incurError({+ code: "SCAN_FAILED",+ message: outcome.error,+ exitCode,+ });+ }+ return outcome.data;+ },+ }).command("rerun", {description: "Rerun a saved scan with its original configuration.",destructive: true,@@ -3938,6 +4006,12 @@ export async function main(),}),options: z.object({+ recover: z+ .boolean()+ .default(false)+ .describe(+ "Recover failed or interrupted attempts in an existing campaign, preserving their artifacts and checkouts.",+ ),outputDir: z.string().min(1, "--output-dir must not be empty.")@@ -4029,6 +4103,11 @@ export async function main(dependencies.addSignalListener("SIGTERM", onTerminate);try {const currentDirectory = dependencies.currentDirectory();+ if (options.recover && args.input === undefined) {+ throw new Error(+ "Bulk recovery requires the original repository CSV and --output-dir.",+ );+ }const prompts = await readPromptFiles(currentDirectory,options.scanPromptFile,@@ -4090,6 +4169,99 @@ export async function main(),},createSecurity: dependencies.createSecurity,+ ...(options.recover+ ? {+ recoverScan: async (scanDir: string) => {+ const history = await dependencies.runWorkbench(+ ["list-scans", "--scan-root", scanDir],+ undefined,+ controller.signal,+ );+ const scan = (history["scans"] as SavedScan[]).find(+ (scan) => resolve(scan.scanDir) === scanDir,+ );+ if (scan === undefined) return undefined;+ const status = (scan["progress"] as JsonObject)["status"];+ if (status === "complete") {+ const contract = await loadContract(scanDir, {+ pluginRoot: await bundledPluginRoot(),+ expectedScanId: scan.scanId,+ signal: controller.signal,+ });+ return {+ coverage: contract.coverage,+ cost:+ (scan["cost"] as unknown as ScanCost | undefined) ??+ null,+ };+ }+ if (status !== "running" || scan["mode"] !== "deep")+ return undefined;+ const saved = await dependencies.runWorkbench(+ [+ "get-cli-scan-resume",+ "--scan-id",+ scan.scanId,+ "--allow-unavailable",+ ],+ undefined,+ controller.signal,+ );+ if (typeof saved["unavailable"] === "string") {+ errorOutput.write(+ `codex-security: ${scan.scanId}: ${saved["unavailable"]} Preserving this attempt and starting a new one.\n`,+ );+ return undefined;+ }+ const session =+ typeof saved["threadId"] === "string"+ ? await findScanSession(+ codexSecurityCredentialHome(+ dependencies.environment,+ ),+ saved["threadId"],+ )+ : null;+ if (session?.workingDirectory !== scanDir) {+ errorOutput.write(+ `codex-security: ${scan.scanId}: Original session logs are unavailable. Preserving this attempt and starting a new one.\n`,+ );+ return undefined;+ }+ const recipe = scanArgumentsFromRecipe(+ saved["recipe"],+ scan.scanId,+ );+ const security = dependencies.createSecurity({+ pluginPath: options.pluginPath,+ pythonPath: options.python,+ codexOverrides: recipe.codexOverrides,+ });+ try {+ return await security.run(recipe.repository!, {+ resumeScanId: scan.scanId,+ outputDir: scanDir,+ mode: recipe.mode,+ target: targetFromArguments(recipe),+ knowledgeBasePaths: recipe.knowledgeBasePaths,+ workers: recipe.workers,+ subagents: recipe.subagents,+ stopAfterNoNew: recipe.stopAfterNoNew,+ maxDiscoveryRuns: recipe.maxDiscoveryRuns,+ maxTimeHours: recipe.maxTimeHours,+ maxCostUsd: recipe.maxCostUsd,+ failureSeverity: recipe.failOnSeverity,+ safetyIdentifier: recipe.safetyIdentifier,+ postScanPrompt:+ recipe.postScanPrompt ?? prompts.postScanPrompt,+ signal: controller.signal,+ });+ } finally {+ await security.close();+ }+ },+ }+ : {}),signal: controller.signal,onProgress: ({ repository, status, attempt, error, warning }) => {const detail = error ?? warning;@@ -5334,11 +5506,23 @@ function scanArgumentsFromRecipe("The saved scan recipe contains deep scan settings for a standard scan.",);}+ const safetyIdentifier = recipe["safetyIdentifier"];+ const postScanPrompt = recipe["postScanPrompt"];+ if (+ (safetyIdentifier !== undefined && typeof safetyIdentifier !== "string") ||+ (postScanPrompt !== undefined && typeof postScanPrompt !== "string")+ ) {+ throw new CodexSecurityError(+ "The saved scan recipe contains invalid launch settings.",+ );+ }return {repository,paths,knowledgeBasePaths,validationPromptFile,+ safetyIdentifier,+ postScanPrompt,diff: kind === "refs" ? reference : undefined,workingTree: kind === "working_tree",head: kind === "refs" ? head ?? "HEAD" : undefined,@@ -7353,6 +7537,9 @@ async function executeScan();}const options: ScanOptions = {+ ...(arguments_.resumeScanId === undefined+ ? {}+ : { resumeScanId: arguments_.resumeScanId }),...(arguments_.mock ? { mock: true } : {}),...(arguments_.workflowId === undefined? {}@@ -7362,6 +7549,7 @@ async function executeScan(target,knowledgeBasePaths: arguments_.knowledgeBasePaths,...prompts,+ postScanPrompt: arguments_.postScanPrompt ?? prompts.postScanPrompt,mode: arguments_.mode,workers: arguments_.workers,subagents: arguments_.subagents,diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.tsindex c63019d2e..4d0c0105c 100644--- a/sdk/typescript/src/multiscan.ts+++ b/sdk/typescript/src/multiscan.ts@@ -6,6 +6,7 @@ import {mkdir,open,readFile,+ readdir,realpath,rename,rm,@@ -21,10 +22,15 @@ import Papa from "papaparse";import type { CodexSecurity } from "./api.js";import type { CodexSecurityConfig } from "./config.js";import type { ScanCost } from "./cost.js";-import { safeErrorMessage, ScanCostLimitExceededError } from "./errors.js";+import {+ OutputDirectoryNotEmptyError,+ safeErrorMessage,+ ScanCostLimitExceededError,+} from "./errors.js";import type { CoverageDocument } from "./models.js";-import { requireSecureOutputAncestry } from "./runtime.js";+import { requireSecureOutputAncestry, validateOutputDir } from "./runtime.js";import type { ScanMode } from "./targets.js";+import type { ScanResult } from "./result.js";import { resolveTrustedExecutable } from "./trusted-executable.js";const execFile = promisify(execFileCallback);@@ -66,6 +72,9 @@ export interface MultiscanOptions {workers: number;mode: ScanMode;maxAttempts: number;+ recoverScan?(+ scanDir: string,+ ): Promise<Pick<ScanResult, "coverage" | "cost"> | undefined>;maxCostUsd?: number;scanPrompt?: string;validationPrompt?: string;@@ -119,6 +128,16 @@ export async function runMultiscan(throw new Error("Custom validation is not supported for Deep scans.");}const requestedOutput = resolve(options.outputDir);+ if (options.recoverScan !== undefined) {+ const manifest = await lstat(join(requestedOutput, "manifest.json")).catch(+ (error: NodeJS.ErrnoException) => {+ if (error.code !== "ENOENT") throw error;+ return undefined;+ },+ );+ if (!manifest?.isFile())+ throw new Error("Bulk recovery requires an existing campaign manifest.");+ }const output = await ensureOutputDirectory(requestedOutput);await requireSecureOutputAncestry(output);const unlock = await acquireLock(output);@@ -141,13 +160,29 @@ async function runCampaign(await ensureOutputDirectory(join(output, "checkouts"));await ensureOutputDirectory(join(output, "artifacts"));await ensureManifest(join(output, "manifest.json"), tasks, options);- const receipts = await readReceipts(ledger);+ const receipts = await readReceipts(+ ledger,+ options.recoverScan !== undefined,+ );const pending: MultiscanTask[] = [];let completed = 0;let incomplete = 0;+ let untouched = 0;for (const task of tasks) {const receipt = receipts.get(task.id.toLowerCase());if (receipt === undefined) {+ if (options.recoverScan !== undefined) {+ const attempts = await readdir(+ join(output, "artifacts", task.id),+ ).catch((error: NodeJS.ErrnoException) => {+ if (error.code !== "ENOENT") throw error;+ return [];+ });+ if (!attempts.some((name) => /^attempt-[1-9][0-9]*$/u.test(name))) {+ untouched += 1;+ continue;+ }+ }pending.push(task);continue;}@@ -192,7 +227,7 @@ async function runCampaign(}pending.push(task);}- const skipped = completed + incomplete;+ const skipped = completed + incomplete + untouched;if (pending.length === 0) {return {total: tasks.length,@@ -214,72 +249,123 @@ async function runCampaign(const task = pending[next++];if (task === undefined) return;let attempt = receipts.get(task.id.toLowerCase())?.attempt ?? 0;+ const artifactRoot = join(output, "artifacts", task.id);+ if (options.recoverScan !== undefined) {+ await ensureOutputDirectory(artifactRoot);+ for (const name of await readdir(artifactRoot)) {+ const match = /^attempt-([1-9][0-9]*)$/u.exec(name);+ if (match && Number.isSafeInteger(Number(match[1])))+ attempt = Math.max(attempt, Number(match[1]));+ }+ }for (let retry = 0; retry < options.maxAttempts; retry += 1) {options.signal?.throwIfAborted();- attempt += 1;- const checkout = join(output, "checkouts", task.id);- const scanDir = join(- output,- "artifacts",- task.id,- `attempt-${attempt}`,- );- const progress = { repository: task.id, attempt };- notifyProgress(options, { ...progress, status: "started" });+ if (options.recoverScan === undefined) attempt += 1;+ let scanDir = join(artifactRoot, `attempt-${attempt}`);+ let checkout: string | undefined;+ let attemptedResume = false;let failure: string | undefined;let warning: string | undefined;let coverage: CoverageDocument["completeness"] | undefined;let cost: Readonly<ScanCost> | null = null;let exhaustedBudget = false;+ let requiresRecovery = false;try {- await ensureOutputDirectory(dirname(scanDir));- await rm(checkout, { recursive: true, force: true });- await mkdir(checkout, { mode: 0o700 });- await checkoutRevision(- task,- checkout,- options.signal,- options.githubHost,- );- if (task.scope !== undefined) {- const scoped = await realpath(join(checkout, task.scope));- const outside = relative(await realpath(checkout), scoped);- if (- outside === ".." ||- outside.startsWith(`..${sep}`) ||- isAbsolute(outside)- ) {- throw new Error("Multiscan scope escapes its repository.");- }- }- const scanPrompt = [options.scanPrompt?.trim(), task.prompt]- .filter(Boolean)- .join("\n\n");- const result = await security.run(checkout, {- ...(task.scope === undefined ? {} : { target: [task.scope] }),- ...(options.knowledgeBasePaths?.length- ? { knowledgeBasePaths: options.knowledgeBasePaths }- : {}),- mode: task.mode,- outputDir: scanDir,- ...(scanPrompt ? { scanPrompt } : {}),- ...(options.validationPrompt === undefined- ? {}- : { validationPrompt: options.validationPrompt }),- ...(options.postScanPrompt === undefined- ? {}- : { postScanPrompt: options.postScanPrompt }),- ...(options.maxCostUsd === undefined- ? {}- : { maxCostUsd: options.maxCostUsd }),- onWarning: (warning) =>+ await ensureOutputDirectory(artifactRoot);+ let result: Pick<ScanResult, "coverage" | "cost"> | undefined;+ if (options.recoverScan !== undefined && retry === 0 && attempt > 0) {+ const existing = await lstat(scanDir).catch(+ (error: NodeJS.ErrnoException) => {+ if (error.code !== "ENOENT") throw error;+ return undefined;+ },+ );+ if (existing !== undefined) {+ await ensureOutputDirectory(scanDir);+ attemptedResume = true;notifyProgress(options, {- ...progress,+ repository: task.id,+ attempt,status: "started",- warning,- }),- ...(options.signal === undefined ? {} : { signal: options.signal }),- });+ });+ result = await options.recoverScan(scanDir);+ attemptedResume = result !== undefined;+ }+ }+ if (result === undefined) {+ if (options.recoverScan !== undefined) attempt += 1;+ scanDir = join(artifactRoot, `attempt-${attempt}`);+ notifyProgress(options, {+ repository: task.id,+ attempt,+ status: "started",+ });+ if (options.recoverScan !== undefined) {+ const checkoutRoot = await ensureOutputDirectory(+ join(output, "recovery-checkouts"),+ );+ const taskRoot = await ensureOutputDirectory(+ join(checkoutRoot, task.id),+ );+ checkout = join(taskRoot, `attempt-${attempt}`);+ // Reserve both paths before starting work. An interrupted attempt is never replaced.+ await mkdir(scanDir, { mode: 0o700 });+ await mkdir(checkout, { mode: 0o700 });+ } else {+ await validateOutputDir(scanDir);+ checkout = join(output, "checkouts", task.id);+ await rm(checkout, { recursive: true, force: true });+ await mkdir(checkout, { mode: 0o700 });+ }+ await checkoutRevision(+ task,+ checkout,+ options.signal,+ options.githubHost,+ );+ if (task.scope !== undefined) {+ const scoped = await realpath(join(checkout, task.scope));+ const outside = relative(await realpath(checkout), scoped);+ if (+ outside === ".." ||+ outside.startsWith(`..${sep}`) ||+ isAbsolute(outside)+ ) {+ throw new Error("Multiscan scope escapes its repository.");+ }+ }+ const scanPrompt = [options.scanPrompt?.trim(), task.prompt]+ .filter(Boolean)+ .join("\n\n");+ result = await security.run(checkout, {+ ...(task.scope === undefined ? {} : { target: [task.scope] }),+ ...(options.knowledgeBasePaths?.length+ ? { knowledgeBasePaths: options.knowledgeBasePaths }+ : {}),+ mode: task.mode,+ outputDir: scanDir,+ ...(scanPrompt ? { scanPrompt } : {}),+ ...(options.validationPrompt === undefined+ ? {}+ : { validationPrompt: options.validationPrompt }),+ ...(options.postScanPrompt === undefined+ ? {}+ : { postScanPrompt: options.postScanPrompt }),+ ...(options.maxCostUsd === undefined+ ? {}+ : { maxCostUsd: options.maxCostUsd }),+ onWarning: (warning) =>+ notifyProgress(options, {+ repository: task.id,+ attempt,+ status: "started",+ warning,+ }),+ ...(options.signal === undefined+ ? {}+ : { signal: options.signal }),+ });+ }cost = result.cost;coverage = result.coverage.completeness;if (coverage !== "complete") {@@ -296,9 +382,16 @@ async function runCampaign(cost = error.cost;exhaustedBudget = true;}- failure = safeErrorMessage(error);+ requiresRecovery = error instanceof OutputDirectoryNotEmptyError;+ failure = requiresRecovery+ ? safeErrorMessage(+ `Bulk attempt directory is not empty: ${scanDir}. Existing artifacts and checkout were preserved. Run the same bulk-scan command with --recover to recover interrupted scans or retry failed scans in new attempt directories.`,+ )+ : safeErrorMessage(error);} finally {- await rm(checkout, { recursive: true, force: true });+ if (options.recoverScan === undefined && checkout !== undefined) {+ await rm(checkout, { recursive: true, force: true });+ }}const status =failure !== undefined@@ -319,8 +412,16 @@ async function runCampaign(...(warning === undefined ? {} : { warning }),})}\n`,);+ if (+ options.recoverScan !== undefined &&+ failure === undefined &&+ checkout !== undefined+ ) {+ await rm(checkout, { recursive: true, force: true });+ }notifyProgress(options, {- ...progress,+ repository: task.id,+ attempt,status,...(failure === undefined ? {} : { error: failure }),...(warning === undefined ? {} : { warning }),@@ -330,7 +431,7 @@ async function runCampaign(else incomplete += 1;break;}- if (exhaustedBudget) {+ if (exhaustedBudget || attemptedResume || requiresRecovery) {failed += 1;break;}@@ -668,6 +769,7 @@ async function ensureManifest(async function readReceipts(path: string,+ preserveInterrupted = false,): Promise<Map<string, MultiscanReceipt>> {let contents: string;try {@@ -679,6 +781,12 @@ async function readReceipts(const lines = contents.split("\n");if (!contents.endsWith("\n")) {const partial = lines.pop()!;+ if (preserveInterrupted) {+ await writeFile(`${path}.interrupted-${randomUUID()}`, partial, {+ flag: "wx",+ mode: 0o600,+ });+ }await truncate(path,Buffer.byteLength(contents) - Buffer.byteLength(partial),diff --git a/sdk/typescript/src/scan-logs.ts b/sdk/typescript/src/scan-logs.tsindex 40def7bb2..4c793a10d 100644--- a/sdk/typescript/src/scan-logs.ts+++ b/sdk/typescript/src/scan-logs.ts@@ -57,9 +57,8 @@ interface SessionLog {path: string;}-export async function readScanLogs(options: ScanLogOptions) {- const logs = new Map<string, SessionLog>();- for await (const path of sessionFiles(join(options.codexHome, "sessions"))) {+async function* scanSessions(codexHome: string): AsyncGenerator<SessionLog> {+ for await (const path of sessionFiles(join(codexHome, "sessions"))) {for await (const first of sessionEvents(path)) {if (first["type"] !== "session_meta" || !isRecord(first["payload"])) {break;@@ -67,17 +66,34 @@ export async function readScanLogs(options: ScanLogOptions) {const metadata = first["payload"];const threadId = metadata["id"];if (typeof threadId !== "string") break;- logs.set(threadId, {+ yield {threadId,parentThreadId: sessionParentThreadId(metadata),startedAt: sessionStartedAt(metadata["timestamp"]),workingDirectory:typeof metadata["cwd"] === "string" ? metadata["cwd"] : null,path,- });+ };break;}}+}++export async function findScanSession(+ codexHome: string,+ threadId: string,+): Promise<SessionLog | null> {+ for await (const session of scanSessions(codexHome)) {+ if (session.threadId === threadId) return session;+ }+ return null;+}++export async function readScanLogs(options: ScanLogOptions) {+ const logs = new Map<string, SessionLog>();+ for await (const session of scanSessions(options.codexHome)) {+ logs.set(session.threadId, session);+ }const root = logs.get(options.threadId);if (root === undefined) {diff --git a/sdk/typescript/tests-ts/multiscan.test.ts b/sdk/typescript/tests-ts/multiscan.test.tsindex c1c9e9ddd..d3ebd2a3e 100644--- a/sdk/typescript/tests-ts/multiscan.test.ts+++ b/sdk/typescript/tests-ts/multiscan.test.ts@@ -25,6 +25,7 @@ import { ScanCostLimitExceededError } from "../src/errors.js";import type { ScanResult } from "../src/result.js";import { buildGitHubCredentialArgs, runMultiscan } from "../src/multiscan.js";import { resolveTrustedExecutable } from "../src/trusted-executable.js";+import { prepareOutputDir } from "../src/runtime.js";import { capture, dependencies, fakeResult } from "./cli-fixtures.js";import { runTestInSubprocess } from "./support/test-subprocess.js";@@ -135,6 +136,319 @@ async function results(path: string): Promise<Record<string, unknown>[]> {}describe("multiscan", () => {+ test("canceled recovery retains the new checkout and attempt without appending a failure receipt", async () => {+ const paths = await fixture();+ const source = await repository(paths.root, "cancel-recovery");+ await writeFile(+ paths.input,+ `id,repository,revision\nrepo,${source.path},${source.revision}\n`,+ );+ await runMultiscan(+ options(+ paths,+ client(async () => {+ throw new Error("Stopped");+ }),+ { maxAttempts: 1 },+ ),+ );+ const before = await readFile(join(paths.output, "results.jsonl"), "utf8");+ const controller = new AbortController();+ let retained = "";+ await expect(+ runMultiscan(+ options(+ paths,+ client(async (checkout, scan = {}) => {+ retained = checkout;+ await writeFile(join(scan.outputDir!, "checkpoint"), "keep");+ controller.abort(new Error("Interrupted recovery"));+ controller.signal.throwIfAborted();+ throw new Error("Unreachable");+ }),+ { recoverScan: async () => undefined, signal: controller.signal },+ ),+ ),+ ).rejects.toThrow("Interrupted recovery");+ expect(await readFile(join(retained, "src", "app.ts"), "utf8")).toContain(+ "cancel-recovery",+ );+ expect(+ await readFile(+ join(paths.output, "artifacts", "repo", "attempt-2", "checkpoint"),+ "utf8",+ ),+ ).toBe("keep");+ expect(await readFile(join(paths.output, "results.jsonl"), "utf8")).toBe(+ before,+ );+ });++ test("occupied bulk attempts preserve the original checkout and recommend bulk recovery", async () => {+ const paths = await fixture();+ const source = await repository(paths.root, "occupied");+ await writeFile(+ paths.input,+ `id,repository,revision\nrepo,${source.path},${source.revision}\n`,+ );+ const scanDir = join(paths.output, "artifacts", "repo", "attempt-1");+ const checkout = join(paths.output, "checkouts", "repo");+ await mkdir(scanDir, { recursive: true, mode: 0o700 });+ await mkdir(checkout, { recursive: true });+ await writeFile(join(scanDir, "checkpoint"), "keep");+ await writeFile(join(checkout, "source"), "keep checkout");+ const error = capture();+ const output = capture();+ const deps = dependencies();+ const code = await main(+ [+ "bulk-scan",+ paths.input,+ "--output-dir",+ paths.output,+ "--max-attempts",+ "3",+ "--json",+ ],+ output.stream,+ error.stream,+ {+ ...deps,+ createSecurity: (config) => ({+ ...deps.createSecurity(config),+ run: async (_repo, scan = {}) => {+ await prepareOutputDir(scan.outputDir, "repo");+ return completedScan(scan.outputDir!);+ },+ }),+ },+ );+ expect(code).toBe(2);+ expect(error.text()).toContain("--recover");+ expect(error.text()).not.toContain("--archive-existing");+ const receipts = await results(JSON.parse(output.text()).resultsPath);+ expect(receipts).toHaveLength(1);+ expect(receipts[0]).toMatchObject({+ status: "failed",+ attempt: 1,+ error: expect.stringContaining("--recover"),+ });+ expect(await readFile(join(checkout, "source"), "utf8")).toBe(+ "keep checkout",+ );+ expect(await readFile(join(scanDir, "checkpoint"), "utf8")).toBe("keep");+ await expect(prepareOutputDir(scanDir, "repo")).rejects.toThrow(+ "--archive-existing",+ );+ });++ test("recovery skips untouched rows and saves an interrupted ledger tail before appending", async () => {+ const paths = await fixture();+ const source = await repository(paths.root, "tail");+ const tasks = ["failed", "untouched"].map((id) => ({+ id,+ repository: source.path,+ revision: source.revision,+ mode: "standard",+ }));+ await writeFile(+ paths.input,+ `id,repository,revision\n${tasks.map((task) => `${task.id},${task.repository},${task.revision}`).join("\n")}\n`,+ );+ await mkdir(paths.output);+ await writeFile(+ join(paths.output, "manifest.json"),+ JSON.stringify({ version: 1, tasks }, null, 2) + "\n",+ );+ const tail = '{"id":"failed","status":';+ const original =+ JSON.stringify({+ ...tasks[0],+ status: "failed",+ attempt: 1,+ outputDir: join(paths.output, "artifacts", "failed", "attempt-1"),+ }) + "\n";+ await writeFile(join(paths.output, "results.jsonl"), original + tail);+ let runs = 0;+ const result = await runMultiscan(+ options(+ paths,+ client(async (_repo, scan = {}) => {+ runs++;+ return completedScan(scan.outputDir!);+ }),+ { recoverScan: async () => undefined },+ ),+ );+ expect(result).toMatchObject({+ total: 2,+ completed: 1,+ failed: 0,+ skipped: 1,+ });+ expect(runs).toBe(1);+ expect(+ (await readFile(result.resultsPath, "utf8")).startsWith(original),+ ).toBe(true);+ const backup = (await readdir(paths.output)).find((name) =>+ name.startsWith("results.jsonl.interrupted-"),+ );+ expect(backup).toBeDefined();+ expect(await readFile(join(paths.output, backup!), "utf8")).toBe(tail);+ });++ test("recovery preserves occupied attempts and checkouts while retrying only failed repositories", async () => {+ const paths = await fixture();+ const source = await repository(paths.root, "recovery");+ await writeFile(+ paths.input,+ `id,repository,revision,mode\nfailed,${source.path},${source.revision},deep\ndone,${source.path},${source.revision},deep\n`,+ );+ const failedDir = join(paths.output, "artifacts", "failed", "attempt-1");+ const first = await runMultiscan(+ options(+ paths,+ client(async (_repo, scan = {}) => {+ if (scan.outputDir === failedDir) throw new Error("Interrupted scan");+ return completedScan(scan.outputDir!, "partial");+ }),+ { maxAttempts: 1 },+ ),+ );+ const before = await readFile(first.resultsPath, "utf8");+ const orphan = join(paths.output, "artifacts", "failed", "attempt-5");+ const checkout = join(paths.output, "checkouts", "failed");+ await mkdir(orphan, { recursive: true });+ await mkdir(checkout, { recursive: true });+ await writeFile(join(orphan, "checkpoint"), "keep checkpoint");+ await writeFile(join(checkout, "source"), "keep checkout");+ const inode = (await lstat(checkout)).ino;+ const resumed: string[] = [];+ let runs = 0;+ const result = await runMultiscan(+ options(+ paths,+ client(async (repo, scan = {}) => {+ runs++;+ expect(repo).not.toBe(checkout);+ expect(git(repo, "rev-parse", "HEAD")).toBe(source.revision);+ expect(scan.mode).toBe("deep");+ expect(scan.outputDir).toBe(+ join(paths.output, "artifacts", "failed", "attempt-6"),+ );+ return completedScan(scan.outputDir!);+ }),+ {+ maxAttempts: 1,+ recoverScan: async (dir) => {+ resumed.push(dir);+ return undefined;+ },+ },+ ),+ );+ expect(result).toMatchObject({+ completed: 1,+ incomplete: 1,+ failed: 0,+ skipped: 1,+ });+ expect(runs).toBe(1);+ expect(resumed).toEqual([orphan]);+ expect((await lstat(checkout)).ino).toBe(inode);+ expect(await readFile(join(checkout, "source"), "utf8")).toBe(+ "keep checkout",+ );+ expect(await readFile(join(orphan, "checkpoint"), "utf8")).toBe(+ "keep checkpoint",+ );+ expect(+ (await readFile(result.resultsPath, "utf8")).startsWith(before),+ ).toBe(true);+ expect((await results(result.resultsPath)).at(-1)).toMatchObject({+ id: "failed",+ attempt: 6,+ status: "completed",+ });+ });++ test.each([false, true])(+ "recovery records the original attempt and preserves it after resume failure=%s",+ async (failure) => {+ const paths = await fixture();+ const source = await repository(paths.root, "retained");+ await writeFile(+ paths.input,+ `id,repository,revision\nretained,${source.path},${source.revision}\n`,+ );+ await runMultiscan(+ options(+ paths,+ client(async () => {+ throw new Error("Stopped");+ }),+ { maxAttempts: 1 },+ ),+ );+ const dir = join(paths.output, "artifacts", "retained", "attempt-1");+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, "checkpoint"), "keep");+ let resumed = 0;+ let runs = 0;+ const summary = await runMultiscan(+ options(+ paths,+ client(async (_repo, scan = {}) => {+ runs++;+ return completedScan(scan.outputDir!);+ }),+ {+ maxAttempts: 3,+ recoverScan: async (scanDir) => {+ resumed++;+ expect(scanDir).toBe(dir);+ if (failure) throw new Error("Resume transport failed");+ return completedScan(scanDir);+ },+ },+ ),+ );+ expect(runs).toBe(0);+ expect(resumed).toBe(1);+ expect(summary.failed).toBe(failure ? 1 : 0);+ expect(summary.completed).toBe(failure ? 0 : 1);+ expect((await results(summary.resultsPath)).at(-1)).toMatchObject({+ attempt: 1,+ outputDir: dir,+ status: failure ? "failed" : "completed",+ });+ expect(await readFile(join(dir, "checkpoint"), "utf8")).toBe("keep");+ },+ );++ test("bulk recovery requires an existing campaign and a CSV", async () => {+ const paths = await fixture();+ const source = await repository(paths.root, "missing-campaign");+ await writeFile(+ paths.input,+ `id,repository,revision\nrepo,${source.path},${source.revision}\n`,+ );+ for (const args of [+ ["--recover"],+ [paths.input, "--output-dir", paths.output, "--recover"],+ ]) {+ const error = capture();+ const code = await main(+ ["bulk-scan", ...args],+ capture().stream,+ error.stream,+ dependencies(),+ );+ expect(code).toBe(2);+ expect(error.text()).toMatch(/recovery requires/i);+ }+ });+test("scopes GitHub CLI credentials to the discovered GitHub host", () => {expect(buildGitHubCredentialArgs(undefined)).toEqual([]);expect(buildGitHubCredentialArgs("github.com")).toEqual([@@ -695,7 +1009,6 @@ describe("multiscan", () => {`id,repository,revision\nsample,${source.path},${source.revision}\n`,);const outputDir = join(paths.output, "artifacts", "sample", "attempt-1");- await completedScan(outputDir, completeness);const stdout = capture();const stderr = capture();let attempts = 0;@@ -715,6 +1028,17 @@ describe("multiscan", () => {attempts += 1;},});+ const createSecurity = clientDependencies.createSecurity;+ clientDependencies.createSecurity = (config) => {+ const security = createSecurity(config);+ return {+ ...security,+ run: async (repository, scan = {}) => {+ await completedScan(scan.outputDir!, completeness);+ return security.run(repository, scan);+ },+ };+ };expect(await main(diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.tsnew file mode 100644index 000000000..d5646bc52--- /dev/null+++ b/sdk/typescript/tests-ts/scan-resume.test.ts@@ -0,0 +1,961 @@+import { randomUUID } from "node:crypto";+import { execFileSync } from "node:child_process";+import {+ appendFile,+ cp,+ mkdir,+ readFile,+ rename,+ rm,+ writeFile,+} from "node:fs/promises";+import { join } from "node:path";+import { afterEach, expect, test } from "bun:test";+import { main } from "../src/cli.js";+import type { ScanOptions } from "../src/api.js";+import { runWorkbench } from "../src/runtime.js";+import { capture, dependencies } from "./cli-fixtures.js";+import { PLUGIN_ROOT } from "./plugin-root.js";+import { TestClient } from "./support/api-client.js";+import {+ completedEvents,+ createApiTestFixtures,+ preparedRuntime,+} from "./support/api-events.js";++const { temporaryDirectory, cleanup } = createApiTestFixtures();+afterEach(cleanup);++async function interruptedScan(+ mode: "deep" | "standard" = "deep",+ bulk = false,+ settings: Pick<ScanOptions, "safetyIdentifier" | "postScanPrompt"> = {},+) {+ const root = await temporaryDirectory();+ const repository = bulk+ ? join(root, "checkouts", "repo")+ : join(root, "repository");+ const scanDir = bulk+ ? join(root, "artifacts", "repo", "attempt-1")+ : join(root, "scan");+ const codexHome = join(root, "state", "codex-home");+ await mkdir(repository, { recursive: true });+ await mkdir(scanDir, { recursive: true, mode: 0o700 });+ await mkdir(join(codexHome, "sessions"), { recursive: true });+ await writeFile(join(repository, "source.py"), "# synthetic source\n");+ const input = join(root, "repositories.csv");+ if (bulk) {+ const git = (...args: string[]) =>+ execFileSync("git", ["-C", repository, ...args], {+ encoding: "utf8",+ }).trim();+ git("init", "-q");+ git("add", ".");+ git(+ "-c",+ "user.name=Recovery Test",+ "-c",+ "[email protected]",+ "commit",+ "-qm",+ "initial",+ );+ const source = join(root, "source");+ await cp(repository, source, { recursive: true });+ const task = {+ id: "repo",+ repository: source,+ revision: git("rev-parse", "HEAD"),+ mode,+ };+ await writeFile(+ input,+ `id,repository,revision,mode\nrepo,${source},${task.revision},${mode}\n`,+ );+ await writeFile(+ join(root, "manifest.json"),+ JSON.stringify({ version: 1, tasks: [task] }, null, 2) + "\n",+ );+ await writeFile(+ join(root, "results.jsonl"),+ JSON.stringify({+ ...task,+ status: "failed",+ attempt: 1,+ outputDir: scanDir,+ error: "Occupied attempt",+ }) + "\n",+ );+ }+ const python = Bun.which("python3") ?? Bun.which("python");+ if (python === null) throw new Error("Python is required for this test.");+ const environment = {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ TEMP: process.env["TEMP"],+ TMP: process.env["TMP"],+ CODEX_HOME: codexHome,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ ...(settings.safetyIdentifier === undefined+ ? {}+ : { OPENAI_API_KEY: "synthetic-resume-key" }),+ };+ const command = (args: readonly string[], input?: string) =>+ runWorkbench({ python, pluginRoot: PLUGIN_ROOT, environment }, args, input);+ const recipe = {+ repository,+ target: { kind: "repository", paths: [] },+ mode,+ config: { model: "gpt-5.6-sol", approval_policy: "never" },+ pluginVersion: "0.1.0",+ ...settings,+ ...(mode === "deep"+ ? { deepScan: { workers: 2, maxDiscoveryRuns: 5 } }+ : {}),+ };+ const registration = await command(+ [+ "register-cli-scan",+ "--repository",+ repository,+ "--scan-dir",+ scanDir,+ "--registration-json-stdin",+ ],+ JSON.stringify({+ recipe,+ userContext: "Keep the original scan instructions.",+ }),+ );+ const scanId = registration["scanId"] as string;+ const threadId = randomUUID();+ await command([+ "set-scan-thread",+ "--scan-id",+ scanId,+ "--thread-id",+ threadId,+ ]);+ const sessionPath = join(codexHome, "sessions", `rollout-${threadId}.jsonl`);+ await writeFile(+ sessionPath,+ JSON.stringify({+ type: "session_meta",+ payload: { id: threadId, cwd: scanDir },+ }) + "\n",+ );+ if (mode === "deep") {+ await command([+ "begin-deep-scan",+ "--scan-id",+ scanId,+ "--thread-id",+ threadId,+ "--available-parallelism",+ "4",+ "--workflow-version",+ "deep-scan-mcp/v1",+ ]);+ const workerId = randomUUID();+ const prompt = join(scanDir, "setup-prompt.md");+ await writeFile(prompt, "Saved setup prompt.\n");+ for (const status of ["running", "succeeded"]) {+ await command([+ "upsert-deep-scan-worker",+ "--scan-id",+ scanId,+ "--worker-id",+ workerId,+ "--kind",+ "setup",+ "--status",+ status,+ "--prompt-path",+ prompt,+ "--artifact-dir",+ scanDir,+ ]);+ }+ }+ const checkpoint = join(scanDir, "checkpoint.json");+ await writeFile(checkpoint, '{"completed":"setup"}\n');+ return {+ root,+ repository,+ scanDir,+ codexHome,+ python,+ environment,+ command,+ recipe,+ scanId,+ threadId,+ registration,+ sessionPath,+ checkpoint,+ input,+ };+}++test("resume resolves an interrupted scan without changing its ID, recipe, or completed workers", async () => {+ const f = await interruptedScan();+ const before = await f.command([+ "get-deep-scan",+ "--scan-id",+ f.scanId,+ "--thread-id",+ f.threadId,+ ]);+ const resumed = await f.command([+ "get-cli-scan-resume",+ "--scan-id",+ f.scanId,+ ]);+ expect(resumed).toMatchObject({+ ...f.registration,+ recipe: f.recipe,+ threadId: f.threadId,+ });+ expect(+ await f.command([+ "get-deep-scan",+ "--scan-id",+ f.scanId,+ "--thread-id",+ f.threadId,+ ]),+ ).toEqual(before);+ expect(await readFile(f.checkpoint, "utf8")).toBe('{"completed":"setup"}\n');+});++test.each([+ "failed",+ "canceled",+ "standard",+ "changed",+ "replaced",+ "wrong-owner",+])(+ "resume refuses %s scans without altering their saved state",+ async (scenario) => {+ const f = await interruptedScan(+ scenario === "standard" ? "standard" : "deep",+ );+ if (scenario === "failed")+ await f.command([+ "fail-scan",+ "--scan-id",+ f.scanId,+ "--message",+ "Synthetic failure",+ ]);+ if (scenario === "canceled")+ await f.command(["cancel-scan", "--scan-id", f.scanId]);+ if (scenario === "changed")+ await writeFile(join(f.repository, "source.py"), "# changed\n");+ if (scenario === "replaced") {+ await rename(f.repository, join(f.root, "original-repository"));+ await mkdir(f.repository);+ await writeFile(join(f.repository, "source.py"), "# synthetic source\n");+ }+ if (scenario === "wrong-owner")+ await f.command([+ "set-scan-thread",+ "--scan-id",+ f.scanId,+ "--thread-id",+ randomUUID(),+ ]);+ const before = await f.command(["get-scan", "--scan-id", f.scanId]);+ expect(+ await f.command([+ "get-cli-scan-resume",+ "--scan-id",+ f.scanId,+ "--allow-unavailable",+ ]),+ ).toMatchObject({ unavailable: expect.any(String) });+ await expect(+ f.command(["get-cli-scan-resume", "--scan-id", f.scanId]),+ ).rejects.toThrow(+ scenario === "changed"+ ? "revision or contents changed"+ : scenario === "replaced"+ ? "checkout is missing or was replaced"+ : scenario === "wrong-owner"+ ? "original owning CLI session"+ : scenario === "standard"+ ? "Deep Scan with a saved CLI launch recipe"+ : "running scan; completed, failed, and canceled",+ );+ expect(await f.command(["get-scan", "--scan-id", f.scanId])).toEqual(+ before,+ );+ expect(await readFile(f.checkpoint, "utf8")).toBe(+ '{"completed":"setup"}\n',+ );+ },+);++test("CLI resumes the owning Codex thread and preserves running state on a transport failure", async () => {+ const f = await interruptedScan();+ const before = await f.command([+ "get-deep-scan",+ "--scan-id",+ f.scanId,+ "--thread-id",+ f.threadId,+ ]);+ let resumedThread: string | undefined;+ const stdout = capture();+ const stderr = capture();+ const code = await main(+ ["scans", "resume", f.scanId, "--json"],+ stdout.stream,+ stderr.stream,+ {+ ...dependencies({ environment: f.environment, currentDirectory: f.root }),+ runWorkbench: f.command,+ createSecurity: (config) =>+ new TestClient(config, {+ environment: f.environment,+ prepareRuntime: async () => preparedRuntime(f.codexHome),+ resolvePluginPython: async () => f.python,+ runWorkbench,+ createCodex: (options) => ({+ startThread() {+ throw new Error("Resume must not create a new thread.");+ },+ resumeThread(threadId, threadOptions) {+ resumedThread = threadId;+ expect(threadOptions.workingDirectory).toBe(f.scanDir);+ expect(options.env).toMatchObject({+ CODEX_SECURITY_SCAN_ID: f.scanId,+ CODEX_SECURITY_SCAN_DIR: f.scanDir,+ });+ return {+ id: threadId,+ async runStreamed(prompt) {+ expect(prompt).toContain(f.scanId);+ expect(prompt).toContain(+ "Keep the original scan instructions.",+ );+ const joined = await f.command([+ "begin-deep-scan",+ "--scan-id",+ f.scanId,+ "--thread-id",+ threadId,+ "--available-parallelism",+ "4",+ ]);+ expect(joined["deepScan"]).toMatchObject({+ scanId: f.scanId,+ });+ throw new Error("Synthetic transport disconnected");+ },+ };+ },+ }),+ }),+ },+ );+ expect(stderr.text()).toContain("Synthetic transport disconnected");+ expect(code).not.toBe(0);+ expect(resumedThread).toBe(f.threadId);+ expect(+ await f.command([+ "get-deep-scan",+ "--scan-id",+ f.scanId,+ "--thread-id",+ f.threadId,+ ]),+ ).toEqual(before);+ expect(+ (await f.command(["get-scan", "--scan-id", f.scanId]))["scan"],+ ).toMatchObject({ progress: { status: "running" } });+ expect(await readFile(f.checkpoint, "utf8")).toBe('{"completed":"setup"}\n');+});++function resumeClient(+ f: Awaited<ReturnType<typeof interruptedScan>>,+ createCodex: NonNullable<+ ConstructorParameters<typeof TestClient>[1]["createCodex"]+ >,+) {+ return (config: ConstructorParameters<typeof TestClient>[0]) =>+ new TestClient(config, {+ environment: f.environment,+ prepareRuntime: async () => {+ const runtime = preparedRuntime(f.codexHome);+ runtime.plugin.version = JSON.parse(+ await readFile(+ join(PLUGIN_ROOT, ".codex-plugin", "plugin.json"),+ "utf8",+ ),+ ).version;+ return runtime;+ },+ resolvePluginPython: async () => f.python,+ runWorkbench,+ createCodex,+ });+}++async function finishDiscovery(f: Awaited<ReturnType<typeof interruptedScan>>) {+ // Advance the persisted clock to exercise a coordinator reaching its time cap.+ const expired = Bun.spawnSync(+ [+ f.python,+ "-I",+ "-B",+ "-c",+ "import sqlite3, sys; c = sqlite3.connect(sys.argv[1]); c.execute(\"UPDATE deep_scan_runs SET created_at = '2000-01-01T00:00:00+00:00' WHERE scan_id = ?\", (sys.argv[2],)); c.commit()",+ join(f.environment.CODEX_SECURITY_STATE_DIR, "workbench.sqlite3"),+ f.scanId,+ ],+ { stdout: "pipe", stderr: "pipe" },+ );+ expect(expired.exitCode, new TextDecoder().decode(expired.stderr)).toBe(0);+ await cp(join(PLUGIN_ROOT, "examples", "completed-scan"), f.scanDir, {+ recursive: true,+ });+ for (const name of ["scan-manifest.json", "findings.json", "coverage.json"]) {+ const path = join(f.scanDir, name);+ const doc = JSON.parse(await readFile(path, "utf8"));+ if (name === "scan-manifest.json") {+ doc.scan.id = f.scanId;+ const contract = f.registration["contract"] as {+ target: { allowedKinds: string[] };+ };+ doc.scan.target = { kind: contract.target.allowedKinds[0] };+ delete doc.scan.sealedAt;+ delete doc.scan.artifacts;+ } else {+ doc.scanId = f.scanId;+ if (name === "findings.json") doc.findings = [];+ else {+ doc.mode = "deep_repository";+ doc.completeness = "partial";+ doc.surfaces = [];+ doc.deferred = [{ id: "time_cap", reason: "Synthetic time cap" }];+ }+ }+ await writeFile(path, JSON.stringify(doc) + "\n");+ }+ await f.command([+ "finish-deep-scan",+ "--scan-id",+ f.scanId,+ "--terminal-reason",+ "capped",+ "--manifest-path",+ join(f.scanDir, "scan-manifest.json"),+ ]);+}++test.each([+ [false, false],+ [true, false],+ [false, true],+ [true, true],+])(+ "resumed CLI seals the original scan (coordinator finished: %s, bulk: %s)",+ async (alreadyFinished, bulk) => {+ const f = await interruptedScan("deep", bulk);+ if (alreadyFinished) await finishDiscovery(f);+ await appendFile(+ f.sessionPath,+ JSON.stringify({+ type: "event_msg",+ payload: {+ type: "token_count",+ info: {+ total_token_usage: { input_tokens: 10000, output_tokens: 2000 },+ },+ },+ }) + "\n",+ );+ const stdout = capture();+ const stderr = capture();+ const code = await main(+ bulk+ ? ["bulk-scan", f.input, "--output-dir", f.root, "--recover", "--json"]+ : ["scans", "resume", f.scanId, "--json"],+ stdout.stream,+ stderr.stream,+ {+ ...dependencies({+ environment: f.environment,+ currentDirectory: f.root,+ }),+ runWorkbench: f.command,+ createSecurity: resumeClient(f, () => ({+ startThread() {+ throw new Error("Unexpected new session");+ },+ resumeThread(threadId) {+ expect(threadId).toBe(f.threadId);+ return {+ id: threadId,+ async runStreamed() {+ if (!alreadyFinished) await finishDiscovery(f);+ return { events: completedEvents(threadId) };+ },+ };+ },+ })),+ },+ );+ // Preserve the CLI's nonzero exit for a valid, sealed partial result.+ expect(code, stderr.text()).toBe(2);+ const result = JSON.parse(stdout.text());+ if (bulk) {+ expect(result, stderr.text()).toMatchObject({ incomplete: 1, failed: 0 });+ const receipts = (await readFile(result.resultsPath, "utf8"))+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line));+ expect(receipts).toHaveLength(2);+ expect(receipts[1]).toMatchObject({+ attempt: 1,+ outputDir: f.scanDir,+ status: "completed_with_incomplete_coverage",+ cost: { inputTokens: 10000, outputTokens: 2000 },+ });+ // Reconcile a crash after sealing but before the bulk receipt was appended.+ await writeFile(result.resultsPath, JSON.stringify(receipts[0]) + "\n");+ const reconciledOutput = capture();+ expect(+ await main(+ ["bulk-scan", f.input, "--output-dir", f.root, "--recover", "--json"],+ reconciledOutput.stream,+ stderr.stream,+ {+ ...dependencies({+ onRun() {+ throw new Error("A sealed scan needs no Codex invocation");+ },+ }),+ runWorkbench: f.command,+ },+ ),+ ).toBe(2);+ expect(JSON.parse(reconciledOutput.text())).toMatchObject({+ incomplete: 1,+ failed: 0,+ });+ const reconciled = (await readFile(result.resultsPath, "utf8"))+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line));+ expect(reconciled[1]).toMatchObject({+ attempt: 1,+ cost: { inputTokens: 10000, outputTokens: 2000 },+ });+ // A subsequent bulk recovery must skip the reconciled completion.+ const nextOutput = capture();+ expect(+ await main(+ ["bulk-scan", f.input, "--output-dir", f.root, "--recover", "--json"],+ nextOutput.stream,+ stderr.stream,+ { ...dependencies(), runWorkbench: f.command },+ ),+ ).toBe(2);+ expect(JSON.parse(nextOutput.text())).toMatchObject({+ skipped: 1,+ incomplete: 1,+ failed: 0,+ });+ } else {+ expect(result.coverage.completeness).toBe("partial");+ expect(result.manifest.scan.id).toBe(f.scanId);+ expect(result.manifest.scan.sealedAt).toBeString();+ expect(result.cost.inputTokens).toBe(10000);+ expect(result.cost.outputTokens).toBe(2000);+ }+ expect(+ (await f.command(["get-scan", "--scan-id", f.scanId]))["scan"],+ ).toMatchObject({+ progress: { status: "complete" },+ continuationThreadId: f.threadId,+ });+ expect(+ (await f.command(["list-scans", "--repository", f.repository]))["scans"],+ ).toHaveLength(1);+ expect(await readFile(f.checkpoint, "utf8")).toBe(+ '{"completed":"setup"}\n',+ );+ await expect(+ f.command(["get-cli-scan-resume", "--scan-id", f.scanId]),+ ).rejects.toThrow("running scan");+ },+);++test.each([+ "single",+ "bulk",+ "unsupported-schema",+ "wrong-producer",+ "changed-findings",+])(+ "resume preserves sealed artifacts across a plugin upgrade (%s)",+ async (scenario) => {+ const f = await interruptedScan("deep", scenario === "bulk");+ await finishDiscovery(f);+ const oldPlugin = join(f.root, "old-plugin");+ for (const path of ["scripts", "schemas", ".codex-plugin"]) {+ await cp(join(PLUGIN_ROOT, path), join(oldPlugin, path), {+ recursive: true,+ });+ }+ const pluginManifest = join(oldPlugin, ".codex-plugin", "plugin.json");+ const plugin = JSON.parse(await readFile(pluginManifest, "utf8"));+ plugin.version = f.recipe.pluginVersion;+ await writeFile(pluginManifest, JSON.stringify(plugin));+ await runWorkbench(+ { python: f.python, pluginRoot: oldPlugin, environment: f.environment },+ ["prepare-scan-completion", "--scan-id", f.scanId],+ );+ const manifestPath = join(f.scanDir, "scan-manifest.json");+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));+ expect(manifest.scan.producer.version).toBe(f.recipe.pluginVersion);+ if (scenario === "unsupported-schema") manifest.schemaVersion = "999.0";+ if (scenario === "wrong-producer")+ manifest.scan.producer.name = "different-producer";+ if (scenario === "unsupported-schema" || scenario === "wrong-producer") {+ await writeFile(manifestPath, JSON.stringify(manifest));+ }+ if (scenario === "changed-findings") {+ await appendFile(join(f.scanDir, "findings.json"), "\n");+ }+ const artifactNames = [+ "scan-manifest.json",+ "findings.json",+ "coverage.json",+ "report.md",+ ];+ const artifacts = await Promise.all(+ artifactNames.map((name) => readFile(join(f.scanDir, name))),+ );+ const before = await f.command(["get-scan", "--scan-id", f.scanId]);+ const rejected = !["single", "bulk"].includes(scenario);+ let turns = 0;+ const stdout = capture();+ const stderr = capture();+ const code = await main(+ scenario === "bulk"+ ? ["bulk-scan", f.input, "--output-dir", f.root, "--recover", "--json"]+ : ["scans", "resume", f.scanId, "--json"],+ stdout.stream,+ stderr.stream,+ {+ ...dependencies({+ environment: f.environment,+ currentDirectory: f.root,+ }),+ runWorkbench: f.command,+ createSecurity: resumeClient(f, () => ({+ startThread() {+ throw new Error("Unexpected new session");+ },+ resumeThread(threadId) {+ expect(threadId).toBe(f.threadId);+ return {+ id: threadId,+ async runStreamed() {+ turns++;+ return { events: completedEvents(threadId) };+ },+ };+ },+ })),+ },+ );+ expect(code, stderr.text()).toBe(2);+ expect(+ await Promise.all(+ artifactNames.map((name) => readFile(join(f.scanDir, name))),+ ),+ ).toEqual(artifacts);+ const after = await f.command(["get-scan", "--scan-id", f.scanId]);+ if (rejected) {+ expect(stderr.text()).toContain("Cannot resume sealed scan");+ expect(turns).toBe(0);+ expect(after).toEqual(before);+ } else {+ expect(after["scan"], stderr.text()).toMatchObject({+ progress: { status: "complete" },+ continuationThreadId: f.threadId,+ });+ if (scenario === "bulk") {+ expect(JSON.parse(stdout.text())).toMatchObject({+ incomplete: 1,+ failed: 0,+ });+ const receipts = (await readFile(join(f.root, "results.jsonl"), "utf8"))+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line));+ expect(receipts).toHaveLength(2);+ expect(receipts[1]).toMatchObject({+ attempt: 1,+ outputDir: f.scanDir,+ status: "completed_with_incomplete_coverage",+ });+ }+ }+ },+);++test("CLI saves launch settings before execution without depending on the prompt file", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "state", "codex-home");+ await mkdir(repository);+ await mkdir(codexHome, { recursive: true });+ await writeFile(join(repository, "source.py"), "# synthetic source\n");+ const promptFile = join(root, "post-scan.md");+ const postScanPrompt = "Keep these original post-scan instructions.\n";+ await writeFile(promptFile, postScanPrompt);+ const python = Bun.which("python3") ?? Bun.which("python");+ if (python === null) throw new Error("Python is required for this test.");+ const environment = {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ TEMP: process.env["TEMP"],+ TMP: process.env["TMP"],+ CODEX_HOME: codexHome,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ OPENAI_API_KEY: "synthetic-launch-key",+ };+ const command = (args: readonly string[], input?: string) =>+ runWorkbench({ python, pluginRoot: PLUGIN_ROOT, environment }, args, input);+ const stdout = capture();+ const stderr = capture();+ const code = await main(+ [+ "scan",+ repository,+ "--mode",+ "deep",+ "--output-dir",+ join(root, "scan"),+ "--safety-identifier",+ "synthetic-original-user",+ "--post-scan-prompt-file",+ promptFile,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ {+ ...dependencies({ environment, currentDirectory: root }),+ runWorkbench: command,+ createSecurity: (config) =>+ new TestClient(config, {+ environment,+ prepareRuntime: async () => preparedRuntime(codexHome),+ resolvePluginPython: async () => python,+ runWorkbench,+ createCodex: () => {+ throw new Error("Synthetic stop after registration");+ },+ }),+ },+ );+ expect(code).toBe(2);+ expect(stderr.text()).toContain("Synthetic stop after registration");+ await writeFile(+ promptFile,+ "Changed instructions that must not replace the saved text.",+ );+ await rm(promptFile);+ const scans = (await command(["list-scans", "--repository", repository]))[+ "scans"+ ] as Array<{ scanId: string }>;+ expect(scans).toHaveLength(1);+ const saved = await command([+ "get-scan-recipe",+ "--scan-id",+ scans[0]!.scanId,+ ]);+ expect(saved["recipe"]).toMatchObject({+ safetyIdentifier: "synthetic-original-user",+ postScanPrompt,+ });+ expect(JSON.stringify(saved)).not.toContain("synthetic-launch-key");+ expect(JSON.stringify(saved)).not.toContain(promptFile);+});++test.each([false, true])(+ "resume restores saved launch settings (bulk: %s)",+ async (bulk) => {+ const settings = {+ safetyIdentifier: "synthetic-original-user",+ postScanPrompt: "Run these exact saved post-scan instructions.\n",+ };+ const f = await interruptedScan("deep", bulk, settings);+ const prompts: string[] = [];+ const stdout = capture();+ const stderr = capture();+ const code = await main(+ bulk+ ? ["bulk-scan", f.input, "--output-dir", f.root, "--recover", "--json"]+ : ["scans", "resume", f.scanId, "--json"],+ stdout.stream,+ stderr.stream,+ {+ ...dependencies({+ environment: f.environment,+ currentDirectory: f.root,+ }),+ runWorkbench: f.command,+ createSecurity: resumeClient(f, (options) => {+ expect(options.env?.["CODEX_SAFETY_IDENTIFIER"]).toBe(+ settings.safetyIdentifier,+ );+ return {+ startThread() {+ throw new Error("Resume must use the original session.");+ },+ resumeThread(threadId) {+ expect(threadId).toBe(f.threadId);+ return {+ id: threadId,+ async runStreamed(prompt) {+ prompts.push(prompt as string);+ if (prompts.length === 1) await finishDiscovery(f);+ return { events: completedEvents(threadId) };+ },+ };+ },+ };+ }),+ },+ );+ expect(code, stderr.text()).toBe(2);+ expect(prompts, stderr.text()).toHaveLength(2);+ expect(prompts[1]).toBe(settings.postScanPrompt);+ expect(+ (await f.command(["get-scan", "--scan-id", f.scanId]))["scan"],+ ).toMatchObject({+ progress: { status: "complete" },+ continuationThreadId: f.threadId,+ });+ },+);++test("missing session logs do not create another session or fail the original scan", async () => {+ const f = await interruptedScan();+ await rm(f.sessionPath);+ const stdout = capture();+ const stderr = capture();+ const code = await main(+ ["scans", "resume", f.scanId],+ stdout.stream,+ stderr.stream,+ {+ ...dependencies({ environment: f.environment, currentDirectory: f.root }),+ runWorkbench: f.command,+ createSecurity: resumeClient(f, () => {+ throw new Error("Must not invoke Codex without the original session");+ }),+ },+ );+ expect(code).not.toBe(0);+ expect(stderr.text()).toContain("original Codex session");+ expect(+ (await f.command(["get-scan", "--scan-id", f.scanId]))["scan"],+ ).toMatchObject({ progress: { status: "running" } });+});++test.each(["failed", "missing-checkout", "missing-session", "standard"])(+ "bulk recovery retries an unavailable %s scan without overwriting its attempt",+ async (scenario) => {+ const f = await interruptedScan(+ scenario === "standard" ? "standard" : "deep",+ true,+ );+ if (scenario === "failed")+ await f.command([+ "fail-scan",+ "--scan-id",+ f.scanId,+ "--message",+ "Synthetic failure",+ ]);+ if (scenario === "missing-checkout")+ await rm(f.repository, { recursive: true });+ if (scenario === "missing-session") await rm(f.sessionPath);+ const before = await f.command(["get-scan", "--scan-id", f.scanId]);+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies({+ environment: f.environment,+ currentDirectory: f.root,+ });+ let attempts = 0;+ expect(+ await main(+ ["bulk-scan", f.input, "--output-dir", f.root, "--recover", "--json"],+ stdout.stream,+ stderr.stream,+ {+ ...deps,+ runWorkbench: f.command,+ createSecurity: (config) => ({+ ...deps.createSecurity(config),+ run: async (repository, options = {}) => {+ attempts++;+ expect(options.resumeScanId).toBeUndefined();+ expect(options.mode).toBe(f.recipe.mode);+ expect(options.outputDir).toBe(+ join(f.root, "artifacts", "repo", "attempt-2"),+ );+ expect(repository).toBe(+ join(f.root, "recovery-checkouts", "repo", "attempt-2"),+ );+ expect(+ (+ await readFile(join(repository, "source.py"), "utf8")+ ).replaceAll("\r\n", "\n"),+ ).toBe("# synthetic source\n");+ return {+ coverage: { completeness: "complete" },+ cost: null,+ } as import("../src/result.js").ScanResult;+ },+ }),+ },+ ),+ stderr.text(),+ ).toBe(0);+ expect(attempts).toBe(1);+ expect(JSON.parse(stdout.text())).toMatchObject({+ completed: 1,+ failed: 0,+ });+ expect(await f.command(["get-scan", "--scan-id", f.scanId])).toEqual(+ before,+ );+ expect(await readFile(f.checkpoint, "utf8")).toBe(+ '{"completed":"setup"}\n',+ );+ },+);++test("resume requires an explicit scan ID", async () => {+ const stdout = capture();+ const stderr = capture();+ const code = await main(["scans", "resume"], stdout.stream, stderr.stream, {+ ...dependencies(),+ runWorkbench: async () => {+ throw new Error("Must select a scan explicitly");+ },+ });+ expect(code).toBe(2);+ expect(stderr.text()).toContain("scanId");+});