@openai/codex-security 0.8.3 → 0.10.0

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 (658) hide show
  1. package/README.md +36 -746
  2. package/_bundled_plugin/.codex-plugin/plugin.json +2 -0
  3. package/_bundled_plugin/.mcp.json +7 -1
  4. package/_bundled_plugin/examples/completed-scan/findings.json +16 -4
  5. package/_bundled_plugin/examples/completed-scan/report.md +11 -8
  6. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +4 -2
  7. package/_bundled_plugin/mcp/fzstd-LICENSE.txt +21 -0
  8. package/_bundled_plugin/mcp/helpers.mjs +2 -11
  9. package/_bundled_plugin/mcp/helpers.mjs.br +0 -0
  10. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +3 -210
  11. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  12. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  13. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  14. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  15. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  16. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  17. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  18. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  19. package/_bundled_plugin/mcp/package.json +1 -0
  20. package/_bundled_plugin/mcp/permission-profile-preflight.mjs +5 -2
  21. package/_bundled_plugin/mcp/server.mjs +2 -11
  22. package/_bundled_plugin/mcp/server.mjs.br +0 -0
  23. package/_bundled_plugin/mcp/session-decompression.mjs +712 -0
  24. package/_bundled_plugin/references/artifact-storage.md +1 -1
  25. package/_bundled_plugin/references/baseline-auditor.md +18 -0
  26. package/_bundled_plugin/references/core-scan.md +5 -42
  27. package/_bundled_plugin/references/default-severity-rubric.md +9 -4
  28. package/_bundled_plugin/references/final-report.md +5 -3
  29. package/_bundled_plugin/references/finding-detail-fields.md +18 -18
  30. package/_bundled_plugin/references/focused-investigator.md +13 -0
  31. package/_bundled_plugin/references/sarif-adapter.md +8 -2
  32. package/_bundled_plugin/references/scan-artifacts.md +21 -12
  33. package/_bundled_plugin/references/scan-contract.md +27 -33
  34. package/_bundled_plugin/references/scan-prologue.md +2 -2
  35. package/_bundled_plugin/references/scan-runtime.md +4 -2
  36. package/_bundled_plugin/references/security-guidance.md +14 -1
  37. package/_bundled_plugin/references/validate-scan-findings.md +3 -0
  38. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +2 -2
  39. package/_bundled_plugin/scripts/check_deep_scan_target.py +97 -0
  40. package/_bundled_plugin/scripts/codex_profile.mjs +7 -1
  41. package/_bundled_plugin/scripts/deep_scan_config.py +20 -1
  42. package/_bundled_plugin/scripts/deep_scan_workbench.py +192 -352
  43. package/_bundled_plugin/scripts/dispatch_inventory_tool +7 -0
  44. package/_bundled_plugin/scripts/filesystem_identity.py +1 -0
  45. package/_bundled_plugin/scripts/finalize_scan_contract.py +182 -230
  46. package/_bundled_plugin/scripts/finding_preview.py +20 -0
  47. package/_bundled_plugin/scripts/launch_codex_security_mcp +55 -16
  48. package/_bundled_plugin/scripts/legacy_findings.py +148 -0
  49. package/_bundled_plugin/scripts/posix_scan_local_files.py +37 -1
  50. package/_bundled_plugin/scripts/read_codex_session.mjs +21 -0
  51. package/_bundled_plugin/scripts/report_projection.py +81 -43
  52. package/_bundled_plugin/scripts/review_state.py +8 -2
  53. package/_bundled_plugin/scripts/servicenow_avit.py +20 -0
  54. package/_bundled_plugin/scripts/snapshot_sqlite.py +9 -2
  55. package/_bundled_plugin/scripts/threat_model_projection.py +22 -26
  56. package/_bundled_plugin/scripts/validate_scan_contract.py +7 -1
  57. package/_bundled_plugin/scripts/windows_scan_local_files.py +582 -20
  58. package/_bundled_plugin/scripts/workbench/__init__.py +1 -1
  59. package/_bundled_plugin/scripts/workbench/handoff.py +100 -23
  60. package/_bundled_plugin/scripts/workbench/retained_coverage.py +30 -51
  61. package/_bundled_plugin/scripts/workbench/retained_records.py +18 -30
  62. package/_bundled_plugin/scripts/workbench/runtime_toml.py +4 -1
  63. package/_bundled_plugin/scripts/workbench/saved_coverage.py +9 -17
  64. package/_bundled_plugin/scripts/workbench/saved_outputs.py +9 -0
  65. package/_bundled_plugin/scripts/workbench/saved_sources.py +47 -40
  66. package/_bundled_plugin/scripts/workbench/storage.py +91 -7
  67. package/_bundled_plugin/scripts/workbench_cli.py +54 -14
  68. package/_bundled_plugin/scripts/workbench_constants.py +12 -0
  69. package/_bundled_plugin/scripts/workbench_coverage_receipts.py +3 -3
  70. package/_bundled_plugin/scripts/workbench_db.py +562 -303
  71. package/_bundled_plugin/scripts/workbench_feedback.py +57 -11
  72. package/_bundled_plugin/scripts/workbench_finding_index.py +1 -0
  73. package/_bundled_plugin/scripts/workbench_finding_workflows.py +4 -0
  74. package/_bundled_plugin/scripts/workbench_native_indexes.py +238 -41
  75. package/_bundled_plugin/scripts/workbench_progress.py +169 -4
  76. package/_bundled_plugin/scripts/workbench_publication.py +16 -13
  77. package/_bundled_plugin/scripts/workbench_remediation.py +155 -2
  78. package/_bundled_plugin/scripts/workbench_saved_results.py +176 -81
  79. package/_bundled_plugin/scripts/workbench_scan_history.py +398 -174
  80. package/_bundled_plugin/scripts/workbench_scan_start.py +224 -31
  81. package/_bundled_plugin/scripts/workbench_scan_usage.py +675 -73
  82. package/_bundled_plugin/scripts/workbench_schema.py +258 -63
  83. package/_bundled_plugin/scripts/workbench_setup.py +14 -2
  84. package/_bundled_plugin/scripts/workbench_source_excerpt.py +13 -0
  85. package/_bundled_plugin/scripts/workbench_source_scopes.py +18 -0
  86. package/_bundled_plugin/scripts/workbench_target.py +594 -136
  87. package/_bundled_plugin/scripts/workbench_target_state.py +1110 -21
  88. package/_bundled_plugin/scripts/workbench_validation.py +43 -3
  89. package/_bundled_plugin/shared/workbench-history-repairs.json +77 -35
  90. package/_bundled_plugin/shared/workbench-migrations.json +100 -0
  91. package/_bundled_plugin/skills/cloud-findings/SKILL.md +5 -5
  92. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +7 -50
  93. package/_bundled_plugin/skills/fix-finding/SKILL.md +2 -1
  94. package/_bundled_plugin/skills/publish-findings/SKILL.md +24 -153
  95. package/_bundled_plugin/skills/publish-findings/agents/openai.yaml +2 -2
  96. package/_bundled_plugin/skills/publish-findings/references/checkmarx-import.md +37 -0
  97. package/_bundled_plugin/skills/publish-findings/references/wiz-import.md +3 -3
  98. package/_bundled_plugin/skills/publish-findings/scripts/collect_checkmarx.py +409 -0
  99. package/_bundled_plugin/skills/publish-findings/scripts/collect_continuum.py +224 -0
  100. package/_bundled_plugin/skills/publish-findings/scripts/collector_paths.py +63 -0
  101. package/_bundled_plugin/skills/security-scan/SKILL.md +9 -46
  102. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +2 -2
  103. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +3 -21
  104. package/_bundled_plugin/skills/security-scan/references/managed-scan.md +11 -0
  105. package/_bundled_plugin/skills/security-scan/references/scan-results.md +15 -0
  106. package/_bundled_plugin/skills/security-scan/references/scoped-paths.md +23 -0
  107. package/_bundled_plugin/skills/security-scan/references/sdk-files.md +24 -0
  108. package/_bundled_plugin/skills/threat-model-visualize/scripts/build_explorer.py +22 -1
  109. package/_bundled_plugin/skills/triage-finding/references/ticket-intake.md +6 -2
  110. package/bin/codex-security.mjs +2 -2
  111. package/dist/api.d.ts +45 -5
  112. package/dist/api.d.ts.map +1 -1
  113. package/dist/api.js +1192 -427
  114. package/dist/api.js.map +1 -1
  115. package/dist/armorcode-findings.d.ts +9 -0
  116. package/dist/armorcode-findings.d.ts.map +1 -0
  117. package/dist/armorcode-findings.js +145 -0
  118. package/dist/armorcode-findings.js.map +1 -0
  119. package/dist/artifact-export.d.ts +2 -0
  120. package/dist/artifact-export.d.ts.map +1 -1
  121. package/dist/artifact-export.js +29 -13
  122. package/dist/artifact-export.js.map +1 -1
  123. package/dist/auth.d.ts +6 -2
  124. package/dist/auth.d.ts.map +1 -1
  125. package/dist/auth.js +37 -18
  126. package/dist/auth.js.map +1 -1
  127. package/dist/batch-cost.d.ts +18 -0
  128. package/dist/batch-cost.d.ts.map +1 -0
  129. package/dist/batch-cost.js +41 -0
  130. package/dist/batch-cost.js.map +1 -0
  131. package/dist/bedrock-oss-pricing.d.ts +6 -0
  132. package/dist/bedrock-oss-pricing.d.ts.map +1 -0
  133. package/dist/bedrock-oss-pricing.js +58 -0
  134. package/dist/bedrock-oss-pricing.js.map +1 -0
  135. package/dist/bedrock-pricing.d.ts +15 -0
  136. package/dist/bedrock-pricing.d.ts.map +1 -0
  137. package/dist/bedrock-pricing.js +117 -0
  138. package/dist/bedrock-pricing.js.map +1 -0
  139. package/dist/blackduck-findings.d.ts +1 -1
  140. package/dist/blackduck-findings.d.ts.map +1 -1
  141. package/dist/blackduck-findings.js +24 -22
  142. package/dist/blackduck-findings.js.map +1 -1
  143. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  144. package/dist/bulk-scan-discovery.js +4 -4
  145. package/dist/bulk-scan-discovery.js.map +1 -1
  146. package/dist/bundled-plugin.d.ts +4 -0
  147. package/dist/bundled-plugin.d.ts.map +1 -0
  148. package/dist/bundled-plugin.js +23 -0
  149. package/dist/bundled-plugin.js.map +1 -0
  150. package/dist/checkmarx-evidence.d.ts +19 -0
  151. package/dist/checkmarx-evidence.d.ts.map +1 -0
  152. package/dist/checkmarx-evidence.js +36 -0
  153. package/dist/checkmarx-evidence.js.map +1 -0
  154. package/dist/checkmarx-findings.d.ts +4 -0
  155. package/dist/checkmarx-findings.d.ts.map +1 -0
  156. package/dist/checkmarx-findings.js +27 -0
  157. package/dist/checkmarx-findings.js.map +1 -0
  158. package/dist/checkmarx-one.d.ts +4 -0
  159. package/dist/checkmarx-one.d.ts.map +1 -0
  160. package/dist/checkmarx-one.js +53 -0
  161. package/dist/checkmarx-one.js.map +1 -0
  162. package/dist/checkmarx-repository.d.ts +12 -0
  163. package/dist/checkmarx-repository.d.ts.map +1 -0
  164. package/dist/checkmarx-repository.js +181 -0
  165. package/dist/checkmarx-repository.js.map +1 -0
  166. package/dist/checkmarx-xml.d.ts +12 -0
  167. package/dist/checkmarx-xml.d.ts.map +1 -0
  168. package/dist/checkmarx-xml.js +196 -0
  169. package/dist/checkmarx-xml.js.map +1 -0
  170. package/dist/classify-scan-severity.d.ts +1 -1
  171. package/dist/classify-scan-severity.d.ts.map +1 -1
  172. package/dist/classify-scan-severity.js +11 -3
  173. package/dist/classify-scan-severity.js.map +1 -1
  174. package/dist/classify-severity-records.d.ts +1 -9
  175. package/dist/classify-severity-records.d.ts.map +1 -1
  176. package/dist/classify-severity-records.js +3 -13
  177. package/dist/classify-severity-records.js.map +1 -1
  178. package/dist/classify-severity.d.ts.map +1 -1
  179. package/dist/classify-severity.js +11 -10
  180. package/dist/classify-severity.js.map +1 -1
  181. package/dist/cli-argument.d.ts +4 -0
  182. package/dist/cli-argument.d.ts.map +1 -0
  183. package/dist/cli-argument.js +17 -0
  184. package/dist/cli-argument.js.map +1 -0
  185. package/dist/cli-help.d.ts +1 -1
  186. package/dist/cli-help.d.ts.map +1 -1
  187. package/dist/cli-help.js +71 -29
  188. package/dist/cli-help.js.map +1 -1
  189. package/dist/cli-hook.d.ts +3 -0
  190. package/dist/cli-hook.d.ts.map +1 -0
  191. package/dist/cli-hook.js +87 -0
  192. package/dist/cli-hook.js.map +1 -0
  193. package/dist/cli-integrations.d.ts +13 -0
  194. package/dist/cli-integrations.d.ts.map +1 -0
  195. package/dist/cli-integrations.js +333 -0
  196. package/dist/cli-integrations.js.map +1 -0
  197. package/dist/cli-mcp.d.ts +15 -0
  198. package/dist/cli-mcp.d.ts.map +1 -0
  199. package/dist/cli-mcp.js +178 -0
  200. package/dist/cli-mcp.js.map +1 -0
  201. package/dist/cli-token-view.d.ts +10 -0
  202. package/dist/cli-token-view.d.ts.map +1 -0
  203. package/dist/cli-token-view.js +41 -0
  204. package/dist/cli-token-view.js.map +1 -0
  205. package/dist/cli.d.ts +16 -8
  206. package/dist/cli.d.ts.map +1 -1
  207. package/dist/cli.js +3382 -2017
  208. package/dist/cli.js.map +1 -1
  209. package/dist/cloud-publish.d.ts.map +1 -1
  210. package/dist/cloud-publish.js +35 -33
  211. package/dist/cloud-publish.js.map +1 -1
  212. package/dist/codex-sdk-environment.d.ts +6 -0
  213. package/dist/codex-sdk-environment.d.ts.map +1 -1
  214. package/dist/codex-sdk-environment.js +19 -0
  215. package/dist/codex-sdk-environment.js.map +1 -1
  216. package/dist/command-words.d.ts +3 -0
  217. package/dist/command-words.d.ts.map +1 -0
  218. package/dist/command-words.js +46 -0
  219. package/dist/command-words.js.map +1 -0
  220. package/dist/component-scan.d.ts +19 -4
  221. package/dist/component-scan.d.ts.map +1 -1
  222. package/dist/component-scan.js +67 -9
  223. package/dist/component-scan.js.map +1 -1
  224. package/dist/config.d.ts +1 -1
  225. package/dist/config.d.ts.map +1 -1
  226. package/dist/config.js +130 -67
  227. package/dist/config.js.map +1 -1
  228. package/dist/continuum-findings.d.ts +1 -1
  229. package/dist/continuum-findings.d.ts.map +1 -1
  230. package/dist/continuum-findings.js +149 -19
  231. package/dist/continuum-findings.js.map +1 -1
  232. package/dist/contract-values.d.ts +2 -0
  233. package/dist/contract-values.d.ts.map +1 -1
  234. package/dist/contract-values.js +12 -9
  235. package/dist/contract-values.js.map +1 -1
  236. package/dist/cost-model.d.ts +13 -1
  237. package/dist/cost-model.d.ts.map +1 -1
  238. package/dist/cost-model.js +66 -112
  239. package/dist/cost-model.js.map +1 -1
  240. package/dist/cost.d.ts +42 -3
  241. package/dist/cost.d.ts.map +1 -1
  242. package/dist/cost.js +484 -149
  243. package/dist/cost.js.map +1 -1
  244. package/dist/custom-publish.d.ts +4 -0
  245. package/dist/custom-publish.d.ts.map +1 -1
  246. package/dist/custom-publish.js +40 -3
  247. package/dist/custom-publish.js.map +1 -1
  248. package/dist/custom-validation-prompt.d.ts +1 -1
  249. package/dist/custom-validation-prompt.d.ts.map +1 -1
  250. package/dist/custom-validation-prompt.js +29 -19
  251. package/dist/custom-validation-prompt.js.map +1 -1
  252. package/dist/deduplication/local.d.ts +4 -2
  253. package/dist/deduplication/local.d.ts.map +1 -1
  254. package/dist/deduplication/local.js +9 -2
  255. package/dist/deduplication/local.js.map +1 -1
  256. package/dist/deduplication/refusal.d.ts.map +1 -1
  257. package/dist/deduplication/refusal.js +26 -5
  258. package/dist/deduplication/refusal.js.map +1 -1
  259. package/dist/deduplication/scan.d.ts +5 -0
  260. package/dist/deduplication/scan.d.ts.map +1 -1
  261. package/dist/deduplication/scan.js +24 -7
  262. package/dist/deduplication/scan.js.map +1 -1
  263. package/dist/deep-config.d.ts +0 -1
  264. package/dist/deep-config.d.ts.map +1 -1
  265. package/dist/deep-config.js +22 -33
  266. package/dist/deep-config.js.map +1 -1
  267. package/dist/deep-scan-defaults.d.ts +2 -0
  268. package/dist/deep-scan-defaults.d.ts.map +1 -1
  269. package/dist/deep-scan-defaults.js +28 -1
  270. package/dist/deep-scan-defaults.js.map +1 -1
  271. package/dist/deep-scan.d.ts +2 -0
  272. package/dist/deep-scan.d.ts.map +1 -1
  273. package/dist/deep-scan.js +44 -19
  274. package/dist/deep-scan.js.map +1 -1
  275. package/dist/default-severity-rubric.d.ts +1 -1
  276. package/dist/default-severity-rubric.d.ts.map +1 -1
  277. package/dist/default-severity-rubric.js +1 -1
  278. package/dist/default-severity-rubric.js.map +1 -1
  279. package/dist/endor-findings.d.ts +3 -1
  280. package/dist/endor-findings.d.ts.map +1 -1
  281. package/dist/endor-findings.js +86 -45
  282. package/dist/endor-findings.js.map +1 -1
  283. package/dist/errors.d.ts +4 -2
  284. package/dist/errors.d.ts.map +1 -1
  285. package/dist/errors.js +15 -4
  286. package/dist/errors.js.map +1 -1
  287. package/dist/executable-path.d.ts +3 -0
  288. package/dist/executable-path.d.ts.map +1 -1
  289. package/dist/executable-path.js +26 -0
  290. package/dist/executable-path.js.map +1 -1
  291. package/dist/external-findings-import.d.ts +5 -3
  292. package/dist/external-findings-import.d.ts.map +1 -1
  293. package/dist/external-findings-import.js +19 -7
  294. package/dist/external-findings-import.js.map +1 -1
  295. package/dist/external-findings-local.d.ts +69 -5
  296. package/dist/external-findings-local.d.ts.map +1 -1
  297. package/dist/external-findings-local.js +537 -108
  298. package/dist/external-findings-local.js.map +1 -1
  299. package/dist/external-findings-publish.d.ts +13 -6
  300. package/dist/external-findings-publish.d.ts.map +1 -1
  301. package/dist/external-findings-publish.js +895 -1142
  302. package/dist/external-findings-publish.js.map +1 -1
  303. package/dist/external-findings-read.d.ts +21 -2
  304. package/dist/external-findings-read.d.ts.map +1 -1
  305. package/dist/external-findings-read.js +130 -68
  306. package/dist/external-findings-read.js.map +1 -1
  307. package/dist/external-findings.d.ts +15 -3
  308. package/dist/external-findings.d.ts.map +1 -1
  309. package/dist/external-findings.js +54 -2
  310. package/dist/external-findings.js.map +1 -1
  311. package/dist/external-import-contract.d.ts +8 -12
  312. package/dist/external-import-contract.d.ts.map +1 -1
  313. package/dist/external-import-contract.js +51 -184
  314. package/dist/external-import-contract.js.map +1 -1
  315. package/dist/external-import-models.d.ts +1 -1
  316. package/dist/external-import-models.d.ts.map +1 -1
  317. package/dist/external-import-models.js.map +1 -1
  318. package/dist/feedback.d.ts.map +1 -1
  319. package/dist/feedback.js +5 -4
  320. package/dist/feedback.js.map +1 -1
  321. package/dist/finding-prompt.d.ts +5 -0
  322. package/dist/finding-prompt.d.ts.map +1 -0
  323. package/dist/finding-prompt.js +32 -0
  324. package/dist/finding-prompt.js.map +1 -0
  325. package/dist/findings-client.d.ts +1 -0
  326. package/dist/findings-client.d.ts.map +1 -1
  327. package/dist/findings-client.js +27 -3
  328. package/dist/findings-client.js.map +1 -1
  329. package/dist/github-advisories.d.ts.map +1 -1
  330. package/dist/github-advisories.js +0 -2
  331. package/dist/github-advisories.js.map +1 -1
  332. package/dist/github-dependabot-findings.d.ts.map +1 -1
  333. package/dist/github-dependabot-findings.js +18 -8
  334. package/dist/github-dependabot-findings.js.map +1 -1
  335. package/dist/github-findings.d.ts +4 -1
  336. package/dist/github-findings.d.ts.map +1 -1
  337. package/dist/github-findings.js +73 -316
  338. package/dist/github-findings.js.map +1 -1
  339. package/dist/hosted-git-remotes.d.ts +5 -0
  340. package/dist/hosted-git-remotes.d.ts.map +1 -0
  341. package/dist/hosted-git-remotes.js +285 -0
  342. package/dist/hosted-git-remotes.js.map +1 -0
  343. package/dist/hosted-git-repository.d.ts +28 -0
  344. package/dist/hosted-git-repository.d.ts.map +1 -0
  345. package/dist/hosted-git-repository.js +222 -0
  346. package/dist/hosted-git-repository.js.map +1 -0
  347. package/dist/hosted-remediation.d.ts +1 -0
  348. package/dist/hosted-remediation.d.ts.map +1 -1
  349. package/dist/hosted-remediation.js +23 -3
  350. package/dist/hosted-remediation.js.map +1 -1
  351. package/dist/hosted-scan-protocol.js +2 -2
  352. package/dist/hosted-scan-protocol.js.map +1 -1
  353. package/dist/hosted-scan.d.ts.map +1 -1
  354. package/dist/hosted-scan.js +16 -11
  355. package/dist/hosted-scan.js.map +1 -1
  356. package/dist/hosted-scanner-http.d.ts +21 -0
  357. package/dist/hosted-scanner-http.d.ts.map +1 -0
  358. package/dist/hosted-scanner-http.js +204 -0
  359. package/dist/hosted-scanner-http.js.map +1 -0
  360. package/dist/import-scan.d.ts.map +1 -1
  361. package/dist/import-scan.js +3 -0
  362. package/dist/import-scan.js.map +1 -1
  363. package/dist/index.d.ts +21 -9
  364. package/dist/index.d.ts.map +1 -1
  365. package/dist/index.js +12 -3
  366. package/dist/index.js.map +1 -1
  367. package/dist/inspector-findings.d.ts.map +1 -1
  368. package/dist/inspector-findings.js +52 -86
  369. package/dist/inspector-findings.js.map +1 -1
  370. package/dist/knowledge-base.d.ts +1 -1
  371. package/dist/knowledge-base.d.ts.map +1 -1
  372. package/dist/knowledge-base.js +102 -32
  373. package/dist/knowledge-base.js.map +1 -1
  374. package/dist/linear.d.ts +11 -0
  375. package/dist/linear.d.ts.map +1 -1
  376. package/dist/linear.js.map +1 -1
  377. package/dist/local-git-metadata.d.ts +5 -2
  378. package/dist/local-git-metadata.d.ts.map +1 -1
  379. package/dist/local-git-metadata.js +8 -5
  380. package/dist/local-git-metadata.js.map +1 -1
  381. package/dist/multiscan.d.ts +10 -4
  382. package/dist/multiscan.d.ts.map +1 -1
  383. package/dist/multiscan.js +217 -102
  384. package/dist/multiscan.js.map +1 -1
  385. package/dist/native-json-findings.d.ts +2 -1
  386. package/dist/native-json-findings.d.ts.map +1 -1
  387. package/dist/native-json-findings.js +12 -2
  388. package/dist/native-json-findings.js.map +1 -1
  389. package/dist/opengrep-findings.d.ts +5 -2
  390. package/dist/opengrep-findings.d.ts.map +1 -1
  391. package/dist/opengrep-findings.js +54 -33
  392. package/dist/opengrep-findings.js.map +1 -1
  393. package/dist/operation-telemetry.d.ts +104 -0
  394. package/dist/operation-telemetry.d.ts.map +1 -0
  395. package/dist/operation-telemetry.js +293 -0
  396. package/dist/operation-telemetry.js.map +1 -0
  397. package/dist/plugin-python-probe.d.ts +4 -0
  398. package/dist/plugin-python-probe.d.ts.map +1 -0
  399. package/dist/plugin-python-probe.js +10 -0
  400. package/dist/plugin-python-probe.js.map +1 -0
  401. package/dist/private-finding-import.d.ts +99 -9
  402. package/dist/private-finding-import.d.ts.map +1 -1
  403. package/dist/private-finding-import.js +116 -152
  404. package/dist/private-finding-import.js.map +1 -1
  405. package/dist/project-config.d.ts.map +1 -1
  406. package/dist/project-config.js +53 -13
  407. package/dist/project-config.js.map +1 -1
  408. package/dist/prompt-files.d.ts +7 -2
  409. package/dist/prompt-files.d.ts.map +1 -1
  410. package/dist/prompt-files.js +42 -20
  411. package/dist/prompt-files.js.map +1 -1
  412. package/dist/provider-profile.d.ts +1 -1
  413. package/dist/provider-profile.d.ts.map +1 -1
  414. package/dist/provider-profile.js +12 -10
  415. package/dist/provider-profile.js.map +1 -1
  416. package/dist/publication-telemetry.d.ts +45 -0
  417. package/dist/publication-telemetry.d.ts.map +1 -0
  418. package/dist/publication-telemetry.js +50 -0
  419. package/dist/publication-telemetry.js.map +1 -0
  420. package/dist/publication.d.ts +1 -1
  421. package/dist/publication.d.ts.map +1 -1
  422. package/dist/publication.js.map +1 -1
  423. package/dist/publish.d.ts +4 -0
  424. package/dist/publish.d.ts.map +1 -1
  425. package/dist/publish.js +42 -2
  426. package/dist/publish.js.map +1 -1
  427. package/dist/record.d.ts +1 -5
  428. package/dist/record.d.ts.map +1 -1
  429. package/dist/record.js +3 -51
  430. package/dist/record.js.map +1 -1
  431. package/dist/remediation.d.ts +1 -4
  432. package/dist/remediation.d.ts.map +1 -1
  433. package/dist/remediation.js +6 -8
  434. package/dist/remediation.js.map +1 -1
  435. package/dist/request-metadata.d.ts +3 -0
  436. package/dist/request-metadata.d.ts.map +1 -1
  437. package/dist/request-metadata.js +9 -0
  438. package/dist/request-metadata.js.map +1 -1
  439. package/dist/result.d.ts +4 -0
  440. package/dist/result.d.ts.map +1 -1
  441. package/dist/result.js +1 -1
  442. package/dist/result.js.map +1 -1
  443. package/dist/retry-windows-rename.d.ts +8 -0
  444. package/dist/retry-windows-rename.d.ts.map +1 -0
  445. package/dist/retry-windows-rename.js +24 -0
  446. package/dist/retry-windows-rename.js.map +1 -0
  447. package/dist/runtime.d.ts +54 -6
  448. package/dist/runtime.d.ts.map +1 -1
  449. package/dist/runtime.js +1084 -256
  450. package/dist/runtime.js.map +1 -1
  451. package/dist/saved-scan-bootstrap.d.ts +7 -1
  452. package/dist/saved-scan-bootstrap.d.ts.map +1 -1
  453. package/dist/saved-scan-bootstrap.js +269 -114
  454. package/dist/saved-scan-bootstrap.js.map +1 -1
  455. package/dist/scan-activity.d.ts.map +1 -1
  456. package/dist/scan-activity.js +141 -56
  457. package/dist/scan-activity.js.map +1 -1
  458. package/dist/scan-archive-path.d.ts +2 -0
  459. package/dist/scan-archive-path.d.ts.map +1 -0
  460. package/dist/scan-archive-path.js +5 -0
  461. package/dist/scan-archive-path.js.map +1 -0
  462. package/dist/scan-comparison.d.ts +10 -5
  463. package/dist/scan-comparison.d.ts.map +1 -1
  464. package/dist/scan-comparison.js +66 -17
  465. package/dist/scan-comparison.js.map +1 -1
  466. package/dist/scan-dashboard.d.ts +7 -6
  467. package/dist/scan-dashboard.d.ts.map +1 -1
  468. package/dist/scan-dashboard.js +92 -43
  469. package/dist/scan-dashboard.js.map +1 -1
  470. package/dist/scan-executor.d.ts +10 -1
  471. package/dist/scan-executor.d.ts.map +1 -1
  472. package/dist/scan-executor.js +24 -2
  473. package/dist/scan-executor.js.map +1 -1
  474. package/dist/scan-history-renderer.d.ts +1 -0
  475. package/dist/scan-history-renderer.d.ts.map +1 -1
  476. package/dist/scan-history-renderer.js +34 -28
  477. package/dist/scan-history-renderer.js.map +1 -1
  478. package/dist/scan-logs.d.ts +12 -0
  479. package/dist/scan-logs.d.ts.map +1 -1
  480. package/dist/scan-logs.js +131 -78
  481. package/dist/scan-logs.js.map +1 -1
  482. package/dist/scan-measurement.d.ts +26 -0
  483. package/dist/scan-measurement.d.ts.map +1 -0
  484. package/dist/scan-measurement.js +77 -0
  485. package/dist/scan-measurement.js.map +1 -0
  486. package/dist/scan-progress.d.ts +1 -0
  487. package/dist/scan-progress.d.ts.map +1 -1
  488. package/dist/scan-progress.js +3 -0
  489. package/dist/scan-progress.js.map +1 -1
  490. package/dist/scan-sessions.d.ts.map +1 -1
  491. package/dist/scan-sessions.js +4 -1
  492. package/dist/scan-sessions.js.map +1 -1
  493. package/dist/scan-settings.d.ts +1 -1
  494. package/dist/scan-settings.d.ts.map +1 -1
  495. package/dist/scan-settings.js +1 -24
  496. package/dist/scan-settings.js.map +1 -1
  497. package/dist/scanner-import.d.ts +25 -13
  498. package/dist/scanner-import.d.ts.map +1 -1
  499. package/dist/scanner-import.js +216 -97
  500. package/dist/scanner-import.js.map +1 -1
  501. package/dist/scanner-repository-url.d.ts +4 -1
  502. package/dist/scanner-repository-url.d.ts.map +1 -1
  503. package/dist/scanner-repository-url.js +10 -6
  504. package/dist/scanner-repository-url.js.map +1 -1
  505. package/dist/security-policy.d.ts +1 -1
  506. package/dist/security-policy.d.ts.map +1 -1
  507. package/dist/security-policy.js +26 -6
  508. package/dist/security-policy.js.map +1 -1
  509. package/dist/semgrep-findings.d.ts +6 -3
  510. package/dist/semgrep-findings.d.ts.map +1 -1
  511. package/dist/semgrep-findings.js +72 -42
  512. package/dist/semgrep-findings.js.map +1 -1
  513. package/dist/semgrep-guardian-findings.d.ts +38 -0
  514. package/dist/semgrep-guardian-findings.d.ts.map +1 -0
  515. package/dist/semgrep-guardian-findings.js +165 -0
  516. package/dist/semgrep-guardian-findings.js.map +1 -0
  517. package/dist/semgrep-platform-collector.d.ts +26 -0
  518. package/dist/semgrep-platform-collector.d.ts.map +1 -0
  519. package/dist/semgrep-platform-collector.js +108 -0
  520. package/dist/semgrep-platform-collector.js.map +1 -0
  521. package/dist/semgrep-platform-findings.d.ts +157 -6
  522. package/dist/semgrep-platform-findings.d.ts.map +1 -1
  523. package/dist/semgrep-platform-findings.js +766 -103
  524. package/dist/semgrep-platform-findings.js.map +1 -1
  525. package/dist/server/api.d.ts +1 -1
  526. package/dist/server/api.d.ts.map +1 -1
  527. package/dist/server/api.js.map +1 -1
  528. package/dist/server/embedding-tokenizer.cdx.json +33 -0
  529. package/dist/server/embedding-tokenizer.d.ts +2 -0
  530. package/dist/server/embedding-tokenizer.d.ts.map +1 -0
  531. package/dist/server/embedding-tokenizer.js +322 -0
  532. package/dist/server/embedding-tokenizer.js.map +6 -0
  533. package/dist/server/embeddings.d.ts +16 -2
  534. package/dist/server/embeddings.d.ts.map +1 -1
  535. package/dist/server/embeddings.js +35 -5
  536. package/dist/server/embeddings.js.map +1 -1
  537. package/dist/session-lines.d.ts +5 -0
  538. package/dist/session-lines.d.ts.map +1 -0
  539. package/dist/session-lines.js +60 -0
  540. package/dist/session-lines.js.map +1 -0
  541. package/dist/severity-review.d.ts +3 -1
  542. package/dist/severity-review.d.ts.map +1 -1
  543. package/dist/severity-review.js +3 -2
  544. package/dist/severity-review.js.map +1 -1
  545. package/dist/skill-authentication.d.ts +1 -0
  546. package/dist/skill-authentication.d.ts.map +1 -1
  547. package/dist/skill-authentication.js +1 -0
  548. package/dist/skill-authentication.js.map +1 -1
  549. package/dist/snyk-findings.d.ts +9 -2
  550. package/dist/snyk-findings.d.ts.map +1 -1
  551. package/dist/snyk-findings.js +90 -70
  552. package/dist/snyk-findings.js.map +1 -1
  553. package/dist/snyk-rest-findings.d.ts +59 -0
  554. package/dist/snyk-rest-findings.d.ts.map +1 -0
  555. package/dist/snyk-rest-findings.js +879 -0
  556. package/dist/snyk-rest-findings.js.map +1 -0
  557. package/dist/snyk-token-origin.d.ts +4 -0
  558. package/dist/snyk-token-origin.d.ts.map +1 -0
  559. package/dist/snyk-token-origin.js +82 -0
  560. package/dist/snyk-token-origin.js.map +1 -0
  561. package/dist/sonar-collector.d.ts.map +1 -1
  562. package/dist/sonar-collector.js +0 -3
  563. package/dist/sonar-collector.js.map +1 -1
  564. package/dist/sonar-findings.d.ts +1 -1
  565. package/dist/sonar-findings.d.ts.map +1 -1
  566. package/dist/sonar-findings.js +2 -4
  567. package/dist/sonar-findings.js.map +1 -1
  568. package/dist/sonar-import.d.ts +3 -0
  569. package/dist/sonar-import.d.ts.map +1 -1
  570. package/dist/sonar-import.js +30 -34
  571. package/dist/sonar-import.js.map +1 -1
  572. package/dist/stored-finding-projection.d.ts +6 -0
  573. package/dist/stored-finding-projection.d.ts.map +1 -0
  574. package/dist/stored-finding-projection.js +104 -0
  575. package/dist/stored-finding-projection.js.map +1 -0
  576. package/dist/stored-findings-publication.d.ts +23 -0
  577. package/dist/stored-findings-publication.d.ts.map +1 -0
  578. package/dist/stored-findings-publication.js +169 -0
  579. package/dist/stored-findings-publication.js.map +1 -0
  580. package/dist/target-drift.d.ts +9 -0
  581. package/dist/target-drift.d.ts.map +1 -0
  582. package/dist/target-drift.js +27 -0
  583. package/dist/target-drift.js.map +1 -0
  584. package/dist/targets.d.ts +8 -1
  585. package/dist/targets.d.ts.map +1 -1
  586. package/dist/targets.js +131 -42
  587. package/dist/targets.js.map +1 -1
  588. package/dist/tenable-findings.d.ts +6 -0
  589. package/dist/tenable-findings.d.ts.map +1 -0
  590. package/dist/tenable-findings.js +122 -0
  591. package/dist/tenable-findings.js.map +1 -0
  592. package/dist/terminal-stream.d.ts +13 -0
  593. package/dist/terminal-stream.d.ts.map +1 -0
  594. package/dist/terminal-stream.js +35 -0
  595. package/dist/terminal-stream.js.map +1 -0
  596. package/dist/trivy-findings.d.ts +19 -0
  597. package/dist/trivy-findings.d.ts.map +1 -0
  598. package/dist/trivy-findings.js +424 -0
  599. package/dist/trivy-findings.js.map +1 -0
  600. package/dist/trivy-import.d.ts +19 -0
  601. package/dist/trivy-import.d.ts.map +1 -0
  602. package/dist/trivy-import.js +151 -0
  603. package/dist/trivy-import.js.map +1 -0
  604. package/dist/trusted-executable.d.ts +6 -0
  605. package/dist/trusted-executable.d.ts.map +1 -1
  606. package/dist/trusted-executable.js +140 -37
  607. package/dist/trusted-executable.js.map +1 -1
  608. package/dist/validation-records.js +1 -1
  609. package/dist/validation-records.js.map +1 -1
  610. package/dist/veracode-findings.d.ts +1 -1
  611. package/dist/veracode-findings.d.ts.map +1 -1
  612. package/dist/veracode-findings.js +19 -6
  613. package/dist/veracode-findings.js.map +1 -1
  614. package/dist/version.d.ts +3 -1
  615. package/dist/version.d.ts.map +1 -1
  616. package/dist/version.js +184 -32
  617. package/dist/version.js.map +1 -1
  618. package/dist/vertex-pricing.d.ts +8 -0
  619. package/dist/vertex-pricing.d.ts.map +1 -0
  620. package/dist/vertex-pricing.js +20 -0
  621. package/dist/vertex-pricing.js.map +1 -0
  622. package/dist/windows-path.d.ts +1 -0
  623. package/dist/windows-path.d.ts.map +1 -1
  624. package/dist/windows-path.js +26 -1
  625. package/dist/windows-path.js.map +1 -1
  626. package/dist/wiz-findings.d.ts +6 -2
  627. package/dist/wiz-findings.d.ts.map +1 -1
  628. package/dist/wiz-findings.js +65 -89
  629. package/dist/wiz-findings.js.map +1 -1
  630. package/docs/classify-severity-records.md +27 -12
  631. package/docs/cli.md +853 -639
  632. package/docs/dedupe-records.md +44 -24
  633. package/docs/findings-service.md +84 -44
  634. package/docs/hosted-remediation.md +27 -11
  635. package/docs/hosted-scans.md +50 -42
  636. package/docs/sdk.md +903 -0
  637. package/docs/telemetry.md +236 -0
  638. package/docs/validate-records.md +78 -44
  639. package/package.json +23 -16
  640. package/schemas/external-findings.schema.json +4 -1
  641. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  642. package/_bundled_plugin/mcp/helpers.mjs.br.part-001 +0 -0
  643. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  644. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  645. package/_bundled_plugin/mcp/server.mjs.br.part-002 +0 -0
  646. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +0 -96
  647. package/dist/external-imports-feature.d.ts +0 -6
  648. package/dist/external-imports-feature.d.ts.map +0 -1
  649. package/dist/external-imports-feature.js +0 -51
  650. package/dist/external-imports-feature.js.map +0 -1
  651. package/dist/finding-normalization.d.ts +0 -5
  652. package/dist/finding-normalization.d.ts.map +0 -1
  653. package/dist/finding-normalization.js +0 -155
  654. package/dist/finding-normalization.js.map +0 -1
  655. package/dist/reader-selection.d.ts +0 -13
  656. package/dist/reader-selection.d.ts.map +0 -1
  657. package/dist/reader-selection.js +0 -81
  658. package/dist/reader-selection.js.map +0 -1
