@openai/codex-security 0.1.31 → 0.3.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 (514) hide show
  1. package/README.md +442 -2434
  2. package/_bundled_plugin/.app.json +5 -1
  3. package/_bundled_plugin/.codex-plugin/plugin.json +9 -5
  4. package/_bundled_plugin/.mcp.json +3 -0
  5. package/_bundled_plugin/examples/completed-scan/coverage.json +0 -1
  6. package/_bundled_plugin/examples/completed-scan/report.md +28 -26
  7. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +1 -1
  8. package/_bundled_plugin/mcp/helpers.mjs +1 -0
  9. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  10. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +7 -214
  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/permission-profile-preflight.mjs +563 -0
  20. package/_bundled_plugin/mcp/server.mjs +1 -0
  21. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  22. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  23. package/_bundled_plugin/preflight/capability-profiles.toml +0 -13
  24. package/_bundled_plugin/references/artifact-storage.md +5 -5
  25. package/_bundled_plugin/references/config-preflight.md +1 -5
  26. package/_bundled_plugin/references/core-scan.md +34 -10
  27. package/_bundled_plugin/references/final-report.md +13 -13
  28. package/_bundled_plugin/references/finding-detail-fields.md +90 -80
  29. package/_bundled_plugin/references/sarif-adapter.md +1 -1
  30. package/_bundled_plugin/references/scan-artifacts.md +3 -4
  31. package/_bundled_plugin/references/scan-contract.md +11 -6
  32. package/_bundled_plugin/references/scan-prologue.md +12 -0
  33. package/_bundled_plugin/references/security-guidance.md +2 -2
  34. package/_bundled_plugin/references/standalone-validation.md +11 -0
  35. package/_bundled_plugin/references/threat-model.md +2 -2
  36. package/_bundled_plugin/schemas/coverage.schema.json +23 -47
  37. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +2 -24
  38. package/_bundled_plugin/schemas/definitions/discovery-candidate.schema.json +49 -25
  39. package/_bundled_plugin/schemas/findings.schema.json +71 -192
  40. package/_bundled_plugin/schemas/scan-manifest.schema.json +83 -95
  41. package/_bundled_plugin/schemas/tools/candidate-attack-paths.schema.json +91 -83
  42. package/_bundled_plugin/schemas/tools/candidate-validations.schema.json +35 -64
  43. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +5 -2
  44. package/_bundled_plugin/schemas/tools/discovery-candidates.schema.json +6 -55
  45. package/_bundled_plugin/schemas/tools/review-items.schema.json +2 -38
  46. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +245 -356
  47. package/_bundled_plugin/scripts/codex_profile.mjs +239 -0
  48. package/_bundled_plugin/scripts/codex_session.mjs +53 -0
  49. package/_bundled_plugin/scripts/config_preflight.py +29 -69
  50. package/_bundled_plugin/scripts/deep_scan_config.py +9 -11
  51. package/_bundled_plugin/scripts/deep_scan_workbench.py +208 -363
  52. package/_bundled_plugin/scripts/filesystem_identity.py +1 -5
  53. package/_bundled_plugin/scripts/finalize_scan_contract.py +733 -375
  54. package/_bundled_plugin/scripts/finding_preview.py +81 -91
  55. package/_bundled_plugin/scripts/generate_in_scope_files.py +48 -102
  56. package/_bundled_plugin/scripts/generate_rank_input.py +117 -888
  57. package/_bundled_plugin/scripts/launch_codex_security_mcp +35 -6
  58. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +5 -5
  59. package/_bundled_plugin/scripts/rank_preview.py +43 -902
  60. package/_bundled_plugin/scripts/report_projection.py +143 -219
  61. package/_bundled_plugin/scripts/snapshot_sqlite.py +6 -1
  62. package/_bundled_plugin/scripts/threat_model_projection.py +161 -0
  63. package/_bundled_plugin/scripts/validate_scan_contract.py +4 -34
  64. package/_bundled_plugin/scripts/validate_tracking_source.py +3 -13
  65. package/_bundled_plugin/scripts/windows_scan_local_files.py +59 -9
  66. package/_bundled_plugin/scripts/workbench/handoff.py +25 -50
  67. package/_bundled_plugin/scripts/workbench/runtime_toml.py +22 -0
  68. package/_bundled_plugin/scripts/workbench/storage.py +21 -6
  69. package/_bundled_plugin/scripts/workbench_cli.py +99 -190
  70. package/_bundled_plugin/scripts/workbench_constants.py +6 -14
  71. package/_bundled_plugin/scripts/workbench_db.py +524 -672
  72. package/_bundled_plugin/scripts/workbench_feedback.py +6 -3
  73. package/_bundled_plugin/scripts/workbench_finding_index.py +20 -7
  74. package/_bundled_plugin/scripts/workbench_finding_workflows.py +18 -4
  75. package/_bundled_plugin/scripts/workbench_local_dedupe.py +136 -0
  76. package/_bundled_plugin/scripts/workbench_native_indexes.py +28 -18
  77. package/_bundled_plugin/scripts/workbench_progress.py +26 -92
  78. package/_bundled_plugin/scripts/workbench_publication.py +77 -116
  79. package/_bundled_plugin/scripts/workbench_remediation.py +14 -20
  80. package/_bundled_plugin/scripts/workbench_saved_results.py +1402 -263
  81. package/_bundled_plugin/scripts/workbench_scan_history.py +57 -57
  82. package/_bundled_plugin/scripts/workbench_scan_start.py +109 -52
  83. package/_bundled_plugin/scripts/workbench_scan_usage.py +30 -49
  84. package/_bundled_plugin/scripts/workbench_schema.py +71 -1370
  85. package/_bundled_plugin/scripts/workbench_source_excerpt.py +16 -7
  86. package/_bundled_plugin/scripts/workbench_target.py +526 -150
  87. package/_bundled_plugin/scripts/workbench_target_state.py +1 -5
  88. package/_bundled_plugin/scripts/workbench_validation.py +19 -44
  89. package/_bundled_plugin/shared/workbench-history-repairs.json +218 -0
  90. package/_bundled_plugin/shared/workbench-migrations.json +397 -0
  91. package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +15 -4
  92. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +1 -0
  93. package/_bundled_plugin/skills/cloud-findings/SKILL.md +54 -0
  94. package/_bundled_plugin/skills/cloud-findings/agents/openai.yaml +4 -0
  95. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +6 -6
  96. package/_bundled_plugin/skills/deep-security-scan/agents/openai.yaml +1 -1
  97. package/_bundled_plugin/skills/finding-discovery/SKILL.md +3 -3
  98. package/_bundled_plugin/skills/propose-security-hardening/references/proposal-format.md +50 -20
  99. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +8 -14
  100. package/_bundled_plugin/skills/security-diff-scan/agents/openai.yaml +1 -1
  101. package/_bundled_plugin/skills/security-scan/SKILL.md +22 -7
  102. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +1 -1
  103. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +2 -2
  104. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +13 -1
  105. package/_bundled_plugin/skills/threat-model/SKILL.md +2 -2
  106. package/_bundled_plugin/skills/track-findings/SKILL.md +46 -178
  107. package/_bundled_plugin/skills/track-findings/agents/openai.yaml +1 -1
  108. package/_bundled_plugin/skills/track-findings/references/github-security-advisories.md +16 -24
  109. package/_bundled_plugin/skills/track-findings/references/jira.md +15 -61
  110. package/_bundled_plugin/skills/triage-finding/SKILL.md +50 -289
  111. package/_bundled_plugin/skills/triage-finding/agents/openai.yaml +2 -2
  112. package/_bundled_plugin/skills/triage-finding/references/ticket-intake.md +23 -43
  113. package/_bundled_plugin/skills/triage-finding/references/triage-result-contract.md +7 -1
  114. package/bin/codex-security.mjs +9 -2
  115. package/dist/api.d.ts +63 -15
  116. package/dist/api.d.ts.map +1 -1
  117. package/dist/api.js +970 -553
  118. package/dist/api.js.map +1 -1
  119. package/dist/artifact-export.d.ts +70 -0
  120. package/dist/artifact-export.d.ts.map +1 -0
  121. package/dist/artifact-export.js +292 -0
  122. package/dist/artifact-export.js.map +1 -0
  123. package/dist/auth.d.ts +2 -6
  124. package/dist/auth.d.ts.map +1 -1
  125. package/dist/auth.js +27 -12
  126. package/dist/auth.js.map +1 -1
  127. package/dist/bulk-scan-discovery.d.ts +1 -0
  128. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  129. package/dist/bulk-scan-discovery.js +9 -9
  130. package/dist/bulk-scan-discovery.js.map +1 -1
  131. package/dist/classify-scan-severity.d.ts.map +1 -1
  132. package/dist/classify-scan-severity.js +2 -5
  133. package/dist/classify-scan-severity.js.map +1 -1
  134. package/dist/classify-severity.d.ts +28 -17
  135. package/dist/classify-severity.d.ts.map +1 -1
  136. package/dist/classify-severity.js +16 -35
  137. package/dist/classify-severity.js.map +1 -1
  138. package/dist/cli-help.d.ts +3 -0
  139. package/dist/cli-help.d.ts.map +1 -0
  140. package/dist/cli-help.js +285 -0
  141. package/dist/cli-help.js.map +1 -0
  142. package/dist/cli-signals.d.ts +8 -0
  143. package/dist/cli-signals.d.ts.map +1 -0
  144. package/dist/cli-signals.js +28 -0
  145. package/dist/cli-signals.js.map +1 -0
  146. package/dist/cli.d.ts +22 -24
  147. package/dist/cli.d.ts.map +1 -1
  148. package/dist/cli.js +1660 -1556
  149. package/dist/cli.js.map +1 -1
  150. package/dist/cloud-publish.d.ts.map +1 -1
  151. package/dist/cloud-publish.js +11 -17
  152. package/dist/cloud-publish.js.map +1 -1
  153. package/dist/codeowners.d.ts +19 -0
  154. package/dist/codeowners.d.ts.map +1 -0
  155. package/dist/codeowners.js +138 -0
  156. package/dist/codeowners.js.map +1 -0
  157. package/dist/codex-prompt.d.ts.map +1 -1
  158. package/dist/codex-prompt.js +1 -2
  159. package/dist/codex-prompt.js.map +1 -1
  160. package/dist/codex-sdk-environment.d.ts +3 -0
  161. package/dist/codex-sdk-environment.d.ts.map +1 -0
  162. package/dist/codex-sdk-environment.js +68 -0
  163. package/dist/codex-sdk-environment.js.map +1 -0
  164. package/dist/component-plan.d.ts +2 -5
  165. package/dist/component-plan.d.ts.map +1 -1
  166. package/dist/component-plan.js +38 -34
  167. package/dist/component-plan.js.map +1 -1
  168. package/dist/component-scan.d.ts +7 -5
  169. package/dist/component-scan.d.ts.map +1 -1
  170. package/dist/component-scan.js +54 -44
  171. package/dist/component-scan.js.map +1 -1
  172. package/dist/config.d.ts.map +1 -1
  173. package/dist/config.js +93 -104
  174. package/dist/config.js.map +1 -1
  175. package/dist/contract.d.ts +15 -2
  176. package/dist/contract.d.ts.map +1 -1
  177. package/dist/contract.js +124 -348
  178. package/dist/contract.js.map +1 -1
  179. package/dist/cost-model.d.ts +13 -6
  180. package/dist/cost-model.d.ts.map +1 -1
  181. package/dist/cost-model.js +75 -34
  182. package/dist/cost-model.js.map +1 -1
  183. package/dist/cost.d.ts +10 -2
  184. package/dist/cost.d.ts.map +1 -1
  185. package/dist/cost.js +116 -134
  186. package/dist/cost.js.map +1 -1
  187. package/dist/custom-validation-prompt.d.ts.map +1 -1
  188. package/dist/custom-validation-prompt.js +7 -6
  189. package/dist/custom-validation-prompt.js.map +1 -1
  190. package/dist/custom-validation.d.ts +1 -2
  191. package/dist/custom-validation.d.ts.map +1 -1
  192. package/dist/custom-validation.js +23 -16
  193. package/dist/custom-validation.js.map +1 -1
  194. package/dist/deduplication/checkpointed-review.d.ts +4 -2
  195. package/dist/deduplication/checkpointed-review.d.ts.map +1 -1
  196. package/dist/deduplication/checkpointed-review.js +33 -20
  197. package/dist/deduplication/checkpointed-review.js.map +1 -1
  198. package/dist/deduplication/codex-review.d.ts +9 -1
  199. package/dist/deduplication/codex-review.d.ts.map +1 -1
  200. package/dist/deduplication/codex-review.js +129 -20
  201. package/dist/deduplication/codex-review.js.map +1 -1
  202. package/dist/deduplication/deduplication-prompts.d.ts +5 -2
  203. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
  204. package/dist/deduplication/deduplication-prompts.js +18 -4
  205. package/dist/deduplication/deduplication-prompts.js.map +1 -1
  206. package/dist/deduplication/deduplication-reviewer.d.ts +26 -4
  207. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
  208. package/dist/deduplication/deduplication-reviewer.js +59 -47
  209. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  210. package/dist/deduplication/deduplication.d.ts.map +1 -1
  211. package/dist/deduplication/deduplication.js +59 -113
  212. package/dist/deduplication/deduplication.js.map +1 -1
  213. package/dist/deduplication/diagnostics.d.ts +17 -0
  214. package/dist/deduplication/diagnostics.d.ts.map +1 -0
  215. package/dist/deduplication/diagnostics.js +5 -0
  216. package/dist/deduplication/diagnostics.js.map +1 -0
  217. package/dist/deduplication/finding-schema.d.ts.map +1 -1
  218. package/dist/deduplication/finding-schema.js +7 -1
  219. package/dist/deduplication/finding-schema.js.map +1 -1
  220. package/dist/deduplication/local.d.ts +31 -0
  221. package/dist/deduplication/local.d.ts.map +1 -0
  222. package/dist/deduplication/local.js +166 -0
  223. package/dist/deduplication/local.js.map +1 -0
  224. package/dist/deduplication/records-protocol.d.ts.map +1 -1
  225. package/dist/deduplication/records-protocol.js +12 -28
  226. package/dist/deduplication/records-protocol.js.map +1 -1
  227. package/dist/deduplication/records.d.ts +188 -12
  228. package/dist/deduplication/records.d.ts.map +1 -1
  229. package/dist/deduplication/records.js +34 -24
  230. package/dist/deduplication/records.js.map +1 -1
  231. package/dist/deduplication/review.d.ts +7 -0
  232. package/dist/deduplication/review.d.ts.map +1 -1
  233. package/dist/deduplication/review.js.map +1 -1
  234. package/dist/deduplication/scan.d.ts +9 -3
  235. package/dist/deduplication/scan.d.ts.map +1 -1
  236. package/dist/deduplication/scan.js +159 -44
  237. package/dist/deduplication/scan.js.map +1 -1
  238. package/dist/deep-config.d.ts +2 -1
  239. package/dist/deep-config.d.ts.map +1 -1
  240. package/dist/deep-config.js +7 -23
  241. package/dist/deep-config.js.map +1 -1
  242. package/dist/deep-progress.d.ts +2 -1
  243. package/dist/deep-progress.d.ts.map +1 -1
  244. package/dist/deep-progress.js +32 -47
  245. package/dist/deep-progress.js.map +1 -1
  246. package/dist/deep-scan.d.ts +20 -0
  247. package/dist/deep-scan.d.ts.map +1 -0
  248. package/dist/deep-scan.js +113 -0
  249. package/dist/deep-scan.js.map +1 -0
  250. package/dist/errors.d.ts +5 -2
  251. package/dist/errors.d.ts.map +1 -1
  252. package/dist/errors.js +7 -7
  253. package/dist/errors.js.map +1 -1
  254. package/dist/feedback.d.ts.map +1 -1
  255. package/dist/feedback.js +53 -21
  256. package/dist/feedback.js.map +1 -1
  257. package/dist/finding-catalogue.d.ts.map +1 -1
  258. package/dist/finding-catalogue.js +26 -30
  259. package/dist/finding-catalogue.js.map +1 -1
  260. package/dist/finding-normalization.d.ts +5 -0
  261. package/dist/finding-normalization.d.ts.map +1 -0
  262. package/dist/finding-normalization.js +120 -0
  263. package/dist/finding-normalization.js.map +1 -0
  264. package/dist/finding-retrieval.d.ts +9 -0
  265. package/dist/finding-retrieval.d.ts.map +1 -1
  266. package/dist/finding-retrieval.js.map +1 -1
  267. package/dist/finding-workflow.d.ts +13 -8
  268. package/dist/finding-workflow.d.ts.map +1 -1
  269. package/dist/finding-workflow.js +18 -13
  270. package/dist/finding-workflow.js.map +1 -1
  271. package/dist/findings-client.d.ts +2 -1
  272. package/dist/findings-client.d.ts.map +1 -1
  273. package/dist/findings-client.js +36 -9
  274. package/dist/findings-client.js.map +1 -1
  275. package/dist/findings-errors.d.ts +16 -0
  276. package/dist/findings-errors.d.ts.map +1 -0
  277. package/dist/findings-errors.js +24 -0
  278. package/dist/findings-errors.js.map +1 -0
  279. package/dist/findings-import.d.ts +1 -1
  280. package/dist/findings-import.d.ts.map +1 -1
  281. package/dist/findings-import.js +16 -44
  282. package/dist/findings-import.js.map +1 -1
  283. package/dist/github.d.ts.map +1 -1
  284. package/dist/github.js +9 -4
  285. package/dist/github.js.map +1 -1
  286. package/dist/import-scan.d.ts.map +1 -1
  287. package/dist/import-scan.js +49 -39
  288. package/dist/import-scan.js.map +1 -1
  289. package/dist/index.d.ts +11 -5
  290. package/dist/index.d.ts.map +1 -1
  291. package/dist/index.js +2 -1
  292. package/dist/index.js.map +1 -1
  293. package/dist/knowledge-base.d.ts +7 -1
  294. package/dist/knowledge-base.d.ts.map +1 -1
  295. package/dist/knowledge-base.js +115 -47
  296. package/dist/knowledge-base.js.map +1 -1
  297. package/dist/linear.d.ts.map +1 -1
  298. package/dist/linear.js +4 -10
  299. package/dist/linear.js.map +1 -1
  300. package/dist/mock-scan.d.ts.map +1 -1
  301. package/dist/mock-scan.js +0 -1
  302. package/dist/mock-scan.js.map +1 -1
  303. package/dist/models.d.ts +24 -2
  304. package/dist/models.d.ts.map +1 -1
  305. package/dist/models.js.map +1 -1
  306. package/dist/multiscan.d.ts +9 -3
  307. package/dist/multiscan.d.ts.map +1 -1
  308. package/dist/multiscan.js +225 -153
  309. package/dist/multiscan.js.map +1 -1
  310. package/dist/owner-evidence.d.ts +10 -2
  311. package/dist/owner-evidence.d.ts.map +1 -1
  312. package/dist/owner-evidence.js +69 -14
  313. package/dist/owner-evidence.js.map +1 -1
  314. package/dist/patch-tui.d.ts.map +1 -1
  315. package/dist/patch-tui.js +5 -6
  316. package/dist/patch-tui.js.map +1 -1
  317. package/dist/project-config-schema.d.ts +10 -0
  318. package/dist/project-config-schema.d.ts.map +1 -1
  319. package/dist/project-config-schema.js +1 -0
  320. package/dist/project-config-schema.js.map +1 -1
  321. package/dist/project-config.d.ts +1 -0
  322. package/dist/project-config.d.ts.map +1 -1
  323. package/dist/project-config.js +5 -3
  324. package/dist/project-config.js.map +1 -1
  325. package/dist/prompt-files.d.ts +0 -1
  326. package/dist/prompt-files.d.ts.map +1 -1
  327. package/dist/prompt-files.js +2 -4
  328. package/dist/prompt-files.js.map +1 -1
  329. package/dist/provider-profile.d.ts +21 -0
  330. package/dist/provider-profile.d.ts.map +1 -0
  331. package/dist/provider-profile.js +133 -0
  332. package/dist/provider-profile.js.map +1 -0
  333. package/dist/publication-events.d.ts +6 -8
  334. package/dist/publication-events.d.ts.map +1 -1
  335. package/dist/publication-events.js +40 -79
  336. package/dist/publication-events.js.map +1 -1
  337. package/dist/publication-store.d.ts.map +1 -1
  338. package/dist/publication-store.js +48 -76
  339. package/dist/publication-store.js.map +1 -1
  340. package/dist/publication.d.ts +1 -2
  341. package/dist/publication.d.ts.map +1 -1
  342. package/dist/publication.js +7 -16
  343. package/dist/publication.js.map +1 -1
  344. package/dist/publish.d.ts +1 -5
  345. package/dist/publish.d.ts.map +1 -1
  346. package/dist/publish.js +138 -199
  347. package/dist/publish.js.map +1 -1
  348. package/dist/record.d.ts +2 -0
  349. package/dist/record.d.ts.map +1 -0
  350. package/dist/record.js +4 -0
  351. package/dist/record.js.map +1 -0
  352. package/dist/request-metadata.d.ts +9 -0
  353. package/dist/request-metadata.d.ts.map +1 -0
  354. package/dist/request-metadata.js +13 -0
  355. package/dist/request-metadata.js.map +1 -0
  356. package/dist/result.d.ts +4 -1
  357. package/dist/result.d.ts.map +1 -1
  358. package/dist/result.js +7 -0
  359. package/dist/result.js.map +1 -1
  360. package/dist/runtime.d.ts +25 -17
  361. package/dist/runtime.d.ts.map +1 -1
  362. package/dist/runtime.js +619 -255
  363. package/dist/runtime.js.map +1 -1
  364. package/dist/saved-scan-bootstrap.d.ts +14 -0
  365. package/dist/saved-scan-bootstrap.d.ts.map +1 -0
  366. package/dist/saved-scan-bootstrap.js +261 -0
  367. package/dist/saved-scan-bootstrap.js.map +1 -0
  368. package/dist/saved-scan.d.ts +1 -1
  369. package/dist/saved-scan.d.ts.map +1 -1
  370. package/dist/saved-scan.js +16 -32
  371. package/dist/saved-scan.js.map +1 -1
  372. package/dist/scan-activity.d.ts.map +1 -1
  373. package/dist/scan-activity.js +19 -30
  374. package/dist/scan-activity.js.map +1 -1
  375. package/dist/scan-comparison.d.ts +31 -18
  376. package/dist/scan-comparison.d.ts.map +1 -1
  377. package/dist/scan-comparison.js +307 -347
  378. package/dist/scan-comparison.js.map +1 -1
  379. package/dist/scan-dashboard.d.ts +3 -1
  380. package/dist/scan-dashboard.d.ts.map +1 -1
  381. package/dist/scan-dashboard.js +351 -92
  382. package/dist/scan-dashboard.js.map +1 -1
  383. package/dist/scan-history-renderer.d.ts.map +1 -1
  384. package/dist/scan-history-renderer.js +55 -15
  385. package/dist/scan-history-renderer.js.map +1 -1
  386. package/dist/scan-inputs.d.ts +6 -0
  387. package/dist/scan-inputs.d.ts.map +1 -0
  388. package/dist/scan-inputs.js +71 -0
  389. package/dist/scan-inputs.js.map +1 -0
  390. package/dist/scan-logs.d.ts +2 -3
  391. package/dist/scan-logs.d.ts.map +1 -1
  392. package/dist/scan-logs.js +14 -12
  393. package/dist/scan-logs.js.map +1 -1
  394. package/dist/scan-sessions.d.ts +4 -0
  395. package/dist/scan-sessions.d.ts.map +1 -1
  396. package/dist/scan-sessions.js +18 -3
  397. package/dist/scan-sessions.js.map +1 -1
  398. package/dist/scan-settings.d.ts +5 -0
  399. package/dist/scan-settings.d.ts.map +1 -1
  400. package/dist/scan-settings.js +4 -0
  401. package/dist/scan-settings.js.map +1 -1
  402. package/dist/scan-skill-paths.d.ts +8 -0
  403. package/dist/scan-skill-paths.d.ts.map +1 -0
  404. package/dist/scan-skill-paths.js +47 -0
  405. package/dist/scan-skill-paths.js.map +1 -0
  406. package/dist/security-policy-cli.d.ts.map +1 -1
  407. package/dist/security-policy-cli.js +15 -33
  408. package/dist/security-policy-cli.js.map +1 -1
  409. package/dist/security-policy.d.ts +17 -9
  410. package/dist/security-policy.d.ts.map +1 -1
  411. package/dist/security-policy.js +131 -98
  412. package/dist/security-policy.js.map +1 -1
  413. package/dist/server/api.d.ts +0 -1
  414. package/dist/server/api.d.ts.map +1 -1
  415. package/dist/server/api.js +0 -1
  416. package/dist/server/api.js.map +1 -1
  417. package/dist/server/embeddings.d.ts +3 -1
  418. package/dist/server/embeddings.d.ts.map +1 -1
  419. package/dist/server/embeddings.js +11 -3
  420. package/dist/server/embeddings.js.map +1 -1
  421. package/dist/server/errors.d.ts +5 -2
  422. package/dist/server/errors.d.ts.map +1 -1
  423. package/dist/server/errors.js +7 -0
  424. package/dist/server/errors.js.map +1 -1
  425. package/dist/server/sqlite-store.d.ts +0 -2
  426. package/dist/server/sqlite-store.d.ts.map +1 -1
  427. package/dist/server/sqlite-store.js +55 -55
  428. package/dist/server/sqlite-store.js.map +1 -1
  429. package/dist/server/storage.d.ts +0 -2
  430. package/dist/server/storage.d.ts.map +1 -1
  431. package/dist/server/storage.js.map +1 -1
  432. package/dist/severity-store.js +20 -32
  433. package/dist/severity-store.js.map +1 -1
  434. package/dist/standalone-validation-prompt.d.ts +2 -0
  435. package/dist/standalone-validation-prompt.d.ts.map +1 -0
  436. package/dist/standalone-validation-prompt.js +10 -0
  437. package/dist/standalone-validation-prompt.js.map +1 -0
  438. package/dist/suggest-owners.d.ts +6 -5
  439. package/dist/suggest-owners.d.ts.map +1 -1
  440. package/dist/suggest-owners.js +15 -10
  441. package/dist/suggest-owners.js.map +1 -1
  442. package/dist/targets.d.ts +12 -0
  443. package/dist/targets.d.ts.map +1 -1
  444. package/dist/targets.js +124 -62
  445. package/dist/targets.js.map +1 -1
  446. package/dist/trusted-executable.d.ts +6 -1
  447. package/dist/trusted-executable.d.ts.map +1 -1
  448. package/dist/trusted-executable.js +28 -9
  449. package/dist/trusted-executable.js.map +1 -1
  450. package/dist/value.d.ts +2 -0
  451. package/dist/value.d.ts.map +1 -0
  452. package/dist/value.js +27 -0
  453. package/dist/value.js.map +1 -0
  454. package/dist/version.d.ts.map +1 -1
  455. package/dist/version.js +3 -6
  456. package/dist/version.js.map +1 -1
  457. package/dist/windows-path.d.ts.map +1 -1
  458. package/dist/windows-path.js +1 -2
  459. package/dist/windows-path.js.map +1 -1
  460. package/dist/workbench-arguments.d.ts +3 -0
  461. package/dist/workbench-arguments.d.ts.map +1 -0
  462. package/dist/workbench-arguments.js +15 -0
  463. package/dist/workbench-arguments.js.map +1 -0
  464. package/dist/worker-progress.d.ts +2 -0
  465. package/dist/worker-progress.d.ts.map +1 -1
  466. package/dist/worker-progress.js +40 -46
  467. package/dist/worker-progress.js.map +1 -1
  468. package/docs/cli.md +1778 -0
  469. package/docs/dedupe-records.md +24 -0
  470. package/docs/findings-service.md +402 -0
  471. package/package.json +23 -23
  472. package/schemas/project-config.schema.json +5 -0
  473. package/_bundled_plugin/schemas/tools/worker-threat-model.schema.json +0 -18
  474. package/_bundled_plugin/scripts/normalize_candidates.py +0 -338
  475. package/_bundled_plugin/scripts/workbench_dashboard.py +0 -159
  476. package/_bundled_plugin/scripts/workbench_findings.py +0 -221
  477. package/_bundled_plugin/scripts/workbench_severity.py +0 -119
  478. package/_bundled_plugin/skills/assess-patch-risk/scripts/validate_patch_risk_assessment.py +0 -163
  479. package/dist/server/dashboard/THIRD_PARTY_NOTICES.txt +0 -276
  480. package/dist/server/dashboard/app.css +0 -2
  481. package/dist/server/dashboard/app.js +0 -66
  482. package/dist/server/dashboard/index.html +0 -18
  483. package/dist/server/dashboard-types.d.ts +0 -48
  484. package/dist/server/dashboard-types.d.ts.map +0 -1
  485. package/dist/server/dashboard-types.js +0 -2
  486. package/dist/server/dashboard-types.js.map +0 -1
  487. package/dist/server/dashboard.d.ts +0 -6
  488. package/dist/server/dashboard.d.ts.map +0 -1
  489. package/dist/server/dashboard.js +0 -59
  490. package/dist/server/dashboard.js.map +0 -1
  491. package/dist/server/findings-service.d.ts +0 -20
  492. package/dist/server/findings-service.d.ts.map +0 -1
  493. package/dist/server/findings-service.js +0 -31
  494. package/dist/server/findings-service.js.map +0 -1
  495. package/dist/server/index.d.ts +0 -2
  496. package/dist/server/index.d.ts.map +0 -1
  497. package/dist/server/index.js +0 -6
  498. package/dist/server/index.js.map +0 -1
  499. package/dist/server/routes.d.ts +0 -6
  500. package/dist/server/routes.d.ts.map +0 -1
  501. package/dist/server/routes.js +0 -86
  502. package/dist/server/routes.js.map +0 -1
  503. package/dist/server/serve.d.ts +0 -2
  504. package/dist/server/serve.d.ts.map +0 -1
  505. package/dist/server/serve.js +0 -28
  506. package/dist/server/serve.js.map +0 -1
  507. package/dist/server/server.d.ts +0 -10
  508. package/dist/server/server.d.ts.map +0 -1
  509. package/dist/server/server.js +0 -17
  510. package/dist/server/server.js.map +0 -1
  511. package/dist/server/validation.d.ts +0 -17
  512. package/dist/server/validation.d.ts.map +0 -1
  513. package/dist/server/validation.js +0 -53
  514. package/dist/server/validation.js.map +0 -1
