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
chore(codex-security): sync public projection
ianw-oai712bd8b1416a
diff --git a/README.md b/README.mdindex efa4cb5dc..0dfc70da6 100644--- a/README.md+++ b/README.md@@ -47,6 +47,11 @@ npx codex-security scan /path/to/repo --output-dir /path/outside/repo/resultsnpx codex-security scan /path/to/repo --output-dir /path/outside/repo/results --archive-existingnpx codex-security scan /path/to/repo --dry-runnpx codex-security scan /path/to/repo --fail-on-severity high+npx codex-security scans list /path/to/repo+npx codex-security scans list --scan-root /path/outside/repo/results+npx codex-security scans show SCAN_ID+npx codex-security scans rerun SCAN_ID+npx codex-security scans compare PREVIOUS_SCAN_ID CURRENT_SCAN_IDnpx codex-security export /path/outside/repo/results --export-format sarif --output results.sarifnpx codex-security export /path/outside/repo/results --export-format csv --output findings.csvnpx codex-security export /path/outside/repo/results --export-format json --output findings.json@@ -98,6 +103,22 @@ either setting, pass valid TOML values (including quotes for strings):npx codex-security scan . --codex 'model="gpt-5.6-sol"' --codex 'model_reasoning_effort="high"'```+## Scan history and reruns++`npx codex-security scans list` lists scans for the current repository. Pass a+repository path to inspect another checkout, `--scan-root DIR` to filter by+scan artifact directory. `scans show SCAN_ID` includes saved configuration,+findings, and coverage.++History is saved in the existing Codex Security workbench database under+`$CODEX_HOME/state/plugins/codex-security`. Set `CODEX_SECURITY_STATE_DIR` to+choose a different location.++`scans rerun SCAN_ID` repeats the same configuration against the current+checkout. `scans compare BEFORE_SCAN_ID AFTER_SCAN_ID` identifies new,+persisting, reopened, and resolved findings; missing findings remain unknown+when coverage is incomplete or the original location was not reviewed.+Use `export` to create CSV, JSON, or SARIF from a completed, sealed scan withoutstarting Codex or loading credentials. JSON preserves the sealed findingsdocument. CSV uses the portable findings columns, marks findings as open, anddiff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 0aab93a82..0fb456974 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -60,6 +60,11 @@ npx codex-security scan /path/to/repository --output-dir /path/outside/repositornpx codex-security scan /path/to/repository --output-dir /path/outside/repository/results --archive-existingnpx codex-security scan /path/to/repository --dry-runnpx codex-security scan /path/to/repository --fail-on-severity high+npx codex-security scans list /path/to/repository+npx codex-security scans list --scan-root /path/outside/repository/results+npx codex-security scans show SCAN_ID+npx codex-security scans rerun SCAN_ID+npx codex-security scans compare PREVIOUS_SCAN_ID CURRENT_SCAN_IDnpx codex-security scan-csv repositories.csv --output-dir /tmp/security-scans --workers 4npx codex-security export /path/outside/repository/results --export-format sarif --output results.sarifnpx codex-security export /path/outside/repository/results --export-format csv --output findings.csv@@ -109,6 +114,26 @@ service,https://github.com/acme/service.git,0123456789abcdef0123456789abcdef0123`--workers` limits concurrent scans and `--max-attempts` retries failures.Results remain under `--output-dir`; rerun the same command to resume.+### Scan history and reruns++`npx codex-security scans list` lists scans for the current repository. Pass a+repository path to inspect another checkout, `--scan-root DIR` to list scans+whose artifacts are under a particular root. `scans show SCAN_ID` includes the+scan configuration, results, coverage, and artifact locations.++Scan history uses the existing Codex Security workbench database at+`$CODEX_HOME/state/plugins/codex-security/workbench.sqlite3`. Set+`CODEX_SECURITY_STATE_DIR` to place the database elsewhere. Scan credentials+are never stored in the scan configuration.++`scans rerun SCAN_ID` repeats the original configuration against the current+checkout so a fixed vulnerability can be checked again.++`scans compare BEFORE_SCAN_ID AFTER_SCAN_ID` reconciles stable vulnerability+identities across both scans. Findings are reported as new, persisting,+reopened, resolved, or unknown. Missing findings are not treated as resolved+when the later scan is incomplete or does not cover their original scope.+The CLI uses [Incur](https://github.com/wevm/incur) for agent-friendly discoveryand structured output. Inspect the command manifest with `--llms`, inspect acommand schema with `scan --schema --format json`, register the CLI as an MCPdiff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.pyindex 641311283..ea9f38a9e 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py@@ -135,7 +135,22 @@ def parse_args(description: str) -> argparse.Namespace:get_scan.add_argument("--scan-id", required=True)get_scan.add_argument("--occurrence-id")- subparsers.add_parser("list-scans")+ list_scans = subparsers.add_parser("list-scans")+ list_scans.add_argument("--repository")+ list_scans.add_argument("--scan-root")++ register_cli_scan = subparsers.add_parser("register-cli-scan")+ register_cli_scan.add_argument("--scan-dir", required=True)+ register_cli_scan.add_argument("--repository", required=True)+ register_cli_scan.add_argument("--recipe-json", required=True)+ register_cli_scan.add_argument("--parent-scan-id")++ get_scan_recipe = subparsers.add_parser("get-scan-recipe")+ get_scan_recipe.add_argument("--scan-id", required=True)++ compare_scans = subparsers.add_parser("compare-scans")+ compare_scans.add_argument("--before-scan-id", required=True)+ compare_scans.add_argument("--after-scan-id", required=True)list_findings = subparsers.add_parser("list-findings")list_findings.add_argument("--scan-id", required=True)diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.pyindex 07dcad374..40224811a 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py@@ -9,7 +9,6 @@ import errnoimport hashlibimport ioimport json-import mathimport osimport reimport sqlite3@@ -71,8 +70,6 @@ from workbench_constants import (FINDING_TITLE_BYTES,FINDINGS_PAGE_MAX,FINDINGS_RESULT_LIMIT,- MAX_CAPABILITY_PREFLIGHT_INPUT_JSON_BYTES,- MAX_CAPABILITY_PREFLIGHT_PERSISTED_JSON_BYTES,PATCH_ARTIFACT_MAX_BYTES,PATCH_PREVIEW_BYTES,SQLITE_RETRY_ATTEMPTS,@@ -103,6 +100,8 @@ from workbench_target import ()from workbench_target_state import backfill_security_targets, ensure_security_targetfrom workbench_validation import (+ capability_preflight_input,+ capability_preflight_json,optional_text,require_occurrence,require_uuid,@@ -111,6 +110,7 @@ from workbench_validation import (FINDING_ARTIFACT_DIRECTORIES_LIMIT = 80FINDING_ARTIFACTS_LIMIT = 40FINDING_WRITEUP_REPORT_PATH = re.compile(r"^findings/([a-z0-9][a-z0-9._-]*)/\1\.md$")+SCAN_RECIPE_MAX_BYTES = 256 * 1024def now() -> str:@@ -310,217 +310,6 @@ def apply_migrations(connection: sqlite3.Connection) -> None:raise-def reject_nonstandard_json_number(value: str) -> None:- raise ValueError(f"invalid JSON number {value}")---def capability_preflight_json(- value: str | None,- *,- checked_target_path: str | None,- checked_mode: str,-) -> str | None:- normalized = optional_text(value)- if normalized is None:- return None- if len(normalized.encode("utf-8")) > MAX_CAPABILITY_PREFLIGHT_INPUT_JSON_BYTES:- raise SystemExit(- "Capability preflight must be no larger than "- f"{MAX_CAPABILITY_PREFLIGHT_INPUT_JSON_BYTES} bytes."- )- try:- payload = json.loads(normalized, parse_constant=reject_nonstandard_json_number)- except (json.JSONDecodeError, ValueError) as exc:- raise SystemExit("Capability preflight must be valid JSON.") from exc- if not isinstance(payload, dict):- raise SystemExit("Capability preflight must be a JSON object.")- _require_object_keys(- payload,- required={"issues", "profile", "status"},- optional={"remediation"},- label="Capability preflight",- )- profile = _bounded_preflight_text(payload.get("profile"), 128, "profile")- status = payload.get("status")- if status not in {"ready", "blocked", "incomplete"}:- raise SystemExit("Capability preflight status is invalid.")- issues = payload.get("issues")- if not isinstance(issues, list) or len(issues) > 32:- raise SystemExit("Capability preflight issues must be an array of at most 32 objects.")- normalized_issues: list[dict[str, str]] = []- for index, issue in enumerate(issues):- if not isinstance(issue, dict):- raise SystemExit("Capability preflight issues must be an array of at most 32 objects.")- label = f"Capability preflight issue {index + 1}"- _require_object_keys(- issue,- required={"capability", "reason", "severity", "status"},- optional=set(),- label=label,- )- severity = issue.get("severity")- issue_status = issue.get("status")- if severity not in {"block", "warn", "suggest"} or issue_status not in {- "fail",- "unknown",- }:- raise SystemExit(f"{label} has an invalid severity or status.")- normalized_issues.append(- {- "capability": _bounded_preflight_text(- issue.get("capability"), 128, f"issue {index + 1} capability"- ),- "reason": _bounded_preflight_text(- issue.get("reason"), 1200, f"issue {index + 1} reason"- ),- "severity": severity,- "status": issue_status,- }- )- remediation = payload.get("remediation")- normalized_remediation: dict[str, Any] | None = None- if remediation is not None:- if not isinstance(remediation, dict):- raise SystemExit("Capability preflight remediation must be a JSON object.")- _require_object_keys(- remediation,- required=set(),- optional={"note", "patches", "summary"},- label="Capability preflight remediation",- )- normalized_remediation = {}- for key, maximum in (("note", 2400), ("summary", 1200)):- if key in remediation:- normalized_remediation[key] = _bounded_preflight_text(- remediation.get(key), maximum, f"remediation {key}"- )- if "patches" in remediation:- patches = remediation.get("patches")- if not isinstance(patches, list) or len(patches) > 32:- raise SystemExit(- "Capability preflight remediation patches must be an array of at most 32 objects."- )- normalized_remediation["patches"] = [- _normalize_preflight_patch(patch, index) for index, patch in enumerate(patches)- ]- has_unknown = any(issue.get("status") == "unknown" for issue in issues)- has_blocking_failure = any(- issue.get("severity") == "block" and issue.get("status") == "fail" for issue in issues- )- expected_status = (- "blocked" if has_blocking_failure else "incomplete" if has_unknown else "ready"- )- if status != expected_status:- raise SystemExit(- f"Capability preflight status must be {expected_status} for the supplied issues."- )- normalized_payload: dict[str, Any] = {- "profile": profile,- "status": status,- "issues": normalized_issues,- "checkedTargetPath": checked_target_path,- "checkedMode": checked_mode,- }- if normalized_remediation is not None:- normalized_payload["remediation"] = normalized_remediation- serialized = json.dumps(- normalized_payload,- ensure_ascii=False,- separators=(",", ":"),- sort_keys=True,- )- serialized = _escape_json_surrogates(serialized)- if len(serialized.encode("utf-8")) > MAX_CAPABILITY_PREFLIGHT_PERSISTED_JSON_BYTES:- raise SystemExit(- "Persisted capability preflight must be no larger than "- f"{MAX_CAPABILITY_PREFLIGHT_PERSISTED_JSON_BYTES} bytes."- )- return serialized---def capability_preflight_input(value: str | None, path: Path | None) -> str | None:- if path is None:- return value- try:- if path.stat().st_size > MAX_CAPABILITY_PREFLIGHT_INPUT_JSON_BYTES:- raise SystemExit(- "Capability preflight must be no larger than "- f"{MAX_CAPABILITY_PREFLIGHT_INPUT_JSON_BYTES} bytes."- )- return path.read_text(encoding="utf-8")- except (OSError, UnicodeError) as exc:- raise SystemExit("Capability preflight JSON file could not be read as UTF-8.") from exc---def _require_object_keys(- value: dict[str, Any], *, required: set[str], optional: set[str], label: str-) -> None:- keys = set(value)- missing = required - keys- extra = keys - required - optional- if missing:- raise SystemExit(f"{label} is missing required fields: {', '.join(sorted(missing))}.")- if extra:- raise SystemExit(f"{label} has unsupported fields: {', '.join(sorted(extra))}.")---def _bounded_preflight_text(value: Any, maximum: int, label: str) -> str:- if not isinstance(value, str):- raise SystemExit(f"Capability preflight {label} must be text.")- normalized = value.strip()- if not normalized or _javascript_string_length(normalized) > maximum:- raise SystemExit(f"Capability preflight {label} must contain 1 to {maximum} characters.")- return normalized---def _javascript_string_length(value: str) -> int:- return len(value.encode("utf-16-le", errors="surrogatepass")) // 2---def _escape_json_surrogates(value: str) -> str:- return "".join(- f"\\u{ord(character):04x}" if 0xD800 <= ord(character) <= 0xDFFF else character- for character in value- )---def _normalize_preflight_patch(value: Any, index: int) -> dict[str, Any]:- label = f"Capability preflight remediation patch {index + 1}"- if not isinstance(value, dict):- raise SystemExit(f"{label} must be a JSON object.")- _require_object_keys(- value,- required={"path", "value"},- optional={"kind"},- label=label,- )- normalized: dict[str, Any] = {- "path": _bounded_preflight_text(value.get("path"), 256, f"patch {index + 1} path")- }- if "kind" in value:- kind = value.get("kind")- if kind not in {"config", "host_setting"}:- raise SystemExit(f"{label} has an invalid kind.")- normalized["kind"] = kind- patch_value = value.get("value")- if isinstance(patch_value, str):- if _javascript_string_length(patch_value) > 2048:- raise SystemExit(f"{label} value must be no longer than 2048 characters.")- elif isinstance(patch_value, bool):- pass- elif isinstance(patch_value, (int, float)):- try:- finite = math.isfinite(float(patch_value))- except OverflowError:- finite = False- if not finite:- raise SystemExit(f"{label} value must be a finite number.")- else:- raise SystemExit(f"{label} value must be text, a number, or a boolean.")- normalized["value"] = patch_value- return normalized--def require_target(value: str) -> Path:expanded = Path(value).expanduser()if not expanded.is_absolute():@@ -766,6 +555,15 @@ def stored_diff_target(row: sqlite3.Row) -> dict[str, str] | None:return target+def requested_scan_paths(scan: sqlite3.Row) -> list[str]:+ if "recipe_json" in scan.keys() and scan["recipe_json"] is not None:+ recipe = json.loads(scan["recipe_json"], parse_constant=reject_non_finite_json)+ target = recipe["target"]+ if target["kind"] == "paths":+ return target["paths"]+ return [scan["scope"]]++def scan_contract(scan: sqlite3.Row) -> dict[str, Any]:target = Path(scan["target_path"])target_contract = {@@ -787,7 +585,11 @@ def scan_contract(scan: sqlite3.Row) -> dict[str, Any]:"scope": {"requiredExcludePaths": [],"requestedPath": scan["scope"],- **({"requiredIncludePaths": [scan["scope"]]} if scan["mode"] != "diff" else {}),+ **(+ {"requiredIncludePaths": requested_scan_paths(scan)}+ if scan["mode"] != "diff"+ else {}+ ),},"target": target_contract,}@@ -803,7 +605,11 @@ def expected_coverage_mode(scan: sqlite3.Row) -> str:if mode is None:raise SystemExit("This migrated diff scan does not have a validated change set.")return mode- if scan["scope"] != ".":+ if scan["scope"] != "." or (+ "recipe_json" in scan.keys()+ and scan["recipe_json"] is not None+ and json.loads(scan["recipe_json"])["target"]["kind"] == "paths"+ ):return "scoped_path"return "deep_repository" if scan["mode"] == "deep" else "repository"@@ -829,7 +635,7 @@ def workbench_completion_binding(scan: sqlite3.Row, completed_at: str) -> dict[starget["snapshotDigest"] = scan["target_snapshot_digest"]scope: dict[str, Any] = {- "includePaths": [scan["scope"]],+ "includePaths": requested_scan_paths(scan),"excludePaths": contract["scope"]["requiredExcludePaths"],}@@ -906,7 +712,7 @@ def verify_manifest_binding(scan: sqlite3.Row, manifest: dict[str, Any]) -> None"scan-manifest.json scope excludePaths must match the workbench scan scope.")requested_scope = scan["scope"]- if scan["mode"] != "diff" and include_paths != [requested_scope]:+ if scan["mode"] != "diff" and include_paths != requested_scan_paths(scan):raise SystemExit("scan-manifest.json scope must match the workbench scan scope.")for include_path in include_paths:if not isinstance(include_path, str) or not path_within_scope(@@ -1648,15 +1454,23 @@ def complete_scan_locked(claim_token,error_message="Scan completion is owned by another continuation.",)- deep_scan.require_deep_scan_ready_for_parent_completion(connection, scan)+ if scan["recipe_json"] is None:+ deep_scan.require_deep_scan_ready_for_parent_completion(connection, scan)require_unchanged_target(scan)scan_dir = require_canonical_scan_directory(Path(scan["scan_dir"]))completion_timestamp = now()+ completion_binding = workbench_completion_binding(scan, completion_timestamp)+ if scan["recipe_json"] is not None:+ manifest = read_json_object(artifact_path(scan_dir, ARTIFACTS["manifest"], required=True))+ manifest_scan = manifest.get("scan")+ if isinstance(manifest_scan, dict) and manifest_scan.get("sealedAt") is not None:+ completion_binding["startedAt"] = manifest_scan.get("startedAt")+ completion_binding["completedAt"] = manifest_scan.get("completedAt")try:prepared = _prepare_scan_finalization(scan_dir,expected_coverage_mode=expected_coverage_mode(scan),- completion_binding=workbench_completion_binding(scan, completion_timestamp),+ completion_binding=completion_binding,)# Keep the second target check between in-memory finalization and the first write.require_unchanged_target(scan)@@ -1677,7 +1491,8 @@ def complete_scan_locked(return scan_context(connection, scan["id"])if scan["status"] != "running":raise SystemExit("Only a running scan can be completed.")- deep_scan.require_deep_scan_ready_for_parent_completion(connection, scan)+ if scan["recipe_json"] is None:+ deep_scan.require_deep_scan_ready_for_parent_completion(connection, scan)handoff.require_current_continuation(scan,claim_token,@@ -1721,6 +1536,189 @@ def complete_scan_locked(return scan_context(connection, scan["id"])+def register_cli_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:+ repository = require_target(args.repository)+ require_scannable_target(repository)+ scan_dir = require_canonical_scan_directory(Path(args.scan_dir).expanduser())+ if scan_dir == repository or repository in scan_dir.parents:+ raise SystemExit("The scan artifact directory must be outside the selected target.")+ if next(scan_dir.iterdir(), None) is not None:+ raise SystemExit("The scan artifact directory must be empty before the scan starts.")++ recipe = parse_scan_recipe(args.recipe_json, repository)+ requested_target = recipe["target"]+ paths = requested_target["paths"]+ scope = paths[0] if len(paths) == 1 else "."+ diff_target = None+ if requested_target["kind"] in {"refs", "working_tree"}:+ current_head = require_review_changes_target(repository)+ base = resolve_git_commit(repository, requested_target["base"], "Base revision")+ head = resolve_git_commit(repository, requested_target["head"], "Head revision")+ diff_target = {+ "kind": "range" if requested_target["kind"] == "refs" else "working_tree",+ "baseRevision": base,+ "headRevision": head,+ }+ if requested_target["kind"] == "working_tree":+ if head != current_head:+ raise SystemExit("Working-tree HEAD changed before the scan started.")+ diff_target["contentDigest"] = worktree_content_digest(repository)+ mode = "diff" if diff_target is not None else recipe["mode"]+ target_identity = scan_target_identity(repository, diff_target)+ scope_file_count = (+ directory_snapshot_regular_file_count(repository)+ if not paths+ else sum(+ 1+ if (repository / path).is_file()+ else directory_snapshot_regular_file_count(repository / path)+ for path in paths+ )+ )+ parent_scan_id = (+ require_uuid(args.parent_scan_id, "parent-scan-id")+ if args.parent_scan_id is not None+ else None+ )+ timestamp = now()+ scan_id = str(uuid.uuid4())+ workspace_id = str(uuid.uuid4())++ connection.execute("BEGIN IMMEDIATE")+ try:+ target_id = ensure_security_target(connection, str(repository))+ if parent_scan_id is not None:+ parent = require_scan(connection, parent_scan_id)+ if parent["target_id"] != target_id:+ raise SystemExit("A rerun must belong to the same repository as its parent scan.")++ connection.execute(+ """+ INSERT INTO workspaces (+ id, target_id, target_path, target_title, default_scope, default_mode,+ diff_target_kind, diff_base_revision, diff_head_revision,+ diff_content_digest, submitted, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)+ """,+ (+ workspace_id,+ target_id,+ str(repository),+ repository.name,+ scope,+ mode,+ *scan_diff_identity(diff_target),+ timestamp,+ timestamp,+ ),+ )+ workspace = require_workspace(connection, workspace_id)+ insert_running_scan(+ connection,+ scan_id=scan_id,+ workspace=workspace,+ target=repository,+ scope=scope,+ diff_target=diff_target,+ target_identity=target_identity,+ target_root=scan_dir.parent,+ target_summary=None,+ scope_file_count=scope_file_count,+ timestamp=timestamp,+ handoff_status="delivered",+ scan_dir=scan_dir,+ )+ connection.execute(+ "UPDATE scans SET recipe_json = ?, parent_scan_id = ? WHERE id = ?",+ (+ json.dumps(recipe, allow_nan=False, separators=(",", ":"), sort_keys=True),+ parent_scan_id,+ scan_id,+ ),+ )+ connection.commit()+ except BaseException:+ connection.rollback()+ raise+ return {"scanDir": str(scan_dir), "scanId": scan_id, "targetId": target_id}+++def parse_scan_recipe(value: str, repository: Path) -> dict[str, Any]:+ if len(value.encode("utf-8")) > SCAN_RECIPE_MAX_BYTES:+ raise SystemExit("Scan launch recipe must be no larger than 256 KiB.")+ try:+ recipe = json.loads(value, parse_constant=reject_non_finite_json)+ except (TypeError, UnicodeError, ValueError) as exc:+ raise SystemExit("Scan launch recipe must be a valid JSON object.") from exc+ if not isinstance(recipe, dict):+ raise SystemExit("Scan launch recipe must be a JSON object.")+ requested_repository = recipe.get("repository")+ if (+ not isinstance(requested_repository, str)+ or require_target(requested_repository) != repository+ ):+ raise SystemExit("Scan launch recipe repository must match the scanned repository.")+ if recipe.get("mode") not in {"standard", "deep"}:+ raise SystemExit("Scan launch recipe mode must be standard or deep.")+ if not isinstance(recipe.get("config"), dict):+ raise SystemExit("Scan launch recipe config must be a JSON object.")+ target = recipe.get("target")+ if not isinstance(target, dict) or target.get("kind") not in {+ "repository",+ "paths",+ "refs",+ "working_tree",+ }:+ raise SystemExit("Scan launch recipe target must identify a supported scan target.")+ paths = target.get("paths")+ if not isinstance(paths, list) or not all(isinstance(path, str) for path in paths):+ raise SystemExit("Scan launch recipe target paths must be an array of strings.")+ if target["kind"] == "paths" and not paths:+ raise SystemExit("A scoped scan launch recipe must include at least one target path.")+ if target["kind"] != "paths" and paths:+ raise SystemExit("Only scoped scan launch recipes can include target paths.")+ for path in paths:+ candidate = PurePosixPath(path)+ if (+ not path+ or candidate.is_absolute()+ or ".." in candidate.parts+ or "\\" in path+ or not (repository / candidate).exists()+ or not (repository / candidate).resolve().is_relative_to(repository)+ ):+ raise SystemExit("Scan launch recipe target paths must exist inside the repository.")+ if target["kind"] in {"refs", "working_tree"}:+ if not isinstance(target.get("base"), str) or not isinstance(target.get("head"), str):+ raise SystemExit("Diff scan launch recipes require resolved base and head revisions.")+ return recipe+++def get_scan_recipe(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:+ scan = require_scan(connection, args.scan_id)+ if scan["recipe_json"] is None:+ raise SystemExit("This scan does not have a saved launch recipe.")+ return {+ "parentScanId": scan["parent_scan_id"],+ "recipe": json.loads(scan["recipe_json"], parse_constant=reject_non_finite_json),+ "scanId": scan["id"],+ }+++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++def fail_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:scan_id = require_uuid(args.scan_id, "scan-id")connection.execute("BEGIN IMMEDIATE")@@ -2865,11 +2863,15 @@ def scan_context(occurrence_id: str | None = None,) -> dict[str, Any]:scan = require_scan(connection, scan_id)- return {+ context = {"otherRunningDeepScans": deep_scan.other_running_deep_scans(connection, scan["id"]),"scan": scan_result(connection, scan, occurrence_id=occurrence_id),"workspace": workspace_state(connection, scan["workspace_id"], result_scan_id=scan["id"]),}+ if scan["recipe_json"] is not None:+ context["parentScanId"] = scan["parent_scan_id"]+ context["recipe"] = json.loads(scan["recipe_json"], parse_constant=reject_non_finite_json)+ return contextdef list_findings(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:@@ -3566,7 +3568,18 @@ def main() -> None:elif args.command == "get-scan":result = scan_context(connection, args.scan_id, args.occurrence_id)elif args.command == "list-scans":- result = scan_history.list_scans(connection)+ result = scan_history.list_scans(connection, args)+ elif args.command == "register-cli-scan":+ result = register_cli_scan(connection, args)+ elif args.command == "get-scan-recipe":+ result = get_scan_recipe(connection, args)+ elif args.command == "compare-scans":+ result = scan_history.compare_scans(+ connection,+ args,+ require_scan=require_scan,+ read_coverage=coverage_for_comparison,+ )elif args.command == "list-findings":result = list_findings(connection, args)elif args.command == "update-progress":diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.pyindex fd64cb255..7bb5a0c43 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py@@ -1,7 +1,10 @@"""Scan history projection for the native Codex Security workbench."""import argparse+import fnmatch+import osimport sqlite3+from pathlib import Path, PurePosixPathfrom typing import Any, Callable@@ -54,9 +57,26 @@ def list_workspace_scans(}-def list_scans(connection: sqlite3.Connection) -> dict[str, Any]:+def list_scans(+ connection: sqlite3.Connection, args: argparse.Namespace | None = None+) -> dict[str, Any]:+ clauses: list[str] = []+ values: list[Any] = []+ if args is not None and args.repository:+ repository = str(Path(args.repository).expanduser().resolve())+ clauses.append(+ "(scans.target_path = ? OR scans.target_id IN "+ "(SELECT id FROM security_targets WHERE current_path = ?))"+ )+ values.extend((repository, repository))+ if args is not None and args.scan_root:+ scan_root = str(Path(args.scan_root).expanduser().resolve())+ prefix = scan_root.rstrip(os.sep) + os.sep+ clauses.append("(scans.scan_dir = ? OR substr(scans.scan_dir, 1, ?) = ?)")+ values.extend((scan_root, len(prefix), prefix))+ where = f"WHERE {' AND '.join(clauses)}" if clauses else ""rows = connection.execute(- """+ f"""SELECTscans.*,progress.reportable_findings_count,@@ -71,20 +91,24 @@ def list_scans(connection: sqlite3.Connection) -> dict[str, Any]:) AS finding_countFROM scansJOIN scan_progress AS progress ON progress.scan_id = scans.id+ {where}ORDER BYCASE WHEN scans.status = 'running' AND scans.canceled_at IS NULL THEN 0 ELSE 1 END,MAX(scans.updated_at, progress.updated_at) DESC,scans.started_at DESC,scans.id- """+ """,+ values,).fetchall()return {"scans": [{+ "completedAt": row["completed_at"],"continuationThreadId": row["continuation_thread_id"],"findingCount": row["finding_count"],"handoffStatus": row["handoff_status"],"mode": row["mode"],+ "parentScanId": row["parent_scan_id"],"progress": {"candidates": {"reportable": row["reportable_findings_count"]},"coverage": {@@ -96,10 +120,14 @@ def list_scans(connection: sqlite3.Connection) -> dict[str, Any]:"status": "canceled" if row["canceled_at"] else row["status"],"updatedAt": row["progress_updated_at"],},+ "recipeAvailable": row["recipe_json"] is not None,+ "scanDir": row["scan_dir"],"scanId": row["id"],"scope": row["scope"],+ "startedAt": row["started_at"],"targetId": row["target_id"],"targetPath": row["target_path"],+ "targetRevision": row["target_revision"],"targetSummary": row["target_summary"],"updatedAt": max(row["updated_at"], row["progress_updated_at"]),}@@ -108,5 +136,136 @@ def list_scans(connection: sqlite3.Connection) -> dict[str, Any]:}+def compare_scans(+ connection: sqlite3.Connection,+ args: argparse.Namespace,+ *,+ require_scan: Callable[[sqlite3.Connection, str], sqlite3.Row],+ read_coverage: Callable[[sqlite3.Row], dict[str, Any]],+) -> dict[str, Any]:+ before = require_scan(connection, args.before_scan_id)+ after = require_scan(connection, args.after_scan_id)+ if before["status"] != "complete" or after["status"] != "complete":+ raise SystemExit("Only completed scans can be compared.")+ after_coverage = read_coverage(after)+ comparable = (+ before["target_id"] == after["target_id"]+ and after_coverage.get("completeness") == "complete"+ )+ before_findings = _scan_findings(connection, before["id"])+ after_findings = _scan_findings(connection, after["id"])+ findings: list[dict[str, Any]] = []+ summary = {status: 0 for status in ("new", "persisting", "resolved", "reopened", "unknown")}++ for finding_id in sorted(before_findings.keys() | after_findings.keys()):+ previous = before_findings.get(finding_id)+ current = after_findings.get(finding_id)+ selected = current if current is not None else previous+ if selected is None:+ continue+ item = {+ "findingId": finding_id,+ "path": selected["relative_path"],+ "severity": selected["severity"],+ "title": selected["title"],+ }+ if previous is None:+ status = "new"+ elif current is not None:+ status = (+ "reopened"+ if previous["triage_status"] == "closed"+ and previous["close_reason"] == "already_fixed"+ and current["triage_status"] == "open"+ else "persisting"+ )+ elif not comparable:+ status = "unknown"+ item["reason"] = "The later scan has a different target or incomplete coverage."+ elif not _path_is_covered(previous["relative_path"], after_coverage):+ status = "unknown"+ item["reason"] = "The affected path was excluded or outside the later scope."+ else:+ status = "resolved"+ if previous is not None:+ item["beforeOccurrenceId"] = previous["id"]+ if current is not None:+ item["afterOccurrenceId"] = current["id"]+ item["triage"] = {+ "closeReason": current["close_reason"],+ "status": current["triage_status"],+ }+ item["status"] = status+ findings.append(item)+ summary[status] += 1++ return {+ "afterScanId": after["id"],+ "beforeScanId": before["id"],+ "comparable": comparable,+ "coverage": {"afterCompleteness": after_coverage.get("completeness")},+ "findings": findings,+ "summary": summary,+ }+++def _scan_findings(connection: sqlite3.Connection, scan_id: str) -> dict[str, sqlite3.Row]:+ rows = connection.execute(+ """+ SELECT occurrences.id, occurrences.finding_id, occurrences.title, occurrences.severity,+ COALESCE(triage.status, 'open') AS triage_status, triage.close_reason,+ (+ SELECT locations.relative_path+ FROM finding_locations AS locations+ WHERE locations.occurrence_id = occurrences.id+ ORDER BY CASE WHEN locations.role = 'root_control' THEN 0 ELSE 1 END,+ locations.sort_order+ LIMIT 1+ ) AS relative_path+ FROM finding_occurrences AS occurrences+ LEFT JOIN finding_triage AS triage ON triage.occurrence_id = occurrences.id+ WHERE occurrences.scan_id = ?+ """,+ (scan_id,),+ )+ return {row["finding_id"]: row for row in rows}+++def _path_is_covered(path: str | None, coverage: dict[str, Any]) -> bool:+ if not isinstance(path, str) or not path:+ return False+ included = coverage.get("includePaths")+ if not isinstance(included, list) or not any(+ isinstance(scope, str) and _path_within(path, scope) for scope in included+ ):+ return False+ excluded = coverage.get("excludePaths")+ if not isinstance(excluded, list):+ return False+ if any(isinstance(scope, str) and _path_matches(path, scope) for scope in excluded):+ return False+ exclusions = coverage.get("explicitExclusions")+ if not isinstance(exclusions, list):+ return False+ if any(+ isinstance(exclusion, dict)+ and isinstance(exclusion.get("pattern"), str)+ and _path_matches(path, exclusion["pattern"])+ for exclusion in exclusions+ ):+ return False+ return True+++def _path_within(path: str, scope: str) -> bool:+ candidate = PurePosixPath(path)+ parent = PurePosixPath(scope)+ return parent == PurePosixPath(".") or candidate == parent or parent in candidate.parents+++def _path_matches(path: str, pattern: str) -> bool:+ return _path_within(path, pattern) or fnmatch.fnmatchcase(path, pattern)++if __name__ == "__main__":argparse.ArgumentParser(description=__doc__).parse_args()diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_start.py b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_start.pyindex f4b914505..44acde5be 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_start.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_start.py@@ -82,14 +82,16 @@ def insert_running_scan(scope_file_count: int,timestamp: str,handoff_status: str = "pending",+ scan_dir: Path | None = None,) -> str:revision = target_identity[0]- scan_dir = Path(- tempfile.mkdtemp(- prefix=f"{safe_segment(revision)}_{compact_timestamp()}_",- dir=target_root,- )- ).resolve()+ if scan_dir is None:+ scan_dir = Path(+ tempfile.mkdtemp(+ prefix=f"{safe_segment(revision)}_{compact_timestamp()}_",+ dir=target_root,+ )+ ).resolve()connection.execute("""INSERT INTO scans (diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py b/sdk/typescript/_bundled_plugin/scripts/workbench_schema.pyindex 7af70586f..bc203226f 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py@@ -551,6 +551,14 @@ MIGRATIONS = (""",),+ (+ 22,+ "replayable scan launch recipes",+ """+ ALTER TABLE scans ADD COLUMN recipe_json TEXT;+ ALTER TABLE scans ADD COLUMN parent_scan_id TEXT REFERENCES scans(id) ON DELETE SET NULL;+ """,+ ),)diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_validation.py b/sdk/typescript/_bundled_plugin/scripts/workbench_validation.pyindex b4dbd5393..eda998bcd 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_validation.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_validation.py@@ -3,8 +3,17 @@from __future__ import annotationsimport argparse+import json+import mathimport sqlite3import uuid+from pathlib import Path+from typing import Any++from workbench_constants import (+ MAX_CAPABILITY_PREFLIGHT_INPUT_JSON_BYTES,+ MAX_CAPABILITY_PREFLIGHT_PERSISTED_JSON_BYTES,+)def require_uuid(value: str, label: str) -> str:@@ -23,6 +32,217 @@ def optional_text(value: str | None, *, maximum: int | None = None) -> str | Nonreturn normalized or None+def reject_nonstandard_json_number(value: str) -> None:+ raise ValueError(f"invalid JSON number {value}")+++def capability_preflight_json(+ value: str | None,+ *,+ checked_target_path: str | None,+ checked_mode: str,+) -> str | None:+ normalized = optional_text(value)+ if normalized is None:+ return None+ if len(normalized.encode("utf-8")) > MAX_CAPABILITY_PREFLIGHT_INPUT_JSON_BYTES:+ raise SystemExit(+ "Capability preflight must be no larger than "+ f"{MAX_CAPABILITY_PREFLIGHT_INPUT_JSON_BYTES} bytes."+ )+ try:+ payload = json.loads(normalized, parse_constant=reject_nonstandard_json_number)+ except (json.JSONDecodeError, ValueError) as exc:+ raise SystemExit("Capability preflight must be valid JSON.") from exc+ if not isinstance(payload, dict):+ raise SystemExit("Capability preflight must be a JSON object.")+ _require_object_keys(+ payload,+ required={"issues", "profile", "status"},+ optional={"remediation"},+ label="Capability preflight",+ )+ profile = _bounded_preflight_text(payload.get("profile"), 128, "profile")+ status = payload.get("status")+ if status not in {"ready", "blocked", "incomplete"}:+ raise SystemExit("Capability preflight status is invalid.")+ issues = payload.get("issues")+ if not isinstance(issues, list) or len(issues) > 32:+ raise SystemExit("Capability preflight issues must be an array of at most 32 objects.")+ normalized_issues: list[dict[str, str]] = []+ for index, issue in enumerate(issues):+ if not isinstance(issue, dict):+ raise SystemExit("Capability preflight issues must be an array of at most 32 objects.")+ label = f"Capability preflight issue {index + 1}"+ _require_object_keys(+ issue,+ required={"capability", "reason", "severity", "status"},+ optional=set(),+ label=label,+ )+ severity = issue.get("severity")+ issue_status = issue.get("status")+ if severity not in {"block", "warn", "suggest"} or issue_status not in {+ "fail",+ "unknown",+ }:+ raise SystemExit(f"{label} has an invalid severity or status.")+ normalized_issues.append(+ {+ "capability": _bounded_preflight_text(+ issue.get("capability"), 128, f"issue {index + 1} capability"+ ),+ "reason": _bounded_preflight_text(+ issue.get("reason"), 1200, f"issue {index + 1} reason"+ ),+ "severity": severity,+ "status": issue_status,+ }+ )+ remediation = payload.get("remediation")+ normalized_remediation: dict[str, Any] | None = None+ if remediation is not None:+ if not isinstance(remediation, dict):+ raise SystemExit("Capability preflight remediation must be a JSON object.")+ _require_object_keys(+ remediation,+ required=set(),+ optional={"note", "patches", "summary"},+ label="Capability preflight remediation",+ )+ normalized_remediation = {}+ for key, maximum in (("note", 2400), ("summary", 1200)):+ if key in remediation:+ normalized_remediation[key] = _bounded_preflight_text(+ remediation.get(key), maximum, f"remediation {key}"+ )+ if "patches" in remediation:+ patches = remediation.get("patches")+ if not isinstance(patches, list) or len(patches) > 32:+ raise SystemExit(+ "Capability preflight remediation patches must be an array of at most 32 objects."+ )+ normalized_remediation["patches"] = [+ _normalize_preflight_patch(patch, index) for index, patch in enumerate(patches)+ ]+ has_unknown = any(issue.get("status") == "unknown" for issue in issues)+ has_blocking_failure = any(+ issue.get("severity") == "block" and issue.get("status") == "fail" for issue in issues+ )+ expected_status = (+ "blocked" if has_blocking_failure else "incomplete" if has_unknown else "ready"+ )+ if status != expected_status:+ raise SystemExit(+ f"Capability preflight status must be {expected_status} for the supplied issues."+ )+ normalized_payload: dict[str, Any] = {+ "profile": profile,+ "status": status,+ "issues": normalized_issues,+ "checkedTargetPath": checked_target_path,+ "checkedMode": checked_mode,+ }+ if normalized_remediation is not None:+ normalized_payload["remediation"] = normalized_remediation+ serialized = json.dumps(+ normalized_payload,+ ensure_ascii=False,+ separators=(",", ":"),+ sort_keys=True,+ )+ serialized = _escape_json_surrogates(serialized)+ if len(serialized.encode("utf-8")) > MAX_CAPABILITY_PREFLIGHT_PERSISTED_JSON_BYTES:+ raise SystemExit(+ "Persisted capability preflight must be no larger than "+ f"{MAX_CAPABILITY_PREFLIGHT_PERSISTED_JSON_BYTES} bytes."+ )+ return serialized+++def capability_preflight_input(value: str | None, path: Path | None) -> str | None:+ if path is None:+ return value+ try:+ if path.stat().st_size > MAX_CAPABILITY_PREFLIGHT_INPUT_JSON_BYTES:+ raise SystemExit(+ "Capability preflight must be no larger than "+ f"{MAX_CAPABILITY_PREFLIGHT_INPUT_JSON_BYTES} bytes."+ )+ return path.read_text(encoding="utf-8")+ except (OSError, UnicodeError) as exc:+ raise SystemExit("Capability preflight JSON file could not be read as UTF-8.") from exc+++def _require_object_keys(+ value: dict[str, Any], *, required: set[str], optional: set[str], label: str+) -> None:+ keys = set(value)+ missing = required - keys+ extra = keys - required - optional+ if missing:+ raise SystemExit(f"{label} is missing required fields: {', '.join(sorted(missing))}.")+ if extra:+ raise SystemExit(f"{label} has unsupported fields: {', '.join(sorted(extra))}.")+++def _bounded_preflight_text(value: Any, maximum: int, label: str) -> str:+ if not isinstance(value, str):+ raise SystemExit(f"Capability preflight {label} must be text.")+ normalized = value.strip()+ if not normalized or _javascript_string_length(normalized) > maximum:+ raise SystemExit(f"Capability preflight {label} must contain 1 to {maximum} characters.")+ return normalized+++def _javascript_string_length(value: str) -> int:+ return len(value.encode("utf-16-le", errors="surrogatepass")) // 2+++def _escape_json_surrogates(value: str) -> str:+ return "".join(+ f"\\u{ord(character):04x}" if 0xD800 <= ord(character) <= 0xDFFF else character+ for character in value+ )+++def _normalize_preflight_patch(value: Any, index: int) -> dict[str, Any]:+ label = f"Capability preflight remediation patch {index + 1}"+ if not isinstance(value, dict):+ raise SystemExit(f"{label} must be a JSON object.")+ _require_object_keys(+ value,+ required={"path", "value"},+ optional={"kind"},+ label=label,+ )+ normalized: dict[str, Any] = {+ "path": _bounded_preflight_text(value.get("path"), 256, f"patch {index + 1} path")+ }+ if "kind" in value:+ kind = value.get("kind")+ if kind not in {"config", "host_setting"}:+ raise SystemExit(f"{label} has an invalid kind.")+ normalized["kind"] = kind+ patch_value = value.get("value")+ if isinstance(patch_value, str):+ if _javascript_string_length(patch_value) > 2048:+ raise SystemExit(f"{label} value must be no longer than 2048 characters.")+ elif isinstance(patch_value, bool):+ pass+ elif isinstance(patch_value, (int, float)):+ try:+ finite = math.isfinite(float(patch_value))+ except OverflowError:+ finite = False+ if not finite:+ raise SystemExit(f"{label} value must be a finite number.")+ else:+ raise SystemExit(f"{label} value must be text, a number, or a boolean.")+ normalized["value"] = patch_value+ return normalized++def require_occurrence(connection: sqlite3.Connection, occurrence_id: str) -> sqlite3.Row:occurrence_id = optional_text(occurrence_id, maximum=256)if occurrence_id is None:diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 0b20d8af6..d084f0568 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -33,6 +33,7 @@ import {ScanInterruptedError,} from "./errors.js";import { ScanResult, type TurnResultMetadata } from "./result.js";+import type { SeverityLevel } from "./models.js";import {workerStatusFromEvent,type ScanWorkerStatus,@@ -41,18 +42,22 @@ import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";import {bootstrapPlugin,cleanupSdkDirectory,+ codexSecurityStateDirectory,createIsolatedHome,importAmbientAuth,pluginExecutionEnvironment,planOutputArchive,prepareOutputDir,+ preparePersistentScanRoot,requireModelSafeOutputDir,resolveCodexCommand,resolvePluginPath,resolvePluginPython,+ runWorkbench,type CodexCommand,type PluginInstall,type ProcessEnvironment,+ type WorkbenchCommandOptions,validateOutputDir,} from "./runtime.js";import {@@ -96,6 +101,7 @@ interface PreparedRuntime {plugin: PluginInstall;environment: Record<string, string>;credentialsAvailable: boolean;+ effectiveConfig?: JsonObject;}export interface ScanOptions {@@ -103,6 +109,9 @@ export interface ScanOptions {mode?: ScanMode;outputDir?: string;archiveExisting?: boolean;+ parentScanId?: string;+ expectedPluginVersion?: string;+ failureSeverity?: SeverityLevel;onOutputArchived?: (archiveDir: string) => void;onOutputDirReady?: (scanDir: string) => void;onScanStarted?: () => void;@@ -149,6 +158,7 @@ interface ClientDependencies {prepareOutputDir?: typeof prepareOutputDir;repositoryRevision?: typeof repositoryRevision;resolveCodexCommand?: () => CodexCommand;+ runWorkbench?: typeof runWorkbench;}const DEFAULT_DEPENDENCIES: ClientDependencies = {@@ -230,6 +240,11 @@ export class CodexSecurity {: AbortSignal.any([this.#abortController.signal, options.signal]);let scanDir = "";let targetPathsFile: string | null = null;+ let activeScan: {+ id: string;+ options: WorkbenchCommandOptions;+ } | null = null;+ const workbench = this.#dependencies.runWorkbench ?? runWorkbench;try {const checkOpen = (): void => {this.#requireOpen();@@ -244,6 +259,10 @@ export class CodexSecurity {outputDir: requestedOutput,protectedRoot,} = await this.#validateLocalInputs(repository, options, signal);+ const stateDirectory = codexSecurityStateDirectory(+ this.#dependencies.environment,+ );+ requireOutputOutsideRepository(protectedRoot, stateDirectory);checkOpen();let temporaryRoot: string | undefined;if (requestedOutput === null || this.#runtime === null) {@@ -264,6 +283,14 @@ export class CodexSecurity {);const runtimeHome = await realpath(runtime.codexHome);requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");+ if (+ options.expectedPluginVersion !== undefined &&+ runtime.plugin.version !== options.expectedPluginVersion+ ) {+ throw new CodexSecurityError(+ `The original scan used plugin version ${options.expectedPluginVersion}, but the installed version is ${runtime.plugin.version}.`,+ );+ }checkOpen();const apiKey = environmentApiKey(this.#dependencies.environment);if (apiKey !== null) {@@ -297,10 +324,18 @@ export class CodexSecurity {signal,});checkOpen();+ const scanOutputRoot =+ requestedOutput === null &&+ this.#dependencies.prepareOutputDir === undefined+ ? await preparePersistentScanRoot(stateDirectory, basename(repo))+ : temporaryRoot;+ if (scanOutputRoot !== undefined) {+ requireOutputOutsideRepository(protectedRoot, scanOutputRoot);+ }scanDir = await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(requestedOutput ?? undefined,basename(repo),- temporaryRoot,+ scanOutputRoot,(path) => requireOutputOutsideRepository(protectedRoot, path),options.archiveExisting,(archiveDir) =>@@ -353,6 +388,51 @@ export class CodexSecurity {mode,pluginVersion: runtime.plugin.version,};+ const effectiveConfig =+ runtime.effectiveConfig ?? (await mergedCodexConfig(this.config));+ const recipe = scanRecipe(+ repo,+ normalized,+ mode,+ expectation.repositoryRevision,+ runtime.plugin.version,+ effectiveConfig,+ options.failureSeverity,+ );+ const workbenchOptions: WorkbenchCommandOptions = {+ python,+ pluginRoot: runtime.plugin.pluginRoot,+ environment: {+ ...runtime.environment,+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ },+ signal,+ failureMessage: "Could not save the Codex Security scan",+ };+ const registration = await workbench(workbenchOptions, [+ "register-cli-scan",+ "--repository",+ repo,+ "--scan-dir",+ scanDir,+ "--recipe-json",+ JSON.stringify(recipe),+ ...(options.parentScanId === undefined+ ? []+ : ["--parent-scan-id", options.parentScanId]),+ ]);+ const scanId = registration["scanId"];+ const targetId = registration["targetId"];+ if (+ typeof scanId !== "string" ||+ typeof targetId !== "string" ||+ registration["scanDir"] !== scanDir+ ) {+ throw new CodexSecurityError(+ "The Codex Security workbench returned an invalid scan registration.",+ );+ }+ activeScan = { id: scanId, options: workbenchOptions };checkOpen();targetPathsFile =normalized.kind === "paths"@@ -367,6 +447,9 @@ export class CodexSecurity {CODEX_SECURITY_REPOSITORY: repo,CODEX_SECURITY_SCAN_DIR: scanDir,CODEX_SECURITY_PLUGIN_ROOT: shellPluginRoot,+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ CODEX_SECURITY_SCAN_ID: scanId,+ CODEX_SECURITY_TARGET_ID: targetId,...(runtime.configPath === undefined? {}: { CODEX_SECURITY_CONFIG_PATH: runtime.configPath }),@@ -443,7 +526,7 @@ export class CodexSecurity {});checkOpen();- return await runScanEvents({+ const result = await runScanEvents({thread,events,signal,@@ -455,7 +538,25 @@ export class CodexSecurity {onWorkerStatus: options.onWorkerStatus,onObserverError: options.onObserverError,});+ await workbench(workbenchOptions, ["complete-scan", "--scan-id", scanId]);+ activeScan = null;+ checkOpen();+ return result;} catch (error) {+ if (activeScan !== null) {+ try {+ await workbench({ ...activeScan.options, signal: undefined }, [+ "fail-scan",+ "--scan-id",+ activeScan.id,+ "--message",+ (error instanceof Error ? error.message : String(error)).slice(+ 0,+ 2400,+ ),+ ]);+ } catch {}+ }if (this.#closed) this.#requireOpen();if (signal.aborted && !(error instanceof ScanInterruptedError)) {throwIfAborted(signal, scanDir);@@ -748,8 +849,11 @@ export class CodexSecurity {environment: {...withoutCodexHome(withoutApiKeys(processEnvironment)),CODEX_HOME: codexHome,+ CODEX_SECURITY_STATE_DIR:+ codexSecurityStateDirectory(processEnvironment),},credentialsAvailable,+ effectiveConfig: mergedConfig,};} catch (error) {const cleanupResults = await Promise.allSettled(@@ -943,6 +1047,8 @@ async function scanPrompt('Use "$PYTHON" as <python_command> for every plugin helper; replace any literal python or python3 helper invocation with this exact interpreter.','Repository root: "$CODEX_SECURITY_REPOSITORY"','Use this exact scan directory for all scan output: "$CODEX_SECURITY_SCAN_DIR"',+ 'Use exactly "$CODEX_SECURITY_SCAN_ID" as the scan ID in the manifest, findings, and coverage.',+ 'Use exactly "$CODEX_SECURITY_TARGET_ID" as scan.target.targetId; do not derive a different target ID.',...(hasConfigPath? ['For normal config-preflight helper calls, append --config "$CODEX_SECURITY_CONFIG_PATH" so preflight reads the sanitized active runtime config. Preserve the documented runtime and --effective-config arguments for session-only values.',@@ -971,6 +1077,33 @@ function targetInstruction(target: NormalizedTarget): string {return `Scan target: staged and unstaged working-tree changes against ${target.base}.`;}+function scanRecipe(+ repository: string,+ target: NormalizedTarget,+ mode: ScanMode,+ repositoryRevision: string | null,+ pluginVersion: string,+ effectiveConfig: JsonObject,+ failOnSeverity?: SeverityLevel,+): JsonObject {+ return {+ repository,+ target: {+ kind: target.kind,+ paths: [...target.paths],+ ...(target.base === undefined ? {} : { base: target.base }),+ ...(target.head === undefined ? {} : { head: target.head }),+ ...(target.baseRef === undefined ? {} : { baseRef: target.baseRef }),+ ...(target.headRef === undefined ? {} : { headRef: target.headRef }),+ },+ mode,+ ...(repositoryRevision === null ? {} : { repositoryRevision }),+ pluginVersion,+ config: scanPreflightCodexConfig(effectiveConfig),+ ...(failOnSeverity === undefined ? {} : { failOnSeverity }),+ };+}+async function collectResult(turnResult: TurnResultMetadata,threadId: string,@@ -1114,8 +1247,8 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {const capabilityFeatures = (value: unknown): JsonObject => {if (!isRecord(value)) return {};const result: JsonObject = {};- if (typeof value["goals"] === "boolean") {- result["goals"] = value["goals"];+ for (const key of ["goals", "multi_agent", "enable_fanout"]) {+ if (typeof value[key] === "boolean") result[key] = value[key];}const multiAgent = value["multi_agent_v2"];if (typeof multiAgent === "boolean") {@@ -1135,21 +1268,38 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {}return result;};-- const result: JsonObject = {};- const features = capabilityFeatures(config["features"]);- if (Object.keys(features).length > 0) result["features"] = features;- const agents = config["agents"];- if (isRecord(agents)) {- const sanitized: JsonObject = {};- for (const key of ["max_threads", "max_depth"]) {- const value = agents[key];- if (safeInteger(value)) {- sanitized[key] = value;+ const executionConfig = (source: JsonObject): JsonObject => {+ const result: JsonObject = {};+ for (const key of [+ "model",+ "model_reasoning_effort",+ "model_provider",+ "service_tier",+ ]) {+ const value = source[key];+ if (safeString(value, 512)) result[key] = value;+ }+ const features = capabilityFeatures(source["features"]);+ if (Object.keys(features).length > 0) result["features"] = features;+ const agents = source["agents"];+ if (isRecord(agents)) {+ const sanitized: JsonObject = {};+ for (const key of ["max_threads", "max_depth"]) {+ const value = agents[key];+ if (safeInteger(value)) sanitized[key] = value;}+ if (Object.keys(sanitized).length > 0) result["agents"] = sanitized;}- if (Object.keys(sanitized).length > 0) result["agents"] = sanitized;- }+ const multiagent = source["multiagent_config"];+ if (isRecord(multiagent) && safeInteger(multiagent["max_concurrency"])) {+ result["multiagent_config"] = {+ max_concurrency: multiagent["max_concurrency"],+ };+ }+ return result;+ };++ const result = executionConfig(config);if (safeProfileName(config["profile"])) {result["profile"] = config["profile"];}@@ -1158,10 +1308,8 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {const sanitized: JsonObject = {};for (const [name, profile] of Object.entries(profiles).slice(0, 256)) {if (!safeProfileName(name) || !isRecord(profile)) continue;- const profileFeatures = capabilityFeatures(profile["features"]);- if (Object.keys(profileFeatures).length > 0) {- sanitized[name] = { features: profileFeatures };- }+ const projected = executionConfig(profile as JsonObject);+ if (Object.keys(projected).length > 0) sanitized[name] = projected;}if (Object.keys(sanitized).length > 0) result["profiles"] = sanitized;}@@ -1184,12 +1332,6 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {}if (Object.keys(sanitized).length > 0) result["projects"] = sanitized;}- const multiagent = config["multiagent_config"];- if (isRecord(multiagent) && safeInteger(multiagent["max_concurrency"])) {- result["multiagent_config"] = {- max_concurrency: multiagent["max_concurrency"],- };- }if (Buffer.byteLength(JSON.stringify(result), "utf8") > 256 * 1024) {throw new CodexSecurityError("The sanitized Codex Security preflight config exceeds the size limit.",diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 82ef24633..1054c1f41 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -38,9 +38,11 @@ import { runMultiscan } from "./multiscan.js";import type { ScanResult } from "./result.js";import {bundledPluginRoot,+ codexSecurityStateDirectory,expandHome,resolveCodexCommand,resolvePluginPython,+ runWorkbench,} from "./runtime.js";import type { ScanWorkerStatus } from "./worker-progress.js";import { DiffTarget, type ScanMode, type ScanTarget } from "./targets.js";@@ -91,6 +93,7 @@ const VALUE_OPTIONS = new Set(["--filter-output","--token-limit","--token-offset",+ "--scan-root",]);function optionValue(flag: string) {@@ -110,8 +113,11 @@ interface ScanArguments {pluginPath?: string;pythonPath?: string;codex: string[];+ codexOverrides?: JsonObject;failOnSeverity?: FailureSeverity;dryRun: boolean;+ parentScanId?: string;+ expectedPluginVersion?: string;}interface ScanOutcome {@@ -145,6 +151,7 @@ interface CliDependencies {output?: Writable,): Promise<Uint8Array | undefined>;runCodex(args: readonly string[]): Promise<number>;+ runWorkbench(args: readonly string[]): Promise<JsonObject>;}const DEFAULT_DEPENDENCIES: CliDependencies = {@@ -275,6 +282,22 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {}return undefined;},+ runWorkbench: async (args) => {+ const environment = {+ ...exportEnvironment(),+ CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),+ };+ const python = await resolvePluginPython({ environment });+ return await runWorkbench(+ {+ python,+ pluginRoot: await bundledPluginRoot(),+ environment,+ failureMessage: "Could not read Codex Security scan history",+ },+ args,+ );+ },};async function writeCliOutput(@@ -348,6 +371,7 @@ export async function main(errorOutput: Writable = process.stderr,dependencies: CliDependencies = DEFAULT_DEPENDENCIES,): Promise<number> {+ argv = defaultScansList(argv);const positionals: string[] = [];const argumentError = validateCliArguments(argv, positionals);if (argumentError !== undefined) {@@ -357,6 +381,132 @@ export async function main(let exitCode = 0;let frameworkExit: number | undefined;let frameworkOutput = "";+ const history = async (+ args: readonly string[],+ select: (value: JsonObject) => JsonObject = (value) => value,+ ): Promise<JsonObject | undefined> => {+ try {+ return select(await dependencies.runWorkbench(args));+ } catch (error) {+ errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);+ exitCode = 2;+ return undefined;+ }+ };+ const scanHistory = Cli.create("scans", {+ description:+ "List, inspect, rerun, and compare saved Codex Security scans.",+ })+ .command("list", {+ description: "List saved scans for a repository or scan root.",+ mcp: false,+ args: z.object({+ repository: z+ .string()+ .optional()+ .describe("Repository to inspect (default: current directory)."),+ }),+ options: z.object({+ scanRoot: z+ .string()+ .optional()+ .describe("Include scans whose output is under ROOT."),+ }),+ output: z.record(z.string(), z.unknown()).optional(),+ async run({ args, options }) {+ const directory = dependencies.currentDirectory();+ return await history([+ "list-scans",+ ...(options.scanRoot !== undefined && args.repository === undefined+ ? []+ : [+ "--repository",+ resolve(directory, args.repository ?? directory),+ ]),+ ...(options.scanRoot === undefined+ ? []+ : ["--scan-root", resolve(directory, options.scanRoot)]),+ ]);+ },+ })+ .command("show", {+ description: "Show the results and saved configuration for a scan.",+ mcp: false,+ args: z.object({+ scanId: z.string().min(1).describe("Saved scan identifier."),+ }),+ output: z.record(z.string(), z.unknown()).optional(),+ async run({ args }) {+ return await history(+ ["get-scan", "--scan-id", args.scanId],+ (value) => {+ const { scan, recipe, parentScanId } = value;+ return {+ ...(scan as JsonObject),+ ...(recipe === undefined ? {} : { recipe }),+ ...(parentScanId === undefined ? {} : { parentScanId }),+ };+ },+ );+ },+ })+ .command("rerun", {+ description: "Rerun a saved scan with its original configuration.",+ destructive: true,+ mcp: false,+ args: z.object({+ scanId: z.string().min(1).describe("Saved scan identifier."),+ }),+ output: z.record(z.string(), z.unknown()).optional(),+ async run({ args, error: incurError }) {+ let scanArguments: ScanArguments;+ try {+ const { recipe } = await dependencies.runWorkbench([+ "get-scan-recipe",+ "--scan-id",+ args.scanId,+ ]);+ scanArguments = scanArgumentsFromRecipe(recipe, args.scanId);+ } catch (error) {+ const message = cliErrorMessage(error);+ errorOutput.write(`codex-security: ${message}\n`);+ exitCode = 2;+ return incurError({+ code: "SCAN_REPLAY_UNAVAILABLE",+ message,+ exitCode,+ });+ }+ const outcome = await runScan(scanArguments, errorOutput, dependencies);+ exitCode = outcome.exitCode;+ if (outcome.error !== undefined) {+ return incurError({+ code: "SCAN_FAILED",+ message: outcome.error,+ exitCode,+ });+ }+ return outcome.data;+ },+ })+ .command("compare", {+ description: "Compare findings and coverage between two saved scans.",+ mcp: false,+ args: z.object({+ beforeId: z.string().min(1).describe("Earlier saved scan identifier."),+ afterId: z.string().min(1).describe("Later saved scan identifier."),+ }),+ output: z.record(z.string(), z.unknown()).optional(),+ async run({ args }) {+ return await history([+ "compare-scans",+ "--before-scan-id",+ args.beforeId,+ "--after-scan-id",+ args.afterId,+ ]);+ },+ });const cli = Cli.create("codex-security", {description: "Run, validate, patch, and export Codex Security findings.",version: VERSION,@@ -498,6 +648,7 @@ export async function main(return outcome.data;},})+ .command(scanHistory).command("scan-csv", {description: "Run resumable repository scans from a CSV inventory.",destructive: true,@@ -755,6 +906,127 @@ export async function main(}}+function defaultScansList(argv: readonly string[]): readonly string[] {+ const commandIndex = argv.findIndex((value, index) => {+ if (value.startsWith("-")) return false;+ return index === 0 || !VALUE_OPTIONS.has(argv[index - 1]!);+ });+ if (+ commandIndex < 0 ||+ argv[commandIndex] !== "scans" ||+ argv.includes("--help") ||+ argv.includes("-h")+ ) {+ return argv;+ }+ const following = argv[commandIndex + 1];+ if (following !== undefined && !following.startsWith("-")) return argv;+ return [+ ...argv.slice(0, commandIndex + 1),+ "list",+ ...argv.slice(commandIndex + 1),+ ];+}++function scanArgumentsFromRecipe(+ recipe: JsonValue | undefined,+ parentScanId: string,+): ScanArguments {+ if (recipe === undefined || !isJsonObject(recipe)) {+ throw new CodexSecurityError(+ "This scan does not have a saved launch recipe.",+ );+ }+ const repository = recipe["repository"];+ if (typeof repository !== "string" || repository.length === 0) {+ throw new CodexSecurityError(+ "The saved scan recipe does not contain a repository.",+ );+ }+ const target = recipe["target"];+ if (target === undefined || !isJsonObject(target)) {+ throw new CodexSecurityError("The saved scan recipe contains no target.");+ }+ const paths = target["paths"];+ if (+ !Array.isArray(paths) ||+ !paths.every(+ (path): path is string => typeof path === "string" && path.length > 0,+ )+ ) {+ throw new CodexSecurityError(+ "The saved scan recipe contains invalid paths.",+ );+ }+ const kind = target["kind"];+ if (+ kind !== "repository" &&+ kind !== "paths" &&+ kind !== "refs" &&+ kind !== "working_tree"+ ) {+ throw new CodexSecurityError(+ "The saved scan recipe contains an invalid target.",+ );+ }+ const mode = recipe["mode"];+ if (mode !== "standard" && mode !== "deep") {+ throw new CodexSecurityError(+ "The saved scan recipe contains an invalid mode.",+ );+ }+ const config = recipe["config"];+ if (config === undefined || !isJsonObject(config)) {+ throw new CodexSecurityError(+ "The saved scan recipe contains invalid configuration.",+ );+ }+ const reference = target["baseRef"] ?? target["base"];+ if (+ (reference !== undefined && typeof reference !== "string") ||+ (kind === "refs" && !reference)+ ) {+ throw new CodexSecurityError(+ "The saved scan recipe has an invalid Git base.",+ );+ }+ const head = target["headRef"];+ if (head !== undefined && (typeof head !== "string" || head.length === 0)) {+ throw new CodexSecurityError(+ "The saved scan recipe has an invalid Git head.",+ );+ }+ const threshold = recipe["failOnSeverity"];+ if (+ threshold !== undefined &&+ (typeof threshold !== "string" ||+ !REPORTABLE_SEVERITIES.includes(threshold as FailureSeverity))+ ) {+ throw new CodexSecurityError(+ "The saved scan recipe contains an invalid severity policy.",+ );+ }+ return {+ repository,+ paths,+ diff: kind === "refs" ? reference : undefined,+ workingTree: kind === "working_tree",+ head: kind === "refs" ? head ?? "HEAD" : undefined,+ base: kind === "working_tree" ? reference : undefined,+ mode,+ archiveExisting: false,+ codex: [],+ codexOverrides: config,+ failOnSeverity: threshold as FailureSeverity | undefined,+ dryRun: false,+ parentScanId,+ expectedPluginVersion:+ typeof recipe["pluginVersion"] === "string"+ ? recipe["pluginVersion"]+ : undefined,+ };+}+function validateCliArguments(argv: readonly string[],positionals: string[],@@ -763,6 +1035,7 @@ function validateCliArguments(const commandIndex = argv.findIndex((value) =>["scan",+ "scans","scan-csv","export","validate",@@ -793,6 +1066,7 @@ function validateCliArguments(return "Markdown output is not supported for scan results.";}}+ const subcommand = command === "scans" ? argv[commandIndex + 1] : undefined;if (command === "info") {const metadataFields = new Set(["sdkVersion",@@ -819,7 +1093,11 @@ function validateCliArguments(}}}- for (let index = commandIndex + 1; index < argv.length; index += 1) {+ for (+ let index = commandIndex + (command === "scans" ? 2 : 1);+ index < argv.length;+ index += 1+ ) {const value = argv[index]!;if (!value.startsWith("-")) {positionals.push(value);@@ -837,9 +1115,14 @@ function validateCliArguments(if (command !== "validate" &&command !== "patch" &&- positionals.length > (command === "logout" || command === "info" ? 0 : 1)+ positionals.length >+ (command === "logout" || command === "info"+ ? 0+ : subcommand === "compare"+ ? 2+ : 1)) {- return `Unexpected positional argument for ${command}.`;+ return `Unexpected positional argument for ${command}${subcommand === undefined ? "" : ` ${subcommand}`}.`;}}@@ -1027,7 +1310,8 @@ async function runScan(const config: CodexSecurityConfig = {pluginPath: arguments_.pluginPath,pythonPath: arguments_.pythonPath,- codexOverrides: parseCodexOverrides(arguments_.codex),+ codexOverrides:+ arguments_.codexOverrides ?? parseCodexOverrides(arguments_.codex),};progress = new Progress(errorOutput, dependencies);progress.startTimer(@@ -1039,6 +1323,9 @@ async function runScan(mode: arguments_.mode,outputDir: arguments_.outputDir,archiveExisting: arguments_.archiveExisting,+ parentScanId: arguments_.parentScanId,+ expectedPluginVersion: arguments_.expectedPluginVersion,+ failureSeverity: arguments_.failOnSeverity,onOutputArchived: (archiveDir) => {progress?.stopTimer();errorOutput.write(diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex fcf82825c..cfc77b7f4 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -35,10 +35,12 @@ import { crc32 } from "node:zlib";import extractZip from "extract-zip";import { parse } from "smol-toml";import {+ CodexSecurityError,OutputDirectoryError,PluginBootstrapError,PluginPythonUnavailableError,} from "./errors.js";+import type { JsonObject } from "./config.js";import { resolveTrustedExecutable } from "./trusted-executable.js";const execFile = promisify(execFileCallback);@@ -81,6 +83,87 @@ export interface PluginPythonOptions {signal?: AbortSignal;}+export interface WorkbenchCommandOptions {+ python: string;+ pluginRoot: string;+ environment: ProcessEnvironment;+ signal?: AbortSignal;+ failureMessage?: string;+}++export function codexSecurityStateDirectory(+ environment: ProcessEnvironment = process.env,+): string {+ const environmentValue = (requested: string): string | undefined => {+ const exact = environment[requested]?.trim();+ if (exact) return exact;+ return Object.entries(environment)+ .find(+ ([name, value]) => name.toUpperCase() === requested && value?.trim(),+ )?.[1]+ ?.trim();+ };+ const configured = environmentValue("CODEX_SECURITY_STATE_DIR");+ if (configured !== undefined) return resolve(expandHome(configured));+ const codexHome = environmentValue("CODEX_HOME") ?? join(homedir(), ".codex");+ return resolve(expandHome(codexHome), "state", "plugins", "codex-security");+}++export async function preparePersistentScanRoot(+ stateDirectory: string,+ repositoryName: string,+): Promise<string> {+ const root = join(stateDirectory, "scans", safePrefix(repositoryName));+ await mkdir(root, { recursive: true, mode: 0o700 });+ return await realpath(root);+}++export async function runWorkbench(+ options: WorkbenchCommandOptions,+ args: readonly string[],+): Promise<JsonObject> {+ let stdout: string;+ try {+ ({ stdout } = await execFile(+ options.python,+ [+ "-I",+ "-B",+ join(options.pluginRoot, "scripts", "workbench_db.py"),+ ...args,+ ],+ {+ env: withoutApiKeyCredentials(options.environment),+ encoding: "utf8",+ maxBuffer: 4 * 1024 * 1024,+ windowsHide: true,+ signal: options.signal,+ },+ ));+ } catch (error) {+ if (options.signal?.aborted) throw error;+ throw new CodexSecurityError(+ `${options.failureMessage ?? "Could not run the Codex Security workbench"}: ${processErrorDetail(error)}`,+ { cause: error },+ );+ }+ let result: unknown;+ try {+ result = JSON.parse(stdout);+ } catch (error) {+ throw new CodexSecurityError(+ "The Codex Security workbench returned invalid JSON.",+ { cause: error },+ );+ }+ if (!isRecord(result)) {+ throw new CodexSecurityError(+ "The Codex Security workbench returned an invalid response.",+ );+ }+ return result as JsonObject;+}+export function bundledPluginCandidates(moduleDirectory: string): string[] {const packageCandidates = [resolve(moduleDirectory, "_bundled_plugin"),diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex e64b6885f..5b1156c39 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -39,6 +39,7 @@ import {runScanEvents,} from "../src/api.js";import { writeCodexConfig } from "../src/config.js";+import { runWorkbench } from "../src/runtime.js";import { normalizeTarget } from "../src/targets.js";import { INTEGRATION_TARGET, PLUGIN_ROOT } from "./plugin-root.js";@@ -49,11 +50,30 @@ type ScanObserverName = Parameters<const REPOSITORY_ROOT = fileURLToPath(new URL("../../..", import.meta.url));const EXAMPLE = join(PLUGIN_ROOT, "examples", "completed-scan");const temporaryDirectories: string[] = [];-const TestClient = CodexSecurity as unknown as new (+const TestClientBase = CodexSecurity as unknown as new (config: Record<string, unknown>,dependencies: Record<string, unknown>,) => CodexSecurity;+class TestClient extends TestClientBase {+ public constructor(+ config: Record<string, unknown>,+ dependencies: Record<string, unknown>,+ ) {+ super(config, {+ runWorkbench: async (_options: unknown, args: readonly string[]) =>+ args[0] === "register-cli-scan"+ ? {+ scanId: "scan_example_001",+ targetId: "target_sha256_example",+ scanDir: args[args.indexOf("--scan-dir") + 1],+ }+ : {},+ ...dependencies,+ });+ }+}+afterEach(async () => {await Promise.all(temporaryDirectories@@ -570,7 +590,10 @@ describe("CodexSecurity orchestration", () => {);await mkdir(repository);const sanitized = scanPreflightCodexConfig({+ model: "gpt-5.6-sol",+ model_reasoning_effort: "high",features: {+ plugins: true,goals: true,multi_agent_v2: { enabled: false, secret: "FEATURE_SECRET" },api_key: "FEATURE_KEY",@@ -579,7 +602,9 @@ describe("CodexSecurity orchestration", () => {profile: "review",profiles: {review: {+ model: "profile-model",features: { goals: true, secret: "PROFILE_SECRET" },+ agents: { max_threads: 4, token: "PROFILE_AGENT_TOKEN" },shell_environment_policy: { set: { SECRET: "PROFILE_ENV_SECRET" } },},secret_profile: { features: { goals: false } },@@ -607,11 +632,17 @@ describe("CodexSecurity orchestration", () => {shell_environment_policy: { set: { SECRET: "SHELL_SECRET" } },});expect(sanitized).toEqual({+ model: "gpt-5.6-sol",+ model_reasoning_effort: "high",features: { goals: true, multi_agent_v2: { enabled: false } },agents: { max_threads: 12, max_depth: 2 },profile: "review",profiles: {- review: { features: { goals: true } },+ review: {+ model: "profile-model",+ features: { goals: true },+ agents: { max_threads: 4 },+ },development: { features: { goals: true } },},project_root_markers: [".git", ".workspace", "settings.gradle"],@@ -627,6 +658,7 @@ describe("CodexSecurity orchestration", () => {"FEATURE_KEY","AGENT_TOKEN","PROFILE_SECRET",+ "PROFILE_AGENT_TOKEN","PROFILE_ENV_SECRET","PROJECT_TOKEN","MCP_TOKEN",@@ -1212,13 +1244,10 @@ describe("CodexSecurity orchestration", () => {let prompt = "";let scanStarted = false;const reconnects: Array<[number, number]> = [];+ const commands: Array<readonly string[]> = [];- const TestClient = CodexSecurity as unknown as new (- config: Record<string, unknown>,- dependencies: Record<string, unknown>,- ) => CodexSecurity;const client = new TestClient(- {},+ { codexOverrides: { model: "replay-model" } },{environment: { PATH: "/usr/bin", OPENAI_API_KEY: "" },prepareRuntime: async () => ({@@ -1243,6 +1272,16 @@ describe("CodexSecurity orchestration", () => {resolvePluginPython: async () => "/managed/python",prepareOutputDir: async () => scanDir,repositoryRevision: async () => "deadbeef",+ runWorkbench: async (_options: unknown, args: readonly string[]) => {+ commands.push(args);+ return args[0] === "register-cli-scan"+ ? {+ scanId: "scan_example_001",+ targetId: "target_sha256_example",+ scanDir,+ }+ : {};+ },createCodex: (options: CodexOptions) => {codexOptions = options;return {@@ -1251,6 +1290,7 @@ describe("CodexSecurity orchestration", () => {return {id: null,async runStreamed(input: string) {+ expect(commands[0]?.[0]).toBe("register-cli-scan");prompt = input;await copyCompletedScan(root);async function* reconnectingEvents(): AsyncGenerator<ThreadEvent> {@@ -1319,6 +1359,9 @@ describe("CodexSecurity orchestration", () => {"CODEX_SECURITY_REPOSITORY","CODEX_SECURITY_SCAN_DIR","CODEX_SECURITY_PLUGIN_ROOT",+ "CODEX_SECURITY_STATE_DIR",+ "CODEX_SECURITY_SCAN_ID",+ "CODEX_SECURITY_TARGET_ID",],set: {PYTHON: "/managed/python",@@ -1326,6 +1369,9 @@ describe("CodexSecurity orchestration", () => {CODEX_SECURITY_REPOSITORY: repository,CODEX_SECURITY_SCAN_DIR: scanDir,CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,+ CODEX_SECURITY_STATE_DIR: expect.any(String),+ CODEX_SECURITY_SCAN_ID: expect.any(String),+ CODEX_SECURITY_TARGET_ID: expect.any(String),},},});@@ -1344,6 +1390,179 @@ describe("CodexSecurity orchestration", () => {);expect(prompt).toContain('Repository root: "$CODEX_SECURITY_REPOSITORY"');expect(prompt).toContain('Use "$PYTHON" as <python_command>');+ expect(+ JSON.parse(commands[0]![commands[0]!.indexOf("--recipe-json") + 1]!),+ ).toMatchObject({+ repository,+ target: { kind: "repository", paths: [] },+ mode: "standard",+ repositoryRevision: "deadbeef",+ pluginVersion: "0.1.0",+ config: { model: "replay-model" },+ });+ expect(commands[1]).toEqual([+ "complete-scan",+ "--scan-id",+ "scan_example_001",+ ]);+ await client.close();+ });++ test("marks a started scan failed without masking its original error", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "codex-home");+ const stateDirectory = join(root, "state");+ const scanDir = join(root, "scan");+ await mkdir(repository);+ await mkdir(codexHome);+ await mkdir(scanDir, { mode: 0o700 });+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const environment = {+ PATH: process.env["PATH"],+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ };+ const commands: Array<readonly string[]> = [];+ const client = new TestClient(+ {},+ {+ environment,+ prepareRuntime: async () => ({+ ...preparedRuntime(codexHome),+ environment,+ }),+ resolvePluginPython: async () => python!,+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ runWorkbench: async (+ options: Parameters<typeof runWorkbench>[0],+ args: readonly string[],+ ) => {+ commands.push(args);+ const result = await runWorkbench(options, args);+ if (args[0] === "fail-scan") {+ throw new Error("failure recording also failed");+ }+ return result;+ },+ createCodex: () => ({+ startThread: () => ({+ id: null,+ async runStreamed() {+ throw new Error("original scan failure");+ },+ }),+ }),+ },+ );+ await expect(client.run(repository)).rejects.toThrow(+ "original scan failure",+ );+ expect(commands[1]).toMatchObject([+ "fail-scan",+ "--scan-id",+ expect.stringMatching(/^[0-9a-f-]{36}$/),+ "--message",+ "original scan failure",+ ]);+ const history = await runWorkbench(+ { python: python!, pluginRoot: PLUGIN_ROOT, environment },+ ["list-scans", "--repository", repository],+ );+ expect(history["scans"]).toMatchObject([+ { progress: { status: "failed" } },+ ]);+ await client.close();+ });++ test("retains default scan output under persistent plugin state", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "codex-home");+ const stateDirectory = join(root, "state");+ await mkdir(repository);+ await mkdir(codexHome);+ const client = new TestClient(+ {},+ {+ environment: { CODEX_SECURITY_STATE_DIR: stateDirectory },+ prepareRuntime: async () => preparedRuntime(codexHome),+ resolvePluginPython: async () => "/managed/python",+ repositoryRevision: async () => "deadbeef",+ createCodex: (options: CodexOptions) => ({+ startThread: () => ({+ id: null,+ async runStreamed() {+ const scanDir = options.env?.["CODEX_SECURITY_SCAN_DIR"];+ if (scanDir === undefined)+ throw new Error("missing scan directory");+ await cp(EXAMPLE, scanDir, { recursive: true });+ await writeFile(join(scanDir, "report.md"), "# Scan report\n");+ return { events: completedEvents() };+ },+ }),+ }),+ },+ );++ const result = await client.run(repository);+ expect(+ result.scanDir.startsWith(join(stateDirectory, "scans", "repository")),+ ).toBe(true);+ if (process.platform !== "win32") {+ expect((await stat(result.scanDir)).mode & 0o777).toBe(0o700);+ }+ await client.close();+ expect(existsSync(join(result.scanDir, "scan-manifest.json"))).toBe(true);+ });++ test("rejects repository-local state even when scan output is outside", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const stateDirectory = join(repository, "state");+ await mkdir(repository);+ const client = new TestClient(+ {},+ {+ environment: { CODEX_SECURITY_STATE_DIR: stateDirectory },+ prepareRuntime: async () => {+ throw new Error("Runtime must not start");+ },+ resolvePluginPython: async () => "/managed/python",+ createCodex: () => {+ throw new Error("Codex must not start");+ },+ },+ );++ await expect(+ client.run(repository, { outputDir: join(root, "output") }),+ ).rejects.toBeInstanceOf(OutputInsideProtectedRootError);+ expect(existsSync(stateDirectory)).toBe(false);+ await client.close();+ });++ test("rejects reruns when the original plugin version is unavailable", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "codex-home");+ await mkdir(repository);+ await mkdir(codexHome);+ const client = new TestClient(+ {},+ {+ environment: {},+ prepareRuntime: async () => preparedRuntime(codexHome),+ createCodex: () => {+ throw new Error("Codex must not start");+ },+ },+ );++ await expect(+ client.run(repository, { expectedPluginVersion: "0.0.1" }),+ ).rejects.toThrow("original scan used plugin version 0.0.1");await client.close();});@@ -1729,6 +1948,9 @@ describe("CodexSecurity orchestration", () => {CODEX_SECURITY_REPOSITORY: repository,CODEX_SECURITY_SCAN_DIR: scanDir,CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,+ CODEX_SECURITY_STATE_DIR: expect.any(String),+ CODEX_SECURITY_SCAN_ID: expect.any(String),+ CODEX_SECURITY_TARGET_ID: expect.any(String),CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile,},include_only: [@@ -1739,6 +1961,9 @@ describe("CodexSecurity orchestration", () => {"CODEX_SECURITY_REPOSITORY","CODEX_SECURITY_SCAN_DIR","CODEX_SECURITY_PLUGIN_ROOT",+ "CODEX_SECURITY_STATE_DIR",+ "CODEX_SECURITY_SCAN_ID",+ "CODEX_SECURITY_TARGET_ID","CODEX_SECURITY_TARGET_PATHS_FILE",],});@@ -1779,6 +2004,9 @@ describe("CodexSecurity orchestration", () => {CODEX_SECURITY_REPOSITORY: repository,CODEX_SECURITY_SCAN_DIR: scanDir,CODEX_SECURITY_PLUGIN_ROOT: PLUGIN_ROOT,+ CODEX_SECURITY_STATE_DIR: expect.any(String),+ CODEX_SECURITY_SCAN_ID: expect.any(String),+ CODEX_SECURITY_TARGET_ID: expect.any(String),CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile,},include_only: [@@ -1787,6 +2015,9 @@ describe("CodexSecurity orchestration", () => {"CODEX_SECURITY_REPOSITORY","CODEX_SECURITY_SCAN_DIR","CODEX_SECURITY_PLUGIN_ROOT",+ "CODEX_SECURITY_STATE_DIR",+ "CODEX_SECURITY_SCAN_ID",+ "CODEX_SECURITY_TARGET_ID","CODEX_SECURITY_TARGET_PATHS_FILE",],});@@ -2029,10 +2260,6 @@ describe("CodexSecurity orchestration", () => {const root = await temporaryDirectory();const codexHome = join(root, "codex-home");await mkdir(codexHome);- const TestClient = CodexSecurity as unknown as new (- config: Record<string, unknown>,- dependencies: Record<string, unknown>,- ) => CodexSecurity;const client = new TestClient({},{@@ -2086,10 +2313,6 @@ if (process.argv.slice(2).join(" ") !== "login --with-api-key") {let codexOptions: CodexOptions | null = null;let pythonEnvironment: Record<string, string | undefined> | undefined;let pythonProtectedRoot: string | undefined;- const TestClient = CodexSecurity as unknown as new (- config: Record<string, unknown>,- dependencies: Record<string, unknown>,- ) => CodexSecurity;const client = new TestClient({},{@@ -2252,10 +2475,6 @@ appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");const environment: Record<string, string | undefined> = {openai_api_key: "ambient-key",};- const TestClient = CodexSecurity as unknown as new (- config: Record<string, unknown>,- dependencies: Record<string, unknown>,- ) => CodexSecurity;const client = new TestClient({},{@@ -2304,10 +2523,6 @@ appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");releaseRuntime = resolve;});let createCodexCalled = false;- const TestClient = CodexSecurity as unknown as new (- config: Record<string, unknown>,- dependencies: Record<string, unknown>,- ) => CodexSecurity;const client = new TestClient({},{@@ -2359,10 +2574,6 @@ appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");const prepared = new Promise<Record<string, unknown>>((resolve) => {releaseRuntime = resolve;});- const TestClient = CodexSecurity as unknown as new (- config: Record<string, unknown>,- dependencies: Record<string, unknown>,- ) => CodexSecurity;const client = new TestClient({},{@@ -2425,10 +2636,6 @@ appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");releaseRevision = resolve;});let createCodexCalled = false;- const TestClient = CodexSecurity as unknown as new (- config: Record<string, unknown>,- dependencies: Record<string, unknown>,- ) => CodexSecurity;const client = new TestClient({},{@@ -2584,10 +2791,6 @@ appendFileSync(${JSON.stringify(keyLog)}, apiKey.trim() + "\\n");fakeCodex,'console.error("Open https://auth.example.test/device");\nconsole.error("User code: ABCD-EFGH");\nsetInterval(() => {}, 1000);\n',);- const TestClient = CodexSecurity as unknown as new (- config: Record<string, unknown>,- dependencies: Record<string, unknown>,- ) => CodexSecurity;const client = new TestClient({},{@@ -2645,10 +2848,6 @@ if (args === "login --with-api-key") {`,);let codexOptions: CodexOptions | null = null;- const TestClient = CodexSecurity as unknown as new (- config: Record<string, unknown>,- dependencies: Record<string, unknown>,- ) => CodexSecurity;const client = new TestClient({},{@@ -2725,10 +2924,6 @@ for await (const _chunk of process.stdin) {}setInterval(() => {}, 1000);`,);- const TestClient = CodexSecurity as unknown as new (- config: Record<string, unknown>,- dependencies: Record<string, unknown>,- ) => CodexSecurity;const client = new TestClient({},{diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex 0e9e40001..0da06ba5e 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -16,7 +16,11 @@ import { join } from "node:path";import { Writable } from "node:stream";import { pathToFileURL } from "node:url";import { describe, expect, test } from "bun:test";-import type { CodexSecurity, CodexSecurityConfig } from "../src/index.js";+import type {+ CodexSecurity,+ CodexSecurityConfig,+ JsonObject,+} from "../src/index.js";import {BUNDLED_PLUGIN_VERSION,CodexSecurityError,@@ -287,6 +291,7 @@ function dependencies(onInterrupt?: () => void;onClose?: () => void | Promise<void>;onCodex?: (args: readonly string[]) => number;+ onWorkbench?: (args: readonly string[]) => JsonObject | Promise<JsonObject>;currentDirectory?: string;preflight?: ScanPreflight;signals?: FakeSignals;@@ -337,6 +342,8 @@ function dependencies(writeSynchronously: (stream, value) => stream.write(value),forceExit: () => {},runCodex: async (args) => options.onCodex?.(args) ?? 0,+ runWorkbench: async (args) =>+ (await options.onWorkbench?.(args)) ?? { scans: [] },exportFindings: async (arguments_) => {const contents = new TextEncoder().encode(arguments_.format === "csv"@@ -402,6 +409,12 @@ describe("CLI", () => {expect(manifest.text()).toContain("codex-security export <scanDir>");expect(manifest.text()).toContain("codex-security validate <findings...>");expect(manifest.text()).toContain("codex-security patch <issues...>");+ expect(manifest.text()).toContain("codex-security scans list [repository]");+ expect(manifest.text()).toContain("codex-security scans show <scanId>");+ expect(manifest.text()).toContain("codex-security scans rerun <scanId>");+ expect(manifest.text()).toContain(+ "codex-security scans compare <beforeId> <afterId>",+ );expect(manifest.text()).toContain("codex-security info");const completions = capture();@@ -547,6 +560,219 @@ describe("CLI", () => {});}, 30_000);+ test("lists repository and scan-root history without starting Codex", async () => {+ const cases: Array<[string[], string[]]> = [+ [["scans"], ["list-scans", "--repository", "/current/repository"]],+ [+ ["scans", "list"],+ ["list-scans", "--repository", "/current/repository"],+ ],+ [+ ["scans", "list", "other"],+ ["list-scans", "--repository", "/current/repository/other"],+ ],+ [+ ["scans", "list", "--scan-root", "/tmp/history"],+ ["list-scans", "--scan-root", "/tmp/history"],+ ],+ ];+ for (const [argv, expected] of cases) {+ let invocation: readonly string[] | undefined;+ const deps = dependencies({+ onWorkbench: (args) => {+ invocation = args;+ return { scans: [{ scanId: "scan-1" }] };+ },+ });+ deps.createSecurity = () => {+ throw new Error("history must not initialize Codex");+ };+ expect(await main(argv, capture().stream, capture().stream, deps)).toBe(+ 0,+ );+ expect(invocation).toEqual(expected);+ }++ const stdout = capture();+ expect(+ await main(+ ["scan", "scans", "--dry-run", "--json"],+ stdout.stream,+ capture().stream,+ dependencies(),+ ),+ ).toBe(0);+ expect(JSON.parse(stdout.text())).toMatchObject({ repository: "scans" });+ });++ test("shows and compares scans with one workbench call per command", async () => {+ const cases: Array<[string[], string[], JsonObject, JsonObject]> = [+ [+ ["scans", "show", "scan-1", "--json"],+ ["get-scan", "--scan-id", "scan-1"],+ {+ scan: { scanId: "scan-1", findingCount: 2 },+ recipe: { repository: "/repo" },+ parentScanId: "scan-0",+ workspace: { results: { duplicated: true } },+ },+ {+ scanId: "scan-1",+ findingCount: 2,+ recipe: { repository: "/repo" },+ parentScanId: "scan-0",+ },+ ],+ [+ ["scans", "show", "legacy", "--json"],+ ["get-scan", "--scan-id", "legacy"],+ { scan: { scanId: "legacy" } },+ { scanId: "legacy" },+ ],+ [+ ["scans", "compare", "before", "after", "--json"],+ [+ "compare-scans",+ "--before-scan-id",+ "before",+ "--after-scan-id",+ "after",+ ],+ { comparable: true, summary: { persisting: 1, resolved: 1 } },+ { comparable: true, summary: { persisting: 1, resolved: 1 } },+ ],+ ];+ for (const [argv, expected, response, output] of cases) {+ const calls: Array<readonly string[]> = [];+ const stdout = capture();+ const deps = dependencies({+ onWorkbench: (args) => {+ calls.push(args);+ return response;+ },+ });+ deps.createSecurity = () => {+ throw new Error("history must not initialize Codex");+ };+ expect(await main(argv, stdout.stream, capture().stream, deps)).toBe(0);+ expect(calls).toEqual([expected]);+ expect(JSON.parse(stdout.text())).toEqual(output);+ }+ });++ test("reruns canonical recipes with exact config, policy, plugin, and lineage", async () => {+ let config: CodexSecurityConfig | undefined;+ let repository: string | undefined;+ let options: Record<string, unknown> | undefined;+ const savedConfig = {+ model: "gpt-original",+ model_reasoning_effort: "high",+ features: { goals: true },+ agents: { max_threads: 6 },+ };+ expect(+ await main(+ ["scans", "rerun", "scan-original"],+ capture().stream,+ capture().stream,+ dependencies({+ onConfig: (value) => {+ config = value;+ },+ onTurn: (value, runOptions) => {+ repository = value;+ options = runOptions as Record<string, unknown>;+ },+ onWorkbench: () => ({+ recipe: {+ repository: "/original/repository",+ target: { kind: "paths", paths: ["src", "packages/core"] },+ mode: "deep",+ pluginVersion: "1.2.3",+ failOnSeverity: "high",+ config: savedConfig,+ },+ }),+ }),+ ),+ ).toBe(0);+ expect(config?.codexOverrides).toEqual(savedConfig);+ expect(repository).toBe("/original/repository");+ expect(options).toMatchObject({+ target: ["src", "packages/core"],+ mode: "deep",+ parentScanId: "scan-original",+ expectedPluginVersion: "1.2.3",+ failureSeverity: "high",+ });++ const references: Array<[JsonObject, ReturnType<typeof DiffTarget.refs>]> =+ [+ [+ {+ kind: "refs",+ paths: [],+ base: "old-base-sha",+ baseRef: "origin/main",+ head: "old-head-sha",+ headRef: "feature",+ },+ DiffTarget.refs({ base: "origin/main", head: "feature" }),+ ],+ [+ { kind: "refs", paths: [], base: "old-base-sha" },+ DiffTarget.refs({ base: "old-base-sha", head: "HEAD" }),+ ],+ ];+ for (const [target, expected] of references) {+ let runOptions: Record<string, unknown> | undefined;+ expect(+ await main(+ ["scans", "rerun", "scan-original"],+ capture().stream,+ capture().stream,+ dependencies({+ onTurn: (_repository, value) => {+ runOptions = value as Record<string, unknown>;+ },+ onWorkbench: () => ({+ recipe: {+ repository: "/original/repository",+ target,+ mode: "standard",+ config: {},+ },+ }),+ }),+ ),+ ).toBe(0);+ expect(runOptions?.["target"]).toEqual(expected);+ }+ });++ test("redacts workbench failures and does not initialize Codex", async () => {+ const stderr = capture();+ let started = false;+ expect(+ await main(+ ["scans", "show", "missing"],+ capture().stream,+ stderr.stream,+ dependencies({+ onRun: () => {+ started = true;+ },+ onWorkbench: () => {+ throw new Error(`Scan lookup failed ${SYNTHETIC_CREDENTIALS}`);+ },+ }),+ ),+ ).toBe(2);+ expect(stderr.text()).toContain(REDACTED_CREDENTIALS);+ expect(stderr.text()).not.toContain("SYNTHETIC_KEY_123");+ expect(started).toBe(false);+ });+test("prints SDK metadata without starting a scan", async () => {const stdout = capture();const stderr = capture();diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex 2eeecfcff..4602a6286 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -43,10 +43,13 @@ import {} from "../src/index.js";import {bundledPluginCandidates,+ codexSecurityStateDirectory,codexPlatformPackage,isPythonPathCandidate,planOutputArchive,+ preparePersistentScanRoot,requirePrivateOutputDirectory,+ runWorkbench,} from "../src/runtime.js";const temporaryDirectories: string[] = [];@@ -638,6 +641,62 @@ describe("plugin runtime preparation", () => {});describe("runtime directories and plugin Python boundary", () => {+ test("derives persistent state from the ambient home or explicit override", async () => {+ const root = await temporaryDirectory();+ expect(codexSecurityStateDirectory({ CODEX_HOME: root })).toBe(+ join(root, "state", "plugins", "codex-security"),+ );+ expect(+ codexSecurityStateDirectory({+ CODEX_HOME: root,+ CODEX_SECURITY_STATE_DIR: join(root, "explicit-state"),+ }),+ ).toBe(join(root, "explicit-state"));+ const scanRoot = await preparePersistentScanRoot(+ join(root, "state"),+ "repository with spaces",+ );+ expect(scanRoot).toBe(+ join(root, "state", "scans", "repository-with-spaces"),+ );+ if (process.platform !== "win32") {+ expect((await stat(scanRoot)).mode & 0o777).toBe(0o700);+ }+ });++ test("runs workbench commands without credentials or generated bytecode", async () => {+ const root = await temporaryDirectory();+ const pluginRoot = join(root, "plugin");+ await mkdir(join(pluginRoot, "scripts"), { recursive: true });+ await writeFile(+ join(pluginRoot, "scripts", "workbench_db.py"),+ [+ "import json, os, sys",+ "assert sys.flags.isolated",+ "assert sys.dont_write_bytecode",+ "assert sys.argv[1] == 'test-command'",+ "assert os.environ.get('OPENAI_API_KEY') is None",+ "assert os.environ.get('CODEX_API_KEY') is None",+ "print(json.dumps({'ok': True}))",+ ].join("\n"),+ );+ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ const result = await runWorkbench(+ {+ python: python!,+ pluginRoot,+ environment: {+ PATH: process.env["PATH"],+ OPENAI_API_KEY: "must-not-reach-python",+ CODEX_API_KEY: "also-must-not-reach-python",+ },+ },+ ["test-command"],+ );+ expect(result).toEqual({ ok: true });+ });+testPosix("rejects private output directories owned by another user", () => {expect(() =>requirePrivateOutputDirectory(