@@ -8,11 +8,11 @@ import os
8
8
  import sqlite3
9
9
  import sys
10
10
  from collections.abc import Iterable, Iterator
11
+ from fractions import Fraction
11
12
  from functools import cache
12
13
  from itertools import chain
13
14
  from pathlib import Path, PurePosixPath
14
15
  from typing import Any, Callable
15
- from urllib.parse import urlsplit
16
16
 
17
17
  # Some plugin hosts launch Python with safe-path isolation enabled.
18
18
  sys.path.insert(0, str(Path(__file__).resolve().parent))
@@ -25,14 +25,40 @@ from finalize_scan_contract import (
25
25
  )
26
26
  from report_projection import SEVERITY_ORDER
27
27
  from review_state import review_state
28
- from workbench_constants import ARTIFACTS, FINDINGS_PAGE_MAX
29
- from workbench_scan_start import scan_target_identity
28
+ from workbench_constants import ARTIFACTS, FINDINGS_PAGE_MAX, PRIMARY_FINDING_LOCATION_SQL
30
29
  from workbench_scan_usage import stored_scan_cost_fields
31
30
  from workbench_source_scopes import public_scan_recipe
32
- from workbench_target import git_output, require_scan_target_identity
31
+ from workbench_target import (
32
+ require_remediation_target,
33
+ require_scan_target_identity,
34
+ verified_windows_checkout,
35
+ )
36
+ from workbench_target_state import (
37
+ RepositoryIdentityCache,
38
+ _timestamp_ns,
39
+ repository_relative_path,
40
+ same_repository_worktree,
41
+ scan_repository_generation,
42
+ )
33
43
  from workbench_validation import timestamp_key
