@openai/codex-security 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/README.md +18 -12
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -0
  3. package/_bundled_plugin/examples/completed-scan/findings.json +34 -34
  4. package/_bundled_plugin/examples/completed-scan/report.md +22 -31
  5. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +27 -29
  6. package/_bundled_plugin/examples/{completed-scan → legacy-completed-scan}/coverage.json +1 -0
  7. package/_bundled_plugin/examples/legacy-completed-scan/findings.json +57 -0
  8. package/_bundled_plugin/examples/legacy-completed-scan/report.md +98 -0
  9. package/_bundled_plugin/examples/legacy-completed-scan/scan-manifest.json +43 -0
  10. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  11. package/_bundled_plugin/mcp/helpers.mjs.br.part-001 +0 -0
  12. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  13. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  14. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  15. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  16. package/_bundled_plugin/mcp/server.mjs.br.part-002 +0 -0
  17. package/_bundled_plugin/references/core-scan.md +2 -2
  18. package/_bundled_plugin/references/final-report.md +16 -6
  19. package/_bundled_plugin/references/scan-artifacts.md +6 -6
  20. package/_bundled_plugin/references/scan-contract.md +10 -12
  21. package/_bundled_plugin/references/threat-model.md +1 -1
  22. package/_bundled_plugin/schemas/scan-manifest.schema.json +36 -11
  23. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +5 -5
  24. package/_bundled_plugin/scripts/deep_scan_workbench.py +1 -1
  25. package/_bundled_plugin/scripts/finalize_scan_contract.py +97 -20
  26. package/_bundled_plugin/scripts/report_projection.py +5 -2
  27. package/_bundled_plugin/scripts/review_state.py +68 -0
  28. package/_bundled_plugin/scripts/servicenow_avit.py +107 -0
  29. package/_bundled_plugin/scripts/validate_scan_contract.py +1 -2
  30. package/_bundled_plugin/scripts/workbench/retained_coverage.py +49 -37
  31. package/_bundled_plugin/scripts/workbench/retained_records.py +7 -7
  32. package/_bundled_plugin/scripts/workbench/saved_coverage.py +15 -15
  33. package/_bundled_plugin/scripts/workbench/saved_sources.py +24 -6
  34. package/_bundled_plugin/scripts/workbench_constants.py +0 -1
  35. package/_bundled_plugin/scripts/workbench_coverage_receipts.py +4 -4
  36. package/_bundled_plugin/scripts/workbench_db.py +5 -150
  37. package/_bundled_plugin/scripts/workbench_saved_results.py +169 -4
  38. package/_bundled_plugin/scripts/workbench_scan_history.py +12 -7
  39. package/_bundled_plugin/scripts/workbench_scan_start.py +4 -1
  40. package/_bundled_plugin/skills/publish-findings/SKILL.md +9 -3
  41. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +1 -1
  42. package/_bundled_plugin/skills/security-scan/SKILL.md +7 -7
  43. package/_bundled_plugin/skills/track-findings/SKILL.md +1 -1
  44. package/dist/api.d.ts.map +1 -1
  45. package/dist/api.js +50 -27
  46. package/dist/api.js.map +1 -1
  47. package/dist/artifact-export.d.ts +12 -3
  48. package/dist/artifact-export.d.ts.map +1 -1
  49. package/dist/artifact-export.js +30 -10
  50. package/dist/artifact-export.js.map +1 -1
  51. package/dist/cli-help.d.ts.map +1 -1
  52. package/dist/cli-help.js +1 -0
  53. package/dist/cli-help.js.map +1 -1
  54. package/dist/cli.d.ts +1 -1
  55. package/dist/cli.d.ts.map +1 -1
  56. package/dist/cli.js +69 -55
  57. package/dist/cli.js.map +1 -1
  58. package/dist/cloud-publish.d.ts.map +1 -1
  59. package/dist/cloud-publish.js +2 -23
  60. package/dist/cloud-publish.js.map +1 -1
  61. package/dist/contract.d.ts +4 -2
  62. package/dist/contract.d.ts.map +1 -1
  63. package/dist/contract.js +39 -21
  64. package/dist/contract.js.map +1 -1
  65. package/dist/custom-publish.js +2 -2
  66. package/dist/custom-publish.js.map +1 -1
  67. package/dist/custom-validation-prompt.d.ts.map +1 -1
  68. package/dist/custom-validation-prompt.js +14 -6
  69. package/dist/custom-validation-prompt.js.map +1 -1
  70. package/dist/custom-validation.d.ts.map +1 -1
  71. package/dist/custom-validation.js +17 -15
  72. package/dist/custom-validation.js.map +1 -1
  73. package/dist/deduplication/codex-review.d.ts.map +1 -1
  74. package/dist/deduplication/codex-review.js +2 -2
  75. package/dist/deduplication/codex-review.js.map +1 -1
  76. package/dist/deduplication/deduplication-prompts.d.ts +1 -0
  77. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
  78. package/dist/deduplication/deduplication-prompts.js +3 -0
  79. package/dist/deduplication/deduplication-prompts.js.map +1 -1
  80. package/dist/deduplication/records-protocol.d.ts.map +1 -1
  81. package/dist/deduplication/records-protocol.js +21 -1
  82. package/dist/deduplication/records-protocol.js.map +1 -1
  83. package/dist/deduplication/scan.d.ts.map +1 -1
  84. package/dist/deduplication/scan.js +2 -2
  85. package/dist/deduplication/scan.js.map +1 -1
  86. package/dist/external-findings-local.d.ts +1 -0
  87. package/dist/external-findings-local.d.ts.map +1 -1
  88. package/dist/external-findings-local.js +25 -2
  89. package/dist/external-findings-local.js.map +1 -1
  90. package/dist/external-findings-publish.d.ts +1 -0
  91. package/dist/external-findings-publish.d.ts.map +1 -1
  92. package/dist/external-findings-publish.js +55 -26
  93. package/dist/external-findings-publish.js.map +1 -1
  94. package/dist/external-findings-read.d.ts +1 -0
  95. package/dist/external-findings-read.d.ts.map +1 -1
  96. package/dist/external-findings-read.js +10 -0
  97. package/dist/external-findings-read.js.map +1 -1
  98. package/dist/external-findings.d.ts +2 -0
  99. package/dist/external-findings.d.ts.map +1 -1
  100. package/dist/external-findings.js.map +1 -1
  101. package/dist/external-import-contract.d.ts +4 -0
  102. package/dist/external-import-contract.d.ts.map +1 -1
  103. package/dist/external-import-contract.js +34 -10
  104. package/dist/external-import-contract.js.map +1 -1
  105. package/dist/finding-workflow.d.ts +2 -0
  106. package/dist/finding-workflow.d.ts.map +1 -1
  107. package/dist/finding-workflow.js +3 -0
  108. package/dist/finding-workflow.js.map +1 -1
  109. package/dist/github-advisories.d.ts.map +1 -1
  110. package/dist/github-advisories.js +5 -5
  111. package/dist/github-advisories.js.map +1 -1
  112. package/dist/github-dependabot-findings.d.ts +6 -0
  113. package/dist/github-dependabot-findings.d.ts.map +1 -0
  114. package/dist/github-dependabot-findings.js +247 -0
  115. package/dist/github-dependabot-findings.js.map +1 -0
  116. package/dist/github-findings.d.ts.map +1 -1
  117. package/dist/github-findings.js +11 -4
  118. package/dist/github-findings.js.map +1 -1
  119. package/dist/github-identifiers.d.ts +4 -0
  120. package/dist/github-identifiers.d.ts.map +1 -0
  121. package/dist/github-identifiers.js +9 -0
  122. package/dist/github-identifiers.js.map +1 -0
  123. package/dist/github.d.ts.map +1 -1
  124. package/dist/github.js +4 -6
  125. package/dist/github.js.map +1 -1
  126. package/dist/host-protocol.d.ts +1 -1
  127. package/dist/host-protocol.d.ts.map +1 -1
  128. package/dist/host-protocol.js +2 -2
  129. package/dist/host-protocol.js.map +1 -1
  130. package/dist/hosted-scan.d.ts.map +1 -1
  131. package/dist/hosted-scan.js +13 -6
  132. package/dist/hosted-scan.js.map +1 -1
  133. package/dist/import-scan.js +16 -16
  134. package/dist/import-scan.js.map +1 -1
  135. package/dist/index.d.ts +2 -0
  136. package/dist/index.d.ts.map +1 -1
  137. package/dist/index.js +2 -0
  138. package/dist/index.js.map +1 -1
  139. package/dist/knowledge-base.js +3 -0
  140. package/dist/knowledge-base.js.map +1 -1
  141. package/dist/mock-scan.d.ts +1 -2
  142. package/dist/mock-scan.d.ts.map +1 -1
  143. package/dist/mock-scan.js +12 -17
  144. package/dist/mock-scan.js.map +1 -1
  145. package/dist/models.d.ts +9 -1
  146. package/dist/models.d.ts.map +1 -1
  147. package/dist/models.js.map +1 -1
  148. package/dist/multiscan.d.ts.map +1 -1
  149. package/dist/multiscan.js +1 -6
  150. package/dist/multiscan.js.map +1 -1
  151. package/dist/native-json-findings.d.ts +30 -0
  152. package/dist/native-json-findings.d.ts.map +1 -0
  153. package/dist/native-json-findings.js +114 -0
  154. package/dist/native-json-findings.js.map +1 -0
  155. package/dist/opengrep-findings.d.ts +10 -0
  156. package/dist/opengrep-findings.d.ts.map +1 -0
  157. package/dist/opengrep-findings.js +198 -0
  158. package/dist/opengrep-findings.js.map +1 -0
  159. package/dist/patch-tui.d.ts.map +1 -1
  160. package/dist/patch-tui.js +2 -0
  161. package/dist/patch-tui.js.map +1 -1
  162. package/dist/publication.js +1 -2
  163. package/dist/publication.js.map +1 -1
  164. package/dist/record.d.ts +1 -0
  165. package/dist/record.d.ts.map +1 -1
  166. package/dist/record.js +10 -0
  167. package/dist/record.js.map +1 -1
  168. package/dist/result.d.ts +5 -3
  169. package/dist/result.d.ts.map +1 -1
  170. package/dist/result.js +9 -6
  171. package/dist/result.js.map +1 -1
  172. package/dist/scan-history-renderer.js +1 -1
  173. package/dist/scan-history-renderer.js.map +1 -1
  174. package/dist/scanner-import.d.ts +0 -1
  175. package/dist/scanner-import.d.ts.map +1 -1
  176. package/dist/scanner-import.js +9 -9
  177. package/dist/scanner-import.js.map +1 -1
  178. package/dist/security-policy.d.ts.map +1 -1
  179. package/dist/security-policy.js +16 -2
  180. package/dist/security-policy.js.map +1 -1
  181. package/dist/semgrep-findings.d.ts.map +1 -1
  182. package/dist/semgrep-findings.js +15 -82
  183. package/dist/semgrep-findings.js.map +1 -1
  184. package/docs/cli.md +55 -10
  185. package/docs/dedupe-records.md +15 -1
  186. package/docs/hosted-scans.md +14 -0
  187. package/package.json +5 -5
