OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix: preserve Deep Scan findings across terminal failures (#617)
soyeon-oai86e1c3f5b29c
diff --git a/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-000 b/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-000index 65ea38538..7ced89d9c 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 916cd6a7a..6d7d85274 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/references/core-scan.md b/sdk/typescript/_bundled_plugin/references/core-scan.mdindex 5e66bfe21..26c80cbba 100644--- a/sdk/typescript/_bundled_plugin/references/core-scan.md+++ b/sdk/typescript/_bundled_plugin/references/core-scan.md@@ -9,7 +9,7 @@ Perform one complete, evidence-backed security audit of the exact supplied repos3. While the baseline runs, read `threat-model.md` once and obtain its independent architecture review within the available worker allowance. Verify its resource rows against their actual consumers, use the returned canonical `threatModel` as the generated model, and build source-backed investigation packets from it. Carry that object and its evidence into the final result instead of reconstructing a shorter summary. Preserve any user-supplied threat model unchanged as the authoritative security assumptions; map its real surfaces and controls without replacing it.4. Group related source-backed security questions into investigation packets. Each group shares its plausible attacker, protected asset, entry points, expected controls, sensitive operations, component relationships, and actual repository-relative source anchors. Keep each question concrete, preserve distinct attacker boundaries and security mechanisms, and let investigators establish the detailed dataflow.5. Launch focused investigator subagents with `fork_turns: "none"` as soon as useful packet groups exist. Choose their number and assignments from the amount, complexity, and independence of source-backed work, bounded by the supplied available subagent allowance; use fewer for related packets and more only when distinct surfaces justify them. Keep mapping other surfaces while they run. Send each only its focused-investigator prompt below, assigned packets, investigator perspective, repository path, authorized scope, any supplied scoped-source inventory, exact user context, supplied threat model, applicable packet-specific security guidance and its resolver command, the optional authoritative knowledge-base location, and verified search command. Do not include this reference or another worker's prompt. Supporting code may be outside a requested path, but an affected entry point, control, or operation must be in scope.-6. Reconcile source coverage before combining findings. Union only the baseline and focused investigators' `fully_reviewed_files` with files the parent fully security-audited, then intersect that set with the supplied authorized inventory or an inventory of the selected current scope. Architecture mapping alone and supporting files outside that inventory do not count toward completed audit coverage. Finish the remaining in-scope files in coherent groups, reusing available investigators within the same allowance. Inspect implementation-owning generated or compressed code as data. Do not add overlapping worker counts or claim that a search hit completed a file. Keep this one transient set; do not create a separate progress ledger or receipt format. If a user limit or unavailable source prevents completion, identify the actual remaining paths and report partial coverage. Then combine baseline and investigator findings once. Group observations only when they share the same broken security control and effective remediation; preserve every affected route, operation, sink, and supporting source location. Never merge different security failures solely because they share a CWE.+6. Before combining or revalidating any returned baseline or investigator result, persist it through the caller's bound `record_codex_security_scan_draft` tool when available, using `complete: false` and partial coverage. Give each candidate a stable `candidateId`; put candidates awaiting parent validation in `coverage.deferred` with a meaningful reason and their original finding payload under `candidate`. Preserve returned counterevidence and unresolved questions too. Checkpoint again after each validation decision, without waiting for other workers or the final report. Put source-validated findings in `findings` with the same `provenance.candidateId`; for a rejection, retain the candidate ID, original evidence, and source-backed counterevidence on a `rejected` coverage surface. An unfinished scan must retain its saved findings and pending candidates without presenting pending work as validated. Reconcile source coverage before combining findings. Union only the baseline and focused investigators' `fully_reviewed_files` with files the parent fully security-audited, then intersect that set with the supplied authorized inventory or an inventory of the selected current scope. Architecture mapping alone and supporting files outside that inventory do not count toward completed audit coverage. Finish the remaining in-scope files in coherent groups, reusing available investigators within the same allowance. Inspect implementation-owning generated or compressed code as data. Do not add overlapping worker counts or claim that a search hit completed a file. Keep this one transient set; do not create a separate progress ledger or receipt format. If a user limit or unavailable source prevents completion, identify the actual remaining paths and report partial coverage. Then combine baseline and investigator findings once. Group observations only when they share the same broken security control and effective remediation; preserve every affected route, operation, sink, and supporting source location. Never merge different security failures solely because they share a CWE.7. Independently validate each unique finding against local source once. Establish its attacker, entry point, trust boundary, attacker-controlled dataflow, transformations, broken control, sensitive operation, prerequisites, effective mitigations, strongest counterevidence, and concrete impact. Record concise, source-backed `rootCause.summary`, `validation.summary`, `attackPath.dataflow.summary`, and `attackPath.reachability.summary` alongside their supporting facts; determine impact, likelihood, and severity from those established facts. State optional configuration, dependency-version, or deployment prerequisites; do not require proof of a real deployment or runtime reproduction. A public library or parser boundary is sufficient when callers control the input. Reject only with source-backed counterevidence, preserve valid baseline findings, record material unresolved proof gaps, and apply the severity rules below.8. Assemble complete semantic `scope`, `threatModel`, `findings`, and `coverage` using the plugin's `examples/completed-scan/` and `schemas/` as shape references, never as values to copy. Use the canonical field mapping and scenario reconciliation in `threat-model.md`, preserving supplied models unchanged and retaining source-backed architecture, capability, deployment, and uncertainty facts. Give each finding a stable lowercase vulnerability-family `ruleId`, its precise `taxonomy.category` and `taxonomy.cwe` values, genuine `provenance.source`, an instance when separately reported findings would otherwise collide, a `root_control` location when identifiable, all materially affected locations, calibrated severity and rationale, confidence and rationale, verified nonempty source evidence, attacker-to-sink reachability, and practical remediation. Use actual coverage surface labels and dispositions; report reviewed surfaces, explicit exclusions, deferred work, and unresolved questions honestly, and mark coverage `complete` only when the requested source scope was actually reviewed. Preserve every genuine finding, evidence item, user-supplied assumption, and unresolved proof gap in the caller's complete semantic result.diff --git a/sdk/typescript/_bundled_plugin/references/final-report.md b/sdk/typescript/_bundled_plugin/references/final-report.mdindex 03dcd6880..5886eff61 100644--- a/sdk/typescript/_bundled_plugin/references/final-report.md+++ b/sdk/typescript/_bundled_plugin/references/final-report.md@@ -22,13 +22,15 @@ For each finding, supply an evidence-supported lowercase vulnerability-family `rSupply semantic coverage as `{ completeness, surfaces, explicitExclusions, deferred }`, with each surface using the actual `label` and one existing `disposition`. Mark coverage `partial` when a deferred item or `needs_follow_up` surface remains; preserve its real reason and supporting context. Each deferred item needs a meaningful reason; preserve any existing `id` or `candidateId`. The workbench derives a missing ID from its candidate identity or stable deferred-work details. Open questions may be nonempty strings or `{ question, followUpPrompt? }` objects. The workbench derives target and scope metadata, scope include and exclude paths, coverage mode and inventory strategy, finding identities and fingerprints, and surface IDs. Do not put those workbench-owned values or top-level coverage receipt references into the semantic draft.-After a workbench-owned Standard or workbench-backed diff draft is accepted, or the Deep coordinator returns its parent scan's canonical manifest, call `complete_codex_security_scan({ scanId, handoffClaimToken? })` and use its returned completion metadata. An SDK-owned scan returns its unsealed canonical files without calling a completion tool or finalizer; the SDK owns completion and report generation. Read full canonical results only when explicitly requested. For a terminal/chat workflow without a `scanId` or completion tool, retain `python <plugin_dir>/scripts/finalize_scan_contract.py --scan-dir <scan_dir> --source-root <repo_root>` after writing the canonical JSON. Outside the SDK path, do not mark the scan goal complete until finalization succeeds and the generated report exists.+During a host-backed scan, checkpoint saved findings and pending candidates with `complete: false`; a checkpoint is not a completed audit. After a final workbench-owned Standard or workbench-backed diff draft is accepted with `complete: true` (or the backwards-compatible omitted flag), or the Deep coordinator returns its parent scan's canonical manifest, call `complete_codex_security_scan({ scanId, handoffClaimToken? })` and use its returned completion metadata. An SDK-owned scan returns its unsealed canonical files without calling a completion tool or finalizer; the SDK owns completion and report generation. Read full canonical results only when explicitly requested. For a terminal/chat workflow without a `scanId` or completion tool, retain `python <plugin_dir>/scripts/finalize_scan_contract.py --scan-dir <scan_dir> --source-root <repo_root>` after writing the canonical JSON. Outside the SDK path, do not mark the scan goal complete until finalization succeeds and the generated report exists.++On a confirmed failure or explicit cancellation, the workbench preserves saved results without marking the scan successful. Report validated findings separately from pending candidates and explain the incomplete coverage. Use the retained report and exports; do not start additional model work after cancellation or replace saved results with a no-findings response.After `complete_codex_security_scan` succeeds, include its returned `usage.totalTokens`, `usage.inputTokens`, and `usage.cachedInputTokens` in the final response when `usage.coverage` is `complete` or `partial`; explicitly label a partial measurement. If coverage is `unavailable`, say that token usage could not be measured instead of reporting zero or estimating a cost. Report only measured completion metadata in a terminal/chat host. Token usage is workbench metadata, not a reason to modify sealed scan artifacts or the deterministic report.Before workbench-owned Standard or workbench-backed diff completion, require `record_codex_security_scan_draft` to succeed. Before Deep completion, require the coordinator to return the parent scan's already-authored canonical manifest; do not submit another draft or rerun worker phases. SDK-owned Standard and terminal diff workflows instead verify their canonical JSON before the appropriate owner finalizes it. Completion validates and seals existing canonical artifacts and generates `report.md`; it does not create missing artifacts or run skipped scan phases.-An MCP `-32602` input rejection, an `isError: true` result reporting `Input validation error`, or an explicit pre-write rejection of complete coverage containing deferred work or a follow-up surface makes no draft write. Correct only the named paths in the same draft, preserving all valid findings, fields, evidence, and deferred work; retry the same scan at most twice. Stop after the first accepted draft. Do not blindly retry an ambiguous transport or write failure.+An MCP `-32602` input rejection, an `isError: true` result reporting `Input validation error`, or an explicit pre-write rejection of complete coverage containing deferred work or a follow-up surface makes no draft write. Correct only the named paths in the same draft, preserving all valid findings, fields, evidence, and deferred work; retry the same scan at most twice. Stop final submission after the first accepted complete draft; an accepted complete:false checkpoint does not end the audit. Do not blindly retry an ambiguous transport or write failure.For any other required scan phase, canonical-artifact write, or on-disk existence check that fails before completion, stop the current response and surface the exact workflow blocker. Do not call completion with missing artifacts, return a final report or no-findings result, or satisfy a structured output schema. Leave the durable scan available for a later continuation instead of canceling or failing it solely because canonical assembly is blocked.diff --git a/sdk/typescript/_bundled_plugin/references/scan-artifacts.md b/sdk/typescript/_bundled_plugin/references/scan-artifacts.mdindex c10523de6..e4fabb441 100644--- a/sdk/typescript/_bundled_plugin/references/scan-artifacts.md+++ b/sdk/typescript/_bundled_plugin/references/scan-artifacts.md@@ -40,7 +40,7 @@ End each repository-scoped threat model with these two lines:### Compact Deep And Workbench-Backed Diff Discovery-Workbench-owned Standard scans submit findings and coverage through `record_codex_security_scan_draft`; SDK-owned Standard scans write unsealed canonical files directly. Deep scans run complete Standard scan workers, each of which submits its validated findings, coverage, threat model, and optional scope through its bound `record_codex_security_scan_draft` tool. The coordinator semantically reduces those complete results and writes the parent scan's unsealed `scan-manifest.json`, `findings.json`, and `coverage.json`. The parent does not list candidates, rerun validation or attack-path phases, or submit another draft. Workbench-backed diff scans retain the compact artifacts described below.+Workbench-owned Standard scans submit findings and coverage through `record_codex_security_scan_draft`; SDK-owned Standard scans write unsealed canonical files directly. Deep scans run complete Standard scan workers, each of which saves `complete: false` checkpoints and submits its final validated findings, coverage, threat model, and optional scope through its bound `record_codex_security_scan_draft` tool. Pending candidates retain their original evidence in `coverage.deferred`. Host-owned immutable checkpoints survive retries, cancellation, and failure; a checkpoint alone is never an accepted complete worker result. The coordinator semantically reduces those complete results and writes the parent scan's unsealed `scan-manifest.json`, `findings.json`, and `coverage.json`. The parent does not list candidates, rerun validation or attack-path phases, or submit another draft. Workbench-backed diff scans retain the compact artifacts described below.- A workbench-backed diff scan records all candidates once with `record_codex_security_discovery_candidates({ scanId, candidates })` and reads the canonical candidates with `list_codex_security_candidates({ scanId, cursor?, limit? })`.- The writer validates candidates against assigned source paths, merges rows with the same CWE ids, locations, and optional instance, preserves their text, and assigns deterministic `candidate_id` values.diff --git a/sdk/typescript/_bundled_plugin/references/scan-contract.md b/sdk/typescript/_bundled_plugin/references/scan-contract.mdindex 34100abbc..97f9efca0 100644--- a/sdk/typescript/_bundled_plugin/references/scan-contract.md+++ b/sdk/typescript/_bundled_plugin/references/scan-contract.md@@ -1,13 +1,13 @@-# Completed Scan Contract+# Sealed Scan Contract-This contract defines the canonical machine-readable documents for completed scans and their readable markdown report projection.+This contract defines the canonical machine-readable documents for scans that reached a sealed terminal outcome and their readable markdown report projection.## Canonical Documents-A completed semantic bundle contains these files under `<scan_dir>`:+A sealed terminal bundle contains these files under `<scan_dir>`:-- `scan-manifest.json`: immutable completed-scan receipt after finalization-- `findings.json`: semantic finding records for the completed scan+- `scan-manifest.json`: immutable terminal scan receipt after finalization+- `findings.json`: semantic finding records retained when the scan reached its terminal outcome- `coverage.json`: structured coverage summary with detailed receipt referencesCanonical UTF-8 document sizes are bounded consistently by the producer and SDK: `scan-manifest.json` is limited to 16 MiB, `findings.json` to 128 MiB, and `coverage.json` to 32 MiB. Finalization rejects oversized inputs or generated documents before sealing or changing scan outputs. Keep detailed evidence in scan-local artifacts and reference it from the canonical summaries.@@ -20,11 +20,22 @@ Deep-scan SARIF results and CSV rows preserve their existing instance-level presThis bundle records immutable scan observations. It is not a workflow-state database. Consumers must store mutable annotations, lifecycle decisions, external links, retention policy, and synchronization state separately.-Retention is an explicit consumer decision. Producing a completed-scan bundle must not silently copy it into an archive.+Retention is an explicit consumer decision. Producing a sealed bundle must not silently copy it into an archive.## Manifest Semantics-A sealed manifest records the completed timestamp and hashes for the canonical documents and immutable evidence receipts included in that bundle. Readable reports and generated exports are projections and are not included in the canonical seal. Later adapters may read the sealed bundle to create projections, but must not mutate the sealed manifest or canonical documents. Store projections separately. Every sealed manifest includes exactly one artifact record for each canonical JSON document, and artifact paths must not repeat.+A sealed manifest records the terminal timestamp and hashes for the canonical documents and immutable evidence receipts included in that bundle. Readable reports and generated exports are projections and are not included in the canonical seal. Later adapters may read the sealed bundle to create projections, but must not mutate the sealed manifest or canonical documents. Store projections separately. Every sealed manifest includes exactly one artifact record for each canonical JSON document, and artifact paths must not repeat.++`scan.status` records why the bundle was sealed:++| Status | Meaning |+| --- | --- |+| `completed` | The requested scan reached normal completion. |+| `failed` | The scan stopped after an unrecoverable failure; retained artifacts may be partial. |+| `canceled` | The scan stopped after an explicit cancellation; retained artifacts may be partial. |+| `interrupted` | The scan stopped before normal completion because execution was interrupted; retained artifacts may be partial. |++Only `completed` supports a completed-scan conclusion. For every stopped outcome, consumers must preserve retained findings and coverage while treating absence of findings as inconclusive.## Target Snapshotsdiff --git a/sdk/typescript/_bundled_plugin/schemas/scan-manifest.schema.json b/sdk/typescript/_bundled_plugin/schemas/scan-manifest.schema.jsonindex 21db96f10..853335e6b 100644--- a/sdk/typescript/_bundled_plugin/schemas/scan-manifest.schema.json+++ b/sdk/typescript/_bundled_plugin/schemas/scan-manifest.schema.json@@ -1,7 +1,7 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","$id": "https://openai.com/codex-security/schemas/scan-manifest.schema.json",- "title": "Codex Security completed scan manifest",+ "title": "Codex Security sealed scan manifest","type": "object","required": ["documentType",@@ -53,7 +53,7 @@}},"status": {- "const": "completed"+ "enum": ["completed", "failed", "canceled", "interrupted"]},"startedAt": {"type": "string",diff --git a/sdk/typescript/_bundled_plugin/schemas/tools/scan-draft.schema.json b/sdk/typescript/_bundled_plugin/schemas/tools/scan-draft.schema.jsonindex d32892223..5e5db7ac4 100644--- a/sdk/typescript/_bundled_plugin/schemas/tools/scan-draft.schema.json+++ b/sdk/typescript/_bundled_plugin/schemas/tools/scan-draft.schema.json@@ -574,6 +574,25 @@"provenance": {"type": "object","properties": {+ "sourceFindingIds": {+ "type": "array",+ "items": { "$ref": "#/$defs/text" },+ "uniqueItems": true,+ "description": "Host-provided source finding references represented by this Deep reduction. Preserve every assigned reference exactly once."+ },+ "sourceFindings": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": { "$ref": "#/$defs/text" },+ "finding": { "type": "object", "additionalProperties": true }+ },+ "required": ["id", "finding"],+ "additionalProperties": false+ },+ "description": "Original source payloads retained by the host for lossless semantic merges."+ },"source": {"$ref": "#/$defs/text","description": "The actual finding producer. Use local_plugin only for a finding discovered by this plugin."@@ -805,6 +824,10 @@"scanDraftInput": {"type": "object","properties": {+ "complete": {+ "type": "boolean",+ "description": "Set false to save progress without declaring this worker or parent audit finished. Omit or set true only for the terminal result. Put provisional candidates in coverage.deferred, not findings."+ },"scanId": {"$ref": "#/$defs/scanId"},diff --git a/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py b/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.pyindex 4aabe29ce..a9de0bffe 100644--- a/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py+++ b/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py@@ -3,6 +3,7 @@from __future__ import annotationsimport argparse+import hashlibimport jsonimport osimport shutil@@ -39,6 +40,8 @@ DEEP_SCAN_TERMINAL_REASONS = ("saturated", "capped")DEEP_SCAN_WORKFLOW_VERSION = "deep-security-scan/v1"DEEP_SCAN_COORDINATOR_LEASE_SECONDS = 30DEEP_SCAN_LEGACY_COORDINATOR_GRACE_SECONDS = 120+DEEP_SCAN_MAX_ERROR_LENGTH = 2400+DEEP_SCAN_PUBLICATION_ERROR_SEPARATOR = "\nOriginal Deep Scan failure:\n"def register_subcommands(subparsers: Any, positive_int: Callable[[str], int]) -> None:@@ -120,6 +123,11 @@ def register_subcommands(subparsers: Any, positive_int: Callable[[str], int]) ->)fail_deep_scan.add_argument("--coordinator-generation", type=positive_int)+ publication_failure = subparsers.add_parser("record-deep-scan-publication-failure")+ publication_failure.add_argument("--scan-id", required=True)+ publication_failure.add_argument("--message", required=True)+ publication_failure.add_argument("--coordinator-generation", type=positive_int)+def non_negative_int(value: str) -> int:parsed = int(value)@@ -143,6 +151,7 @@ class DeepScanDependencies:safe_segment: Callable[[str], str]compact_timestamp: Callable[[], str]scan_completion_lock: Callable[[str], Any]+ preserve_stopped_results: Callable[[sqlite3.Connection, str], None]_dependencies: DeepScanDependencies | None = None@@ -163,6 +172,34 @@ def now() -> str:return dependencies().now()+def _bounded_error_text(message: str, maximum: int) -> str:+ if len(message) <= maximum:+ return message+ digest = hashlib.sha256(message.encode()).hexdigest()+ suffix = f"\n...[truncated; sha256:{digest}]"+ if len(suffix) >= maximum:+ return message[:maximum]+ return f"{message[: maximum - len(suffix)]}{suffix}"+++def deep_scan_error(run: sqlite3.Row) -> str | None:+ original = run["error_message"]+ publication = run["publication_error_message"]+ if not isinstance(publication, str):+ return original if isinstance(original, str) else None+ if not isinstance(original, str):+ return publication+ available = DEEP_SCAN_MAX_ERROR_LENGTH - len(DEEP_SCAN_PUBLICATION_ERROR_SEPARATOR)+ publication_budget = min(len(publication), available // 2)+ original_budget = min(len(original), available - publication_budget)+ publication_budget = min(len(publication), available - original_budget)+ return (+ _bounded_error_text(publication, publication_budget)+ + DEEP_SCAN_PUBLICATION_ERROR_SEPARATOR+ + _bounded_error_text(original, original_budget)+ )++def _parse_timestamp(value: str) -> datetime:if isinstance(value, str) and value.endswith(("Z", "z")):value = value[:-1] + "+00:00"@@ -439,7 +476,7 @@ def deep_scan_state(connection: sqlite3.Connection, scan_id: str) -> dict[str, A"canonicalArtifacts": canonical_artifacts,"manifestPath": run["manifest_path"],"terminalReason": run["terminal_reason"],- "error": run["error_message"],+ "error": deep_scan_error(run),"createdAt": run["created_at"],"updatedAt": run["updated_at"],"completedAt": run["completed_at"],@@ -2022,9 +2059,59 @@ def fail_deep_scan_locked(raiseif promotion is not None:finish_staged_file(promotion)+ dependencies().preserve_stopped_results(connection, scan_id)+ return deep_scan_result(connection, scan_id)+++def record_deep_scan_publication_failure(+ connection: sqlite3.Connection, args: argparse.Namespace+) -> dict[str, Any]:+ scan_id = require_uuid(args.scan_id, "scan-id")+ message = optional_text(args.message, maximum=2400)+ if message is None:+ raise SystemExit("message is required.")+ with scan_completion_lock(scan_id):+ connection.execute("BEGIN IMMEDIATE")+ try:+ run = require_deep_scan_run(connection, scan_id)+ require_current_coordinator(run, args)+ scan = require_scan(connection, scan_id)+ if (+ run["status"] not in {"failed", "canceled", "interrupted"}+ or scan["status"] != "failed"+ ):+ raise SystemExit(+ "Saved result publication failures can only update a stopped Deep Scan."+ )+ if scan["seal_manifest_digest"] is not None:+ connection.commit()+ return deep_scan_result(connection, scan_id)+ if run["publication_error_message"] != message:+ timestamp = now()+ connection.execute(+ """+ UPDATE deep_scan_runs+ SET publication_error_message = ?, updated_at = ?+ WHERE scan_id = ?+ """,+ (message, timestamp, scan_id),+ )+ connection.commit()+ except BaseException:+ connection.rollback()+ raisereturn deep_scan_result(connection, scan_id)+def clear_deep_scan_publication_failure(connection: sqlite3.Connection, scan_id: str) -> None:+ with connection:+ connection.execute(+ "UPDATE deep_scan_runs SET publication_error_message = NULL, updated_at = ? "+ "WHERE scan_id = ? AND publication_error_message IS NOT NULL",+ (now(), scan_id),+ )++def fail_from_parent_scan(connection: sqlite3.Connection,scan_id: str,diff --git a/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py b/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.pyindex d99436dbf..d250e5c91 100644--- a/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py+++ b/sdk/typescript/_bundled_plugin/scripts/finalize_scan_contract.py@@ -857,6 +857,20 @@ def _recover_unsealed_findings(if previous_position is not None:previous = recovered[previous_position]+ strongest, earlier = (+ (previous, finding)+ if _finding_strength(finding) <= _finding_strength(previous)+ else (finding, previous)+ )+ if strongest != earlier:+ original = copy.deepcopy(earlier)+ older = original["provenance"].pop("previousFindings", [])+ if not isinstance(strongest["provenance"].get("previousFindings"), list):+ strongest["provenance"]["previousFindings"] = []+ history = strongest["provenance"]["previousFindings"]+ for record in [*(older if isinstance(older, list) else []), original]:+ if record not in history:+ history.append(record)if _finding_strength(finding) <= _finding_strength(previous):warnings.append(f"Skipped malformed finding {index + 1}: duplicate logical finding."@@ -1060,7 +1074,9 @@ def _populate_unsealed_manifest_envelope(manifest["documentType"] = "codex-security.scan-manifest"manifest["schemaVersion"] = SCHEMA_VERSION- scan["status"] = "completed"+ scan["status"] = (+ completion_binding.get("status", "completed") if completion_binding else "completed"+ )scan["coverageRef"] = "coverage.json"scan["findingsRef"] = "findings.json"if completion_binding is None:@@ -1188,6 +1204,8 @@ def _validate_completion_binding(scan = _require_dict(manifest, "scan", "manifest")if scan.get("id") != completion_binding["scanId"]:raise ContractError("manifest.scan.id: must match the workbench scan")+ if scan.get("status") != completion_binding.get("status", "completed"):+ raise ContractError("manifest.scan.status: must match the workbench outcome")if scan.get("startedAt") != completion_binding["startedAt"]:raise ContractError("manifest.scan.startedAt: must match the workbench scan")if scan.get("completedAt") != completion_binding["completedAt"]:@@ -1370,8 +1388,8 @@ def _validate_manifest(manifest: dict[str, Any]) -> None:scan = _require_dict(manifest, "scan", "manifest")for key in ("id", "startedAt", "completedAt", "sealedAt"):_require_str(scan, key, "manifest.scan")- if scan.get("status") != "completed":- raise ContractError("manifest.scan.status: expected completed")+ if scan.get("status") not in {"completed", "failed", "canceled", "interrupted"}:+ raise ContractError("manifest.scan.status: expected a terminal scan outcome")producer = _require_dict(scan, "producer", "manifest.scan")_require_str(producer, "name", "manifest.scan.producer")_require_str(producer, "version", "manifest.scan.producer")@@ -2175,7 +2193,7 @@ def _artifact_record() -> dict[str, str]:relative_path = _require_portable_relative_path(relative_path, "artifact path")if contents is not None:- _require_scan_local_file(scan_dir, relative_path, relative_path)+ _validate_scan_local_output_path(scan_dir, scan_dir / relative_path, relative_path)return {"mediaType": media_type,"path": relative_path,@@ -2292,12 +2310,18 @@ def build_sarif_projection(sarif = build_sarif(manifest, findings, source_root)run = sarif["runs"][0]completeness = coverage["completeness"]- run["invocations"] = [{"executionSuccessful": completeness == "complete"}]- if completeness != "complete":+ scan_status = manifest["scan"]["status"]+ execution_successful = scan_status == "completed" and completeness == "complete"+ run["invocations"] = [{"executionSuccessful": execution_successful}]+ if not execution_successful:run["properties"]["codexSecurityCoverageCompleteness"] = completeness- reasons = [item["reason"] for item in coverage["deferred"]] or [- f"Scan coverage is {completeness}; results may be incomplete."- ]+ reasons = [item["reason"] for item in coverage["deferred"]]+ if not reasons:+ reasons = [+ f"Scan status is {scan_status}; results may be incomplete."+ if scan_status != "completed"+ else f"Scan coverage is {completeness}; results may be incomplete."+ ]run["invocations"][0]["toolExecutionNotifications"] = [{"level": "warning", "message": {"text": reason}} for reason in reasons]@@ -2326,6 +2350,13 @@ def csv_cell(value: Any) -> Any:def finding_candidate_id(finding: dict[str, Any]) -> str | None:+ provenance = finding.get("provenance")+ if (+ isinstance(provenance, dict)+ and isinstance(value := provenance.get("candidateId"), str)+ and value.strip()+ ):+ return valueextensions = finding.get("extensions")if not isinstance(extensions, dict):return None@@ -2517,23 +2548,32 @@ def _prepare_scan_finalization(expected_coverage_mode: str | None = None,completion_binding: dict[str, Any] | None = None,completion_warnings: list[str] | None = None,+ draft_documents: tuple[dict[str, Any], dict[str, Any], dict[str, Any]] | None = None,) -> PreparedScanFinalization:"""Read, populate, and validate a scan without writing any output files."""scan_dir = _require_scan_directory(scan_dir)schema_dir = schema_dir or Path(__file__).resolve().parent.parent / "schemas"- manifest = _read_scan_local_json(scan_dir, "scan-manifest.json", "scan-manifest.json")+ manifest = (+ copy.deepcopy(draft_documents[0])+ if draft_documents is not None+ else _read_scan_local_json(scan_dir, "scan-manifest.json", "scan-manifest.json")+ )scan = _require_dict(manifest, "scan", "manifest")was_sealed = scan.get("sealedAt") is not None or scan.get("artifacts") is not Noneif not was_sealed:_populate_unsealed_manifest_envelope(manifest, scan, completion_binding)_validate_contract_refs(scan)- findings, findings_input_bytes = _read_scan_local_json_bytes(- scan_dir, scan["findingsRef"], scan["findingsRef"]- )- coverage, coverage_input_bytes = _read_scan_local_json_bytes(- scan_dir, scan["coverageRef"], scan["coverageRef"]- )+ if draft_documents is None:+ findings, findings_input_bytes = _read_scan_local_json_bytes(+ scan_dir, scan["findingsRef"], scan["findingsRef"]+ )+ coverage, coverage_input_bytes = _read_scan_local_json_bytes(+ scan_dir, scan["coverageRef"], scan["coverageRef"]+ )+ else:+ findings, coverage = copy.deepcopy(draft_documents[1:])+ findings_input_bytes, coverage_input_bytes = _json_bytes(findings), _json_bytes(coverage)if not was_sealed:_populate_unsealed_artifact_envelope(manifest, findings, coverage, completion_binding)_normalize_unsealed_deep_repository_inventory_strategy(@@ -2544,8 +2584,8 @@ def _prepare_scan_finalization(if manifest.get("schemaVersion") != SCHEMA_VERSION:raise ContractError(f"manifest.schemaVersion: expected {SCHEMA_VERSION}")- if scan.get("status") != "completed":- raise ContractError("manifest.scan.status: expected completed before sealing")+ if scan.get("status") not in {"completed", "failed", "canceled", "interrupted"}:+ raise ContractError("manifest.scan.status: expected a terminal scan outcome before sealing")if (expected_coverage_mode is not Noneand completion_binding is not Nonediff --git a/sdk/typescript/_bundled_plugin/scripts/report_projection.py b/sdk/typescript/_bundled_plugin/scripts/report_projection.pyindex 6149d5f4f..281eb7d1c 100644--- a/sdk/typescript/_bundled_plugin/scripts/report_projection.py+++ b/sdk/typescript/_bundled_plugin/scripts/report_projection.py@@ -865,6 +865,7 @@ def build_report_markdown("","| Field | Value |","| --- | --- |",+ f"| Scan outcome | {scan.get('status', 'completed')} |",*summary_count_lines,f"| Coverage | {coverage['completeness']} |",f"| Validation mode | {_cell(scope.get('validationMode', 'not recorded'))} |",@@ -973,20 +974,30 @@ def build_report_markdown(for item in deferred))+ stopped = manifest.get("scan", {}).get("status") in {+ "failed",+ "canceled",+ "interrupted",+ }lines.extend(["### No findings","",(- "No source review completed before the configured time limit. "- "No vulnerability conclusion can be drawn."- if no_source_review+ "No findings were retained before the scan stopped. "+ "The scan did not complete. No vulnerability conclusion can be drawn."+ if stoppedelse (- "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."+ "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."+ ))),]diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.pyindex 49fe45d26..045cd8376 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py@@ -241,6 +241,19 @@ def parse_args(description: str) -> argparse.Namespace:fail_scan.add_argument("--claim-token")fail_scan.add_argument("--cost-json")+ preserve_scan = subparsers.add_parser("preserve-scan-results")+ preserve_scan.add_argument("--scan-id", required=True)+ preserve_scan.add_argument("--thread-id")+ preserve_scan.add_argument("--claim-token")+ preserve_scan.add_argument("--coordinator-generation", type=positive_int)++ write_scan_draft = subparsers.add_parser("write-scan-draft")+ write_scan_draft.add_argument("--scan-id", required=True)+ write_scan_draft.add_argument("--draft-path", required=True)+ write_scan_draft.add_argument("--checkpoint-path")+ write_scan_draft.add_argument("--expected-draft-digest")+ write_scan_draft.add_argument("--claim-token")+mark_handoff_delivered = subparsers.add_parser("mark-handoff-delivered")mark_handoff_delivered.add_argument("--scan-id", required=True)mark_handoff_delivered.add_argument("--claim-token", required=True)diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.pyindex 33332a490..e3717c1da 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py@@ -37,6 +37,7 @@ import deep_scan_workbench as deep_scanimport workbench_native_indexes as native_indexesimport workbench_progress as progressimport workbench_remediation as remediation+import workbench_saved_results as saved_resultsimport workbench_scan_history as scan_historyimport workbench_scan_usage as scan_usagefrom filesystem_identity import serialize_filesystem_identity as serialize_filesystem_identity@@ -46,6 +47,7 @@ from filesystem_identity import (from finalize_scan_contract import (PRODUCER_NAME,ContractError,+ RecoverableContractError,_prepare_scan_finalization,_write_prepared_scan_finalization,csv_cell,@@ -78,6 +80,7 @@ from workbench_constants import (SQLITE_RETRY_ATTEMPTS,)from workbench_feedback import get_scan_feedback+from workbench_finding_index import index_findingsfrom workbench_remediation import remediation_claim_is_activefrom workbench_scan_start import (archive_scan,@@ -1467,6 +1470,24 @@ def complete_scan_locked(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)+ if current_manifest_path is not None:+ current_manifest = read_json_object(current_manifest_path)+ if (+ isinstance(current_manifest.get("scan"), dict)+ and current_manifest["scan"].get("complete") is False+ ):+ raise SystemExit(+ "The latest saved scan draft is incomplete; continue the scan before completing it."+ )+ already_sealed = (+ current_manifest_path is not None+ and isinstance(current_manifest.get("scan"), dict)+ and (+ current_manifest["scan"].get("sealedAt") is not None+ or current_manifest["scan"].get("artifacts") is not None+ )+ )if scan["recipe_json"] is not None:draft_artifacts: dict[str, Path] = {}missing_drafts = []@@ -1494,16 +1515,38 @@ def complete_scan_locked(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(scan_dir,expected_coverage_mode=expected_coverage_mode(scan),completion_binding=completion_binding,completion_warnings=warnings,+ draft_documents=saved_results.merge_saved_results(+ scan_dir,+ scan["id"],+ completion_binding,+ connection.execute(+ "SELECT * FROM deep_scan_workers WHERE scan_id = ? ORDER BY created_at, id",+ (scan["id"],),+ ).fetchall(),+ warnings,+ stopped=False,+ reason="",+ )+ if current_manifest_path is not None and not already_sealed+ else None,)add_warning()+ wrote = Truemanifest, findings, _ = _write_prepared_scan_finalization(prepared)except ContractError as exc:+ if wrote or (+ scan["mode"] == "deep" and not isinstance(exc, RecoverableContractError)+ ):+ args = argparse.Namespace(claim_token=claim_token, cost_json=cost_json)+ args.message, args.scan_id = str(exc), scan_id+ fail_scan_locked(connection, args)raise SystemExit(str(exc)) from excartifacts = {kind: artifact_path(scan_dir, filename, required=True)@@ -1793,101 +1836,63 @@ def get_scan_recipe(connection: sqlite3.Connection, args: argparse.Namespace) ->}+_WORKBENCH_DB_CONTEXT: saved_results.WorkbenchDbContext++def coverage_for_comparison(scan: sqlite3.Row) -> dict[str, Any]:- if scan["seal_manifest_digest"] is None:- raise SystemExit("Only sealed scans can be compared.")- scan_dir = require_canonical_scan_directory(Path(scan["scan_dir"]))- require_recorded_manifest_digest(scan, scan_dir)- try:- _, _, manifest, _, coverage, was_sealed, _ = _prepare_scan_finalization(scan_dir)- except ContractError as exc:- raise SystemExit(str(exc)) from exc- if not was_sealed or manifest["scan"]["id"] != scan["id"]:- raise SystemExit("Only sealed scans can be compared.")- return coverage+ return saved_results.coverage_for_comparison(_WORKBENCH_DB_CONTEXT, scan)+++def preserve_scan_results_locked(connection: sqlite3.Connection, scan_id: str) -> bool:+ return saved_results.preserve_scan_results_locked(_WORKBENCH_DB_CONTEXT, connection, scan_id)+++def refresh_stopped_scan_results(+ connection: sqlite3.Connection, scan_id: str, *, strict: bool = False+) -> None:+ saved_results.refresh_stopped_scan_results(+ _WORKBENCH_DB_CONTEXT, connection, scan_id, strict=strict+ )+++def refresh_all_stopped_scan_results(connection: sqlite3.Connection) -> None:+ scan_ids = [+ row["id"] for row in connection.execute("SELECT id FROM scans WHERE status = 'failed'")+ ]+ for scan_id in scan_ids:+ refresh_stopped_scan_results(connection, scan_id)+++def preserve_scan_results(+ connection: sqlite3.Connection, args: argparse.Namespace+) -> dict[str, Any]:+ return saved_results.preserve_scan_results(_WORKBENCH_DB_CONTEXT, connection, args)+++def write_scan_draft(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:+ return saved_results.write_scan_draft(_WORKBENCH_DB_CONTEXT, connection, args)def fail_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)- connection.execute("BEGIN IMMEDIATE")- try:- timestamp = now()- scan = require_scan(connection, scan_id)- if scan["status"] == "failed":- connection.commit()- return scan_context(connection, scan["id"])- if scan["status"] == "complete":- raise SystemExit("A completed scan cannot be marked failed.")- handoff.require_current_continuation(- scan,- args.claim_token,- error_message="Scan failure is owned by another continuation.",- )- message = optional_text(args.message, maximum=2400)- updated = connection.execute(- """- UPDATE scans- SET status = 'failed', failure_message = ?, completed_at = ?, updated_at = ?,- cost_json = ?- WHERE id = ? AND status = 'running'- """,- (message, timestamp, timestamp, cost_json, scan["id"]),- )- if updated.rowcount != 1:- raise SystemExit("Only a running scan can be marked failed.")- deep_scan.fail_from_parent_scan(connection, scan["id"], message, timestamp)- progress_updated = connection.execute(- "UPDATE scan_progress SET updated_at = ? WHERE scan_id = ?",- (timestamp, scan["id"]),- )- if progress_updated.rowcount != 1:- raise SystemExit("Codex Security scan progress not found.")- connection.commit()- except BaseException:- connection.rollback()- raise- return scan_context(connection, scan["id"])+ return saved_results.fail_scan(_WORKBENCH_DB_CONTEXT, connection, args)+++def fail_scan_locked(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:+ return saved_results.fail_scan_locked(_WORKBENCH_DB_CONTEXT, connection, args)def cancel_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:- scan_id = require_uuid(args.scan_id, "scan-id")- thread_id = optional_text(args.thread_id, maximum=512)- connection.execute("BEGIN IMMEDIATE")- try:- timestamp = now()- scan = require_scan(connection, scan_id)- workspace = require_workspace(connection, scan["workspace_id"])- owning_thread_id = scan["continuation_thread_id"] or workspace["thread_id"]- if thread_id is not None and owning_thread_id != thread_id:- raise SystemExit("A scan can only be canceled from its owning Codex thread.")- if scan["canceled_at"] is not None:- connection.commit()- return workspace_state(connection, scan["workspace_id"])- if scan["status"] != "running":- raise SystemExit("Only a running scan can be canceled.")- updated = connection.execute(- """- UPDATE scans- SET status = 'failed', canceled_at = ?, completed_at = ?, updated_at = ?- WHERE id = ? AND status = 'running'- """,- (timestamp, timestamp, timestamp, scan["id"]),- )- if updated.rowcount != 1:- raise SystemExit("Only a running scan can be canceled.")- deep_scan.cancel_from_parent_scan(connection, scan["id"], timestamp)- progress_updated = connection.execute(- "UPDATE scan_progress SET updated_at = ? WHERE scan_id = ?",- (timestamp, scan["id"]),- )- if progress_updated.rowcount != 1:- raise SystemExit("Codex Security scan progress not found.")- connection.commit()- except BaseException:- connection.rollback()- raise- return workspace_state(connection, scan["workspace_id"])+ return saved_results.cancel_scan(_WORKBENCH_DB_CONTEXT, connection, args)+++def cancel_scan_locked(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:+ return saved_results.cancel_scan_locked(_WORKBENCH_DB_CONTEXT, connection, args)+++def preserve_stopped_results_after_transition(connection: sqlite3.Connection, scan_id: str) -> None:+ saved_results.preserve_stopped_results_after_transition(+ _WORKBENCH_DB_CONTEXT, connection, scan_id+ )def set_finding_triage(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:@@ -2666,9 +2671,14 @@ def record_linear_publications(def export_findings(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:+ refresh_stopped_scan_results(connection, args.scan_id, strict=True)scan = require_scan(connection, args.scan_id)- if scan["status"] != "complete":- raise SystemExit("Findings can be exported after the scan completes.")+ if scan["status"] != "complete" and not (+ scan["status"] == "failed" and scan["seal_manifest_digest"]+ ):+ raise SystemExit(+ "Findings can be exported after the scan completes or preserves stopped results."+ )scan_dir = require_canonical_scan_directory(Path(scan["scan_dir"]))require_recorded_manifest_digest(scan, scan_dir)verify_manifest_binding(scan, read_json_object(scan_dir / ARTIFACTS["manifest"]))@@ -3004,82 +3014,6 @@ def open_scan_local_file(scan_dir: Path, relative_path: str) -> Any:raise SystemExit("Patch path must identify a scan-local regular file.") from exc-def index_findings(- connection: sqlite3.Connection,- scan_id: str,- document: dict[str, Any],- timestamp: str,-) -> None:- findings = document.get("findings")- if not isinstance(findings, list):- raise SystemExit("findings.json must contain a findings array.")- for finding in findings:- if not isinstance(finding, dict):- raise SystemExit("findings.json entries must be objects.")- identity = finding["identity"]- fingerprints = finding["fingerprints"]- severity = finding["severity"]- confidence = finding["confidence"]- connection.execute(- """- INSERT INTO findings (- id, fingerprint, rule_id, identity_anchor, identity_instance, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?)- ON CONFLICT(id) DO UPDATE SET- fingerprint = excluded.fingerprint,- rule_id = excluded.rule_id,- identity_anchor = excluded.identity_anchor,- identity_instance = excluded.identity_instance,- updated_at = excluded.updated_at- """,- (- finding["findingId"],- fingerprints["primary"],- finding["ruleId"],- identity["anchor"],- identity.get("instance"),- timestamp,- timestamp,- ),- )- connection.execute(- """- INSERT INTO finding_occurrences (- id, finding_id, scan_id, title, summary, severity, confidence, remediation,- details_json, created_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- """,- (- finding["occurrenceId"],- finding["findingId"],- scan_id,- finding["title"],- finding["summary"],- severity["level"],- confidence["level"],- finding["remediation"],- json.dumps(finding, allow_nan=False, sort_keys=True),- timestamp,- ),- )- for index, location in enumerate(finding["locations"]):- connection.execute(- """- INSERT INTO finding_locations (- occurrence_id, relative_path, start_line, end_line, role, sort_order- ) VALUES (?, ?, ?, ?, ?, ?)- """,- (- finding["occurrenceId"],- location["path"],- location["startLine"],- location.get("endLine", location["startLine"]),- location.get("role"),- index,- ),- )--def diff_target_summary(diff_target: dict[str, str]) -> str:kind = diff_target["kind"]if kind == "working_tree":@@ -3095,6 +3029,7 @@ def workspace_state(*,result_scan_id: str | None = None,thread_id: str | None = None,+ refresh_stopped: bool = False,) -> dict[str, Any]:workspace = require_workspace(connection, workspace_id)if thread_id is not None and workspace["thread_id"] != optional_text(thread_id, maximum=512):@@ -3115,6 +3050,8 @@ def workspace_state(}selected_scan_id = result_scan_id or workspace["active_scan_id"]if selected_scan_id:+ if refresh_stopped:+ refresh_stopped_scan_results(connection, selected_scan_id)selected_scan = require_scan(connection, selected_scan_id)result["userContext"] = selected_scan["user_context"]result["results"] = scan_result(connection, selected_scan)@@ -3176,6 +3113,7 @@ def scan_context(def list_findings(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:+ refresh_stopped_scan_results(connection, args.scan_id)scan = require_scan(connection, args.scan_id)backfill_legacy_finding_details(connection, scan)limit = min(args.limit, FINDINGS_PAGE_MAX)@@ -3335,6 +3273,8 @@ def scan_result(def remediation_availability(scan: sqlite3.Row) -> tuple[bool, str | None]:+ if scan["status"] != "complete":+ return False, remediation.SCAN_STATUS_ERRORtry:current_revision = git_revision(require_scan_target_identity(scan))except SystemExit as exc:@@ -3815,6 +3755,31 @@ def reject_non_finite_json(value: str) -> None:raise ValueError(f"non-finite JSON number {value!r} is not supported")+_WORKBENCH_DB_CONTEXT = saved_results.WorkbenchDbContext(+ ARTIFACTS=ARTIFACTS,+ artifact_path=artifact_path,+ deep_scan=deep_scan,+ expected_coverage_mode=expected_coverage_mode,+ handoff=handoff,+ index_findings=index_findings,+ now=now,+ optional_text=optional_text,+ parse_scan_cost=parse_scan_cost,+ published_manifest_digest=published_manifest_digest,+ read_json_object=read_json_object,+ require_canonical_scan_directory=require_canonical_scan_directory,+ require_recorded_manifest_digest=require_recorded_manifest_digest,+ require_scan=require_scan,+ require_uuid=require_uuid,+ require_workspace=require_workspace,+ scan_completion_lock=scan_completion_lock,+ scan_context=scan_context,+ verify_manifest_binding=verify_manifest_binding,+ workbench_completion_binding=workbench_completion_binding,+ workspace_state=workspace_state,+)++def main() -> None:# Workbench callers send UTF-8 even when Windows uses a legacy code page.sys.stdin.reconfigure(encoding="utf-8")@@ -3834,6 +3799,7 @@ def main() -> None:safe_segment=safe_segment,compact_timestamp=compact_timestamp,scan_completion_lock=scan_completion_lock,+ preserve_stopped_results=preserve_stopped_results_after_transition,))if args.command == "inspect-target":@@ -3845,10 +3811,16 @@ def main() -> None:print(json.dumps(result, allow_nan=False, sort_keys=True))returnwith closing(connect()) as connection:+ remediation.require_available(connection, args, require_scan)if args.command == "create-workspace":result = create_workspace(connection, args)elif args.command == "get-workspace":- result = workspace_state(connection, args.workspace_id, thread_id=args.thread_id)+ result = workspace_state(+ connection,+ args.workspace_id,+ thread_id=args.thread_id,+ refresh_stopped=True,+ )elif args.command == "save-workspace":result = save_workspace(connection, args)elif args.command == "start-scan":@@ -3873,11 +3845,15 @@ def main() -> None:result = deep_scan.finish_deep_scan(connection, args)elif args.command == "fail-deep-scan":result = deep_scan.fail_deep_scan(connection, args)+ elif args.command == "record-deep-scan-publication-failure":+ result = deep_scan.record_deep_scan_publication_failure(connection, args)elif args.command == "get-scan":+ refresh_stopped_scan_results(connection, args.scan_id)result = scan_context(connection, args.scan_id, args.occurrence_id)elif args.command == "get-scan-feedback":result = get_scan_feedback(connection, require_scan(connection, args.scan_id))elif args.command == "list-scans":+ refresh_all_stopped_scan_results(connection)result = scan_history.list_scans(connection, args)elif args.command == "list-unmatched-scan-pairs":result = scan_history.list_unmatched_scan_pairs(@@ -3911,8 +3887,10 @@ def main() -> None:read_coverage=coverage_for_comparison,)elif args.command == "list-global-findings":+ refresh_all_stopped_scan_results(connection)result = native_indexes.list_global_findings(connection, args)elif args.command == "list-repositories":+ refresh_all_stopped_scan_results(connection)result = native_indexes.list_repositories(connection, args)elif args.command == "list-findings":result = list_findings(connection, args)@@ -3930,6 +3908,10 @@ def main() -> None:result = cancel_scan(connection, args)elif args.command == "fail-scan":result = fail_scan(connection, args)+ elif args.command == "preserve-scan-results":+ result = preserve_scan_results(connection, args)+ elif args.command == "write-scan-draft":+ result = write_scan_draft(connection, args)elif args.command == "mark-handoff-delivered":result = handoff.mark_handoff_delivered(connection,diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_finding_index.py b/sdk/typescript/_bundled_plugin/scripts/workbench_finding_index.pynew file mode 100644index 000000000..2d68b4c7e--- /dev/null+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_finding_index.py@@ -0,0 +1,101 @@+"""Persist normalized scan findings and their occurrences."""++from __future__ import annotations++import argparse+import json+import sqlite3+from typing import Any+++def index_findings(+ connection: sqlite3.Connection,+ scan_id: str,+ document: dict[str, Any],+ timestamp: str,+) -> None:+ findings = document.get("findings")+ if not isinstance(findings, list):+ raise SystemExit("findings.json must contain a findings array.")+ for finding in findings:+ if not isinstance(finding, dict):+ raise SystemExit("findings.json entries must be objects.")+ identity = finding["identity"]+ fingerprints = finding["fingerprints"]+ severity = finding["severity"]+ confidence = finding["confidence"]+ connection.execute(+ """+ INSERT INTO findings (+ id, fingerprint, rule_id, identity_anchor, identity_instance, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id) DO UPDATE SET+ fingerprint = excluded.fingerprint,+ rule_id = excluded.rule_id,+ identity_anchor = excluded.identity_anchor,+ identity_instance = excluded.identity_instance,+ updated_at = excluded.updated_at+ """,+ (+ finding["findingId"],+ fingerprints["primary"],+ finding["ruleId"],+ identity["anchor"],+ identity.get("instance"),+ timestamp,+ timestamp,+ ),+ )+ connection.execute(+ """+ INSERT INTO finding_occurrences (+ id, finding_id, scan_id, title, summary, severity, confidence, remediation,+ details_json, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id) DO UPDATE SET+ finding_id = excluded.finding_id,+ scan_id = excluded.scan_id,+ title = excluded.title,+ summary = excluded.summary,+ severity = excluded.severity,+ confidence = excluded.confidence,+ remediation = excluded.remediation,+ details_json = excluded.details_json+ """,+ (+ finding["occurrenceId"],+ finding["findingId"],+ scan_id,+ finding["title"],+ finding["summary"],+ severity["level"],+ confidence["level"],+ finding["remediation"],+ json.dumps(finding, allow_nan=False, sort_keys=True),+ timestamp,+ ),+ )+ connection.execute(+ "DELETE FROM finding_locations WHERE occurrence_id = ?",+ (finding["occurrenceId"],),+ )+ for index, location in enumerate(finding["locations"]):+ connection.execute(+ """+ INSERT INTO finding_locations (+ occurrence_id, relative_path, start_line, end_line, role, sort_order+ ) VALUES (?, ?, ?, ?, ?, ?)+ """,+ (+ finding["occurrenceId"],+ location["path"],+ location["startLine"],+ location.get("endLine", location["startLine"]),+ location.get("role"),+ index,+ ),+ )+++if __name__ == "__main__":+ argparse.ArgumentParser(description=__doc__).parse_args()diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_remediation.py b/sdk/typescript/_bundled_plugin/scripts/workbench_remediation.pyindex 5d38e0553..c4faf66c6 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_remediation.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_remediation.py@@ -14,6 +14,25 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))from workbench_constants import CLAIM_LEASE_SECONDS, DELIVERED_ACTION_LEASE_SECONDSfrom workbench_validation import require_occurrence, require_uuid+COMMANDS = {+ "request-finding-remediation",+ "request-finding-remediation-action",+ "claim-finding-remediation-resend",+ "mark-finding-remediation-delivered",+ "release-finding-remediation-claim",+ "cancel-finding-remediation-request",+ "set-finding-remediation",+}+SCAN_STATUS_ERROR = "Remediation is available only for successfully completed scans."+++def require_available(connection: sqlite3.Connection, args: Any, require_scan: Any) -> None:+ if args.command not in COMMANDS:+ return+ occurrence = require_occurrence(connection, args.occurrence_id)+ if require_scan(connection, occurrence["scan_id"])["status"] != "complete":+ raise SystemExit(SCAN_STATUS_ERROR)+def remediation_claim_is_active(remediation: sqlite3.Row) -> bool:if remediation["pending_action_claim_token"] is None:diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_saved_results.py b/sdk/typescript/_bundled_plugin/scripts/workbench_saved_results.pynew file mode 100644index 000000000..7d4e1c979--- /dev/null+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_saved_results.py@@ -0,0 +1,1289 @@+"""Retain semantic scan drafts without rerunning analysis or changing run state."""++from __future__ import annotations++import argparse+import copy+import hashlib+import json+import os+import re+import stat+import sys+from collections.abc import Callable, Iterator+from dataclasses import dataclass+from pathlib import Path+from types import ModuleType+from typing import Any++sys.path.insert(0, str(Path(__file__).resolve().parent))+from finalize_scan_contract import (+ ContractError,+ _finding_strength,+ _populate_unsealed_artifact_envelope,+ _populate_unsealed_manifest_envelope,+ _prepare_scan_finalization,+ _read_scan_local_json,+ _read_scan_local_json_bytes,+ _recover_unsealed_findings,+ _remove_scan_local_file_if_exists,+ _validate_completion_binding,+ _write_prepared_scan_finalization,+ finalize_scan,+ finding_candidate_id,+ open_scan_local_file_descriptor,+ write_scan_local_bytes,+)+from workbench_validation import path_within_scope++_PUBLISHED_OUTPUTS = (+ "findings.json",+ "coverage.json",+ "scan-manifest.json",+ "report.md",+ "report.html",+ "exports/results.sarif",+)+_PUBLICATION_FOLLOW_UP_WARNING = (+ "Saved scan evidence remains on disk; result publication needs follow-up:"+)+++@dataclass(frozen=True)+class WorkbenchDbContext:+ ARTIFACTS: dict[str, str]+ artifact_path: Callable[..., Path | None]+ deep_scan: ModuleType+ expected_coverage_mode: Callable[..., str]+ handoff: ModuleType+ index_findings: Callable[..., None]+ now: Callable[[], str]+ optional_text: Callable[..., str | None]+ parse_scan_cost: Callable[..., dict[str, Any] | None]+ published_manifest_digest: Callable[..., str]+ read_json_object: Callable[[Path], dict[str, Any]]+ require_canonical_scan_directory: Callable[[Path], Path]+ require_recorded_manifest_digest: Callable[..., None]+ require_scan: Callable[..., Any]+ require_uuid: Callable[[str, str], str]+ require_workspace: Callable[..., Any]+ scan_completion_lock: Callable[..., Any]+ scan_context: Callable[..., dict[str, Any]]+ verify_manifest_binding: Callable[..., None]+ workbench_completion_binding: Callable[..., dict[str, Any]]+ workspace_state: Callable[..., dict[str, Any]]+++def _encoded(value: Any) -> bytes:+ return json.dumps(+ value, ensure_ascii=True, allow_nan=False, sort_keys=True, separators=(",", ":")+ ).encode()+++def _digest(value: Any) -> str:+ return hashlib.sha256(_encoded(value)).hexdigest()+++def _children(scan_dir: Path, relative: str) -> list[str]:+ cursor = scan_dir+ for part in Path(relative).parts:+ if part in {"..", "."}:+ return []+ cursor = cursor / part+ try:+ if not stat.S_ISDIR(cursor.lstat().st_mode):+ return []+ except FileNotFoundError:+ return []+ return sorted(child.name for child in cursor.iterdir())+++def _finding_key(finding: dict[str, Any]) -> str:+ # Wording and evidence may improve between checkpoints; distinct source locations+ # must not collide merely because two workers chose the same semantic identity.+ provenance = finding.get("provenance")+ identity = (+ provenance.get("preservedIdentity", finding.get("identity"))+ if isinstance(provenance, dict)+ else finding.get("identity")+ )+ if not isinstance(identity, dict):+ extensions = finding.get("extensions")+ source = str(+ (extensions.get("candidateId") if isinstance(extensions, dict) else None)+ or finding.get("title")+ or "finding"+ )+ identity = {+ "anchor": re.sub(r"[^a-z0-9._/-]+", "-", source.lower()).strip("._/-") or "finding"+ }+ locations = finding.get("locations", [])+ if not isinstance(locations, list):+ locations = []+ return _digest(+ [+ finding.get("ruleId"),+ identity,+ sorted(+ (+ (+ location.get("path"),+ location.get("startLine"),+ location.get("endLine", location.get("startLine")),+ )+ for location in locations+ if isinstance(location, dict)+ ),+ key=_encoded,+ ),+ ]+ )+++def _worker_candidate_key(+ worker_id: str, candidate_id: str, finding: dict[str, Any]+) -> tuple[str, str, Any, Any, Any]:+ """Identify one worker-local candidate without merging unrelated locations."""+ provenance = finding.get("provenance")+ identity = (+ provenance.get("preservedIdentity", finding.get("identity"))+ if isinstance(provenance, dict)+ else finding.get("identity")+ )+ anchor = identity.get("anchor") if isinstance(identity, dict) else None+ instance = identity.get("instance") if isinstance(identity, dict) else None+ return worker_id, candidate_id, finding.get("ruleId"), anchor, instance+++def _finding_content(finding: dict[str, Any]) -> dict[str, Any]:+ """Return substantive finding content without generated identity or provenance."""+ return {+ key: value+ for key, value in finding.items()+ if key not in {"findingId", "occurrenceId", "fingerprints", "identity", "provenance"}+ }+++def _ensure_finding_identity(finding: Any, *, candidate_only: bool = False) -> None:+ if not isinstance(finding, dict) or "identity" in finding:+ return+ if candidate_only and not finding_candidate_id(finding):+ return+ extensions = finding.get("extensions")+ source = str(+ (extensions.get("candidateId") if isinstance(extensions, dict) else None)+ or finding.get("title")+ or "finding"+ )+ anchor = re.sub(r"[^a-z0-9._/-]+", "-", source.lower()).strip("._/-") or "finding"+ finding["identity"] = {"anchor": anchor}+++def _retained_findings(finding: dict[str, Any]) -> Iterator[dict[str, Any]]:+ """Yield canonical and historical findings without trusting candidate IDs."""+ pending = [finding]+ seen: set[int] = set()+ while pending:+ current = pending.pop()+ marker = id(current)+ if marker in seen:+ continue+ seen.add(marker)+ yield current+ provenance = current.get("provenance")+ if not isinstance(provenance, dict):+ continue+ previous = provenance.get("previousFindings")+ if isinstance(previous, list):+ pending.extend(item for item in reversed(previous) if isinstance(item, dict))+ sources = provenance.get("sourceFindings")+ if isinstance(sources, list):+ pending.extend(+ source["finding"]+ for source in reversed(sources)+ if isinstance(source, dict) and isinstance(source.get("finding"), dict)+ )+++def merge_saved_results(+ scan_dir: Path,+ scan_id: str,+ binding: dict[str, Any],+ workers: list[Any],+ warnings: list[str],+ *,+ stopped: bool,+ reason: str,+ frozen_source_digests: dict[str, str] | None = None,+) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]] | None:+ """Read only bound parent/worker files; return an unsealed loss-preserving union."""+ initial_warnings = set(warnings)+ parent: dict[str, Any] | None = None+ parent_manifest: dict[str, Any] | None = None+ if frozen_source_digests is None:+ try:+ parent_manifest = _read_scan_local_json(+ scan_dir, "scan-manifest.json", "Saved parent manifest"+ )+ parent_findings = _read_scan_local_json(+ scan_dir, "findings.json", "Saved parent findings"+ )+ parent_coverage = _read_scan_local_json(+ scan_dir, "coverage.json", "Saved parent coverage"+ )+ parent_scan = parent_manifest.get("scan")+ if not isinstance(parent_scan, dict):+ raise ContractError("Saved parent manifest has no scan object")+ if (parent_scan.get("sealedAt") or parent_scan.get("artifacts")) and (+ parent_scan.get("id", scan_id) != scan_id+ or parent_findings.get("scanId", scan_id) != scan_id+ or parent_coverage.get("scanId", scan_id) != scan_id+ ):+ raise ContractError("Saved parent documents belong to a different scan")+ parent = {+ "scanId": scan_id,+ "findings": parent_findings.get("findings"),+ "coverage": parent_coverage,+ **{+ key: parent_scan[key]+ for key in ("scope", "threatModel", "complete")+ if key in parent_scan+ },+ }+ if not isinstance(parent["findings"], list):+ raise ContractError("Saved parent draft has no findings array")+ if not parent_scan.get("sealedAt"):+ payload = _encoded(parent)+ write_scan_local_bytes(+ scan_dir,+ f"checkpoints/{hashlib.sha256(payload).hexdigest()}.json",+ payload,+ )+ except (ContractError, OSError, ValueError) as exc:+ if not stopped:+ raise+ if (scan_dir / "scan-manifest.json").exists():+ warnings.append(f"Could not read the saved parent draft: {exc}")+ parent_manifest = None+ parent = None++ sources: list[tuple[str, dict[str, Any], str | None]] = []+ parent_preserved_sources: dict[str, str] = {}+ source_digests: dict[str, str] = {}+ if parent_manifest:+ recorded = parent_manifest["scan"].get("preservedSources", {})+ if isinstance(recorded, dict):+ parent_preserved_sources = recorded+ source_digests.update(parent_preserved_sources)+ paths: dict[str, str | None] = {}+ current_results: set[str] = set()+ reducer_outputs: list[tuple[Any, str, list[str], int]] = []+ accepted_reducers = [+ worker+ for worker in workers+ if worker["kind"] == "dedup"+ and worker["status"] == "succeeded"+ and worker["result_manifest_path"]+ ]+ latest_reducer: str | None = None+ if accepted_reducers:+ reducer = max(+ accepted_reducers, key=lambda worker: (worker["completed_at"] or "", worker["id"])+ )+ try:+ latest_reducer = Path(reducer["result_manifest_path"]).relative_to(scan_dir).as_posix()+ paths[latest_reducer] = None+ except ValueError:+ warnings.append("Skipped a reducer result outside the scan directory.")++ def checkpoints(directory: str, worker_id: str | None) -> None:+ for name in _children(scan_dir, directory):+ if re.fullmatch(r"[0-9a-f]{64}\.json", name):+ paths[f"{directory}/{name}"] = worker_id++ checkpoints("checkpoints", None)+ for worker in workers:+ try:+ output = Path(worker["artifact_dir"]).relative_to(scan_dir).as_posix()+ except (TypeError, ValueError):+ warnings.append("Skipped a worker checkpoint outside the scan directory.")+ continue+ if worker["kind"] == "dedup":++ def reducer_output(directory: str, attempt: int, reducer_worker: Any) -> None:+ result_path = f"{directory}/result.json"+ checkpoint_paths = [+ f"{directory}/checkpoints/{name}"+ for name in _children(scan_dir, f"{directory}/checkpoints")+ if re.fullmatch(r"[0-9a-f]{64}\.json", name)+ ]+ if not checkpoint_paths:+ return+ paths[result_path] = None+ for checkpoint_path in checkpoint_paths:+ paths[checkpoint_path] = None+ reducer_outputs.append((reducer_worker, result_path, checkpoint_paths, attempt))++ reducer_output(output, int(worker["attempt"] or 0), worker)+ attempts = (+ Path(output).parent if Path(output).name == "output" else Path(output)+ ) / "attempts"+ for name in _children(scan_dir, attempts.as_posix()):+ match = re.fullmatch(r"attempt-(\d+)", name)+ if match:+ reducer_output((attempts / name).as_posix(), int(match.group(1)), worker)+ continue+ if worker["kind"] != "discovery":+ continue+ paths[f"{output}/result.json"] = worker["id"]+ current_results.add(f"{output}/result.json")+ checkpoints(f"{output}/checkpoints", worker["id"])+ attempts = (+ Path(output).parent if Path(output).name == "output" else Path(output)+ ) / "attempts"+ for name in _children(scan_dir, attempts.as_posix()):+ if re.fullmatch(r"attempt-\d+", name):+ archived = (attempts / name).as_posix()+ paths[f"{archived}/result.json"] = worker["id"]+ checkpoints(f"{archived}/checkpoints", worker["id"])+ if worker["result_manifest_path"]:+ try:+ current_path = Path(worker["result_manifest_path"]).relative_to(scan_dir).as_posix()+ paths[current_path] = worker["id"]+ current_results.add(current_path)+ except ValueError:+ warnings.append("Skipped a worker result outside the scan directory.")++ if frozen_source_digests is not None:+ paths = {+ relative: worker_id+ for relative, worker_id in paths.items()+ if relative in frozen_source_digests+ }+ current_results.intersection_update(frozen_source_digests)+ if latest_reducer not in frozen_source_digests:+ latest_reducer = None++ for relative, worker_id in paths.items():+ try:+ draft = _read_scan_local_json(scan_dir, relative, "Saved scan checkpoint")+ if draft.get("scanId") != scan_id:+ raise ContractError("checkpoint belongs to a different scan")+ if not isinstance(draft.get("findings"), list) or not isinstance(+ draft.get("coverage"), dict+ ):+ raise ContractError("checkpoint has no semantic findings or coverage")+ digest = _digest(draft)+ if frozen_source_digests is not None and frozen_source_digests[relative] != digest:+ raise ContractError("checkpoint changed after the scan stopped")+ source_digests[relative] = digest+ sources.append((relative, draft, worker_id))+ except (ContractError, OSError, ValueError) as exc:+ if (scan_dir / relative).exists():+ warnings.append(f"Preserved unreadable checkpoint {relative}: {exc}")+ if frozen_source_digests is not None:+ if frozen_source_digests.keys() - source_digests.keys():+ raise ContractError("Frozen stopped-scan checkpoint set is incomplete.")++ drafts_by_path = {relative: draft for relative, draft, _ in sources}+ latest_reducer_key = (+ (reducer["completed_at"] or "", reducer["id"], int(reducer["attempt"] or 0))+ if accepted_reducers and latest_reducer in drafts_by_path+ else None+ )+ if latest_reducer_key is None:+ latest_reducer = None+ for worker, result_path, checkpoint_paths, attempt in reducer_outputs:+ result = drafts_by_path.get(result_path)+ if result is None or not any(+ drafts_by_path.get(checkpoint_path) == result for checkpoint_path in checkpoint_paths+ ):+ continue+ current_results.add(result_path)+ candidate_key = (worker["completed_at"] or "", worker["id"], attempt)+ if latest_reducer_key is None or candidate_key > latest_reducer_key:+ latest_reducer_key = candidate_key+ latest_reducer = result_path++ if parent is None and latest_reducer is not None:+ parent = next((draft for relative, draft, _ in sources if relative == latest_reducer), None)++ if parent is None and not sources:+ return None+ if (+ parent_manifest+ and parent_manifest["scan"].get("sealedAt")+ and parent_manifest["scan"].get("status") == binding["status"]+ and parent_manifest["scan"].get("preservedSources") == source_digests+ and all(warning in initial_warnings for warning in warnings)+ ):+ return None++ target_kind = binding["allowedTargetKinds"][0]+ if (+ target_kind == "git_worktree"+ and "snapshotDigest" not in binding["target"]+ and "git_revision" in binding["allowedTargetKinds"]+ ):+ target_kind = "git_revision"+ target = {"kind": target_kind, **binding["target"]}+ if target["kind"] == "git_diff" and "snapshotDigest" not in target:+ diff_kind = {"commit": "commit", "branch_diff": "range"}[binding["coverageMode"]]+ digest = hashlib.sha256(+ b"codex-security-diff/v1\0"+ + diff_kind.encode()+ + b"\0"+ + target["baseRevision"].encode()+ + b"\0"+ + target["headRevision"].encode()+ ).hexdigest()+ target["snapshotDigest"] = f"codex-security-snapshot/v1:sha256:{digest}"+ manifest = (+ copy.deepcopy(parent_manifest)+ if parent_manifest+ else {"scan": {"target": target, "scope": binding["scope"]}}+ )+ for key in ("sealedAt", "artifacts"):+ manifest["scan"].pop(key, None)+ manifest["scan"]["preservedSources"] = source_digests+ coverage = (+ copy.deepcopy(parent["coverage"])+ if parent+ else {+ "completeness": "partial",+ "mode": binding["coverageMode"],+ "inventoryStrategy": "diff"+ if binding["coverageMode"] in {"commit", "branch_diff", "working_tree"}+ else "scoped_path"+ if binding["coverageMode"] == "scoped_path"+ else "repository",+ **binding["scope"],+ "surfaces": [],+ "explicitExclusions": [],+ "deferred": [],+ }+ )+ canonical_rows = (+ {+ id(item)+ for field in ("surfaces", "explicitExclusions", "deferred")+ for item in (coverage.get(field) if isinstance(coverage.get(field), list) else [])+ }+ if parent_manifest+ else set()+ )+ findings: list[dict[str, Any]] = []+ finding_positions: dict[str, int] = {}+ represented: dict[str, str | None] = {}+ represented_candidates: dict[tuple[str, str, Any, Any, Any], str | None] = {}+ represented_history: dict[str, set[str]] = {}+ represented_candidate_history: dict[tuple[str, str, Any, Any, Any], set[str]] = {}+ rejected_history: dict[tuple[str, str], list[dict[str, Any]]] = {}+ stopped_parent_seal = bool(+ stopped and parent_manifest and parent_manifest["scan"].get("sealedAt")+ )++ def valid_finding(value: Any) -> bool:+ # Use the finalizer's own per-record recovery before a draft can suppress+ # an earlier checkpoint. Invalid latest records must not hide valid history.+ document = {"scanId": scan_id, "findings": [copy.deepcopy(value)]}+ if isinstance(document["findings"][0], dict):+ _ensure_finding_identity(document["findings"][0], candidate_only=True)+ _recover_unsealed_findings(+ {"scan": {"id": scan_id, "target": binding["target"]}},+ document,+ Path(__file__).resolve().parent.parent / "schemas",+ scan_dir,+ [],+ )+ return bool(document["findings"])++ all_sources = ([("parent", parent, None)] if parent else []) + sources+ current_drafts = ([(None, parent)] if parent else []) + [+ (worker_id, draft) for relative, draft, worker_id in sources if relative in current_results+ ]+ resolved: dict[tuple[str | None, str], str] = {}+ for owner, draft in current_drafts:+ for finding in draft["findings"]:+ if (+ isinstance(finding, dict)+ and valid_finding(finding)+ and (candidate_id := finding_candidate_id(finding))+ ):+ resolved.setdefault((owner, candidate_id), "reported")+ for field in ("surfaces", "explicitExclusions"):+ items = draft["coverage"].get(field, [])+ for item in items if isinstance(items, list) else []:+ if (+ isinstance(item, dict)+ and isinstance(item.get("candidateId"), str)+ and item.get("disposition") in {"reported", "rejected", "not_applicable"}+ ):+ resolved.setdefault((owner, item["candidateId"]), item["disposition"])+ # Only the current parent may claim that another worker finding was absorbed.+ # A superseded checkpoint must not suppress a newer independent result.+ for draft in [parent] if parent else []:+ for finding in draft["findings"]:+ if valid_finding(finding):+ canonical_key = _finding_key(finding)+ for retained in _retained_findings(finding):+ retained_key = _finding_key(retained)+ if retained is not finding:+ represented_history.setdefault(retained_key, set()).add(+ _digest(_finding_content(retained))+ )+ previous_key = represented.get(retained_key)+ if retained_key not in represented:+ represented[retained_key] = canonical_key+ elif previous_key != canonical_key:+ # Ambiguous history cannot suppress an independent source.+ represented[retained_key] = None+ originals = finding["provenance"].get("sourceFindings", [])+ for original in originals if isinstance(originals, list) else []:+ if isinstance(original, dict) and isinstance(original.get("finding"), dict):+ source_id = original.get("id")+ candidate_id = finding_candidate_id(original["finding"])+ if isinstance(source_id, str) and ":" in source_id and candidate_id:+ candidate_key = _worker_candidate_key(+ source_id.rsplit(":", 1)[0],+ candidate_id,+ original["finding"],+ )+ previous_key = represented_candidates.get(candidate_key)+ if candidate_key not in represented_candidates:+ represented_candidates[candidate_key] = canonical_key+ elif previous_key != canonical_key:+ # Candidate ids are only authoritative within one+ # logical worker. Multiple canonical owners make+ # that worker-local identity ambiguous.+ represented_candidates[candidate_key] = None+ represented_candidate_history.setdefault(candidate_key, set()).add(+ _digest(_finding_content(original["finding"]))+ )+ resolved.setdefault(candidate_key, "reported")+ for relative, draft, worker_id in all_sources:+ superseded = (+ worker_id is None+ and parent is not None+ and parent.get("complete") is not False+ and relative != "parent"+ and (not stopped_parent_seal or relative in parent_preserved_sources)+ ) or (+ relative not in current_results+ and any(+ saved_worker == worker_id+ and saved_path in current_results+ and current.get("complete") is not False+ for saved_path, current, saved_worker in sources+ )+ )+ if (+ (relative != "parent" or not parent_manifest)+ and not superseded+ and (+ draft.get("complete") is False+ or draft["coverage"].get("completeness") != "complete"+ )+ and coverage.get("completeness") in {"complete", "unknown"}+ ):+ coverage["completeness"] = "partial"+ if superseded and not stopped:+ continue+ if "threatModel" not in manifest["scan"] and isinstance(draft.get("threatModel"), dict):+ manifest["scan"]["threatModel"] = copy.deepcopy(draft["threatModel"])+ for value in draft["findings"]:+ if relative == "parent" and parent_manifest:+ finding = copy.deepcopy(value)+ _ensure_finding_identity(finding, candidate_only=True)+ provenance = finding.get("provenance") if isinstance(finding, dict) else None+ owner = provenance.get("workerId") if isinstance(provenance, dict) else None+ candidate_id = finding_candidate_id(finding) if isinstance(finding, dict) else None+ if (+ stopped_parent_seal+ and isinstance(owner, str)+ and candidate_id+ and resolved.get((owner, candidate_id)) in {"rejected", "not_applicable"}+ ):+ rejected_history.setdefault((owner, candidate_id), []).append(finding)+ continue+ if valid_finding(finding):+ finding_positions.setdefault(_finding_key(finding), len(findings))+ findings.append(finding)+ continue+ if relative != "parent" and parent and value in parent["findings"]:+ continue+ if not isinstance(value, dict):+ warnings.append(f"Retained malformed finding evidence in {relative}.")+ continue+ source_value = copy.deepcopy(value)+ finding = copy.deepcopy(value)+ candidate_id = finding_candidate_id(finding)+ if relative != "parent" and resolved.get((worker_id, candidate_id)) in {+ "rejected",+ "not_applicable",+ }:+ surfaces = coverage.get("surfaces")+ for item in surfaces if isinstance(surfaces, list) else []:+ if isinstance(item, dict) and item.get("candidateId") == candidate_id:+ if not isinstance(item.get("previousFindings"), list):+ item["previousFindings"] = []+ history = item["previousFindings"]+ if not any(+ isinstance(previous, dict)+ and _finding_key(previous) == _finding_key(finding)+ and _finding_content(previous) == _finding_content(finding)+ for previous in history+ ):+ history.append(finding)+ continue+ for key in ("findingId", "occurrenceId", "fingerprints"):+ finding.pop(key, None)+ locations = finding.get("locations", [])+ if not isinstance(locations, list) or not any(+ isinstance(location, dict)+ and isinstance(location.get("path"), str)+ and any(+ path_within_scope(location["path"], path)+ for path in binding["scope"]["includePaths"]+ )+ for location in locations+ ):+ warnings.append(f"Skipped out-of-scope finding from {relative}.")+ coverage["completeness"] = "partial"+ continue+ provenance = finding.setdefault("provenance", {"source": "local_plugin"})+ if not isinstance(provenance, dict):+ findings.append(finding)+ continue+ if worker_id:+ provenance.setdefault("workerId", worker_id)+ _ensure_finding_identity(finding)+ if not valid_finding(finding):+ findings.append(finding)+ continue+ key = _finding_key(finding)+ represented_by_parent = False+ if relative != "parent":+ if key in represented:+ mapped_key = represented[key]+ historical_contents = represented_history.get(key, set())+ elif worker_id and candidate_id:+ candidate_key = _worker_candidate_key(+ worker_id, candidate_id, finding+ )+ if candidate_key not in represented_candidates:+ represented_candidates[candidate_key] = key+ mapped_key = represented_candidates[candidate_key]+ historical_contents = represented_candidate_history.get(candidate_key, set())+ else:+ mapped_key = None+ historical_contents = set()+ if mapped_key is not None:+ key = mapped_key+ represented_by_parent = (+ _digest(_finding_content(source_value)) in historical_contents+ )+ if key in finding_positions:+ retained = findings[finding_positions[key]]+ if finding != retained:+ if represented_by_parent:+ previous = copy.deepcopy(source_value)+ previous_history = previous.get("provenance", {}).pop(+ "previousFindings", []+ )+ elif _finding_strength(finding) > _finding_strength(retained):+ previous = copy.deepcopy(retained)+ previous_history = previous["provenance"].pop("previousFindings", [])+ retained = finding+ findings[finding_positions[key]] = retained+ else:+ previous = copy.deepcopy(source_value)+ previous_history = previous.get("provenance", {}).pop(+ "previousFindings", []+ )+ retained_provenance = retained["provenance"]+ retained_history = retained_provenance.get("previousFindings")+ history = (+ [item for item in retained_history if isinstance(item, dict)]+ if isinstance(retained_history, list)+ else []+ )+ retained_provenance["previousFindings"] = history+ for original in [+ *(previous_history if isinstance(previous_history, list) else []),+ previous,+ ]:+ if not isinstance(original, dict):+ continue+ source_key = _finding_key(original)+ source_content = _finding_content(original)+ already_retained = any(+ source_key == _finding_key(historical)+ and source_content == _finding_content(historical)+ for historical in _retained_findings(retained)+ )+ if (+ not already_retained+ and original not in history+ and original != retained+ ):+ history.append(original)+ continue+ finding_positions[key] = len(findings)+ findings.append(finding)+ if superseded:+ continue+ for field in ("surfaces", "explicitExclusions", "deferred", "openQuestions"):+ items = draft["coverage"].get(field, [])+ if not isinstance(items, list):+ continue+ output = coverage.setdefault(field, [])+ if not isinstance(output, list):+ # Keep malformed canonical collections for the existing finalizer's+ # recovery and warnings rather than silently changing its contract.+ continue+ for item in items:+ if field == "openQuestions" and isinstance(item, str):+ item = {"question": item.strip()}+ if (+ field == "surfaces"+ and isinstance(item, dict)+ and item.get("disposition") in {"rejected", "not_applicable"}+ and isinstance(item.get("candidateId"), str)+ and (history_findings := rejected_history.get((worker_id, item["candidateId"])))+ ):+ item = copy.deepcopy(item)+ if not isinstance(item.get("previousFindings"), list):+ item["previousFindings"] = []+ history = item["previousFindings"]+ for finding in history_findings:+ if not any(+ isinstance(previous, dict)+ and _finding_key(previous) == _finding_key(finding)+ and _finding_content(previous) == _finding_content(finding)+ for previous in history+ ):+ history.append(copy.deepcopy(finding))+ if (+ isinstance(item, dict)+ and (worker_id, item.get("candidateId")) in resolved+ and (field == "deferred" or item.get("disposition") == "needs_follow_up")+ ):+ continue+ if isinstance(item, dict) and "id" not in item:+ semantic_item = dict(item)+ if field == "surfaces":+ semantic_item.setdefault("receiptRefs", [])+ if any(+ isinstance(existing, dict)+ and {key: value for key, value in existing.items() if key != "id"}+ == semantic_item+ for existing in output+ ):+ continue+ if item not in output:+ output.append(copy.deepcopy(item))++ identities: dict[str, str] = {}+ for finding in findings:+ if not valid_finding(finding):+ continue+ identity = finding.get("identity")+ if not isinstance(identity, dict):+ continue+ key = _encoded([finding.get("ruleId"), identity]).decode()+ variant = _finding_key(finding)+ if key in identities and identities[key] != variant:+ finding.setdefault("provenance", {})["preservedIdentity"] = copy.deepcopy(identity)+ identity["instance"] = f"{identity.get('instance', 'saved')}-{variant[:16]}"+ identities[key] = variant+ for field in ("surfaces", "explicitExclusions", "deferred"):+ used: set[str] = set()+ items = coverage.setdefault(field, [])+ for item in items if isinstance(items, list) else []:+ if not isinstance(item, dict):+ continue+ if id(item) in canonical_rows:+ if isinstance(item.get("id"), str):+ used.add(item["id"])+ continue+ item.setdefault("id", item.get("candidateId") or f"saved-{_digest(item)[:16]}")+ if item["id"] in used:+ item["id"] = f"{item['id']}-{_digest(item)[:16]}"+ used.add(item["id"])+ if field == "surfaces":+ item.setdefault("receiptRefs", [])+ if stopped or any(warning not in initial_warnings for warning in warnings):+ coverage["completeness"] = "partial"+ if stopped:+ if not isinstance(coverage.get("deferred"), list):+ coverage["deferred"] = []+ item = {"id": "scan-stopped", "reason": reason}+ if item not in coverage["deferred"]:+ coverage["deferred"].append(item)+ return manifest, {"findings": findings}, coverage+++def coverage_for_comparison(db: Any, scan: Any) -> dict[str, Any]:+ if scan["seal_manifest_digest"] is None:+ raise SystemExit("Only sealed scans can be compared.")+ scan_dir = db.require_canonical_scan_directory(Path(scan["scan_dir"]))+ db.require_recorded_manifest_digest(scan, scan_dir)+ try:+ _, _, manifest, _, coverage, was_sealed, _ = _prepare_scan_finalization(scan_dir)+ except ContractError as exc:+ raise SystemExit(str(exc)) from exc+ if not was_sealed or manifest["scan"]["id"] != scan["id"]:+ raise SystemExit("Only sealed scans can be compared.")+ return coverage+++def _snapshot_published_outputs(scan_dir: Path) -> dict[str, bytes | None]:+ snapshots: dict[str, bytes | None] = {}+ for relative in _PUBLISHED_OUTPUTS:+ descriptor = -1+ try:+ descriptor = open_scan_local_file_descriptor(+ scan_dir, relative, "Published scan output"+ )+ with os.fdopen(descriptor, "rb") as handle:+ descriptor = -1+ snapshots[relative] = handle.read()+ except ContractError:+ path = scan_dir / relative+ if path.exists() or path.is_symlink():+ raise+ snapshots[relative] = None+ finally:+ if descriptor >= 0:+ os.close(descriptor)+ return snapshots+++def _restore_published_outputs(scan_dir: Path, snapshots: dict[str, bytes | None]) -> None:+ for relative, contents in snapshots.items():+ if contents is None:+ path = scan_dir / relative+ if path.exists() or path.is_symlink():+ _remove_scan_local_file_if_exists(scan_dir, relative)+ else:+ write_scan_local_bytes(scan_dir, relative, contents)+++def preserve_scan_results_locked(db: Any, connection: Any, scan_id: str) -> bool:+ """Publish or verify retained terminal results through the workbench host."""+ scan = db.require_scan(connection, scan_id)+ if scan["status"] != "failed":+ return False+ frozen_source_digests: dict[str, str] | None = None+ raw_frozen_sources = scan["retained_source_digests_json"]+ if raw_frozen_sources is not None:+ parsed_frozen_sources = json.loads(raw_frozen_sources)+ if not isinstance(parsed_frozen_sources, dict) or not all(+ isinstance(relative, str) and isinstance(digest, str)+ for relative, digest in parsed_frozen_sources.items()+ ):+ raise ContractError("Saved stopped-scan source digests are malformed.")+ frozen_source_digests = parsed_frozen_sources+ scan_dir = db.require_canonical_scan_directory(Path(scan["scan_dir"]))+ deep_run = connection.execute(+ "SELECT status FROM deep_scan_runs WHERE scan_id = ?", (scan_id,)+ ).fetchone()+ outcome = (+ "canceled"+ if scan["canceled_at"]+ else "interrupted"+ if deep_run and deep_run["status"] == "interrupted"+ else "failed"+ )+ stored_warnings = json.loads(scan["completion_warnings_json"])+ publication_follow_up_warnings = [+ warning+ for warning in stored_warnings+ if isinstance(warning, str) and warning.startswith(_PUBLICATION_FOLLOW_UP_WARNING)+ ]+ warnings = [+ warning for warning in stored_warnings if warning not in publication_follow_up_warnings+ ]++ def record_publication(manifest: dict[str, Any], findings: dict[str, Any]) -> None:+ retained_sources = manifest.get("scan", {}).get("preservedSources")+ if not isinstance(retained_sources, dict) or not all(+ isinstance(relative, str) and isinstance(source_digest, str)+ for relative, source_digest in retained_sources.items()+ ):+ raise ContractError("Stopped scan source digests could not be frozen.")+ digest = db.published_manifest_digest(scan_dir, manifest)+ timestamp = db.now()+ with connection:+ for kind, filename in db.ARTIFACTS.items():+ path = db.artifact_path(scan_dir, filename, required=True)+ connection.execute(+ "INSERT OR REPLACE INTO scan_artifacts "+ "(scan_id, kind, path, created_at) VALUES (?, ?, ?, ?)",+ (scan_id, kind, str(path), scan["completed_at"]),+ )+ # Delete only vanished occurrences; stable IDs retain triage and remediation.+ existing_ids = {+ row["id"]+ for row in connection.execute(+ "SELECT id FROM finding_occurrences WHERE scan_id = ?", (scan_id,)+ )+ }+ retained_ids = {finding["occurrenceId"] for finding in findings["findings"]}+ connection.executemany(+ "DELETE FROM finding_occurrences WHERE id = ? AND scan_id = ?",+ ((occurrence_id, scan_id) for occurrence_id in existing_ids - retained_ids),+ )+ db.index_findings(connection, scan_id, findings, scan["completed_at"])+ connection.execute(+ "UPDATE scans SET seal_manifest_digest = ?, retained_source_digests_json = "+ "COALESCE(retained_source_digests_json, ?), completion_warnings_json = ?, "+ "updated_at = ? WHERE id = ? AND status = 'failed'",+ (+ digest,+ json.dumps(retained_sources, sort_keys=True),+ json.dumps(list(dict.fromkeys(warnings))),+ timestamp,+ scan_id,+ ),+ )+ connection.execute(+ "UPDATE scan_progress SET reportable_findings_count = ?, updated_at = ? "+ "WHERE scan_id = ?",+ (len(findings["findings"]), timestamp, scan_id),+ )++ existing_path = db.artifact_path(scan_dir, db.ARTIFACTS["manifest"], required=False)+ existing_scan = db.read_json_object(existing_path).get("scan", {}) if existing_path else {}+ if scan["seal_manifest_digest"] is not None or (+ isinstance(existing_scan, dict)+ and (+ existing_scan.get("sealedAt") is not None or existing_scan.get("artifacts") is not None+ )+ ):+ db.require_recorded_manifest_digest(scan, scan_dir)+ existing, existing_findings, _ = finalize_scan(+ scan_dir, expected_coverage_mode=db.expected_coverage_mode(scan)+ )+ db.verify_manifest_binding(scan, existing)+ if existing_scan.get("status") == outcome:+ existing_sources = existing_scan.get("preservedSources")+ if frozen_source_digests is None:+ if not isinstance(existing_sources, dict) or not all(+ isinstance(relative, str) and isinstance(digest, str)+ for relative, digest in existing_sources.items()+ ):+ raise ContractError("Stopped scan source digests could not be frozen.")+ frozen_source_digests = existing_sources+ if existing_sources == frozen_source_digests:+ if (+ raw_frozen_sources is not None+ and scan["seal_manifest_digest"] is not None+ and not publication_follow_up_warnings+ ):+ return True+ record_publication(existing, existing_findings)+ return True+ raise ContractError("Stopped scan sources changed after terminal publication.")+ binding = {**db.workbench_completion_binding(scan, scan["completed_at"]), "status": outcome}+ documents = merge_saved_results(+ scan_dir,+ scan_id,+ binding,+ connection.execute(+ "SELECT * FROM deep_scan_workers WHERE scan_id = ? ORDER BY created_at, id",+ (scan_id,),+ ).fetchall(),+ warnings,+ stopped=True,+ reason=(+ f"Scan {outcome}; saved findings and pending review were preserved. "+ f"{scan['failure_message'] or ''}"+ ).strip(),+ frozen_source_digests=frozen_source_digests,+ )+ if documents is None:+ unpublished_warnings = list(dict.fromkeys([*warnings, *publication_follow_up_warnings]))+ if unpublished_warnings != stored_warnings:+ with connection:+ connection.execute(+ "UPDATE scans SET completion_warnings_json = ?, updated_at = ? "+ "WHERE id = ? AND status = 'failed'",+ (json.dumps(unpublished_warnings), db.now(), scan_id),+ )+ return False+ prepared = _prepare_scan_finalization(+ scan_dir,+ expected_coverage_mode=db.expected_coverage_mode(scan),+ completion_binding=binding,+ completion_warnings=warnings,+ draft_documents=documents,+ )+ snapshots = _snapshot_published_outputs(scan_dir)+ try:+ manifest, findings, _ = _write_prepared_scan_finalization(prepared)+ db.verify_manifest_binding(scan, manifest)+ record_publication(manifest, findings)+ except BaseException:+ _restore_published_outputs(scan_dir, snapshots)+ raise+ return True+++def refresh_stopped_scan_results(+ db: Any, connection: Any, scan_id: str, *, strict: bool = False+) -> None:+ scan = db.require_scan(connection, scan_id)+ if scan["status"] != "failed":+ return+ scan_id = scan["id"]+ with db.scan_completion_lock(scan_id):+ if strict:+ if preserve_scan_results_locked(db, connection, scan_id):+ db.deep_scan.clear_deep_scan_publication_failure(connection, scan_id)+ else:+ preserve_stopped_results_after_transition(db, connection, scan_id)+++def preserve_scan_results(db: Any, connection: Any, args: Any) -> dict[str, Any]:+ scan_id = db.require_uuid(args.scan_id, "scan-id")+ with db.scan_completion_lock(scan_id):+ scan = db.require_scan(connection, scan_id)+ if scan["status"] != "failed":+ raise SystemExit("Only a stopped scan can preserve terminal results.")+ workspace = db.require_workspace(connection, scan["workspace_id"])+ owner = (+ scan["continuation_thread_id"]+ or scan["deep_scan_owner_thread_id"]+ or workspace["thread_id"]+ )+ if args.thread_id is not None and args.thread_id != owner:+ raise SystemExit("Saved results can only be published from the owning Codex thread.")+ if args.coordinator_generation is not None:+ if args.thread_id is None:+ raise SystemExit("A coordinator result refresh requires its owning thread.")+ db.deep_scan.require_current_coordinator(+ db.deep_scan.require_deep_scan_run(connection, scan_id), args+ )+ else:+ db.handoff.require_current_continuation(+ scan,+ args.claim_token,+ error_message="Saved results are owned by another continuation.",+ )+ published = preserve_scan_results_locked(db, connection, scan_id)+ if not published and scan["canceled_at"] is not None:+ raise SystemExit("Saved scan results could not be published or verified.")+ if published:+ db.deep_scan.clear_deep_scan_publication_failure(connection, scan_id)+ return db.scan_context(connection, scan_id)+++def write_scan_draft(db: Any, connection: Any, args: Any) -> dict[str, Any]:+ scan_id = db.require_uuid(args.scan_id, "scan-id")+ with db.scan_completion_lock(scan_id):+ scan = db.require_scan(connection, scan_id)+ db.handoff.require_current_continuation(+ scan, args.claim_token, error_message="Scan draft is owned by another continuation."+ )+ if scan["status"] != "running" or scan["seal_manifest_digest"] is not None:+ raise SystemExit(+ "The scan stopped; its saved checkpoint was retained without replacing sealed results."+ )+ scan_dir = db.require_canonical_scan_directory(Path(scan["scan_dir"]))+ if args.checkpoint_path is not None:+ try:+ checkpoint_relative = Path(args.checkpoint_path).relative_to(scan_dir).as_posix()+ except ValueError as exc:+ raise SystemExit(+ "Scan checkpoint must be inside the registered scan drafts directory."+ ) from exc+ if not re.fullmatch(r"drafts/[0-9a-fA-F-]+\.checkpoint\.json", checkpoint_relative):+ raise SystemExit(+ "Scan checkpoint must be inside the registered scan drafts directory."+ )+ checkpoint, checkpoint_contents = _read_scan_local_json_bytes(+ scan_dir, checkpoint_relative, "Staged scan checkpoint"+ )+ if checkpoint.get("scanId") != scan_id:+ raise SystemExit("Staged scan checkpoint belongs to another scan.")+ checkpoint_digest = hashlib.sha256(checkpoint_contents).hexdigest()+ write_scan_local_bytes(+ scan_dir,+ f"checkpoints/{checkpoint_digest}.json",+ checkpoint_contents,+ )+ if (+ args.expected_draft_digest is not None+ and args.expected_draft_digest != _scan_draft_digest(scan_dir)+ ):+ raise SystemExit(+ "scan_draft_conflict: canonical scan results changed; reconcile the saved checkpoint again."+ )+ try:+ relative = Path(args.draft_path).relative_to(scan_dir).as_posix()+ except ValueError as exc:+ raise SystemExit(+ "Scan draft must be inside the registered scan drafts directory."+ ) from exc+ if not re.fullmatch(r"drafts/[0-9a-fA-F-]+\.json", relative):+ raise SystemExit("Scan draft must be inside the registered scan drafts directory.")+ draft = _read_scan_local_json(scan_dir, relative, "Staged scan draft")+ manifest, findings, coverage = draft["manifest"], draft["findings"], draft["coverage"]+ binding = db.workbench_completion_binding(scan, db.now())+ # Validate on copies: saved canonical documents remain ordinary unsealed drafts.+ copied_manifest = copy.deepcopy(manifest)+ copied_findings = copy.deepcopy(findings)+ copied_coverage = copy.deepcopy(coverage)+ _populate_unsealed_manifest_envelope(copied_manifest, copied_manifest["scan"], binding)+ _populate_unsealed_artifact_envelope(+ copied_manifest, copied_findings, copied_coverage, binding+ )+ _validate_completion_binding(copied_manifest, copied_findings, copied_coverage, binding)+ for filename, document in (+ ("findings.json", findings),+ ("coverage.json", coverage),+ ("scan-manifest.json", manifest),+ ):+ write_scan_local_bytes(+ scan_dir,+ filename,+ (json.dumps(document, allow_nan=False, indent=2) + "\n").encode(),+ )+ return {"scanId": scan_id, "status": "draft_written"}+++def _scan_draft_digest(scan_dir: Path) -> str:+ digest = hashlib.sha256()+ for filename in ("scan-manifest.json", "findings.json", "coverage.json"):+ digest.update(filename.encode())+ digest.update(b"\0")+ try:+ (scan_dir / filename).lstat()+ except FileNotFoundError:+ digest.update(b"missing\0")+ continue+ _, contents = _read_scan_local_json_bytes(scan_dir, filename, filename)+ digest.update(b"present\0")+ digest.update(contents)+ digest.update(b"\0")+ return digest.hexdigest()+++def fail_scan(db: Any, connection: Any, args: Any) -> dict[str, Any]:+ with db.scan_completion_lock(db.require_uuid(args.scan_id, "scan-id")):+ return fail_scan_locked(db, connection, args)+++def fail_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:+ scan_id = db.require_uuid(args.scan_id, "scan-id")+ cost_json = db.parse_scan_cost(args.cost_json)+ connection.execute("BEGIN IMMEDIATE")+ try:+ timestamp = db.now()+ scan = db.require_scan(connection, scan_id)+ if scan["status"] == "failed":+ connection.commit()+ return db.scan_context(connection, scan["id"])+ if scan["status"] == "complete":+ raise SystemExit("A completed scan cannot be marked failed.")+ db.handoff.require_current_continuation(+ scan,+ args.claim_token,+ error_message="Scan failure is owned by another continuation.",+ )+ message = db.optional_text(args.message, maximum=2400)+ updated = connection.execute(+ """+ UPDATE scans+ SET status = 'failed', failure_message = ?, completed_at = ?, updated_at = ?,+ cost_json = ?+ WHERE id = ? AND status = 'running'+ """,+ (message, timestamp, timestamp, cost_json, scan["id"]),+ )+ if updated.rowcount != 1:+ raise SystemExit("Only a running scan can be marked failed.")+ db.deep_scan.fail_from_parent_scan(connection, scan["id"], message, timestamp)+ progress_updated = connection.execute(+ "UPDATE scan_progress SET updated_at = ? WHERE scan_id = ?",+ (timestamp, scan["id"]),+ )+ if progress_updated.rowcount != 1:+ raise SystemExit("Codex Security scan progress not found.")+ connection.commit()+ except BaseException:+ connection.rollback()+ raise+ preserve_stopped_results_after_transition(db, connection, scan["id"])+ return db.scan_context(connection, scan["id"])+++def cancel_scan(db: Any, connection: Any, args: Any) -> dict[str, Any]:+ with db.scan_completion_lock(db.require_uuid(args.scan_id, "scan-id")):+ return cancel_scan_locked(db, connection, args)+++def cancel_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:+ scan_id = db.require_uuid(args.scan_id, "scan-id")+ thread_id = db.optional_text(args.thread_id, maximum=512)+ connection.execute("BEGIN IMMEDIATE")+ try:+ timestamp = db.now()+ scan = db.require_scan(connection, scan_id)+ workspace = db.require_workspace(connection, scan["workspace_id"])+ owning_thread_id = scan["continuation_thread_id"] or workspace["thread_id"]+ if thread_id is not None and owning_thread_id != thread_id:+ raise SystemExit("A scan can only be canceled from its owning Codex thread.")+ if scan["canceled_at"] is not None:+ connection.commit()+ return db.workspace_state(connection, scan["workspace_id"])+ if scan["status"] != "running":+ raise SystemExit("Only a running scan can be canceled.")+ updated = connection.execute(+ """+ UPDATE scans+ SET status = 'failed', canceled_at = ?, completed_at = ?, updated_at = ?+ WHERE id = ? AND status = 'running'+ """,+ (timestamp, timestamp, timestamp, scan["id"]),+ )+ if updated.rowcount != 1:+ raise SystemExit("Only a running scan can be canceled.")+ db.deep_scan.cancel_from_parent_scan(connection, scan["id"], timestamp)+ progress_updated = connection.execute(+ "UPDATE scan_progress SET updated_at = ? WHERE scan_id = ?",+ (timestamp, scan["id"]),+ )+ if progress_updated.rowcount != 1:+ raise SystemExit("Codex Security scan progress not found.")+ connection.commit()+ except BaseException:+ connection.rollback()+ raise+ preserve_stopped_results_after_transition(db, connection, scan["id"])+ return db.workspace_state(connection, scan["workspace_id"])+++def preserve_stopped_results_after_transition(+ db: Any, connection: Any, scan_id: str+) -> None:+ try:+ published = preserve_scan_results_locked(db, connection, scan_id)+ except (ContractError, OSError, SystemExit, ValueError) as exc:+ scan = db.require_scan(connection, scan_id)+ warnings = json.loads(scan["completion_warnings_json"])+ warning = f"Saved scan evidence remains on disk; result publication needs follow-up: {exc}"+ with connection:+ connection.execute(+ "UPDATE scans SET completion_warnings_json = ? WHERE id = ?",+ (json.dumps(list(dict.fromkeys([*warnings, warning]))), scan_id),+ )+ return+ if published:+ db.deep_scan.clear_deep_scan_publication_failure(connection, scan_id)+++if __name__ == "__main__":+ argparse.ArgumentParser(description=__doc__).parse_args()diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py b/sdk/typescript/_bundled_plugin/scripts/workbench_schema.pyindex 7fb414ae7..90111fdd7 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py@@ -683,6 +683,20 @@ MIGRATIONS = (WHERE project_id IS NULL;""",),+ (+ 31,+ "freeze stopped scan source digests",+ """+ ALTER TABLE scans ADD COLUMN retained_source_digests_json TEXT;+ """,+ ),+ (+ 32,+ "separate deep scan publication failures",+ """+ ALTER TABLE deep_scan_runs ADD COLUMN publication_error_message TEXT;+ """,+ ),)@@ -744,6 +758,20 @@ def apply_migrations("max_time_hours","REAL NOT NULL DEFAULT 96",)+ elif version == 31:+ add_column_if_missing(+ connection,+ "scans",+ "retained_source_digests_json",+ "TEXT",+ )+ elif version == 32:+ add_column_if_missing(+ connection,+ "deep_scan_runs",+ "publication_error_message",+ "TEXT",+ )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 6904af9a2..72007f5c8 100644--- a/sdk/typescript/_bundled_plugin/skills/deep-security-scan/SKILL.md+++ b/sdk/typescript/_bundled_plugin/skills/deep-security-scan/SKILL.md@@ -5,7 +5,7 @@ description: Use when the user asks for a deep, exhaustive, multi-pass, or varia# Deep Security Scan-Use `start_codex_security_deep_scan` to run repeated independent workers against the exact requested target and scope. Each worker loads `../../references/core-scan.md` directly and performs the complete ordinary Standard audit, including its own threat map, investigation, source-backed validation, and attack-path reasoning, then submits one worker-bound semantic scan draft. The coordinator aggregates the finished Standard results and writes the parent scan's unsealed `scan-manifest.json`, `findings.json`, and `coverage.json` before returning `{ manifestPath }`.+Use `start_codex_security_deep_scan` to run repeated independent workers against the exact requested target and scope. Each worker loads `../../references/core-scan.md` directly and performs the complete ordinary Standard audit, including its own threat map, investigation, source-backed validation, and attack-path reasoning, saving worker-bound checkpoints as results arrive and one final semantic scan draft when its audit finishes. The coordinator aggregates the finished Standard results and writes the parent scan's unsealed `scan-manifest.json`, `findings.json`, and `coverage.json` before returning `{ manifestPath }`.## Phase Ownership@@ -58,8 +58,8 @@ If the host represents the pending call as a running execution cell, keep waitinHandle the result as follows:- `{ manifestPath }`: this is the parent scan's already-authored, unsealed canonical `scan-manifest.json`, not a request for another parent workflow. Its complete Standard worker results have already been validated. Older generic or benchmark instructions describing discovery-only coordinator manifests, candidate lists, parent validation or attack-path phases, or another semantic draft do not apply to this canonical-manifest result. Confirm that the manifest, `findings.json`, and `coverage.json` exist in the authoritative scan directory. For native continuations, keep the existing authoritative `scanId`; for a first target-based CLI or headless call, use the authoritative scan ID explicitly returned in the successful tool result's text. The unsealed manifest may not contain an ID, so never infer one from it, reload global context, or start a replacement scan. Immediately complete that same scan. Do not rerun validation or attack-path analysis, list candidates, aggregate findings, submit another semantic draft, or start another scan.-- `status: "canceled"`: stop without producing a report or calling finalization.-- Tool error or a result without `manifestPath`: surface the exact stable MCP error and any preserved failure-manifest path, then stop the current response. Do not call `start_codex_security_deep_scan` again, reload scan context, call completion, create a replacement scan, cancel an already terminal scan, synthesize findings or coverage, or return final, no-findings, structured, or benchmark output.+- `status: "canceled"`: stop all scan work and do not call completion. The workbench preserves saved findings and pending candidates; report those retained results with incomplete coverage without claiming a successful scan or generating a replacement report.+- Terminal scan failure: surface the exact stable MCP error, then read the existing scan context to report preserved findings and pending candidates with incomplete coverage. Do not start more scan work, call completion, cancel an already terminal scan, synthesize findings, or claim a successful/no-findings scan. An invocation failure before a scan starts is still a blocker; do not create a replacement scan or infer results.The native Security workbench observes durable progress without another scan-start call.@@ -71,4 +71,4 @@ Detailed finding write-ups and hardening proposals remain optional, exactly as iReturn user-facing or benchmark output only after completion succeeds and the generated `report.md` exists. Link the report and canonical artifacts. Include measured total, input, and cached input token counts; explicitly label partial coverage and state when measurement is unavailable instead of reporting zero or estimating. If the configured time limit elapsed before any source review completed, report the existing coverage as partial and never claim the repository is free of vulnerabilities. An empty finding set with completed review is the ordinary Codex Security no-findings result, not permission to skip completion.-If canonical coordinator artifacts are missing or malformed, stop and surface the exact blocker without calling completion, fabricating a report, or claiming success. If completion fails, surface its exact MCP error without retrying, canceling, failing the durable scan, or returning final, no-findings, structured, or benchmark output. Leave resumable work running and preserve its handoff claim. On explicit cancellation, call `cancel_codex_security_scan` and do not accept later progress or artifacts. Never edit repository files, widen the target, expose internal worker bookkeeping unless requested, or call `fail_codex_security_scan` merely because a waiter detached, a turn ended, workers are still active, or partial artifacts exist.+If canonical coordinator artifacts are missing or malformed, stop and surface the exact blocker without calling completion, fabricating a report, or claiming success. If completion fails, surface its exact MCP error without retrying, canceling, failing the durable scan, or returning final, no-findings, structured, or benchmark output. Leave resumable work running and preserve its handoff claim. On explicit cancellation, call `cancel_codex_security_scan` and do not accept later scan progress or success. The host may preserve a final in-flight checkpoint after worker cleanup without resuming analysis. Never edit repository files, widen the target, expose internal worker bookkeeping unless requested, or call `fail_codex_security_scan` merely because a waiter detached, a turn ended, workers are still active, or partial artifacts exist.diff --git a/sdk/typescript/_bundled_plugin/skills/security-diff-scan/SKILL.md b/sdk/typescript/_bundled_plugin/skills/security-diff-scan/SKILL.mdindex faf2d4674..af59e39c2 100644--- a/sdk/typescript/_bundled_plugin/skills/security-diff-scan/SKILL.md+++ b/sdk/typescript/_bundled_plugin/skills/security-diff-scan/SKILL.md@@ -25,7 +25,7 @@ Read `../../references/config-preflight.md` before dispatching the `security_dif2. Prepare the file list with `prepare_codex_security_review_items` and read all pages from `list_codex_security_review_items`. Inspect deleted files at the baseline revision and unchanged files only when needed to explain the change.3. Run `$finding-discovery` in compact diff mode across the existing file inventory. Do not create ranked worklists, per-finding ledgers, or discovery reports. Divide large changes among available workers without overlap; review any unassigned files yourself. Keep independently reachable bugs separate and record all candidates once with `record_codex_security_discovery_candidates`.4. If candidates exist, run `$validation` once, then `$attack-path-analysis` once for candidates marked `reportable` or `deferred`. Preserve exact locations, evidence, affected instances, and unresolved questions.-5. Record findings, coverage, and the retained canonical model with `record_codex_security_scan_draft({ scanId, handoffClaimToken?, scope?, threatModel, findings, coverage })`. Mark unresolved work as deferred. Request detailed write-ups or hardening plans only when the user asks.+5. Record `complete: false` semantic checkpoints with `record_codex_security_scan_draft` as findings and validation decisions arrive, retaining unresolved candidates and original evidence in `coverage.deferred`. After the review settles, record one final `complete: true` semantic draft with the retained canonical model, findings, and coverage. Request detailed write-ups or hardening plans only when the user asks.6. Call `complete_codex_security_scan` once, then read `get_codex_security_completed_scan`. Finalization creates `report.md` and SARIF. Include measured token usage when available and identify incomplete coverage.For terminal scans without a `scanId`, generate the changed-file list with:diff --git a/sdk/typescript/_bundled_plugin/skills/security-scan/SKILL.md b/sdk/typescript/_bundled_plugin/skills/security-scan/SKILL.mdindex 423a68aa8..67e160de6 100644--- a/sdk/typescript/_bundled_plugin/skills/security-scan/SKILL.md+++ b/sdk/typescript/_bundled_plugin/skills/security-scan/SKILL.md@@ -23,7 +23,7 @@ When an SDK or terminal host sets `CODEX_SECURITY_SCAN_ID`, emit its standalone1. Resolve the repository, requested scope, and output scan directory from the host-provided scan context when available; otherwise use the requested output directory or `<platform_temp>/codex-security-scans/<repo_name>/<scan_id>`. Preserve the exact user context, supplied threat model, applicable inherited `SECURITY.md` guidance, and optional `CODEX_SECURITY_KNOWLEDGE_BASE` for the core audit. Resolve `<python_command>` from the configured interpreter (`"$PYTHON"` in POSIX shells or `& "$env:PYTHON"` in PowerShell), otherwise use `python3` on Unix-like hosts or `python` on Windows. Only when `CODEX_SECURITY_TARGET_PATHS_FILE` is supplied, resolve every authorized source path before review with `<python_command> <plugin_dir>/scripts/generate_rank_input.py make-repo-scope-input --repo <repo_root> --scopes-file <target_paths_file> --out <scan_dir>/scoped-source-input.jsonl`; use `"$CODEX_SECURITY_TARGET_PATHS_FILE"` in POSIX shells or `"$env:CODEX_SECURITY_TARGET_PATHS_FILE"` in PowerShell and honor repository ignore rules for directory descendants while retaining every directly requested file. Never print, modify, or treat the scope input as shell syntax; pass it to the core audit without widening the authorized target or scope.2. Read `../../references/core-scan.md` once and perform its complete source-backed security audit against the resolved target, authorized scope, exact user context, supplied threat model, inherited security policy, optional knowledge base, available workers, and any resolved scoped-source inventory. Retain the resulting complete semantic `scope`, `threatModel`, `findings`, and `coverage`; preserve every finding's source evidence, calibrated severity, confidence, root cause, validation, attack path, and honest coverage.-3. For a host-backed scan, submit one accepted semantic draft with `record_codex_security_scan_draft({ scanId, handoffClaimToken?, scope?, threatModel, findings, coverage })`; let the workbench derive its authoritative target, scope, coverage metadata, surface IDs, finding identities, and fingerprints. If the draft is explicitly rejected before writing, correct only the identified fields without dropping valid findings or evidence and retry the same scan at most twice. For an SDK-owned or prompt-only headless scan, write unsealed canonical `scan-manifest.json`, `findings.json`, and `coverage.json`; use `scoped_path` for both coverage fields when a scope was requested, otherwise set `coverage.mode` to `repository` and `coverage.inventoryStrategy` to `directory` for a non-Git directory or `repository` for a Git-backed target. Omit `scan.sealedAt` and `scan.artifacts`; an SDK scan preserves its exact registered directory and all SDK-provided scan and target values. When `CODEX_SECURITY_TARGET_PATHS_FILE` is supplied on either file-authored path, bind its exact requested paths with `<python_command> <plugin_dir>/scripts/generate_rank_input.py bind-repo-scopes --scopes-file <target_paths_file> --manifest <scan_dir>/scan-manifest.json --coverage <scan_dir>/coverage.json`, using the same shell-specific target-paths reference.+3. For a host-backed scan, save `complete: false` checkpoints during the core audit, then submit one accepted final semantic draft with `record_codex_security_scan_draft({ scanId, complete: true, handoffClaimToken?, scope?, threatModel, findings, coverage })`; let the workbench derive its authoritative target, scope, coverage metadata, surface IDs, finding identities, and fingerprints. If the draft is explicitly rejected before writing, correct only the identified fields without dropping valid findings or evidence and retry the same scan at most twice. For an SDK-owned or prompt-only headless scan, write unsealed canonical `scan-manifest.json`, `findings.json`, and `coverage.json`; use `scoped_path` for both coverage fields when a scope was requested, otherwise set `coverage.mode` to `repository` and `coverage.inventoryStrategy` to `directory` for a non-Git directory or `repository` for a Git-backed target. Omit `scan.sealedAt` and `scan.artifacts`; an SDK scan preserves its exact registered directory and all SDK-provided scan and target values. When `CODEX_SECURITY_TARGET_PATHS_FILE` is supplied on either file-authored path, bind its exact requested paths with `<python_command> <plugin_dir>/scripts/generate_rank_input.py bind-repo-scopes --scopes-file <target_paths_file> --manifest <scan_dir>/scan-manifest.json --coverage <scan_dir>/coverage.json`, using the same shell-specific target-paths reference.4. Verify all three canonical JSON files exist. For an SDK-owned scan, return control without finalizing, sealing, generating `report.md`, or starting another scan; the SDK owns completion. For another host-backed scan, call `complete_codex_security_scan({ scanId, handoffClaimToken? })` once. For a prompt-only headless scan, run `<python_command> <plugin_dir>/scripts/finalize_scan_contract.py --scan-dir <scan_dir> --source-root <repo_root>`. Outside the SDK path, return only after completion succeeds and the generated `report.md` exists; never write the report by hand or reread the complete canonical findings unless the user explicitly requests them. Report measured token counts when returned and label partial measurement or unavailable usage honestly.Keep discovery, validation, and attack-path reasoning within this Standard workflow; do not invoke separate phase skills or load Deep or diff references. Never call Deep-only tools. Do not create ranking phases, per-file or per-candidate ledgers, separate phase worker pools, repeated phase reports, or receipt files.diff --git a/sdk/typescript/_bundled_plugin/skills/security-scan/references/desktop-scan.md b/sdk/typescript/_bundled_plugin/skills/security-scan/references/desktop-scan.mdindex 574b26c79..610060747 100644--- a/sdk/typescript/_bundled_plugin/skills/security-scan/references/desktop-scan.md+++ b/sdk/typescript/_bundled_plugin/skills/security-scan/references/desktop-scan.md@@ -16,7 +16,7 @@ Use the existing desktop phase labels for work that actually occurs: threat mapp## Complete The Same Scan-Record the complete semantic scan draft once with `record_codex_security_scan_draft({ scanId, handoffClaimToken?, scope?, threatModel?, findings, coverage })`. Supply the actual findings, source-backed coverage, and preserved threat model; let the workbench write the unsealed canonical artifacts and derive authoritative target, scope, coverage metadata, finding identities, and fingerprints.+Save `complete: false` checkpoints as results arrive and validation decisions are made. Preserve pending candidates with their original evidence in `coverage.deferred`; they are not validated findings. When the audit finishes, record the final semantic scan draft once with `record_codex_security_scan_draft({ scanId, complete: true, handoffClaimToken?, scope?, threatModel?, findings, coverage })`. Supply the actual findings, source-backed coverage, and preserved threat model; let the workbench write the unsealed canonical artifacts and derive authoritative target, scope, coverage metadata, finding identities, and fingerprints.Honor desktop handoff requirements for any per-finding write-ups before completion. After the semantic draft succeeds and all three canonical JSON files exist, call `complete_codex_security_scan` exactly once with the same authoritative scan ID and handoff token. Return only after completion succeeds and `report.md` exists, linking the generated report and canonical artifacts; retrieve the complete findings only when the user explicitly requests them. Include measured token usage when available and explicitly label partial or unavailable measurement.diff --git a/sdk/typescript/plugin-files.json b/sdk/typescript/plugin-files.jsonindex 922f7abcc..41919526f 100644--- a/sdk/typescript/plugin-files.json+++ b/sdk/typescript/plugin-files.json@@ -63,9 +63,11 @@"scripts/workbench_constants.py","scripts/workbench_db.py","scripts/workbench_feedback.py",+ "scripts/workbench_finding_index.py","scripts/workbench_native_indexes.py","scripts/workbench_progress.py","scripts/workbench_remediation.py",+ "scripts/workbench_saved_results.py","scripts/workbench_scan_history.py","scripts/workbench_scan_start.py","scripts/workbench_scan_usage.py",diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 413c7b9e7..cae426dba 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -1248,11 +1248,36 @@ export class CodexSecurity {);}completionCost = snapshot.cost;- const preparation = await workbench(workbenchOptions, [- "prepare-scan-completion",- "--scan-id",- scanId,- ]);+ let preparation: JsonObject;+ try {+ preparation = await workbench(workbenchOptions, [+ "prepare-scan-completion",+ "--scan-id",+ scanId,+ ]);+ } catch (error) {+ const saved = await workbench(workbenchOptions, [+ "get-scan",+ "--scan-id",+ scanId,+ ]).catch(() => null);+ const savedScan = isRecord(saved) ? saved["scan"] : undefined;+ const progress = isRecord(savedScan)+ ? savedScan["progress"]+ : undefined;+ const failureMessage = isRecord(savedScan)+ ? savedScan["failureMessage"]+ : undefined;+ if (+ isRecord(progress) &&+ progress["status"] === "failed" &&+ typeof failureMessage === "string" &&+ failureMessage.trim() !== ""+ ) {+ throw new IncompleteScanError(failureMessage);+ }+ throw error;+ }preparedTargetWarnings = Array.isArray(preparation["targetWarnings"])? preparation["targetWarnings"].filter((warning): warning is string => typeof warning === "string",diff --git a/sdk/typescript/src/custom-validation-prompt.ts b/sdk/typescript/src/custom-validation-prompt.tsindex ad8cc0128..94c316a58 100644--- a/sdk/typescript/src/custom-validation-prompt.ts+++ b/sdk/typescript/src/custom-validation-prompt.ts@@ -9,11 +9,11 @@ import { PLUGIN_NAME } from "./runtime.js";// the ordinary validation sequence with a custom-validation request.const SOURCES = {"references/core-scan.md":- "806efc9432b3352e86c495466b00a700d77e338b6db297a67f3d78d1f7ec359e",+ "e8be71ca85643e9f31e0e8f6354551738ea2783afca72491535645dd83d63454","skills/security-scan/SKILL.md":- "ef4d18fdf85667877f80f68be557214d5edca629c97075c85d7ccdefcc76fb8f",+ "5b8f5d7debeca14c6b37e8e7ba737671362b8eb4b7f49e693c99c6bd04bc8fa0","skills/security-diff-scan/SKILL.md":- "5c2bcdf8c862da4e7fb2c01b0fed8f0de61b65a479c6ae6897d7f12f11f9f87a",+ "0a4c519ad713585876ea7eb0a8af4b59892c86746f4c69851db9ab347b7fad2f",} as const;const DISABLED_TOOLS = [diff --git a/sdk/typescript/src/models.ts b/sdk/typescript/src/models.tsindex b9d9fefd6..471fb3daf 100644--- a/sdk/typescript/src/models.ts+++ b/sdk/typescript/src/models.ts@@ -10,7 +10,7 @@ export interface ScanManifest {version: string;[k: string]: unknown;};- status: "completed";+ status: "completed" | "failed" | "canceled" | "interrupted";startedAt: string;completedAt: string;sealedAt: string;diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 7f1d70908..5dc11da09 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -2853,6 +2853,75 @@ describe("CodexSecurity orchestration", () => {await client.close();});+ test("reports a Deep Scan terminal failure instead of a completion-state error", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "codex-home");+ const scanDir = join(root, "scan");+ await mkdir(repository);+ await mkdir(codexHome);+ await mkdir(scanDir, { mode: 0o700 });+ const commands: string[] = [];+ const terminalFailure =+ "Deep Scan reached its discovery limit after worker policy refusals.";++ 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[],+ input?: string,+ ): Promise<JsonObject> => {+ commands.push(args[0]!);+ if (args[0] === "register-cli-scan") {+ return mockScanRegistration(args, input);+ }+ if (args[0] === "get-scan-feedback") {+ return {+ scanId: "scan_example_001",+ targetId: "target_sha256_example",+ falsePositives: [],+ };+ }+ if (args[0] === "prepare-scan-completion") {+ throw new Error("Only a running scan can be completed.");+ }+ if (args[0] === "get-scan") {+ return {+ scan: {+ failureMessage: terminalFailure,+ progress: { status: "failed" },+ },+ };+ }+ return {};+ },+ createCodex: () => ({+ startThread: () => ({+ id: null,+ async runStreamed() {+ await copyCompletedScan(root);+ return { events: completedEvents() };+ },+ }),+ }),+ },+ );++ await expect(client.run(repository, { mode: "deep" })).rejects.toThrow(+ terminalFailure,+ );+ expect(commands).toContain("prepare-scan-completion");+ expect(commands).toContain("get-scan");+ await client.close();+ });+test.each([["without", false],["with", true],diff --git a/sdk/typescript/tests-ts/compact-diff-scan.test.ts b/sdk/typescript/tests-ts/compact-diff-scan.test.tsindex 106fd38e5..f117cb0c3 100644--- a/sdk/typescript/tests-ts/compact-diff-scan.test.ts+++ b/sdk/typescript/tests-ts/compact-diff-scan.test.ts@@ -805,6 +805,12 @@ describe("compact diff scan", () => {openQuestions,},});+ const canonicalDraftIdentities = (+ JSON.parse(readFileSync(join(scanDir, "findings.json"), "utf8")) as {+ findings: JsonObject[];+ }+ ).findings.map((draftFinding) => draftFinding["identity"]);+ expect(canonicalDraftIdentities).toHaveLength(9);await call("complete_codex_security_scan", {scanId,handoffClaimToken,@@ -830,11 +836,11 @@ describe("compact diff scan", () => {expect((completed["coverage"] as JsonObject)["inventoryStrategy"]).toBe("diff",);- expect(- ((completed["findings"] as JsonObject)["findings"] as JsonObject[]).map(- (completedFinding) => completedFinding["identity"],- ),- ).toEqual([+ const completedIdentities = (+ (completed["findings"] as JsonObject)["findings"] as JsonObject[]+ ).map((completedFinding) => completedFinding["identity"]);+ expect(completedIdentities).toEqual(canonicalDraftIdentities);+ expect(completedIdentities).toEqual([{ anchor: "candidate-singleton", instance: "dss-144-a" },{ anchor: "unsafe-archive-extraction" },{ anchor: "candidate-cross-rule", instance: "shared-report" },@@ -846,6 +852,7 @@ describe("compact diff scan", () => {instance: "dss-147-b",},{ anchor: "candidate-authored-instance", instance: "ledger-row-c" },+ { anchor: "candidate-duplicate-instance", instance: "dss-147-a" },]);const legacyFinding = ((completed["findings"] as JsonObject)["findings"] as JsonObject[]diff --git a/sdk/typescript/tests-ts/custom-validation.test.ts b/sdk/typescript/tests-ts/custom-validation.test.tsindex d7ff59f99..4829639d7 100644--- a/sdk/typescript/tests-ts/custom-validation.test.ts+++ b/sdk/typescript/tests-ts/custom-validation.test.ts@@ -533,7 +533,16 @@ describe("custom validation", () => {(await json<FindingsDocument>(join(scanDir, "findings.json"))).findings,).toHaveLength(1);- await expect(readFile(join(scanDir, "report.md"))).rejects.toThrow();+ expect(+ (+ await json<{ scan: { status: string } }>(+ join(scanDir, "scan-manifest.json"),+ )+ ).scan.status,+ ).toBe("failed");+ expect(await readFile(join(scanDir, "report.md"), "utf8")).toContain(+ "Fixture 0",+ );return;}const completed = await pending;diff --git a/sdk/typescript/tests-ts/deep-scan-reducer-recovery.test.ts b/sdk/typescript/tests-ts/deep-scan-reducer-recovery.test.tsindex 542dd037d..c33104c52 100644--- a/sdk/typescript/tests-ts/deep-scan-reducer-recovery.test.ts+++ b/sdk/typescript/tests-ts/deep-scan-reducer-recovery.test.ts@@ -173,6 +173,38 @@ test("classifies owned worker tool failures without exposing their contents", asexpect(unrelatedDiagnostics).toEqual([]);});+test("does not retry textual missing-path worker failures", async () => {+ const runtime = await loadBundledRuntime();+ const errorClass =+ /var DeepScanNonRetryableError = class extends Error \{[\s\S]*?\n\};/u.exec(+ runtime,+ )?.[0];+ expect(errorClass).toBeDefined();+ const classify = new Function(+ "ARTIFACT_MCP_STARTUP_TIMEOUT_PATTERN",+ "REMOTE_PLUGIN_AUTH_WARNING_PATTERN",+ "isCodexCybersecurityPolicyRefusal",+ [+ errorClass!,+ bundledFunction(runtime, "classifyCodexWorkerError"),+ bundledFunction(runtime, "isCodexConfigurationFailure"),+ "return classifyCodexWorkerError;",+ ].join("\n"),+ )(/$^/u, /$^/u, () => false) as (error: Error) => Error;++ for (const diagnostic of [+ "Error: No such file or directory (os error 2)",+ "Error: The system cannot find the file specified. (os error 2)",+ ]) {+ const original = new Error(+ ["Codex Exec exited with code 1:", diagnostic].join("\n"),+ );+ const classified = classify(original);+ expect(classified.name).toBe("DeepScanNonRetryableError");+ expect(classified.cause).toBe(original);+ }+});+test("resumes only when the exact Standard worker or reducer result is missing", async () => {const runtime = await loadBundledRuntime();const source = bundledFunction(runtime, "isMissingWorkerResult");diff --git a/sdk/typescript/tests-ts/publication-store.test.ts b/sdk/typescript/tests-ts/publication-store.test.tsindex 194230bfb..92a927763 100644--- a/sdk/typescript/tests-ts/publication-store.test.ts+++ b/sdk/typescript/tests-ts/publication-store.test.ts@@ -234,9 +234,11 @@ connection.close()test("upgrades existing scan history and verifies every completed finding before publication", async () => {const fixture = await publicationFixture();databaseRows(fixture, "DROP TABLE finding_publications");- databaseRows(fixture, "DELETE FROM schema_migrations WHERE version >= ?", [- 29,- ]);+ databaseRows(+ fixture,+ "DELETE FROM schema_migrations WHERE version IN (?, ?)",+ [29, 30],+ );await expect(preparePublicationStore(fixture.publication, fixture.environment),@@ -245,8 +247,8 @@ connection.close()expect(databaseRows(fixture,- "SELECT version, name FROM schema_migrations WHERE version >= ? ORDER BY version",- [29],+ "SELECT version, name FROM schema_migrations WHERE version BETWEEN ? AND ? ORDER BY version",+ [29, 30],),).toEqual([{ version: 29, name: "persist finding publication associations" },@@ -263,6 +265,48 @@ connection.close()).toEqual([{ count: 0 }]);});+ test("upgrades scan history from before stopped-result preservation", async () => {+ const fixture = await publicationFixture();+ databaseRows(+ fixture,+ "ALTER TABLE scans DROP COLUMN retained_source_digests_json",+ );+ databaseRows(+ fixture,+ "ALTER TABLE deep_scan_runs DROP COLUMN publication_error_message",+ );+ databaseRows(fixture, "DELETE FROM schema_migrations WHERE version >= ?", [+ 31,+ ]);++ await expect(+ preparePublicationStore(fixture.publication, fixture.environment),+ ).resolves.toBeUndefined();++ expect(+ databaseRows(+ fixture,+ "SELECT version, name FROM schema_migrations WHERE version >= ? ORDER BY version",+ [31],+ ),+ ).toEqual([+ { version: 31, name: "freeze stopped scan source digests" },+ { version: 32, name: "separate deep scan publication failures" },+ ]);+ expect(+ databaseRows(+ fixture,+ "SELECT name FROM pragma_table_info('scans') WHERE name = 'retained_source_digests_json'",+ ),+ ).toEqual([{ name: "retained_source_digests_json" }]);+ expect(+ databaseRows(+ fixture,+ "SELECT name FROM pragma_table_info('deep_scan_runs') WHERE name = 'publication_error_message'",+ ),+ ).toEqual([{ name: "publication_error_message" }]);+ });+test("upgrades existing project-scoped associations without changing recorded issues", async () => {const fixture = await publicationFixture({ count: 1 });const original = publishedIssue(fixture.publication, 0, "EXAMPLE-401");diff --git a/sdk/typescript/tests-ts/stopped-scan-results.test.ts b/sdk/typescript/tests-ts/stopped-scan-results.test.tsnew file mode 100644index 000000000..1a4c1964f--- /dev/null+++ b/sdk/typescript/tests-ts/stopped-scan-results.test.ts@@ -0,0 +1,308 @@+import { spawnSync } from "node:child_process";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, expect, test } from "bun:test";+import { PLUGIN_ROOT } from "./plugin-root.js";++const temporaryDirectories: string[] = [];++afterEach(() => {+ for (const path of temporaryDirectories.splice(0)) {+ rmSync(path, { recursive: true, force: true });+ }+});++const stoppedScanProbe = [+ "import argparse, hashlib, json, os, pathlib, shutil, sqlite3, subprocess, sys, uuid",+ "plugin = pathlib.Path(sys.argv[1])",+ "root = pathlib.Path(sys.argv[2])",+ "source = sys.argv[3]",+ "terminal_status = sys.argv[4] if len(sys.argv) > 4 else 'failed'",+ "state = root / 'state'",+ "home = root / 'codex-home'",+ "target = root / 'target'",+ "target_file = target / 'src' / 'extract.py'",+ "target_file.parent.mkdir(parents=True)",+ "target_file.write_text('\\n' * 50, encoding='utf-8')",+ "config = home / 'codex-security' / 'config.toml'",+ "config.parent.mkdir(parents=True)",+ "config.write_text('[deep_scan]\\nworkers = 1\\nmax_discovery_runs = 1\\n', encoding='utf-8')",+ "environment = {**os.environ, 'CODEX_SECURITY_STATE_DIR': str(state), 'CODEX_HOME': str(home)}",+ "script = plugin / 'scripts' / 'workbench_db.py'",+ "def run(*arguments):",+ " completed = subprocess.run([sys.executable, '-I', '-B', str(script), *arguments], check=True, capture_output=True, text=True, env=environment)",+ " return json.loads(completed.stdout)",+ "started = run('begin-deep-scan', '--thread-id', 'stopped-result-owner', '--target-path', str(target), '--scope', '.', '--scan-root', str(root / 'scans'), '--available-parallelism', '4')['deepScan']",+ "scan_id = started['scanId']",+ "scan_dir = pathlib.Path(started['scanDir'])",+ "worker_id = str(uuid.uuid4())",+ "artifact_dir = scan_dir / 'artifacts' / 'deep_discovery' / source",+ "artifact_dir.mkdir(parents=True)",+ "prompt_path = artifact_dir / 'prompt.md'",+ "prompt_path.write_text('Review the fixture.\\n', encoding='utf-8')",+ "result_path = artifact_dir / 'result.json'",+ "base = ('upsert-deep-scan-worker', '--scan-id', scan_id, '--worker-id', worker_id, '--kind', 'discovery', '--prompt-path', str(prompt_path), '--artifact-dir', str(artifact_dir), '--attempt', '1')",+ "run(*base, '--status', 'running')",+ "finding = json.loads((plugin / 'examples' / 'completed-scan' / 'findings.json').read_text(encoding='utf-8'))['findings'][0]",+ "finding.setdefault('provenance', {})['candidateId'] = 'checkpoint-candidate'",+ "payload = {'scanId': scan_id, 'findings': [finding], 'coverage': {'completeness': 'partial', 'surfaces': [], 'explicitExclusions': [], 'deferred': [{'candidateId': 'pending-validation', 'reason': 'Validation stopped with the scan.', 'paths': ['src/extract.py']}]}, 'threatModel': {'summary': 'Synthetic stopped-scan threat model.'}}",+ "if source == 'accepted':",+ " result_path.write_text(json.dumps(payload), encoding='utf-8')",+ " run(*base, '--status', 'succeeded', '--result-manifest-path', str(result_path))",+ "else:",+ " checkpoint = {**payload, 'complete': False}",+ " checkpoint_dir = artifact_dir / 'checkpoints'",+ " checkpoint_dir.mkdir()",+ " if source == 'refined-checkpoint':",+ " earlier = json.loads(json.dumps(checkpoint))",+ " earlier['findings'][0]['locations'][0].update({'startLine': 21, 'endLine': 26})",+ " later = json.loads(json.dumps(checkpoint))",+ " later['findings'][0]['locations'][0].update({'startLine': 24, 'endLine': 26})",+ " for document in (earlier, later):",+ " encoded = json.dumps(document).encode()",+ " (checkpoint_dir / f'{hashlib.sha256(encoded).hexdigest()}.json').write_bytes(encoded)",+ " result_path.write_text(json.dumps(later), encoding='utf-8')",+ " else:",+ " if source == 'distinct-instances':",+ " first = json.loads(json.dumps(finding))",+ " first['identity'] = {'anchor': 'shared-anchor', 'instance': 'first'}",+ " second = json.loads(json.dumps(finding))",+ " second['identity'] = {'anchor': 'shared-anchor', 'instance': 'second'}",+ " checkpoint['findings'] = [first, second]",+ " encoded = json.dumps(checkpoint).encode()",+ " (checkpoint_dir / f'{hashlib.sha256(encoded).hexdigest()}.json').write_bytes(encoded)",+ " result_path.write_text('{incomplete', encoding='utf-8')",+ "if source == 'cancel-io-retry':",+ " os.environ.update(environment)",+ " sys.path.insert(0, str(plugin / 'scripts'))",+ " import workbench_db",+ " connection = workbench_db.connect()",+ " original_write = workbench_db.saved_results._write_prepared_scan_finalization",+ " workbench_db.saved_results._write_prepared_scan_finalization = lambda prepared: (_ for _ in ()).throw(OSError('synthetic cancellation publication failure'))",+ " workbench_db.cancel_scan_locked(connection, argparse.Namespace(scan_id=scan_id, thread_id=None))",+ " workbench_db.saved_results._write_prepared_scan_finalization = original_write",+ " connection.close()",+ " stored = run('get-scan', '--scan-id', scan_id)['scan']",+ " findings_path = scan_dir / 'findings.json'",+ " findings = json.loads(findings_path.read_text(encoding='utf-8'))['findings'] if findings_path.exists() else []",+ " with sqlite3.connect(state / 'workbench.sqlite3') as database:",+ " frozen = database.execute('SELECT retained_source_digests_json FROM scans WHERE id = ?', (scan_id,)).fetchone()[0]",+ " print(json.dumps({'findingCount': stored['findingCount'], 'progressStatus': stored['progress']['status'], 'artifactFindingCount': len(findings), 'frozen': json.loads(frozen) if frozen else None}))",+ " raise SystemExit(0)",+ "run('fail-deep-scan', '--scan-id', scan_id, '--message', 'Synthetic worker stopped.', '--deep-status', terminal_status)",+ "if source == 'legacy-seal-io-retry':",+ " shutil.rmtree(artifact_dir)",+ " manifest_path = scan_dir / 'scan-manifest.json'",+ " legacy_manifest = json.loads(manifest_path.read_text(encoding='utf-8'))",+ " legacy_manifest['scan']['status'] = 'completed'",+ " legacy_manifest['scan'].pop('preservedSources', None)",+ " manifest_path.write_text(json.dumps(legacy_manifest, indent=2, sort_keys=True) + '\\n', encoding='utf-8')",+ " os.environ.update(environment)",+ " sys.path.insert(0, str(plugin / 'scripts'))",+ " import workbench_db",+ " connection = workbench_db.connect()",+ " connection.execute('UPDATE scans SET seal_manifest_digest = NULL, retained_source_digests_json = NULL WHERE id = ?', (scan_id,))",+ " connection.commit()",+ " original_write = workbench_db.saved_results._write_prepared_scan_finalization",+ " workbench_db.saved_results._write_prepared_scan_finalization = lambda prepared: (_ for _ in ()).throw(OSError('synthetic publication failure'))",+ " first_failed = False",+ " try:",+ " workbench_db.preserve_scan_results_locked(connection, scan_id)",+ " except OSError:",+ " first_failed = True",+ " frozen_after_failure = connection.execute('SELECT retained_source_digests_json FROM scans WHERE id = ?', (scan_id,)).fetchone()[0]",+ " workbench_db.saved_results._write_prepared_scan_finalization = original_write",+ " retry_published = workbench_db.preserve_scan_results_locked(connection, scan_id)",+ " frozen_after_success = connection.execute('SELECT retained_source_digests_json FROM scans WHERE id = ?', (scan_id,)).fetchone()[0]",+ " final_manifest = json.loads(manifest_path.read_text(encoding='utf-8'))",+ " final_findings = json.loads((scan_dir / 'findings.json').read_text(encoding='utf-8'))['findings']",+ " connection.close()",+ " print(json.dumps({'firstFailed': first_failed, 'frozenAfterFailure': frozen_after_failure, 'retryPublished': retry_published, 'frozenAfterSuccess': json.loads(frozen_after_success) if frozen_after_success else None, 'status': final_manifest['scan']['status'], 'findingCount': len(final_findings)}))",+ " raise SystemExit(0)",+ "if source == 'late-checkpoint':",+ " manifest_before = (scan_dir / 'scan-manifest.json').read_bytes()",+ " findings_before = (scan_dir / 'findings.json').read_bytes()",+ " late = json.loads(json.dumps(checkpoint))",+ " late_finding = json.loads(json.dumps(finding))",+ " late_finding['occurrenceId'] = 'occ_111111111111111111111111'",+ " late_finding['ruleId'] = 'late.checkpoint'",+ " late_finding['title'] = 'Late checkpoint finding'",+ " late_finding['locations'][0].update({'startLine': 10, 'endLine': 12})",+ " late_finding.setdefault('provenance', {})['candidateId'] = 'late-checkpoint-candidate'",+ " late['findings'].append(late_finding)",+ " encoded = json.dumps(late).encode()",+ " (checkpoint_dir / f'{hashlib.sha256(encoded).hexdigest()}.json').write_bytes(encoded)",+ "stored = run('get-scan', '--scan-id', scan_id)['scan']",+ "findings_path = scan_dir / 'findings.json'",+ "findings = json.loads(findings_path.read_text(encoding='utf-8'))['findings'] if findings_path.exists() else []",+ "if source == 'late-checkpoint':",+ " print(json.dumps({'findingCount': stored['findingCount'], 'artifactFindingCount': len(findings), 'manifestUnchanged': manifest_before == (scan_dir / 'scan-manifest.json').read_bytes(), 'findingsUnchanged': findings_before == (scan_dir / 'findings.json').read_bytes()}))",+ "elif source == 'refined-checkpoint':",+ " histories = [item for finding in findings for item in finding.get('provenance', {}).get('previousFindings', [])]",+ " print(json.dumps({'findingCount': stored['findingCount'], 'progressStatus': stored['progress']['status'], 'artifactFindingCount': len(findings), 'historyCount': len(histories), 'representedStartLines': sorted([finding['locations'][0]['startLine'] for finding in findings] + [finding['locations'][0]['startLine'] for finding in histories])}))",+ "elif source == 'distinct-instances':",+ " print(json.dumps({'findingCount': stored['findingCount'], 'artifactFindingCount': len(findings), 'instances': sorted(finding['identity']['instance'] for finding in findings)}))",+ "else:",+ " print(json.dumps({'findingCount': stored['findingCount'], 'progressStatus': stored['progress']['status'], 'artifactFindingCount': len(findings)}))",+].join("\n");++test.each(["accepted", "checkpoint"] as const)(+ "preserves %s Deep findings when the scan stops",+ (source) => {+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const root = mkdtempSync(join(tmpdir(), "codex-security-stopped-scan-"));+ temporaryDirectories.push(root);+ const result = spawnSync(+ python!,+ ["-I", "-B", "-c", stoppedScanProbe, PLUGIN_ROOT, root, source],+ { encoding: "utf8" },+ );+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({+ findingCount: 1,+ progressStatus: "failed",+ artifactFindingCount: 1,+ });+ },+ 30_000,+);++test("keeps refined checkpoints as one finding with retained history", () => {+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const root = mkdtempSync(+ join(tmpdir(), "codex-security-refined-checkpoint-"),+ );+ temporaryDirectories.push(root);+ const result = spawnSync(+ python!,+ [+ "-I",+ "-B",+ "-c",+ stoppedScanProbe,+ PLUGIN_ROOT,+ root,+ "refined-checkpoint",+ ],+ { encoding: "utf8" },+ );+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({+ findingCount: 1,+ progressStatus: "failed",+ artifactFindingCount: 1,+ historyCount: 1,+ representedStartLines: [21, 24],+ });+}, 30_000);++test.each(["failed", "interrupted"] as const)(+ "keeps the first %s seal immutable when a worker writes late",+ (terminalStatus) => {+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const root = mkdtempSync(join(tmpdir(), "codex-security-late-checkpoint-"));+ temporaryDirectories.push(root);+ const result = spawnSync(+ python!,+ [+ "-I",+ "-B",+ "-c",+ stoppedScanProbe,+ PLUGIN_ROOT,+ root,+ "late-checkpoint",+ terminalStatus,+ ],+ { encoding: "utf8" },+ );+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({+ findingCount: 1,+ artifactFindingCount: 1,+ manifestUnchanged: true,+ findingsUnchanged: true,+ });+ },+ 30_000,+);++test("retries a legacy stopped seal after transient publication failure", () => {+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const root = mkdtempSync(join(tmpdir(), "codex-security-legacy-seal-retry-"));+ temporaryDirectories.push(root);+ const result = spawnSync(+ python!,+ [+ "-I",+ "-B",+ "-c",+ stoppedScanProbe,+ PLUGIN_ROOT,+ root,+ "legacy-seal-io-retry",+ ],+ { encoding: "utf8" },+ );+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({+ firstFailed: true,+ frozenAfterFailure: null,+ retryPublished: true,+ frozenAfterSuccess: {},+ status: "failed",+ findingCount: 1,+ });+}, 30_000);++test("preserves distinct instances from one worker candidate", () => {+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const root = mkdtempSync(+ join(tmpdir(), "codex-security-distinct-instances-"),+ );+ temporaryDirectories.push(root);+ const result = spawnSync(+ python!,+ [+ "-I",+ "-B",+ "-c",+ stoppedScanProbe,+ PLUGIN_ROOT,+ root,+ "distinct-instances",+ ],+ { encoding: "utf8" },+ );+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({+ findingCount: 2,+ artifactFindingCount: 2,+ instances: ["first", "second"],+ });+}, 30_000);++test("retries canceled result publication after a transient failure", () => {+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const root = mkdtempSync(join(tmpdir(), "codex-security-cancel-retry-"));+ temporaryDirectories.push(root);+ const result = spawnSync(+ python!,+ ["-I", "-B", "-c", stoppedScanProbe, PLUGIN_ROOT, root, "cancel-io-retry"],+ { encoding: "utf8" },+ );+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({+ findingCount: 1,+ progressStatus: "canceled",+ artifactFindingCount: 1,+ frozen: expect.any(Object),+ });+}, 30_000);