34
44
 
35
45
 
46
+ def reads_missing_history(args: argparse.Namespace, path: Path) -> bool:
47
+ """Select an in-memory database only for history reads on a fresh profile."""
48
+ if args.command not in {"list-scans", "list-repositories", "list-global-findings"} and not (
49
+ args.command == "get-scan" and not (args.request_id or args.action_token)
50
+ ):
51
+ return False
52
+ try:
53
+ path.lstat()
54
+ except FileNotFoundError:
55
+ return True
56
+ except OSError:
57
+ # The ordinary connection reports inaccessible storage.
58
+ pass
59
+ return False
60
+
61
+
36
62
  def rename_scan(connection: sqlite3.Connection, scan: sqlite3.Row, name: str) -> dict[str, Any]:
37
63
  name = name.strip()
38
64
  if not name:
@@ -43,6 +69,7 @@ def rename_scan(connection: sqlite3.Connection, scan: sqlite3.Row, name: str) ->
43
69
 
44
70
 
45
71
  def scan_recipe(scan: sqlite3.Row) -> dict[str, Any]:
72
+ """Return the public launch recipe with its scan and parent IDs, raising SystemExit if the recipe was never saved."""
46
73
  if scan["recipe_json"] is None:
47
74
  raise SystemExit("This scan does not have a saved launch recipe.")