@@ -19,7 +19,6 @@ FINDING_CLOSE_REASONS = ("already_fixed", "wont_fix", "false_positive")
19
19
  REMEDIATION_UPDATE_STATES = ("generated", "applied", "verifying", "verified", "failed")
20
20
  EXPORT_FORMATS = ("csv", "json", "sarif")
21
21
  ARTIFACTS = {
22
- "coverage": "coverage.json",
23
22
  "findings": "findings.json",
24
23
  "manifest": "scan-manifest.json",
25
24
  "markdownReport": "report.md",
@@ -116,7 +116,7 @@ def retain_recorded_receipt_ownership(
116
116
  continue
117
117
  if payload_digest(draft) in recorded.get(directory, set()):
118
118
  continue
119
- surfaces = draft["coverage"].get("surfaces", [])
119
+ surfaces = draft["reviewState"].get("surfaces", [])
120
120
  for surface in surfaces if isinstance(surfaces, list) else []:
121
121
  if isinstance(surface, dict) and isinstance(surface.get("provenance"), dict):
122
122
  surface["provenance"].pop("scanReceiptRefs", None)
@@ -240,7 +240,7 @@ def _generic_surface_updates(
240
240
 
241
241
  saved_surfaces: dict[tuple[str | None, str], list[tuple[str, dict[str, Any]]]] = {}
242
242
  for relative, draft, owner in sources:
243
- rows = draft["coverage"].get("surfaces", [])
243
+ rows = draft["reviewState"].get("surfaces", [])
244
244
  for row in rows if isinstance(rows, list) else []:
245
245
  if isinstance(row, dict) and isinstance(row.get("id"), str):
246
246
  saved_surfaces.setdefault(record_key("surfaces", owner, row), []).append(
@@ -270,7 +270,7 @@ def _generic_surface_updates(
270
270
  == record_order(latest_source, key[0], latest_surface)
271
271
  )
272
272
  for relative, draft, owner in sources:
273
- rows = draft["coverage"].get("surfaces", [])
273
+ rows = draft["reviewState"].get("surfaces", [])
274
274
  for row in rows if isinstance(rows, list) else []:
275
275
  if (
276
276
  isinstance(row, dict)
@@ -296,7 +296,7 @@ def _generic_surface_updates(
296
296
  normalized = _require_portable_relative_path(ref, "Saved coverage receipt")
297
297
  receipt_paths.setdefault(normalized.lower(), normalized)
298
298
  for relative, draft, owner in sources:
299
- current = draft["coverage"].get("surfaces", [])
299
+ current = draft["reviewState"].get("surfaces", [])
300
300
  for surface in current if isinstance(current, list) else []:
301
301
  if not isinstance(surface, dict):
302
302
  continue
@@ -51,10 +51,8 @@ from finalize_scan_contract import (
51
51
  _prepare_scan_finalization,
52
52
  _write_prepared_scan_finalization,
53
53
  finalize_scan,
54
- finding_candidate_id,
55
54
  manifest_is_sealed,
56
55
  open_scan_local_file_descriptor,
57
- write_scan_local_bytes,
58
56
  )
59
57
  from finding_preview import bounded_finding_details
60
58
  from workbench import handoff
@@ -1355,151 +1353,9 @@ def budget_exhausted_candidates(scan: sqlite3.Row, scan_dir: Path) -> list[dict[
1355
1353
 
1356
1354
 
1357
1355
  def budget_exhausted_draft(
1358
- scan: sqlite3.Row,
1359
- scan_dir: Path,
1360
- candidates: list[dict[str, Any]],
1361
- warning: str,
1356
+ scan: sqlite3.Row, scan_dir: Path, candidates: list[dict[str, Any]], warning: str
1362
1357
  ) -> None:
1363
- documents: dict[str, dict[str, Any]] = {}
1364
- for name in ("scan-manifest.json", "findings.json", "coverage.json"):
1365
- path = artifact_path(scan_dir, name, required=False)
1366
- if path is not None:
1367
- documents[name] = read_json_object(path)
1368
- if documents and len(documents) != 3:
1369
- raise SystemExit("Budget-exhausted scan contains an incomplete canonical scan draft.")
1370
-
1371
- if documents:
1372
- manifest = documents["scan-manifest.json"]
1373
- findings = documents["findings.json"]
1374
- coverage = documents["coverage.json"]
1375
- if not isinstance(manifest.get("scan"), dict) or not isinstance(
1376
- findings.get("findings"), list
1377
- ):
1378
- raise SystemExit("Budget-exhausted scan contains an invalid canonical scan draft.")
1379
- for key in ("surfaces", "explicitExclusions", "deferred"):
1380
- if not isinstance(coverage.get(key), list):
1381
- raise SystemExit("Budget-exhausted scan contains invalid canonical coverage.")
1382
- if manifest_is_sealed(manifest["scan"]):
1383
- raise SystemExit("Budget-exhausted scan cannot replace an already sealed scan draft.")
1384
- else:
1385
- contract = scan_contract(scan)
1386
- target_contract = contract["target"]
1387
- target: dict[str, Any] = {
1388
- "kind": target_contract["allowedKinds"][0],
1389
- "targetId": target_contract["targetId"],
1390
- "displayName": target_contract["displayName"],
1391
- }
1392
- if scan["target_revision"] != "unversioned":
1393
- target["revision"] = scan["target_revision"]
1394
- if "requiredSnapshotDigest" in target_contract:
1395
- target["snapshotDigest"] = target_contract["requiredSnapshotDigest"]
1396
- manifest = {
1397
- "scan": {
1398
- "target": target,
1399
- "scope": {"limitations": [warning]},
1400
- }
1401
- }
1402
- findings = {"findings": []}
1403
- coverage = {
1404
- "inventoryStrategy": (
1405
- "scoped_path" if expected_coverage_mode(scan) == "scoped_path" else "repository"
1406
- ),
1407
- "surfaces": [],
1408
- "explicitExclusions": [],
1409
- "deferred": [],
1410
- }
1411
-
1412
- findings_by_candidate = {
1413
- candidate_id
1414
- for finding in findings["findings"]
1415
- if isinstance(finding, dict)
1416
- and isinstance(candidate_id := finding_candidate_id(finding), str)
1417
- }
1418
- existing_deferred = {
1419
- item.get("candidateId", item.get("id"))
1420
- for item in coverage["deferred"]
1421
- if isinstance(item, dict) and isinstance(item.get("candidateId", item.get("id")), str)
1422
- }
1423
- existing_surfaces = {
1424
- item.get("id")
1425
- for item in coverage["surfaces"]
1426
- if isinstance(item, dict) and isinstance(item.get("id"), str)
1427
- }
1428
- for candidate in candidates:
1429
- candidate_id = candidate["candidate_id"]
1430
- if candidate_id in findings_by_candidate or candidate_id in existing_deferred:
1431
- continue
1432
- paths = list(dict.fromkeys(location["path"] for location in candidate["locations"]))
1433
- surface_id = f"candidate-{candidate_id}"
1434
- validation = candidate.get("validation")
1435
- validation = validation.get("disposition") if isinstance(validation, dict) else None
1436
- attack = candidate.get("attack_path")
1437
- attack = attack.get("decision") if isinstance(attack, dict) else None
1438
- disposition = (
1439
- "needs_follow_up"
1440
- if validation == "deferred" or attack == "deferred"
1441
- else "not_applicable"
1442
- if validation == "not_applicable"
1443
- else "rejected"
1444
- if validation == "suppressed" or attack == "ignore"
1445
- else "needs_follow_up"
1446
- )
1447
- if surface_id not in existing_surfaces:
1448
- coverage["surfaces"].append(
1449
- {
1450
- "id": surface_id,
1451
- "label": candidate["summary"],
1452
- "disposition": disposition,
1453
- "notes": candidate["evidence"],
1454
- "receiptRefs": [],
1455
- }
1456
- )
1457
- existing_surfaces.add(surface_id)
1458
- if disposition != "needs_follow_up":
1459
- continue
1460
- coverage["deferred"].append(
1461
- {
1462
- "id": candidate_id,
1463
- "candidateId": candidate_id,
1464
- "reason": (
1465
- "Validation was deferred because the scan reached its cost limit: "
1466
- f"{candidate['summary']}. Evidence: {candidate['evidence']}"
1467
- ),
1468
- "paths": paths,
1469
- "surfaceIds": [surface_id],
1470
- }
1471
- )
1472
- if not any(
1473
- isinstance(item, dict)
1474
- and isinstance(reason := item.get("reason"), str)
1475
- and (
1476
- reason == "Validation was deferred because the scan reached its cost limit."
1477
- or reason.startswith(
1478
- "Validation was deferred because the scan reached its cost limit: "
1479
- )
1480
- )
1481
- for item in coverage["deferred"]
1482
- ):
1483
- coverage["deferred"].append(
1484
- {
1485
- "id": "scan-cost-limit",
1486
- "reason": "Validation was deferred because the scan reached its cost limit.",
1487
- }
1488
- )
1489
- coverage.pop("completeness", None)
1490
- for name, payload in (
1491
- ("findings.json", findings),
1492
- ("coverage.json", coverage),
1493
- ("scan-manifest.json", manifest),
1494
- ):
1495
- try:
1496
- write_scan_local_bytes(
1497
- scan_dir,
1498
- name,
1499
- (json.dumps(payload, allow_nan=False, indent=2, sort_keys=True) + "\n").encode(),
1500
- )
1501
- except (ContractError, OSError, TypeError, ValueError) as exc:
1502
- raise SystemExit(f"Budget-exhausted scan draft could not be saved: {exc}") from exc
1358
+ saved_results.budget_exhausted_draft(sys.modules[__name__], scan, scan_dir, candidates, warning)
1503
1359
 
1504
1360
 
1505
1361
  def complete_scan_locked(
@@ -1552,7 +1408,6 @@ def complete_scan_locked(
1552
1408
  for file_name in (
1553
1409
  ARTIFACTS["manifest"],
1554
1410
  ARTIFACTS["findings"],
1555
- ARTIFACTS["coverage"],
1556
1411
  ):
1557
1412
  try:
1558
1413
  (scan_dir / file_name).lstat()
@@ -1613,9 +1468,9 @@ def complete_scan_locked(
1613
1468
  )
1614
1469
  warnings.extend(warning for warning in prepared.warnings if warning not in warnings)
1615
1470
  add_warning()
1616
- if prepared.warnings:
1617
- # Save the explanation before publication removes the broken reference,
1618
- # so a retry after failed publication retains it.
1471
+ if warnings != json.loads(scan["completion_warnings_json"]):
1472
+ # Persist all observed warnings before output writes can fail, so
1473
+ # stopped-result publication and retries retain those diagnostics.
1619
1474
  with connection:
1620
1475
  connection.execute(
1621
1476
  "UPDATE scans SET completion_warnings_json = ? WHERE id = ? AND status = 'running'",
@@ -38,6 +38,7 @@ from finalize_scan_contract import (
38
38
  write_threat_model_projection_if_possible,
39
39
  )
40
40
  from finalize_scan_contract import finding_candidate_id as finding_candidate_id
41
+ from review_state import checkpoint_review_state, review_state, review_summary, uses_legacy_review
41
42
  from workbench.retained_coverage import (
42
43
  _append_previous_finding as _append_previous_finding,
43
44
  )
@@ -606,6 +607,7 @@ def preserve_deep_deadline_draft(
606
607
  manifest, findings, coverage = prepared.manifest, prepared.findings, prepared.coverage
607
608
  manifest["scan"].pop("sealedAt", None)
608
609
  manifest["scan"].pop("artifacts", None)
610
+ manifest["scan"]["reviewState"] = checkpoint_review_state(coverage)
609
611
  checkpoint = _parent_scan_draft(scan["id"], manifest["scan"], findings, coverage)
610
612
  contents = _encoded(checkpoint)
611
613
  name = f"{hashlib.sha256(contents).hexdigest()}.json"
@@ -617,7 +619,7 @@ def preserve_deep_deadline_draft(
617
619
  write_scan_local_bytes(scan_dir, "checkpoint-head.json", _encoded({"checkpoint": name}))
618
620
  for filename, document in (
619
621
  ("findings.json", findings),
620
- ("coverage.json", coverage),
622
+ *([("coverage.json", coverage)] if "coverageRef" in manifest["scan"] else []),
621
623
  ("scan-manifest.json", manifest),
622
624
  ):
623
625
  write_scan_local_bytes(scan_dir, filename, _encoded(document))
@@ -1102,12 +1104,20 @@ def write_scan_draft(db: Any, connection: Any, args: Any) -> dict[str, Any]:
1102
1104
  draft = _read_scan_local_json(scan_dir, relative, "Staged scan draft")
1103
1105
  accepted_input = copy.deepcopy(draft)
1104
1106
  accepted_checkpoint = None
1105
- manifest, findings, coverage = draft["manifest"], draft["findings"], draft["coverage"]
1107
+ manifest, findings, coverage = (
1108
+ draft["manifest"],
1109
+ draft["findings"],
1110
+ draft.get("reviewState", draft.get("coverage")),
1111
+ )
1112
+ manifest["scan"]["reviewState"] = checkpoint_review_state(coverage)
1113
+ manifest["scan"].pop("coverageRef", None)
1106
1114
  binding = db.workbench_completion_binding(scan, db.now())
1107
1115
  # Save scan IDs without sealing the draft.
1108
1116
  _populate_unsealed_manifest_envelope(manifest, manifest["scan"], binding)
1109
1117
  _populate_unsealed_artifact_envelope(manifest, findings, coverage, binding)
1110
1118
  _validate_completion_binding(manifest, findings, coverage, binding)
1119
+ manifest["scan"]["mode"] = coverage["mode"]
1120
+ manifest["scan"]["review"] = review_summary(coverage)
1111
1121
  projected = _parent_scan_draft(scan_id, manifest["scan"], findings, coverage)
1112
1122
  admitted_input = None
1113
1123
  checkpoint = manifest["scan"]
@@ -1202,12 +1212,12 @@ def write_scan_draft(db: Any, connection: Any, args: Any) -> dict[str, Any]:
1202
1212
  filename: (json.dumps(document, allow_nan=False, indent=2) + "\n").encode()
1203
1213
  for filename, document in (
1204
1214
  ("findings.json", findings),
1205
- ("coverage.json", coverage),
1206
1215
  ("scan-manifest.json", manifest),
1207
1216
  )
1208
1217
  }
1209
1218
  for filename, contents in documents.items():
1210
1219
  write_scan_local_bytes(scan_dir, filename, contents)
1220
+ _remove_scan_local_file_if_exists(scan_dir, "coverage.json")
1211
1221
  if scan["mode"] == "deep" and manifest["scan"].get("complete") is not False:
1212
1222
  # Select the accepted final publication before releasing the write lock.
1213
1223
  with connection:
@@ -1286,7 +1296,7 @@ def _scan_draft_contents_digest(documents: dict[str, bytes | None]) -> str:
1286
1296
  for filename in ("scan-manifest.json", "findings.json", "coverage.json"):
1287
1297
  digest.update(filename.encode())
1288
1298
  digest.update(b"\0")
1289
- contents = documents[filename]
1299
+ contents = documents.get(filename)
1290
1300
  if contents is None:
1291
1301
  digest.update(b"missing\0")
1292
1302
  else:
@@ -1402,3 +1412,158 @@ def preserve_stopped_results_after_transition(db: Any, connection: Any, scan_id:
1402
1412
 
1403
1413
  if __name__ == "__main__":
1404
1414
  argparse.ArgumentParser(description=__doc__).parse_args()
1415
+
1416
+
1417
+ def budget_exhausted_draft(
1418
+ db: Any,
1419
+ scan: sqlite3.Row,
1420
+ scan_dir: Path,
1421
+ candidates: list[dict[str, Any]],
1422
+ warning: str,
1423
+ ) -> None:
1424
+ documents: dict[str, dict[str, Any]] = {}
1425
+ for name in ("scan-manifest.json", "findings.json"):
1426
+ path = db.artifact_path(scan_dir, name, required=False)
1427
+ if path is not None:
1428
+ documents[name] = db.read_json_object(path)
1429
+ if documents and len(documents) != 2:
1430
+ raise SystemExit("Budget-exhausted scan contains an incomplete canonical scan draft.")
1431
+
1432
+ if documents:
1433
+ manifest = documents["scan-manifest.json"]
1434
+ findings = documents["findings.json"]
1435
+ coverage = (
1436
+ db.read_json_object(db.artifact_path(scan_dir, "coverage.json", required=True))
1437
+ if uses_legacy_review(manifest["scan"])
1438
+ else review_state(manifest["scan"])
1439
+ )
1440
+ if not isinstance(manifest.get("scan"), dict) or not isinstance(
1441
+ findings.get("findings"), list
1442
+ ):
1443
+ raise SystemExit("Budget-exhausted scan contains an invalid canonical scan draft.")
1444
+ for key in ("surfaces", "explicitExclusions", "deferred"):
1445
+ if not isinstance(coverage.get(key), list):
1446
+ raise SystemExit("Budget-exhausted scan contains invalid canonical coverage.")
1447
+ if manifest_is_sealed(manifest["scan"]):
1448
+ raise SystemExit("Budget-exhausted scan cannot replace an already sealed scan draft.")
1449
+ else:
1450
+ contract = db.scan_contract(scan)
1451
+ target_contract = contract["target"]
1452
+ target: dict[str, Any] = {
1453
+ "kind": target_contract["allowedKinds"][0],
1454
+ "targetId": target_contract["targetId"],
1455
+ "displayName": target_contract["displayName"],
1456
+ }
1457
+ if scan["target_revision"] != "unversioned":
1458
+ target["revision"] = scan["target_revision"]
1459
+ if "requiredSnapshotDigest" in target_contract:
1460
+ target["snapshotDigest"] = target_contract["requiredSnapshotDigest"]
1461
+ manifest = {
1462
+ "scan": {
1463
+ "target": target,
1464
+ "scope": {"limitations": [warning]},
1465
+ }
1466
+ }
1467
+ findings = {"findings": []}
1468
+ coverage = {
1469
+ "inventoryStrategy": (
1470
+ "scoped_path" if db.expected_coverage_mode(scan) == "scoped_path" else "repository"
1471
+ ),
1472
+ "surfaces": [],
1473
+ "explicitExclusions": [],
1474
+ "deferred": [],
1475
+ }
1476
+
1477
+ findings_by_candidate = {
1478
+ candidate_id
1479
+ for finding in findings["findings"]
1480
+ if isinstance(finding, dict)
1481
+ and isinstance(candidate_id := finding_candidate_id(finding), str)
1482
+ }
1483
+ existing_deferred = {
1484
+ item.get("candidateId", item.get("id"))
1485
+ for item in coverage["deferred"]
1486
+ if isinstance(item, dict) and isinstance(item.get("candidateId", item.get("id")), str)
1487
+ }
1488
+ existing_surfaces = {
1489
+ item.get("id")
1490
+ for item in coverage["surfaces"]
1491
+ if isinstance(item, dict) and isinstance(item.get("id"), str)
1492
+ }
1493
+ for candidate in candidates:
1494
+ candidate_id = candidate["candidate_id"]
1495
+ if candidate_id in findings_by_candidate or candidate_id in existing_deferred:
1496
+ continue
1497
+ paths = list(dict.fromkeys(location["path"] for location in candidate["locations"]))
1498
+ surface_id = f"candidate-{candidate_id}"
1499
+ validation = candidate.get("validation")
1500
+ validation = validation.get("disposition") if isinstance(validation, dict) else None
1501
+ attack = candidate.get("attack_path")
1502
+ attack = attack.get("decision") if isinstance(attack, dict) else None
1503
+ disposition = (
1504
+ "needs_follow_up"
1505
+ if validation == "deferred" or attack == "deferred"
1506
+ else "not_applicable"
1507
+ if validation == "not_applicable"
1508
+ else "rejected"
1509
+ if validation == "suppressed" or attack == "ignore"
1510
+ else "needs_follow_up"
1511
+ )
1512
+ if surface_id not in existing_surfaces:
1513
+ coverage["surfaces"].append(
1514
+ {
1515
+ "id": surface_id,
1516
+ "label": candidate["summary"],
1517
+ "disposition": disposition,
1518
+ "notes": candidate["evidence"],
1519
+ "receiptRefs": [],
1520
+ }
1521
+ )
1522
+ existing_surfaces.add(surface_id)
1523
+ if disposition != "needs_follow_up":
1524
+ continue
1525
+ coverage["deferred"].append(
1526
+ {
1527
+ "id": candidate_id,
1528
+ "candidateId": candidate_id,
1529
+ "reason": (
1530
+ "Validation was deferred because the scan reached its cost limit: "
1531
+ f"{candidate['summary']}. Evidence: {candidate['evidence']}"
1532
+ ),
1533
+ "paths": paths,
1534
+ "surfaceIds": [surface_id],
1535
+ }
1536
+ )
1537
+ if not any(
1538
+ isinstance(item, dict)
1539
+ and isinstance(reason := item.get("reason"), str)
1540
+ and (
1541
+ reason == "Validation was deferred because the scan reached its cost limit."
1542
+ or reason.startswith(
1543
+ "Validation was deferred because the scan reached its cost limit: "
1544
+ )
1545
+ )
1546
+ for item in coverage["deferred"]
1547
+ ):
1548
+ coverage["deferred"].append(
1549
+ {
1550
+ "id": "scan-cost-limit",
1551
+ "reason": "Validation was deferred because the scan reached its cost limit.",
1552
+ }
1553
+ )
1554
+ coverage.pop("completeness", None)
1555
+ manifest["scan"].pop("coverageRef", None)
1556
+ manifest["scan"]["mode"] = db.expected_coverage_mode(scan)
1557
+ manifest["scan"]["reviewState"] = checkpoint_review_state(coverage)
1558
+ for name, payload in (
1559
+ ("findings.json", findings),
1560
+ ("scan-manifest.json", manifest),
1561
+ ):
1562
+ try:
1563
+ write_scan_local_bytes(
1564
+ scan_dir,
1565
+ name,
1566
+ (json.dumps(payload, allow_nan=False, indent=2, sort_keys=True) + "\n").encode(),
1567
+ )
1568
+ except (ContractError, OSError, TypeError, ValueError) as exc:
1569
+ raise SystemExit(f"Budget-exhausted scan draft could not be saved: {exc}") from exc
@@ -23,6 +23,7 @@ from finalize_scan_contract import (
23
23
  manifest_is_sealed,
24
24
  )
25
25
  from report_projection import SEVERITY_ORDER
26
+ from review_state import review_state
26
27
  from workbench_constants import ARTIFACTS, FINDINGS_PAGE_MAX
27
28
  from workbench_scan_start import scan_target_identity
28
29
  from workbench_scan_usage import stored_scan_cost_fields
@@ -147,7 +148,7 @@ def coverage_summary_for_history(
147
148
  wb: Any, scan: sqlite3.Row, canonical_scan_directory: Callable[[Path], Path]
148
149
  ) -> dict[str, Any]:
149
150
  scan_dir = canonical_scan_directory(Path(scan["scan_dir"]))
150
- coverage_ref = ARTIFACTS["coverage"]
151
+ coverage_ref = "coverage.json"
151
152
  try:
152
153
  if scan["seal_manifest_digest"] is None:
153
154
  # Older workbench rows can have valid seals without a pinned digest.
@@ -157,7 +158,7 @@ def coverage_summary_for_history(
157
158
  raise ContractError("coverage.mode: must match the workbench scan")
158
159
  else:
159
160
  # Completion already validated the full scan. History only needs the
160
- # pinned manifest and its coverage artifact, not findings or receipts.
161
+ # pinned manifest and any legacy coverage artifact, not findings or receipts.
161
162
  manifest, manifest_bytes = _read_scan_local_json_bytes(
162
163
  scan_dir, ARTIFACTS["manifest"], ARTIFACTS["manifest"]
163
164
  )
@@ -167,11 +168,15 @@ def coverage_summary_for_history(
167
168
  ):
168
169
  raise ContractError("The sealed scan manifest changed after completion.")
169
170
  sealed_scan = manifest["scan"]
170
- if (
171
- sealed_scan["id"] != scan["id"]
172
- or not sealed_scan.get("sealedAt")
173
- or sealed_scan["coverageRef"] != coverage_ref
174
- ):
171
+ if sealed_scan["id"] != scan["id"] or not sealed_scan.get("sealedAt"):
172
+ raise ContractError("The sealed coverage does not belong to this scan.")
173
+ if "coverageRef" not in sealed_scan:
174
+ coverage = review_state(sealed_scan)
175
+ return {
176
+ key: coverage[key]
177
+ for key in ("mode", "includePaths", "excludePaths", "explicitExclusions")
178
+ }
179
+ if sealed_scan["coverageRef"] != coverage_ref:
175
180
  raise ContractError("The sealed coverage does not belong to this scan.")
176
181
  coverage, coverage_bytes = _read_scan_local_json_bytes(
177
182
  scan_dir, coverage_ref, coverage_ref
@@ -30,7 +30,10 @@ from workbench_validation import optional_text
30
30
 
31
31
 
32
32
  def safe_segment(value: str) -> str:
33
- return re.sub(r"[^\w.-]", "-", value).strip("-") or "scan"
33
+ segment = re.sub(r"[^\w.-]", "-", value)
34
+ if segment != value:
35
+ segment = segment.strip("-")
36
+ return segment or "scan"
34
37
 
35
38
 
36
39
  def compact_timestamp() -> str:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: publish-findings
3
- description: Disabled by default; requires user opt-in with CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1. Import selected Snyk Open Source findings, Semgrep Code CLI/CI reports, Endor Labs findings, GitHub code-scanning alerts or GHSA advisories, or Wiz package vulnerabilities, SAST, repository secrets, and IaC findings locally or to Codex Security Cloud after previewing the destination and evidence. Prefers native JSON; also supports Snyk plugin SCA bundles, Snyk Open Source and Semgrep Code SARIF, endorctl SARIF, saved GitHub JSON/JSONL, Wiz normalized JSONL and repository package-vulnerability CSV, and gzip; does not import workload secrets or cloud configuration, run a scan, assess findings, or synchronize triage decisions.
3
+ description: Requires explicit opt-in with CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1. Preview and import scanner findings into the local workbench or Codex Security Cloud. Use the selected provider's documented export format.
4
4
  ---
5
5
 
6
6
  # Publish external findings
@@ -80,12 +80,18 @@ Import the native report with `--provider semgrep`, a stable organization/projec
80
80
 
81
81
  Keep supplied fingerprints. Reimporting the same fingerprint after code moves updates the existing source record with the new range. If the fingerprint is absent or `requires login`, the fallback uses rule, literal path and range: movement creates a second retained record, and the earlier record remains stored. Do not infer a merge or deletion. Read the persisted evidence with `codex-security findings imported /path/to/project --format json` before assessment. Source rule, CWE, snippets, traces and status are vendor evidence, not Codex assessments. Do not infer a report revision from the current checkout. Resolve scan errors and review all exclusions before uploading; do not remove error metadata to force acceptance.
82
82
 
83
+ ## OpenGrep
84
+
85
+ Import native OpenGrep JSON with `--provider opengrep`, `--source-repository-url`, and a stable OpenGrep-specific `--source-key`. Preview the destination and scan diagnostics before importing. Local and Cloud imports use the Semgrep provider and retain OpenGrep as the scanner origin.
86
+
83
87
  ## GitHub alerts and advisories
84
88
 
85
- Acquire code-scanning findings with `codex-security import github OWNER/REPO --format json` and save its complete JSON output for local import or Cloud publication. This existing collector completes pagination, fetches alert details, and retains the selected ref's instance. In Codex, use the official [GitHub Codex plugin](https://github.com/openai/plugins/tree/main/plugins/github) for discovery and selecting alerts, then pass that selection to the collector. Its GitHub MCP server paginates each list call separately. Do not ask the user to download JSON from a website or reconstruct an import envelope from MCP summaries; raw MCP/API responses are not accepted by `--provider github`.
89
+ Acquire code-scanning findings with `codex-security import github OWNER/REPO --format json` and save its complete JSON output for local import or Cloud publication. This existing collector completes pagination, fetches alert details, and retains the selected ref's instance. In Codex, use the official [GitHub Codex plugin](https://github.com/openai/plugins/tree/main/plugins/github) for discovery and selecting alerts, then pass that selection to the collector. Its GitHub MCP server paginates each list call separately. Do not ask the user to download JSON from a website or reconstruct a code-scanning import envelope from MCP summaries. Use the saved collector output for code-scanning alerts.
86
90
 
87
91
  The importer uses the user's GitHub CLI authentication and `GH_HOST`; plugin authentication is separate. It defaults to open alerts on the default branch. Use repeated `--github-alert NUMBER` for exact alerts or `--github-ref REF` for another ref. Save complete output without field/token filters or `--full-output`. Reading code-scanning alerts requires a token with Code scanning alerts read permission (classic: `security_events`, or `public_repo` for public repositories), along with repository access.
88
92
 
93
+ For Dependabot, follow the [repository alert export guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-dependabot.md) to save the native REST alert records from one repository. The read-only export requires Dependabot alerts read permission. Preview the file with `publish findings FILE --provider github`, the intended destination and a separate source key such as `github.com/example/project/dependabot`.
94
+
89
95
  **GHSA import stages advisory evidence for investigation; it does not establish an installed dependency or applicability to the destination repository.** Keep advisories separate from code scanning. `codex-security import github-advisories OWNER/REPO --format json` reads published repository disclosures by default. Repeated `--github-advisory GHSA-xxxx-xxxx-xxxx` selects exact IDs; `--github-state draft|triage|closed` explicitly selects an unpublished list and cannot be combined with exact IDs. Add `--github-advisory-source global` for exact public database IDs. This does not enumerate the global database. Private advisory access needs Repository security advisories read permission and access to those records. Stop on a read failure instead of publishing an incomplete selection.
90
96
 
91
97
  ```sh
@@ -107,7 +113,7 @@ codex-security publish findings /path/to/advisories.json \
107
113
 
108
114
  Choose the local or Cloud preview for the intended destination. GHSA input supports the same choice: use `--to local --repository /path/to/project` with the advisory file and source key. Follow [local imports](#import-locally) for confirmation and readback or [Cloud publication](#publish-to-cloud) for upload review.
109
115
 
110
- Use separate stable source keys for the two families. Code-scanning identities include the ref; repository alerts and advisories must match the selected Cloud repository or, when available, a configured local Git remote. Global advisories omit source-repository provenance and are bound to the explicit local or Cloud destination for investigation. Preserve original evidence, package ranges and patches; do not infer installed packages or source locations from an advisory. Missing security severity stays `unknown`. Dismissal, resolution and withdrawal are source state, not Codex assessment. This path does not import Dependabot or secret-scanning alerts or write back to GitHub.
116
+ Use a separate stable source key for each GitHub finding family. Code-scanning identities include the ref; repository alerts and advisories must match the selected Cloud repository or, when available, a configured local Git remote. Global advisories omit source-repository provenance and are bound to the explicit local or Cloud destination for investigation. Preserve original evidence, package ranges and patches; do not infer installed packages or source locations from an advisory. Missing security severity stays `unknown`. Dismissal, resolution and withdrawal are source state, not Codex assessment. Secret-scanning alerts and writeback to GitHub are outside this workflow.
111
117
 
112
118
  ## Publish to Cloud
113
119
 
@@ -29,7 +29,7 @@ Use `cancel_codex_security_scan` only when the user explicitly cancels. Reserve
29
29
  2. Prepare the changed-file list with `prepare_codex_security_review_items` and read all pages from `list_codex_security_review_items`. Review supporting unchanged files only as needed to explain changed behavior.
30
30
  3. Run `$finding-discovery` in compact diff mode across that inventory. Divide independent assignments among available workers and review unassigned files yourself. Keep independently vulnerable instances addressable and record all candidates once with `record_codex_security_discovery_candidates`. Do not create ranked worklists, per-finding ledgers, or discovery reports.
31
31
  4. If candidates exist, run `$validation` once, then `$attack-path-analysis` once for candidates marked `reportable` or `deferred`. Preserve locations, evidence, affected instances, and unresolved questions.
32
- 5. Read `../../references/final-report.md` for the finding, coverage, and completion contract. Save `complete: false` semantic checkpoints through `record_codex_security_scan_draft` as decisions arrive, preserving unresolved candidates and original evidence in `coverage.deferred`. After review settles, submit `complete: true` with the retained model, findings, and coverage. Reuse saved surface IDs; close finished generic tasks with `coverage.resolvedDeferred: [{ id, reason }]` using their saved IDs. Detailed write-ups and hardening plans are optional requested outputs.
32
+ 5. Read `../../references/final-report.md` for the finding, review-state, and completion contract. Save `complete: false` semantic checkpoints through `record_codex_security_scan_draft` as decisions arrive, preserving unresolved candidates and original evidence in `reviewState.deferred`. After review settles, submit `complete: true` with the retained model, findings, and review state. Reuse saved surface IDs; close finished generic tasks with `reviewState.resolvedDeferred: [{ id, reason }]` using their saved IDs. Detailed write-ups and hardening plans are optional requested outputs.
33
33
  6. Call `complete_codex_security_scan` once, then read `get_codex_security_completed_scan`, except when the SDK owns completion. Finalization creates `report.md` and SARIF. Return the generated report, actual coverage limitations, measured token usage when available, and Codex review comments for confirmed findings.
34
34
 
35
35
  Every changed file and candidate must be accounted for as reviewed, resolved, or explicitly unfinished; do not turn an incomplete review into a no-findings claim.
@@ -19,18 +19,18 @@ SDK hosts supply their own progress instructions. Use actual deduplicated review
19
19
 
20
20
  ## Workflow
21
21
 
22
- 1. Resolve the authorized target, scope, scan directory, and source context. Preserve the supplied threat model, applicable inherited `SECURITY.md` guidance, and optional `CODEX_SECURITY_KNOWLEDGE_BASE`. When `CODEX_SECURITY_TARGET_PATHS_FILE` is supplied, use the SDK's exact `make-repo-scope-input` command to resolve every requested file and non-ignored directory descendant before review. If the host does not supply the command, run `<plugin_dir>/scripts/launch_codex_security_mcp --helper make-repo-scope-input --repo <repo_root> --scopes-file "$CODEX_SECURITY_TARGET_PATHS_FILE" --out <scan_dir>/scoped-source-input.jsonl` or use the [PowerShell command](#windows-scoped-input) on Windows. Pass the resulting inventory to the core audit without widening scope; do not print, modify, or evaluate the scope file.
23
- 2. Read `../../references/core-scan.md` and perform the audit within the resolved scope and configured limits. Retain its semantic `scope`, `threatModel`, `findings`, and `coverage`, including source evidence, validation, attack paths, calibrated severity/confidence, and unresolved work.
24
- 3. Save semantic checkpoints throughout the audit as described below. For an SDK-owned scan with a bound semantic draft tool, save the first `complete: false` checkpoint as soon as the threat model is available, then checkpoint new findings and decisions and submit `complete: true` when review finishes. Without that tool, retain the model in an early unsealed canonical draft and update `scan-manifest.json`, `findings.json`, and `coverage.json` using `../../references/scan-contract.md` and the SDK's exact identity and directory. Omit `scan.sealedAt` and `scan.artifacts`. For requested scopes, use `scoped_path` for coverage mode and inventory strategy; otherwise use `repository` mode with `directory` strategy for non-Git targets and `repository` strategy for Git targets. On SDK file-authored paths, run the supplied scope-binding command when a target-paths file is present.
25
- 4. Verify all three canonical JSON files exist. Return control for an SDK-owned scan; the SDK owns finalization and report generation. For other host-backed scans, call `complete_codex_security_scan({ scanId, handoffClaimToken? })` once and return after it succeeds and `report.md` exists. If completion fails, surface its exact error and preserve the scan for continuation. Do not hand-author reports or reread complete canonical findings unless requested. Report complete measured token usage only; leave pending usage to the host and identify unavailable counts.
22
+ 1. Resolve the authorized target, scope, scan directory, and source context. Preserve the supplied threat model, applicable inherited `SECURITY.md` guidance, and optional `CODEX_SECURITY_KNOWLEDGE_BASE`. When `CODEX_SECURITY_TARGET_PATHS_FILE` is supplied, run the SDK's primary inventory command exactly as supplied to resolve every requested file and non-ignored directory descendant before review. For `make-hosted-repo-scope-input`, use the path it reports. Run the supplied recovery command only if that inventory is missing or unreadable in a later shell. If the host does not supply an inventory command, run `<plugin_dir>/scripts/launch_codex_security_mcp --helper make-repo-scope-input --repo <repo_root> --scopes-file "$CODEX_SECURITY_TARGET_PATHS_FILE" --out <scan_dir>/scoped-source-input.jsonl` or use the [PowerShell command](#windows-scoped-input) on Windows. Pass the resulting inventory to the core audit without widening scope; do not print, modify, or evaluate the scope file.
23
+ 2. Read `../../references/core-scan.md` and perform the audit within the resolved scope and configured limits. Retain its semantic `scope`, `threatModel`, `findings`, and `reviewState`, including source evidence, validation, attack paths, calibrated severity/confidence, and unresolved work.
24
+ 3. Save semantic checkpoints throughout the audit as described below. For an SDK-owned scan with a bound semantic draft tool, save the first `complete: false` checkpoint as soon as the threat model is available, then checkpoint new findings and decisions and submit `complete: true` when review finishes. Without that tool, retain the model in an early unsealed canonical draft and update `scan-manifest.json` and `findings.json` using `../../references/scan-contract.md` and the SDK's exact identity and directory. Omit `scan.sealedAt` and `scan.artifacts`. Put review bookkeeping in `scan.reviewState` and set `scan.mode` to `scoped_path` for requested scopes or `repository` otherwise. On SDK file-authored paths, run the supplied scope-binding command when a target-paths file is present.
25
+ 4. Verify both canonical JSON files exist. Return control for an SDK-owned scan; the SDK owns finalization and report generation. For other host-backed scans, call `complete_codex_security_scan({ scanId, handoffClaimToken? })` once and return after it succeeds and `report.md` exists. If completion fails, surface its exact error and preserve the scan for continuation. Do not hand-author reports or reread complete canonical findings unless requested. Report complete measured token usage only; leave pending usage to the host and identify unavailable counts.
26
26
 
27
27
  Keep discovery, validation, and attack-path reasoning within this Standard workflow. Do not invoke separate phase skills, Deep-only tools, ranking phases, or per-file/per-candidate ledgers. Once assigned review and concrete follow-ups are settled, finish the configured audit with honest limitations rather than waiting for unspecified worker updates.
28
28
 
29
29
  ## Semantic Checkpoints
30
30
 
31
- For a host-backed scan, use `record_codex_security_scan_draft({ scanId, complete, handoffClaimToken?, scope?, threatModel, findings, coverage })`. Save a `complete: false` checkpoint as soon as the threat model is available, with no findings when none exist yet. Checkpoint new findings and decisions, then submit an accepted `complete: true` draft when review finishes. Let the host derive authoritative metadata and identities.
31
+ For a host-backed scan, use `record_codex_security_scan_draft({ scanId, complete, handoffClaimToken?, scope?, threatModel, findings, reviewState })`. Save a `complete: false` checkpoint as soon as the threat model is available, with no findings when none exist yet. Checkpoint new findings and decisions, then submit an accepted `complete: true` draft when review finishes. Let the host derive authoritative metadata and identities.
32
32
 
33
- Preserve saved surface IDs and unfinished candidates; close completed generic tasks using `coverage.resolvedDeferred: [{ id, reason }]` with their saved IDs. Follow `../../references/final-report.md` for rejected drafts and interrupted writes, preserving the same scan.
33
+ Preserve saved surface IDs and unfinished candidates; close completed generic tasks using `reviewState.resolvedDeferred: [{ id, reason }]` with their saved IDs. Follow `../../references/final-report.md` for rejected drafts and interrupted writes, preserving the same scan.
34
34
 
35
35
  ## Windows Scope Binding
36
36
 
@@ -40,7 +40,7 @@ Use the SDK-supplied command when available. For another explicitly permitted fi
40
40
  $env:scopePluginRoot = Convert-Path -LiteralPath '<plugin_dir>' -ErrorAction Stop
41
41
  $env:scopeScanDir = Convert-Path -LiteralPath '<scan_dir>' -ErrorAction Stop
42
42
  $env:scopeTargetPaths = Convert-Path -LiteralPath $env:CODEX_SECURITY_TARGET_PATHS_FILE -ErrorAction Stop
43
- cmd.exe /d /v:off /s /c '""%scopePluginRoot%\scripts\launch_codex_security_mcp.cmd" --helper bind-repo-scopes --scopes-file "%scopeTargetPaths%" --manifest "%scopeScanDir%\scan-manifest.json" --coverage "%scopeScanDir%\coverage.json""'
43
+ cmd.exe /d /v:off /s /c '""%scopePluginRoot%\scripts\launch_codex_security_mcp.cmd" --helper bind-repo-scopes --scopes-file "%scopeTargetPaths%" --manifest "%scopeScanDir%\scan-manifest.json""'
44
44
  ```
45
45
 
46
46
  These are temporary shell variables. Resolve paths against PowerShell's current location, including UNC shares. Missing paths stop the command. CMD expands these references once, preserving literal `%` and `!` in paths.
@@ -89,7 +89,7 @@ A successful provider response establishes an accepted write. Immediately call `
89
89
 
90
90
  After recording an accepted write, read the returned object through the same transport when possible to check identity and changed fields, allowing provider formatting that preserves meaning and links. Record the same receipt again with `readback: {status: "verified"}` or `{status: "failed", error}`; omit readback when no read was attempted. A current read confirming reuse can be recorded as verified immediately. Keep accepted writes and read failures distinct. An unreadable issue does not authorize another create.
91
91
 
92
- For CLI issue writes, put the approved body in a mode-`0600` temporary file outside the repository and scan bundle, arrange cleanup on every exit, and pass it to one `gh issue create` or `gh issue edit`. Never print the file. Capture the issue identity and read it with `gh issue view --json`. Use the advisory reference for JSON file creation and required readback.
92
+ For CLI issue writes, put the approved body in a mode-`0600` temporary file outside the repository and scan bundle, arrange cleanup on every exit, and pass it to one `gh issue create` or `gh issue edit`. Never print the file. Capture the returned issue URL as `issue_url` and read it with `gh issue view "$issue_url" --json number,url,title,body`. Append the JSON fields for any other metadata in the approved write, such as `labels` or `assignees`. Use the advisory reference for JSON file creation and required readback.
93
93
 
94
94
  If a mutation fails or times out and may have succeeded, reconcile through exact reads or binding searches before any retry. Stop if the result remains uncertain. After an interrupted batch, reconcile receipts and current reads for completed items, then validate and check duplicates for the remaining items. Keep approval when the remaining writes and destination are unchanged.
95
95