@@ -20,7 +20,16 @@ from workbench_constants import ARTIFACTS, FINDINGS_PAGE_MAX
20
20
  from workbench_scan_start import scan_target_identity
21
21
  from workbench_scan_usage import stored_scan_cost_fields
22
22
  from workbench_target import git_output, require_scan_target_identity
23
- from workbench_validation import reject_non_finite_json
23
+ from workbench_validation import reject_non_finite_json, timestamp_key
24
+
25
+
26
+ def rename_scan(connection: sqlite3.Connection, scan: sqlite3.Row, name: str) -> dict[str, Any]:
27
+ name = name.strip()
28
+ if not name:
29
+ raise SystemExit("Scan name cannot be empty.")
30
+ connection.execute("UPDATE scans SET name = ? WHERE id = ?", (name, scan["id"]))
31
+ connection.commit()
32
+ return {"scanId": scan["id"], "name": name}
24
33
 
25
34
 
26
35
  def scan_recipe(scan: sqlite3.Row) -> dict[str, Any]:
@@ -48,16 +57,10 @@ def preserve_sealed_completion(
48
57
 
49
58
 
50
59
  def cli_scan_resume(
60
+ wb: Any,
51
61
  connection: sqlite3.Connection,
52
62
  scan: sqlite3.Row,
53
63
  workspace: sqlite3.Row,
54
- *,
55
- parse_scan_recipe: Callable[[str, Path], dict[str, Any]],
56
- scan_contract: Callable[[sqlite3.Row], dict[str, Any]],
57
- require_scan_directory: Callable[[Path], Path],
58
- artifact_path: Callable[..., Path | None],
59
- read_json_object: Callable[[Path], dict[str, Any]],
60
- workbench_completion_binding: Callable[..., dict[str, Any]],
61
64
  ) -> dict[str, Any]:
62
65
  if scan["mode"] != "deep" or scan["recipe_json"] is None:
63
66
  raise SystemExit("Resume requires a Deep Scan with a saved CLI launch recipe.")
@@ -94,13 +97,13 @@ def cli_scan_resume(
94
97
  scan["target_inode"],
95
98
  ):
96
99
  raise SystemExit("Cannot resume: the original checkout revision or contents changed.")
97
- recipe = parse_scan_recipe(scan["recipe_json"], repository)
98
- scan_dir = require_scan_directory(Path(scan["scan_dir"]))
100
+ recipe = wb.parse_scan_recipe(scan["recipe_json"], repository)
101
+ scan_dir = wb.require_canonical_scan_directory(Path(scan["scan_dir"]))
99
102
  progress = connection.execute(
100
103
  "SELECT scope_file_count FROM scan_progress WHERE scan_id = ?", (scan["id"],)
101
104
  ).fetchone()
102
105
  result = {
103
- "contract": scan_contract(scan),
106
+ "contract": wb.scan_contract(scan),
104
107
  "recipe": recipe,
105
108
  "scanDir": str(scan_dir),
106
109
  "scanId": scan["id"],
@@ -114,16 +117,16 @@ def cli_scan_resume(
114
117
  # Active coordinators may still be writing drafts. Validate sealed results
115
118
  # before attaching to a coordinator that has finished.
116
119
  if run is not None and run["status"] == "succeeded":
117
- manifest_path = artifact_path(scan_dir, ARTIFACTS["manifest"], required=False)
120
+ manifest_path = wb.artifact_path(scan_dir, ARTIFACTS["manifest"], required=False)
118
121
  if manifest_path is not None:
119
- manifest = read_json_object(manifest_path)
122
+ manifest = wb.read_json_object(manifest_path)
120
123
  manifest_scan = manifest.get("scan")
121
124
  if isinstance(manifest_scan, dict) and (
122
125
  manifest_scan.get("sealedAt") is not None
123
126
  or manifest_scan.get("artifacts") is not None
124
127
  ):
125
128
  try:
126
- binding = workbench_completion_binding(scan, scan["started_at"], manifest)
129
+ binding = wb.workbench_completion_binding(scan, scan["started_at"], manifest)
127
130
  _prepare_scan_finalization(
128
131
  scan_dir,
129
132
  expected_coverage_mode=binding["coverageMode"],
@@ -201,6 +204,7 @@ def _repository_origin(target: Path) -> tuple[str, str] | None:
201
204
  def list_scans(
202
205
  connection: sqlite3.Connection, args: argparse.Namespace | None = None
203
206
  ) -> dict[str, Any]:
207
+ connection.create_function("casefold", 1, str.casefold, deterministic=True)
204
208
  if os.name == "nt":
205
209
  connection.create_function("codex_security_path_key", 1, _windows_path_key)
206
210
  clauses: list[str] = []
@@ -261,12 +265,13 @@ def list_scans(
261
265
  query = args.query.strip().casefold()
262
266
  if query:
263
267
  clauses.append(
264
- "(instr(lower(scans.target_path), ?) > 0 "
265
- "OR instr(lower(COALESCE(scans.target_summary, '')), ?) > 0 "
266
- "OR instr(lower(scans.scope), ?) > 0 "
267
- "OR instr(lower(scans.mode), ?) > 0)"
268
+ "(instr(casefold(scans.target_path), ?) > 0 "
269
+ "OR instr(casefold(COALESCE(scans.name, '')), ?) > 0 "
270
+ "OR instr(casefold(COALESCE(scans.target_summary, '')), ?) > 0 "
271
+ "OR instr(casefold(scans.scope), ?) > 0 "
272
+ "OR instr(casefold(scans.mode), ?) > 0)"
268
273
  )
269
- values.extend((query, query, query, query))
274
+ values.extend((query, query, query, query, query))
270
275
  where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
271
276
  paginated = args is not None and (args.limit is not None or args.offset != 0)
272
277
  limit = min(args.limit or FINDINGS_PAGE_MAX, FINDINGS_PAGE_MAX) if paginated else None
@@ -292,8 +297,8 @@ def list_scans(
292
297
  {where}
293
298
  ORDER BY
294
299
  CASE WHEN scans.status = 'running' AND scans.canceled_at IS NULL THEN 0 ELSE 1 END,
295
- MAX(scans.updated_at, progress.updated_at) DESC,
296
- scans.started_at DESC,
300
+ MAX(julianday(upper(scans.updated_at)), julianday(upper(progress.updated_at))) DESC,
301
+ julianday(upper(scans.started_at)) DESC,
297
302
  scans.id
298
303
  {pagination}
299
304
  """,
@@ -309,6 +314,7 @@ def list_scans(
309
314
  "handoffStatus": row["handoff_status"],
310
315
  "mode": row["mode"],
311
316
  "model": row["model"],
317
+ "name": row["name"],
312
318
  "parentScanId": row["parent_scan_id"],
313
319
  "progress": {
314
320
  "candidates": {"reportable": row["reportable_findings_count"]},
@@ -331,7 +337,11 @@ def list_scans(
331
337
  "targetPath": row["target_path"],
332
338
  "targetRevision": row["target_revision"],
333
339
  "targetSummary": row["target_summary"],
334
- "updatedAt": max(row["updated_at"], row["progress_updated_at"]),
340
+ "updatedAt": max(
341
+ row["updated_at"],
342
+ row["progress_updated_at"],
343
+ key=lambda value: (timestamp_key(value), value),
344
+ ),
335
345
  **(
336
346
  {"warnings": json.loads(row["completion_warnings_json"])}
337
347
  if row["completion_warnings_json"] != "[]"
@@ -454,7 +464,7 @@ def _saved_finding_links(connection: sqlite3.Connection, scan_ids: set[str]) ->
454
464
  FROM scan_comparison_matches AS matches
455
465
  JOIN finding_occurrences AS before ON before.id = matches.before_occurrence_id
456
466
  JOIN finding_occurrences AS after ON after.id = matches.after_occurrence_id
457
- WHERE matches.before_scan_id IN ({placeholders})
467
+ WHERE matches.before_scan_id IN (SELECT value FROM json_each(?))
458
468
  ORDER BY matches.before_scan_id, after.scan_id, before.finding_id, after.finding_id
459
469
  """,
460
470
  sorted(scan_ids),
@@ -529,7 +539,6 @@ def compare_scans(
529
539
  backfill_finding_details(connection, before)
530
540
  backfill_finding_details(connection, after)
531
541
  after_coverage = read_coverage(after)
532
- comparable = after_coverage.get("completeness") == "complete"
533
542
  before_findings = _scan_findings(connection, before["id"])
534
543
  after_findings = _scan_findings(connection, after["id"])
535
544
  matches = json.loads(cached["result_json"]) if cached is not None else None
@@ -549,7 +558,10 @@ def compare_scans(
549
558
  else {}
550
559
  )
551
560
  findings: list[dict[str, Any]] = []
552
- summary = {status: 0 for status in ("new", "persisting", "resolved", "reopened", "unknown")}
561
+ summary = {
562
+ status: 0
563
+ for status in ("new", "persisting", "resolved", "not_observed", "reopened", "unknown")
564
+ }
553
565
 
554
566
  for previous_rows, current_rows, match_reason in groups:
555
567
  previous = (
@@ -599,9 +611,6 @@ def compare_scans(
599
611
  elif uncertain_reason is not None:
600
612
  status = "unknown"
601
613
  item["reason"] = uncertain_reason
602
- elif not comparable:
603
- status = "unknown"
604
- item["reason"] = "The later scan has incomplete coverage."
605
614
  elif not all(
606
615
  scan_covers_path(
607
616
  after,
@@ -613,8 +622,14 @@ def compare_scans(
613
622
  ):
614
623
  status = "unknown"
615
624
  item["reason"] = "The affected path was excluded or outside the later scope."
616
- else:
625
+ elif all(
626
+ row["triage_status"] == "closed" and row["close_reason"] == "already_fixed"
627
+ for row in previous_rows
628
+ ):
617
629
  status = "resolved"
630
+ else:
631
+ status = "not_observed"
632
+ item["reason"] = "Not observed in the later scan; remediation has not been verified."
618
633
  if len(previous_rows) == 1:
619
634
  item["beforeOccurrenceId"] = previous["id"]
620
635
  elif previous_rows:
@@ -635,8 +650,6 @@ def compare_scans(
635
650
  result = {
636
651
  "afterScanId": after["id"],
637
652
  "beforeScanId": before["id"],
638
- "comparable": comparable,
639
- "coverage": {"afterCompleteness": after_coverage.get("completeness")},
640
653
  "findings": findings,
641
654
  "repository": before["target_path"],
642
655
  "summary": summary,
@@ -822,14 +835,8 @@ def _rows_for_ids(
822
835
  connection: sqlite3.Connection, query: str, ids: Iterable[str]
823
836
  ) -> Iterator[sqlite3.Row]:
824
837
  values = tuple(dict.fromkeys(ids))
825
- getlimit = getattr(connection, "getlimit", None)
826
- # Python 3.10 lacks getlimit; 999 is SQLite's older host-parameter limit.
827
- limit = getlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER) if getlimit else 999
828
- for start in range(0, len(values), limit):
829
- batch = values[start : start + limit]
830
- yield from connection.execute(
831
- query.format(placeholders=", ".join("?" for _ in batch)), batch
832
- )
838
+ if values:
839
+ yield from connection.execute(query, (json.dumps(values),))
833
840
 
834
841
 
835
842
  # Stable finding IDs already include the target identity. Follow their indexed
@@ -849,7 +856,7 @@ _LINKED_FINDINGS_SQL = f"""
849
856
  WITH RECURSIVE linked(finding_id) AS (
850
857
  SELECT occurrences.finding_id
851
858
  FROM finding_occurrences AS occurrences
852
- WHERE occurrences.id IN ({{placeholders}})
859
+ WHERE occurrences.id IN (SELECT value FROM json_each(?))
853
860
  UNION
854
861
  SELECT neighbor.finding_id
855
862
  {_FINDING_NEIGHBORS_SQL}
@@ -918,7 +925,7 @@ def finding_relations(
918
925
  for row in _rows_for_ids(
919
926
  connection,
920
927
  "SELECT id, finding_id, scan_id, title FROM finding_occurrences "
921
- "WHERE id IN ({placeholders})",
928
+ "WHERE id IN (SELECT value FROM json_each(?))",
922
929
  (pair[key] for pair in pairs for key in ("beforeOccurrenceId", "afterOccurrenceId")),
923
930
  )
924
931
  }
@@ -1087,9 +1094,13 @@ def finding_occurrence_rows(
1087
1094
  severity: str | None = None,
1088
1095
  status: str | None = None,
1089
1096
  ) -> list[sqlite3.Row]:
1097
+ connection.create_function("casefold", 1, str.casefold, deterministic=True)
1090
1098
  conditions, values = finding_occurrence_conditions(
1091
1099
  scan_id, query=query, severity=severity, status=status
1092
1100
  )
1101
+ severity_order = " ".join(
1102
+ f"WHEN '{level}' THEN {rank}" for level, rank in SEVERITY_ORDER.items()
1103
+ )
1093
1104
  return connection.execute(
1094
1105
  f"""
1095
1106
  SELECT
@@ -1106,14 +1117,7 @@ def finding_occurrence_rows(
1106
1117
  LEFT JOIN finding_triage AS triage ON triage.occurrence_id = occurrences.id
1107
1118
  WHERE {conditions}
1108
1119
  ORDER BY
1109
- CASE occurrences.severity
1110
- WHEN 'critical' THEN 0
1111
- WHEN 'high' THEN 1
1112
- WHEN 'medium' THEN 2
1113
- WHEN 'low' THEN 3
1114
- WHEN 'informational' THEN 4
1115
- ELSE 5
1116
- END,
1120
+ CASE occurrences.severity {severity_order} ELSE 5 END,
1117
1121
  occurrences.created_at,
1118
1122
  occurrences.id
1119
1123
  LIMIT ? OFFSET ?
@@ -1141,12 +1145,12 @@ def finding_occurrence_conditions(
1141
1145
  search = query.strip().casefold()
1142
1146
  if search:
1143
1147
  conditions.append(
1144
- "(instr(lower(occurrences.title), ?) > 0 "
1145
- "OR instr(lower(occurrences.summary), ?) > 0 "
1148
+ "(instr(casefold(occurrences.title), ?) > 0 "
1149
+ "OR instr(casefold(occurrences.summary), ?) > 0 "
1146
1150
  "OR EXISTS ("
1147
1151
  "SELECT 1 FROM finding_locations AS locations "
1148
1152
  "WHERE locations.occurrence_id = occurrences.id "
1149
- "AND instr(lower(locations.relative_path), ?) > 0))"
1153
+ "AND instr(casefold(locations.relative_path), ?) > 0))"
1150
1154
  )
1151
1155
  values.extend((search, search, search))
1152
1156
  return " AND ".join(conditions), values
@@ -1181,11 +1185,7 @@ def scan_covers_path(
1181
1185
  path: str | None,
1182
1186
  coverage: dict[str, Any],
1183
1187
  ) -> bool:
1184
- if (
1185
- scan["status"] != "complete"
1186
- or scan["target_id"] != target_id
1187
- or coverage.get("completeness") != "complete"
1188
- ):
1188
+ if scan["status"] != "complete" or scan["target_id"] != target_id:
1189
1189
  return False
1190
1190
  if not isinstance(path, str) or not path:
1191
1191
  return False
@@ -5,10 +5,12 @@ from __future__ import annotations
5
5
  import argparse
6
6
  import json
7
7
  import os
8
+ import re
8
9
  import sqlite3
9
10
  import sys
10
11
  import tempfile
11
- from collections.abc import Callable
12
+ from collections.abc import Callable, Iterator
13
+ from contextlib import contextmanager
12
14
  from datetime import datetime, timezone
13
15
  from pathlib import Path
14
16
 
@@ -16,20 +18,18 @@ from pathlib import Path
16
18
  sys.path.insert(0, str(Path(__file__).resolve().parent))
17
19
  from filesystem_identity import serialize_filesystem_identity
18
20
  from finalize_scan_contract import write_scan_local_bytes
21
+ from workbench.storage import state_dir
19
22
  from workbench_feedback import get_scan_feedback
20
23
  from workbench_target import (
21
24
  directory_content_digest,
22
25
  git_revision,
23
26
  worktree_content_digest,
24
27
  )
25
- from workbench_validation import optional_text, user_text
28
+ from workbench_validation import optional_text
26
29
 
27
30
 
28
31
  def safe_segment(value: str) -> str:
29
- segment = "".join(
30
- character if character.isalnum() or character in "._-" else "-" for character in value
31
- )
32
- return segment.strip("-") or "scan"
32
+ return re.sub(r"[^\w.-]", "-", value).strip("-") or "scan"
33
33
 
34
34
 
35
35
  def compact_timestamp() -> str:
@@ -86,13 +86,16 @@ def stored_diff_target(row: sqlite3.Row) -> dict[str, str] | None:
86
86
  return target
87
87
 
88
88
 
89
+ @contextmanager
89
90
  def archive_scan(
90
91
  connection: sqlite3.Connection,
91
92
  args: argparse.Namespace,
92
93
  scan_dir: Path,
93
94
  timestamp: str,
94
95
  canonical_directory: Callable[[Path], Path],
95
- ) -> None:
96
+ *,
97
+ before_archive: Callable[[], None] | None = None,
98
+ ) -> Iterator[Path | None]:
96
99
  archived_scan_dir = (
97
100
  canonical_directory(Path(args.archived_scan_dir).expanduser())
98
101
  if args.archived_scan_dir is not None
@@ -108,44 +111,105 @@ def archive_scan(
108
111
  previous_scan = connection.execute(
109
112
  "SELECT id, status FROM scans WHERE scan_dir = ?", (str(scan_dir),)
110
113
  ).fetchone()
111
- if previous_scan is None:
112
- return
113
- if not args.archive_existing:
114
- raise SystemExit(
115
- "The scan artifact directory belongs to an existing scan. "
116
- "Use --archive-existing to preserve that scan and start a new one."
117
- )
118
- if previous_scan["status"] == "running":
119
- raise SystemExit("Cannot archive the output of a running scan.")
120
- artifacts = connection.execute(
121
- "SELECT kind, path FROM scan_artifacts WHERE scan_id = ?",
122
- (previous_scan["id"],),
123
- ).fetchall()
124
- if archived_scan_dir is None:
125
- if artifacts:
114
+ if previous_scan is not None:
115
+ if not args.archive_existing:
126
116
  raise SystemExit(
127
- "The archived scan directory is required to preserve existing scan artifacts."
117
+ "The scan artifact directory belongs to an existing scan. "
118
+ "Use --archive-existing to preserve that scan and start a new one."
128
119
  )
129
- archived_scan_dir = Path(
130
- tempfile.mkdtemp(prefix=f"{scan_dir.name}.previous-", dir=scan_dir.parent)
131
- ).resolve()
132
- connection.execute(
133
- "UPDATE scans SET scan_dir = ?, updated_at = ? WHERE id = ?",
134
- (str(archived_scan_dir), timestamp, previous_scan["id"]),
135
- )
136
- for artifact in artifacts:
137
- try:
138
- relative_path = Path(artifact["path"]).relative_to(scan_dir)
139
- except ValueError:
140
- continue
120
+ if previous_scan["status"] == "running":
121
+ raise SystemExit("Cannot archive the output of a running scan.")
122
+ has_contents = next(scan_dir.iterdir(), None) is not None
123
+ if has_contents and (not args.archive_existing or archived_scan_dir is not None):
124
+ raise SystemExit("The scan artifact directory must be empty before the scan starts.")
125
+ if previous_scan is None and not (args.archive_existing and has_contents):
126
+ yield archived_scan_dir
127
+ return
128
+ artifacts = (
141
129
  connection.execute(
142
- "UPDATE scan_artifacts SET path = ? WHERE scan_id = ? AND kind = ?",
143
- (
144
- str(archived_scan_dir / relative_path),
145
- previous_scan["id"],
146
- artifact["kind"],
147
- ),
148
- )
130
+ "SELECT kind, path FROM scan_artifacts WHERE scan_id = ?", (previous_scan["id"],)
131
+ ).fetchall()
132
+ if previous_scan is not None
133
+ else []
134
+ )
135
+ moved = False
136
+ try:
137
+ if archived_scan_dir is None:
138
+ configured_state = state_dir(canonical=False)
139
+ protected_directories = [
140
+ *(path.resolve() for path in (configured_state, *configured_state.parents)),
141
+ *(
142
+ Path(row[2]).resolve().parent
143
+ for row in connection.execute("PRAGMA database_list")
144
+ if row[2]
145
+ ),
146
+ ]
147
+ if any(path == scan_dir or scan_dir in path.parents for path in protected_directories):
148
+ raise SystemExit(
149
+ "Cannot archive output containing the workbench state or active database."
150
+ )
151
+ if artifacts and not has_contents:
152
+ raise SystemExit(
153
+ "The archived scan directory is required to preserve existing scan artifacts."
154
+ )
155
+ if before_archive is not None:
156
+ before_archive()
157
+ archived_scan_dir = Path(
158
+ tempfile.mkdtemp(prefix=f"{scan_dir.name}.previous-", dir=scan_dir.parent)
159
+ ).resolve()
160
+ archived_scan_dir.rmdir()
161
+ scan_dir.rename(archived_scan_dir)
162
+ moved = True
163
+ scan_dir.mkdir(mode=0o700)
164
+ scan_dir.chmod(0o700)
165
+ if previous_scan is not None:
166
+ connection.execute(
167
+ "UPDATE scans SET scan_dir = ?, updated_at = ? WHERE id = ?",
168
+ (str(archived_scan_dir), timestamp, previous_scan["id"]),
169
+ )
170
+ connection.execute(
171
+ """UPDATE finding_workflows SET scan_dir = ?,
172
+ results_json = CASE WHEN json_extract(results_json, '$.scan.sarifPath') = ?
173
+ THEN json_set(results_json, '$.scan.sarifPath', ?) ELSE results_json END
174
+ WHERE scan_id = ? AND scan_dir = ?""",
175
+ (
176
+ str(archived_scan_dir),
177
+ str(scan_dir / "exports" / "results.sarif"),
178
+ str(archived_scan_dir / "exports" / "results.sarif"),
179
+ previous_scan["id"],
180
+ str(scan_dir),
181
+ ),
182
+ )
183
+ for artifact in artifacts:
184
+ try:
185
+ relative_path = Path(artifact["path"]).relative_to(scan_dir)
186
+ except ValueError:
187
+ continue
188
+ connection.execute(
189
+ "UPDATE scan_artifacts SET path = ? WHERE scan_id = ? AND kind = ?",
190
+ (str(archived_scan_dir / relative_path), previous_scan["id"], artifact["kind"]),
191
+ )
192
+ # The caller commits registration before leaving this context. Older SDKs
193
+ # supplied an already-moved directory; only restore moves we own.
194
+ yield archived_scan_dir
195
+ except BaseException:
196
+ if moved:
197
+ if not connection.in_transaction:
198
+ current_owner = connection.execute(
199
+ "SELECT id FROM scans WHERE scan_dir = ?", (str(scan_dir),)
200
+ ).fetchone()
201
+ if current_owner is not None and (
202
+ previous_scan is None or current_owner["id"] != previous_scan["id"]
203
+ ):
204
+ # A post-commit interrupt must not undo the saved archive location.
205
+ raise
206
+ try:
207
+ scan_dir.rmdir()
208
+ except FileNotFoundError:
209
+ # Registration may fail before recreating the empty output directory.
210
+ pass
211
+ archived_scan_dir.rename(scan_dir)
212
+ raise
149
213
 
150
214
 
151
215
  def insert_running_scan(
@@ -168,7 +232,7 @@ def insert_running_scan(
168
232
  ) -> str:
169
233
  revision = target_identity[0]
170
234
  native_scan = scan_dir is None
171
- user_context = user_text(workspace["user_context"])
235
+ user_context = optional_text(workspace["user_context"])
172
236
  if scan_dir is None:
173
237
  scan_dir = Path(
174
238
  tempfile.mkdtemp(
@@ -197,10 +261,7 @@ def insert_running_scan(
197
261
  workspace["default_mode"],
198
262
  user_context,
199
263
  workspace["thread_id"] if workspace["default_mode"] == "deep" else None,
200
- diff_target["kind"] if diff_target else None,
201
- diff_target["baseRevision"] if diff_target else None,
202
- diff_target["headRevision"] if diff_target else None,
203
- diff_target.get("contentDigest") if diff_target else None,
264
+ *scan_diff_identity(diff_target or None),
204
265
  target_summary,
205
266
  str(scan_dir),
206
267
  optional_text(model, maximum=200),
@@ -236,9 +297,5 @@ def insert_running_scan(
236
297
  return scan_id
237
298
 
238
299
 
239
- def main() -> None:
240
- argparse.ArgumentParser(description=__doc__).parse_args()
241
-
242
-
243
300
  if __name__ == "__main__":
244
- main()
301
+ argparse.ArgumentParser(description=__doc__).parse_args()