48
75
  return {
@@ -52,9 +79,30 @@ def scan_recipe(scan: sqlite3.Row) -> dict[str, Any]:
52
79
  }
53
80
 
54
81
 
82
+ def expected_coverage_mode(scan: sqlite3.Row) -> str:
83
+ """Return the coverage mode implied by the recorded scope, scan mode, and diff target kind."""
84
+ if scan["mode"] == "diff":
85
+ mode = {
86
+ "commit": "commit",
87
+ "range": "branch_diff",
88
+ "working_tree": "working_tree",
89
+ }.get(scan["diff_target_kind"])
90
+ if mode is None:
91
+ raise SystemExit("This migrated diff scan does not have a validated change set.")
92
+ return mode
93
+ if scan["scope"] != "." or (
94
+ "recipe_json" in scan.keys()
95
+ and scan["recipe_json"] is not None
96
+ and json.loads(scan["recipe_json"])["target"]["kind"] == "paths"
97
+ ):
98
+ return "scoped_path"
99
+ return "deep_repository" if scan["mode"] == "deep" else "repository"
100
+
101
+
55
102
  def preserve_sealed_completion(
56
103
  binding: dict[str, Any], manifest: dict[str, Any] | None
57
104
  ) -> dict[str, Any]:
105
+ """Copy the original timestamps and producer version from a sealed manifest into binding, then return it."""
58
106
  manifest_scan = manifest.get("scan") if manifest is not None else None
59
107
  if isinstance(manifest_scan, dict) and manifest_scan.get("sealedAt") is not None:
60
108
  # Keep the original producer; finalization still validates schema, seal and owner.
@@ -66,14 +114,34 @@ def preserve_sealed_completion(
66
114
  return binding
67
115
 
68
116
 
117
+ def _windows_resume_checkout(scan: sqlite3.Row) -> Path:
118
+ from workbench_scan_start import scan_target_identity
119
+
120
+ replaced = "Cannot resume: the original checkout is missing or was replaced."
121
+ try:
122
+ repository = require_remediation_target(scan["target_path"])
123
+ except SystemExit as exc:
124
+ raise SystemExit(replaced) from exc
125
+ with verified_windows_checkout(scan, repository, replaced_message=replaced):
126
+ expected = (scan["target_revision"], scan["target_snapshot_digest"])
127
+ current = scan_target_identity(
128
+ repository, None, expected_digest=scan["target_snapshot_digest"]
129
+ )
130
+ if current[:2] != expected:
131
+ raise SystemExit("Cannot resume: the original checkout revision or contents changed.")
132
+ return repository
133
+
134
+
69
135
  def cli_scan_resume(
70
136
  wb: Any,
71
137
  connection: sqlite3.Connection,
72
138
  scan: sqlite3.Row,
73
139
  workspace: sqlite3.Row,
74
140
  ) -> dict[str, Any]:
75
- if scan["mode"] != "deep" or scan["recipe_json"] is None:
76
- raise SystemExit("Resume requires a Deep Scan with a saved CLI launch recipe.")
141
+
142
+ scan = scan_with_progress(connection, scan["id"])
143
+ if scan["mode"] not in {"standard", "deep"} or scan["recipe_json"] is None:
144
+ raise SystemExit("Resume requires a Standard or Deep Scan with a saved CLI launch recipe.")
77
145
  if scan["status"] != "running" or scan["canceled_at"] is not None:
78
146
  raise SystemExit(
79
147
  "Resume requires a running scan; completed, failed, and canceled scans cannot resume."
@@ -94,30 +162,58 @@ def cli_scan_resume(
94
162
  run["status"] not in {"running", "succeeded"} or run["cancel_requested"]
95
163
  ):
96
164
  raise SystemExit("This Deep Scan has stopped and cannot resume.")
97
- try:
98
- repository = require_scan_target_identity(scan)
99
- except SystemExit as exc:
100
- raise SystemExit(
101
- "Cannot resume: the original checkout is missing or was replaced."
102
- ) from exc
103
- if scan_target_identity(repository, None) != (
104
- scan["target_revision"],
105
- scan["target_snapshot_digest"],
106
- scan["target_device"],
107
- scan["target_inode"],
108
- ):
109
- raise SystemExit("Cannot resume: the original checkout revision or contents changed.")
165
+ if os.name == "nt":
166
+ try:
167
+ repository = _windows_resume_checkout(scan)
168
+ except OSError as exc:
169
+ raise SystemExit(f"Cannot verify the original Windows checkout: {exc}") from exc
170
+ else:
171
+ from workbench_scan_start import scan_target_identity
172
+
173
+ try:
174
+ repository = require_scan_target_identity(scan)
175
+ except SystemExit as exc:
176
+ raise SystemExit(
177
+ "Cannot resume: the original checkout is missing or was replaced."
178
+ ) from exc
179
+ if scan_target_identity(
180
+ repository, None, expected_digest=scan["target_snapshot_digest"]
181
+ ) != (
182
+ scan["target_revision"],
183
+ scan["target_snapshot_digest"],
184
+ scan["target_device"],
185
+ scan["target_inode"],
186
+ ):
187
+ raise SystemExit("Cannot resume: the original checkout revision or contents changed.")
110
188
  recipe = wb.parse_scan_recipe(scan["recipe_json"], repository)
111
189
  scan_dir = wb.require_canonical_scan_directory(Path(scan["scan_dir"]))
112
- progress = connection.execute(
113
- "SELECT scope_file_count FROM scan_progress WHERE scan_id = ?", (scan["id"],)
114
- ).fetchone()
190
+ if os.name == "nt":
191
+ from windows_scan_local_files import DEEP_RESUME_DIRECTORY, deep_resume_output_identity
192
+
193
+ identity = scan["windows_resume_output_identity"]
194
+ if identity is not None:
195
+ try:
196
+ current = deep_resume_output_identity(scan_dir)
197
+ except OSError as exc:
198
+ raise SystemExit(
199
+ f"Cannot verify the registered Windows resume output: {exc}"
200
+ ) from exc
201
+ if current != json.loads(identity):
202
+ raise SystemExit(
203
+ "Cannot resume: the original Windows output directory was replaced."
204
+ )
205
+ elif not any(entry != scan_dir / DEEP_RESUME_DIRECTORY for entry in scan_dir.iterdir()):
206
+ raise SystemExit(
207
+ "Cannot resume this empty Windows output because its original directory identity "
208
+ f"was not saved. Start a new scan with 'codex-security scans rerun {scan['id']}'."
209
+ )
115
210
  result = {
116
211
  "contract": wb.scan_contract(scan),
212
+ "lifecycle": json.loads(scan["lifecycle_json"]),
117
213
  "recipe": recipe,
118
214
  "scanDir": str(scan_dir),
119
215
  "scanId": scan["id"],
120
- "scopeFileCount": progress["scope_file_count"],
216
+ "scopeFileCount": scan["scope_file_count"],
121
217
  "startedAt": scan["started_at"],
122
218
  "targetId": scan["target_id"],
123
219
  "targetRevision": scan["target_revision"],
@@ -148,6 +244,7 @@ def cli_scan_resume(
148
244
  def coverage_summary_for_history(
149
245
  wb: Any, scan: sqlite3.Row, canonical_scan_directory: Callable[[Path], Path]
150
246
  ) -> dict[str, Any]:
247
+ """Return the coverage mode and path filters for history after verifying the sealed scan data."""
151
248
  scan_dir = canonical_scan_directory(Path(scan["scan_dir"]))
152
249
  coverage_ref = "coverage.json"
153
250
  try:
@@ -213,61 +310,64 @@ def _windows_path_key(value: str) -> str:
213
310
 
214
311
 
215
312
  def _same_repository(
313
+ connection: sqlite3.Connection,
216
314
  before: sqlite3.Row,
217
315
  after: sqlite3.Row,
218
316
  *,
219
- after_git: Callable[..., str | None] | None = None,
317
+ identities: RepositoryIdentityCache | None = None,
220
318
  ) -> bool:
221
- if before["target_id"] is not None and before["target_id"] == after["target_id"]:
222
- return True
223
- before_target = Path(before["target_path"])
224
- after_target = Path(after["target_path"])
225
- if before_target.resolve() == after_target.resolve():
319
+ before_stored = scan_repository_generation(before)
320
+ after_stored = scan_repository_generation(after)
321
+ if before_stored is not None and before_stored == after_stored:
226
322
  return True
227
- common_dir = ("rev-parse", "--path-format=absolute", "--git-common-dir")
228
- after_git = after_git or git_output
229
- before_git_dir = git_output(before_target, *common_dir)
323
+ if before["target_id"] and before["target_id"] == after["target_id"]:
324
+ return before_stored is None or after_stored is None
325
+ identities = identities or RepositoryIdentityCache(connection)
326
+ before_state = identities.for_row(before)
327
+ after_state = identities.for_row(after)
230
328
  if (
231
- before_git_dir is not None
232
- and (after_git_dir := after_git(after_target, *common_dir)) is not None
233
- and Path(before_git_dir).resolve() == Path(after_git_dir).resolve()
329
+ not before_state.ownership_matches
330
+ or not after_state.ownership_matches
331
+ or before_stored is not None
332
+ and before_stored != before_state.live_identity
333
+ or after_stored is not None
334
+ and after_stored != after_state.live_identity
234
335
  ):
336
+ return False
337
+ if (
338
+ before_state.resolved_path is not None
339
+ and before_state.resolved_path == after_state.resolved_path
340
+ ):
341
+ return before_stored is None or after_stored is None
342
+ if before_state.repository is None or after_state.repository is None:
343
+ if same_repository_worktree(Path(before_state.target_path), Path(after_state.target_path)):
344
+ return True
345
+ before_relative = repository_relative_path(Path(before_state.target_path))
346
+ after_relative = repository_relative_path(Path(after_state.target_path))
347
+ after_origin = identities.origin(after_state)
348
+ return (
349
+ before_relative is not None
350
+ and before_relative == after_relative
351
+ and after_origin is not None
352
+ and identities.origin(before_state) == after_origin
353
+ )
354
+ before_identity = before_state.live_identity
355
+ after_identity = after_state.live_identity
356
+ if before_identity is not None and before_identity == after_identity:
235
357
  return True
236
- origin = ("remote", "get-url", "origin")
237
- before_origin = _repository_origin(git_output(before_target, *origin))
238
- return before_origin is not None and before_origin == _repository_origin(
239
- after_git(after_target, *origin)
358
+ if before_identity is None or after_identity is None:
359
+ return False
360
+ after_origin = identities.origin(after_state)
361
+ return (
362
+ after_origin is not None
363
+ and identities.origin(before_state) == after_origin
364
+ and before_state.repository.relative_path == after_state.repository.relative_path
240
365
  )
241
366
 
242
367
 
243
- def _repository_origin(remote: str | None) -> tuple[str, str] | None:
244
- if remote is None:
245
- return None
246
- if "://" in remote:
247
- try:
248
- parsed = urlsplit(remote)
249
- port = parsed.port
250
- except ValueError:
251
- return None
252
- if parsed.scheme not in {"https", "ssh"} or parsed.hostname is None:
253
- return None
254
- if parsed.query or parsed.fragment:
255
- return None
256
- host = parsed.hostname
257
- if port is not None and port != {"https": 443, "ssh": 22}[parsed.scheme]:
258
- host = f"{host}:{port}"
259
- path = parsed.path
260
- else:
261
- authority, separator, path = remote.partition(":")
262
- if not separator or "?" in path or "#" in path:
263
- return None
264
- host = authority.rsplit("@", 1)[-1]
265
- path = path.strip("/").removesuffix(".git")
266
- return (host.lower(), path) if host and path else None
267
-
268
-
269
368
  SCAN_SUMMARY_COLUMNS = """
270
369
  scans.*,
370
+ lifecycle.snapshot AS lifecycle_json,
271
371
  progress.reportable_findings_count,
272
372
  progress.scope_file_count,
273
373
  progress.review_items_completed,
@@ -283,15 +383,36 @@ SCAN_SUMMARY_QUERY = f"""
283
383
  SELECT {SCAN_SUMMARY_COLUMNS}
284
384
  FROM scans
285
385
  JOIN scan_progress AS progress ON progress.scan_id = scans.id
386
+ JOIN scan_lifecycles AS lifecycle ON lifecycle.scan_id = scans.id
286
387
  """
287
388
 
288
389
 
390
+ def scan_with_progress(connection: sqlite3.Connection, scan_id: str) -> sqlite3.Row:
391
+ return connection.execute(
392
+ """
393
+ SELECT scans.*, lifecycle.snapshot AS lifecycle_json, progress.updated_at AS progress_updated_at,
394
+ progress.scope_file_count, progress.reportable_findings_count,
395
+ progress.review_items_total, progress.review_items_completed, progress.deep_review_pass,
396
+ progress.phase_items_total, progress.phase_items_completed, progress.phase_progress_unit,
397
+ progress.preflight_checks_total, progress.preflight_checks_completed,
398
+ progress.preflight_issues_json
399
+ FROM scans
400
+ JOIN scan_progress AS progress ON progress.scan_id = scans.id
401
+ JOIN scan_lifecycles AS lifecycle ON lifecycle.scan_id = scans.id
402
+ WHERE scans.id = ?
403
+ """,
404
+ (scan_id,),
405
+ ).fetchone()
406
+
407
+
289
408
  def scan_summary(row: sqlite3.Row) -> dict[str, Any]:
290
409
  return {
291
410
  "completedAt": row["completed_at"],
411
+ "logCompletedAt": row["log_completed_at"],
292
412
  "continuationThreadId": row["continuation_thread_id"],
293
413
  **stored_scan_cost_fields(row["cost_json"]),
294
414
  "findingCount": row["finding_count"],
415
+ "lifecycle": json.loads(row["lifecycle_json"]),
295
416
  "handoffStatus": row["handoff_status"],
296
417
  "mode": row["mode"],
297
418
  "model": row["model"],
@@ -339,30 +460,27 @@ def list_scans(
339
460
  connection.create_function("codex_security_path_key", 1, _windows_path_key)
340
461
  clauses: list[str] = []
341
462
  values: list[Any] = []
463
+ worktree_order = ""
342
464
  if args is not None and args.repository:
343
- repository = Path(args.repository).expanduser().resolve()
344
- requested_repository = connection.execute(
345
- """
346
- SELECT COALESCE((SELECT id FROM security_targets WHERE current_path = ?), '') AS target_id,
347
- ? AS target_path
348
- """,
349
- (str(repository), str(repository)),
350
- ).fetchone()
351
- requested_git = cache(git_output)
352
- related_target_ids = [
353
- target["target_id"]
354
- for target in connection.execute(
355
- "SELECT id AS target_id, current_path AS target_path FROM security_targets"
356
- )
357
- if _same_repository(target, requested_repository, after_git=requested_git)
358
- ]
359
- repository_clauses = ["scans.target_path = ?"]
360
- values.append(str(repository))
361
- if related_target_ids:
362
- placeholders = ", ".join("?" for _ in related_target_ids)
363
- repository_clauses.append(f"scans.target_id IN ({placeholders})")
364
- values.extend(related_target_ids)
365
- clauses.append(f"({' OR '.join(repository_clauses)})")
465
+ repository = Path(args.repository).expanduser().absolute()
466
+ identities = RepositoryIdentityCache(connection)
467
+ repository = Path(identities.history_path(str(repository)))
468
+ clause, scope_values = identities.scope_for_path(str(repository)).sql(
469
+ supports_generation=identities.supports_generation
470
+ )
471
+ clauses.append(clause)
472
+ values.extend(scope_values)
473
+ if getattr(args, "prefer_worktree", False):
474
+
475
+ @cache
476
+ def in_worktree(target_path: str) -> bool:
477
+ try:
478
+ return repository.samefile(target_path)
479
+ except OSError:
480
+ return False
481
+
482
+ connection.create_function("in_worktree", 1, in_worktree)
483
+ worktree_order = "in_worktree(scans.target_path) DESC,"
366
484
  if args is not None and args.scan_root:
367
485
  scan_root = str(Path(args.scan_root).expanduser().resolve())
368
486
  prefix = scan_root.rstrip(os.sep) + os.sep
@@ -401,7 +519,7 @@ def list_scans(
401
519
  values.extend((query, query, query, query, query))
402
520
  where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
403
521
  paginated = args is not None and (args.limit is not None or args.offset != 0)
404
- limit = min(args.limit or FINDINGS_PAGE_MAX, FINDINGS_PAGE_MAX) if paginated else None
522
+ limit = (args.limit or FINDINGS_PAGE_MAX) if paginated else None
405
523
  pagination = "LIMIT ? OFFSET ?" if paginated else ""
406
524
  if limit is not None:
407
525
  values.extend((limit + 1, args.offset))
@@ -409,7 +527,7 @@ def list_scans(
409
527
  f"""
410
528
  {SCAN_SUMMARY_QUERY}
411
529
  {where}
412
- ORDER BY
530
+ ORDER BY {worktree_order}
413
531
  CASE WHEN scans.status = 'running' AND scans.canceled_at IS NULL THEN 0 ELSE 1 END,
414
532
  MAX(julianday(upper(scans.updated_at)), julianday(upper(progress.updated_at))) DESC,
415
533
  julianday(upper(scans.started_at)) DESC,
@@ -418,7 +536,11 @@ def list_scans(
418
536
  """,
419
537
  values,
420
538
  ).fetchall()
421
- result = {"scans": [scan_summary(row) for row in rows[:limit]]}
539
+ scans = [scan_summary(row) for row in rows[:limit]]
540
+ if worktree_order:
541
+ for scan in scans:
542
+ scan["inCurrentWorktree"] = in_worktree(scan["targetPath"])
543
+ result = {"scans": scans}
422
544
  if limit is not None:
423
545
  result.update(
424
546
  {
@@ -430,6 +552,72 @@ def list_scans(
430
552
  return result
431
553
 
432
554
 
555
+ def _scan_completion_order(scan: sqlite3.Row) -> tuple[int, int | Fraction, str]:
556
+ sequence = scan["completion_sequence"] if "completion_sequence" in scan.keys() else None
557
+ if sequence is not None:
558
+ return (1, sequence, scan["id"])
559
+ completed_at = scan["completed_at"] if "completed_at" in scan.keys() else None
560
+ timestamp = _timestamp_ns(completed_at)
561
+ if timestamp is None:
562
+ timestamp = _timestamp_ns(scan["started_at"])
563
+ return (0, timestamp if timestamp is not None else 0, scan["id"])
564
+
565
+
566
+ _FindingSites = dict[tuple[str, str | None, PurePosixPath, int, int], dict[str, Any] | None]
567
+ # Match the first location shown by compactFinding in finding-catalogue.ts.
568
+ _COMPARISON_LOCATION_RANK = {"root_control": 0, "expected_control": 1, "concrete_implementation": 1}
569
+
570
+
571
+ def _unique_finding_sites(findings: list[dict[str, Any]]) -> _FindingSites:
572
+ sites = {}
573
+ for finding in findings:
574
+ if not finding.get("locations"):
575
+ return {}
576
+ location = min(
577
+ finding["locations"],
578
+ key=lambda site: _COMPARISON_LOCATION_RANK.get(site.get("role"), 2),
579
+ )
580
+ key = (
581
+ finding["ruleId"],
582
+ finding["identity"].get("instance"),
583
+ PurePosixPath(location["path"]),
584
+ location["startLine"],
585
+ location.get("endLine", location["startLine"]),
586
+ )
587
+ sites[key] = None if key in sites else finding
588
+ return sites
589
+
590
+
591
+ def _cross_mode_context(
592
+ before: sqlite3.Row,
593
+ after: sqlite3.Row,
594
+ findings: dict[str, list[dict[str, Any]]],
595
+ sites: dict[str, _FindingSites],
596
+ ) -> dict[str, Any]:
597
+ # Different repository subdirectories can share both the Git revision and clean digest.
598
+ if (
599
+ {before["mode"], after["mode"]} != {"standard", "deep"}
600
+ or before["target_id"] is None
601
+ or before["target_id"] != after["target_id"]
602
+ or before["target_revision"] != after["target_revision"]
603
+ or before["target_snapshot_digest"] is None
604
+ or before["target_snapshot_digest"] != after["target_snapshot_digest"]
605
+ or not findings[before["id"]]
606
+ or not findings[after["id"]]
607
+ ):
608
+ return {}
609
+ for scan_id in (before["id"], after["id"]):
610
+ if scan_id not in sites:
611
+ sites[scan_id] = _unique_finding_sites(findings[scan_id])
612
+ later = sites[after["id"]]
613
+ occurrences = []
614
+ for site, old in sites[before["id"]].items():
615
+ new = later.get(site)
616
+ if old and new and old["identity"]["anchor"] != new["identity"]["anchor"]:
617
+ occurrences.extend((old["occurrenceId"], new["occurrenceId"]))
618
+ return {"crossModeOccurrenceIds": occurrences} if occurrences else {}
619
+
620
+
433
621
  def list_unmatched_scan_pairs(
434
622
  connection: sqlite3.Connection,
435
623
  args: argparse.Namespace,
@@ -437,49 +625,58 @@ def list_unmatched_scan_pairs(
437
625
  backfill_finding_details: Callable[[sqlite3.Connection, sqlite3.Row], None],
438
626
  read_coverage: Callable[[sqlite3.Row], dict[str, Any]],
439
627
  ) -> dict[str, Any]:
440
- repository = Path(args.repository).expanduser().resolve()
441
- requested = connection.execute(
442
- """
443
- SELECT COALESCE((SELECT id FROM security_targets WHERE current_path = ?), '') AS target_id,
444
- ? AS target_path
445
- """,
446
- (str(repository), str(repository)),
447
- ).fetchone()
448
- selected = []
449
- requested_git = cache(git_output)
450
- membership: dict[tuple[str | None, str], bool] = {}
451
- for scan in connection.execute("SELECT * FROM scans WHERE status = 'complete'"):
452
- target = (scan["target_id"], scan["target_path"])
453
- if target not in membership:
454
- membership[target] = _same_repository(scan, requested, after_git=requested_git)
455
- if membership[target]:
456
- selected.append(scan)
628
+ requested_repository = Path(args.repository).expanduser().absolute()
629
+ repository = requested_repository.resolve()
630
+ identities = RepositoryIdentityCache(connection)
631
+ requested = identities.for_path(str(requested_repository))
632
+ if identities.supports_identity:
633
+ requested.require_owner()
634
+ clause, values = identities.scope_for_path(str(requested_repository)).sql(
635
+ supports_generation=identities.supports_generation
636
+ )
637
+ selected = connection.execute(
638
+ f"SELECT * FROM scans WHERE status = 'complete' AND {clause}",
639
+ values,
640
+ ).fetchall()
457
641
 
458
642
  selected.sort(key=lambda scan: (timestamp_key(scan["started_at"]), scan["id"]))
459
643
 
460
644
  available = []
461
- for selected_index, scan in enumerate(selected):
645
+ for scan in selected:
462
646
  try:
463
647
  read_coverage(scan)
464
648
  except SystemExit:
465
649
  continue
466
- available.append((selected_index, scan))
650
+ available.append(scan)
467
651
 
468
652
  saved_pairs = {
469
- (row["before_scan_id"], row["after_scan_id"])
653
+ frozenset((row["before_scan_id"], row["after_scan_id"]))
470
654
  for row in connection.execute("SELECT before_scan_id, after_scan_id FROM scan_comparisons")
471
655
  }
656
+ focus_scan_id = getattr(args, "after_scan_id", None)
657
+ if focus_scan_id is not None and not any(scan["id"] == focus_scan_id for scan in selected):
658
+ raise SystemExit("The scan to match is not a completed scan in this repository.")
659
+ if focus_scan_id is not None:
660
+ available.sort(key=_scan_completion_order)
472
661
  batches = []
473
662
  skipped = 0
474
663
  matching_findings: dict[str, list[dict[str, Any]]] = {}
664
+ sites: dict[str, _FindingSites] = {}
475
665
  known_links: list[sqlite3.Row] | None = None
476
- for index, (selected_index, after) in enumerate(available):
666
+ for index, after in enumerate(available):
667
+ if focus_scan_id is not None and after["id"] != focus_scan_id:
668
+ continue
669
+ candidates = [
670
+ before
671
+ for before in available[:index]
672
+ if _same_repository(connection, before, after, identities=identities)
673
+ ]
477
674
  previous = [
478
675
  before
479
- for _, before in available[:index]
480
- if args.force or (before["id"], after["id"]) not in saved_pairs
676
+ for before in candidates
677
+ if args.force or frozenset((before["id"], after["id"])) not in saved_pairs
481
678
  ]
482
- skipped += index - len(previous)
679
+ skipped += len(candidates) - len(previous)
483
680
  if not previous:
484
681
  continue
485
682
  if known_links is None:
@@ -496,7 +693,16 @@ def list_unmatched_scan_pairs(
496
693
  ]
497
694
  known_groups = _known_finding_groups(
498
695
  known_links,
499
- {scan["id"] for scan in selected[: selected_index + 1]},
696
+ {
697
+ scan["id"]
698
+ for scan in selected
699
+ if (
700
+ _scan_completion_order(scan) <= _scan_completion_order(after)
701
+ if focus_scan_id is not None
702
+ else (timestamp_key(scan["started_at"]), scan["id"])
703
+ <= (timestamp_key(after["started_at"]), after["id"])
704
+ )
705
+ },
500
706
  )
501
707
  batches.append(
502
708
  {
@@ -504,6 +710,7 @@ def list_unmatched_scan_pairs(
504
710
  "afterScanId": after["id"],
505
711
  "beforeScans": [
506
712
  {
713
+ **_cross_mode_context(before, after, matching_findings, sites),
507
714
  "findings": matching_findings[before["id"]],
508
715
  "scanId": before["id"],
509
716
  }
@@ -578,13 +785,14 @@ def compare_scans(
578
785
  include_matching_inputs: bool = False,
579
786
  require_matches: bool = False,
580
787
  ) -> dict[str, Any]:
788
+ """Compare completed scans of the same repository, returning finding groups and any inputs needed for matching."""
581
789
  before = require_scan(connection, args.before_scan_id)
582
790
  after = require_scan(connection, args.after_scan_id)
583
791
  if before["id"] == after["id"]:
584
792
  raise SystemExit("Select two different scans to compare.")
585
793
  if before["status"] != "complete" or after["status"] != "complete":
586
794
  raise SystemExit("Only completed scans can be compared.")
587
- if not _same_repository(before, after):
795
+ if not _same_repository(connection, before, after):
588
796
  raise SystemExit("Semantic scan comparisons require the same repository target.")
589
797
  cached = connection.execute(
590
798
  "SELECT result_json FROM scan_comparisons WHERE before_scan_id = ? AND after_scan_id = ?",
@@ -601,7 +809,7 @@ def compare_scans(
601
809
  f"'codex-security scans compare {after['id']} {before['id']}'."
602
810
  )
603
811
  raise SystemExit(
604
- "No saved matches for these scans. Run 'codex-security scans match BEFORE AFTER' first."
812
+ "No saved matches for these scans. Run 'codex-security scans compare BEFORE AFTER' first."
605
813
  )
606
814
  if include_matching_inputs and backfill_finding_details is not None:
607
815
  backfill_finding_details(connection, before)
@@ -611,9 +819,7 @@ def compare_scans(
611
819
  after_findings = _scan_findings(connection, after["id"])
612
820
  matches = json.loads(cached["result_json"]) if cached is not None else None
613
821
  saved_matches = matches["matches"] if matches is not None else []
614
- occurrences = {
615
- row["id"]: row for row in chain(before_findings.values(), after_findings.values())
616
- }
822
+ occurrences = before_findings | after_findings
617
823
  aliases = _confirmed_finding_aliases(connection, occurrences)
618
824
  groups = _finding_groups(before_findings, after_findings, saved_matches, aliases)
619
825
  uncertain = (
@@ -632,17 +838,8 @@ def compare_scans(
632
838
  }
633
839
 
634
840
  for previous_rows, current_rows, match_reason in groups:
635
- previous = (
636
- min(previous_rows, key=lambda row: SEVERITY_ORDER[row["severity"]])
637
- if previous_rows
638
- else None
639
- )
640
- current = (
641
- min(current_rows, key=lambda row: SEVERITY_ORDER[row["severity"]])
642
- if current_rows
643
- else None
644
- )
645
- selected = current if current is not None else previous
841
+ selected_rows = current_rows or previous_rows
842
+ selected = min(selected_rows, key=lambda row: SEVERITY_ORDER[row["severity"]])
646
843
  item = {
647
844
  "findingId": selected["finding_id"],
648
845
  "path": selected["relative_path"],
@@ -653,18 +850,12 @@ def compare_scans(
653
850
  uncertain_reason = next(
654
851
  (
655
852
  uncertain[(side, row["id"])]
656
- for row in current_rows or previous_rows
853
+ for row in selected_rows
657
854
  if (side, row["id"]) in uncertain
658
855
  ),
659
856
  None,
660
857
  )
661
- if previous is None:
662
- if uncertain_reason is None:
663
- status = "new"
664
- else:
665
- status = "unknown"
666
- item["reason"] = uncertain_reason
667
- elif current is not None:
858
+ if previous_rows and current_rows:
668
859
  status = (
669
860
  "reopened"
670
861
  if any(
@@ -679,6 +870,8 @@ def compare_scans(
679
870
  elif uncertain_reason is not None:
680
871
  status = "unknown"
681
872
  item["reason"] = uncertain_reason
873
+ elif current_rows:
874
+ status = "new"
682
875
  elif not all(
683
876
  scan_covers_path(
684
877
  after,
@@ -699,17 +892,17 @@ def compare_scans(
699
892
  status = "not_observed"
700
893
  item["reason"] = "Not observed in the later scan; remediation has not been verified."
701
894
  if len(previous_rows) == 1:
702
- item["beforeOccurrenceId"] = previous["id"]
895
+ item["beforeOccurrenceId"] = previous_rows[0]["id"]
703
896
  elif previous_rows:
704
897
  item["beforeOccurrenceIds"] = [row["id"] for row in previous_rows]
705
898
  if len(current_rows) == 1:
706
- item["afterOccurrenceId"] = current["id"]
899
+ item["afterOccurrenceId"] = current_rows[0]["id"]
707
900
  elif current_rows:
708
901
  item["afterOccurrenceIds"] = [row["id"] for row in current_rows]
709
- if current is not None:
902
+ if current_rows:
710
903
  item["triage"] = {
711
- "closeReason": current["close_reason"],
712
- "status": current["triage_status"],
904
+ "closeReason": selected["close_reason"],
905
+ "status": selected["triage_status"],
713
906
  }
714
907
  item["status"] = status
715
908
  findings.append(item)
@@ -734,14 +927,13 @@ def compare_scans(
734
927
  for pair in related
735
928
  ]
736
929
  if include_matching_inputs:
930
+ identities = RepositoryIdentityCache(connection)
737
931
  after_key = (timestamp_key(after["started_at"]), after["id"])
738
932
  known_scan_ids = {
739
933
  scan["id"]
740
- for scan in connection.execute(
741
- "SELECT id, started_at, target_id, target_path FROM scans WHERE status = 'complete'"
742
- )
934
+ for scan in connection.execute("SELECT * FROM scans WHERE status = 'complete'")
743
935
  if (timestamp_key(scan["started_at"]), scan["id"]) <= after_key
744
- and _same_repository(scan, after)
936
+ and _same_repository(connection, scan, after, identities=identities)
745
937
  }
746
938
  excluded_pairs = {(before["id"], after["id"]), (after["id"], before["id"])}
747
939
  known_groups = _known_finding_groups(
@@ -752,10 +944,15 @@ def compare_scans(
752
944
  ],
753
945
  known_scan_ids,
754
946
  )
947
+ inputs = {
948
+ before["id"]: [_matching_input(row) for row in before_findings.values()],
949
+ after["id"]: [_matching_input(row) for row in after_findings.values()],
950
+ }
755
951
  result["matchingCached"] = cached is not None
756
952
  result["matchingInputs"] = {
757
- "before": [_matching_input(row) for row in before_findings.values()],
758
- "after": [_matching_input(row) for row in after_findings.values()],
953
+ "before": inputs[before["id"]],
954
+ "after": inputs[after["id"]],
955
+ **_cross_mode_context(before, after, inputs, {}),
759
956
  **({"knownFindingGroups": known_groups} if known_groups else {}),
760
957
  }
761
958
  return result
@@ -775,11 +972,13 @@ def save_scan_comparison(
775
972
  raise SystemExit("Select two different scans to compare.")
776
973
  if before["status"] != "complete" or after["status"] != "complete":
777
974
  raise SystemExit("Only completed scans can be compared.")
778
- if not _same_repository(before, after):
975
+ if not _same_repository(connection, before, after):
779
976
  raise SystemExit("Semantic scan comparisons require the same repository target.")
780
977
  read_coverage(after)
781
- before_findings = _scan_findings(connection, before["id"])
782
- after_findings = _scan_findings(connection, after["id"])
978
+ allowed = {
979
+ "before": set(_scan_findings(connection, before["id"])),
980
+ "after": set(_scan_findings(connection, after["id"])),
981
+ }
783
982
  matches_json = (
784
983
  sys.stdin.read() if getattr(args, "matches_json_stdin", False) else args.matches_json
785
984
  )
@@ -797,10 +996,6 @@ def save_scan_comparison(
797
996
  not isinstance(payload.get(key, []), list) for key in ("matches", "uncertain", "related")
798
997
  ):
799
998
  raise SystemExit("Scan comparison matches must contain matches and uncertain arrays.")
800
- allowed = {
801
- "before": {row["id"] for row in before_findings.values()},
802
- "after": {row["id"] for row in after_findings.values()},
803
- }
804
999
  consumed: dict[str, dict[str, int]] = {"before": {}, "after": {}}
805
1000
  for group, match in enumerate(payload["matches"]):
806
1001
  if (
@@ -858,8 +1053,10 @@ def save_scan_comparison(
858
1053
  with connection:
859
1054
  connection.execute("BEGIN IMMEDIATE")
860
1055
  connection.execute(
861
- "DELETE FROM scan_comparisons WHERE before_scan_id = ? AND after_scan_id = ?",
862
- (before["id"], after["id"]),
1056
+ "DELETE FROM scan_comparisons "
1057
+ "WHERE (before_scan_id = ? AND after_scan_id = ?) "
1058
+ "OR (before_scan_id = ? AND after_scan_id = ?)",
1059
+ (before["id"], after["id"], after["id"], before["id"]),
863
1060
  )
864
1061
  connection.execute(
865
1062
  """
@@ -1021,6 +1218,41 @@ def finding_relations(
1021
1218
  return result
1022
1219
 
1023
1220
 
1221
+ def finding_management_updated_at(connection: sqlite3.Connection, scan_id: str) -> str | None:
1222
+ return connection.execute(
1223
+ """
1224
+ SELECT MAX(updated_at)
1225
+ FROM (
1226
+ SELECT triage.updated_at
1227
+ FROM finding_triage AS triage
1228
+ JOIN finding_occurrences AS occurrences ON occurrences.id = triage.occurrence_id
1229
+ WHERE occurrences.scan_id = ?
1230
+ UNION ALL
1231
+ SELECT remediation.updated_at
1232
+ FROM finding_remediation_attempts AS remediation
1233
+ JOIN finding_occurrences AS occurrences ON occurrences.id = remediation.occurrence_id
1234
+ WHERE occurrences.scan_id = ?
1235
+ )
1236
+ """,
1237
+ (scan_id, scan_id),
1238
+ ).fetchone()[0]
1239
+
1240
+
1241
+ def finding_triage_result(connection: sqlite3.Connection, occurrence_id: str) -> dict[str, Any]:
1242
+ row = connection.execute(
1243
+ "SELECT status, close_reason, note, updated_at FROM finding_triage WHERE occurrence_id = ?",
1244
+ (occurrence_id,),
1245
+ ).fetchone()
1246
+ if row is None:
1247
+ return {"status": "open"}
1248
+ return {
1249
+ "closeReason": row["close_reason"],
1250
+ "note": row["note"],
1251
+ "status": row["status"],
1252
+ "updatedAt": row["updated_at"],
1253
+ }
1254
+
1255
+
1024
1256
  def finding_matches(
1025
1257
  connection: sqlite3.Connection, occurrence_id: str, scan_id: str, started_at: str
1026
1258
  ) -> tuple[list[dict[str, Any]], str, list[str]]:
@@ -1095,10 +1327,7 @@ def _finding_groups(
1095
1327
  matches: list[dict[str, Any]],
1096
1328
  aliases: dict[str, str],
1097
1329
  ) -> list[tuple[list[sqlite3.Row], list[sqlite3.Row], str | None]]:
1098
- rows = {
1099
- side: {row["id"]: row for row in findings.values()}
1100
- for side, findings in (("before", before_findings), ("after", after_findings))
1101
- }
1330
+ rows = {"before": before_findings, "after": after_findings}
1102
1331
  groups: dict[str, tuple[list[sqlite3.Row], list[sqlite3.Row], list[str]]] = {}
1103
1332
 
1104
1333
  def group(row: sqlite3.Row) -> tuple[list[sqlite3.Row], list[sqlite3.Row], list[str]]:
@@ -1226,25 +1455,19 @@ def finding_occurrence_conditions(
1226
1455
 
1227
1456
 
1228
1457
  def _scan_findings(connection: sqlite3.Connection, scan_id: str) -> dict[str, sqlite3.Row]:
1458
+ """Index one scan's finding rows by the occurrence IDs used in comparisons."""
1229
1459
  rows = connection.execute(
1230
- """
1460
+ f"""
1231
1461
  SELECT occurrences.*,
1232
1462
  COALESCE(triage.status, 'open') AS triage_status, triage.close_reason,
1233
- (
1234
- SELECT locations.relative_path
1235
- FROM finding_locations AS locations
1236
- WHERE locations.occurrence_id = occurrences.id
1237
- ORDER BY CASE WHEN locations.role = 'root_control' THEN 0 ELSE 1 END,
1238
- locations.sort_order
1239
- LIMIT 1
1240
- ) AS relative_path
1463
+ (SELECT relative_path {PRIMARY_FINDING_LOCATION_SQL}) AS relative_path
1241
1464
  FROM finding_occurrences AS occurrences
1242
1465
  LEFT JOIN finding_triage AS triage ON triage.occurrence_id = occurrences.id
1243
1466
  WHERE occurrences.scan_id = ?
1244
1467
  """,
1245
1468
  (scan_id,),
1246
1469
  )
1247
- return {row["finding_id"]: row for row in rows}
1470
+ return {row["id"]: row for row in rows}
1248
1471
 
1249
1472
 
1250
1473
  def scan_covers_path(
@@ -1254,6 +1477,7 @@ def scan_covers_path(
1254
1477
  path: str | None,
1255
1478
  coverage: dict[str, Any],
1256
1479
  ) -> bool:
1480
+ """Check whether a completed scan of this target included the path after applying all recorded exclusions."""
1257
1481
  if scan["status"] != "complete" or scan["target_id"] != target_id:
1258
1482
  return False
1259
1483
  if not isinstance(path, str) or not path: