@openai/codex-security 0.9.1 → 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 (387) hide show
  1. package/README.md +37 -788
  2. package/_bundled_plugin/.codex-plugin/plugin.json +2 -0
  3. package/_bundled_plugin/.mcp.json +2 -0
  4. package/_bundled_plugin/mcp/helpers.mjs.br +0 -0
  5. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  6. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  7. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  8. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  9. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  10. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  11. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  12. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  13. package/_bundled_plugin/mcp/server.mjs.br +0 -0
  14. package/_bundled_plugin/references/artifact-storage.md +1 -1
  15. package/_bundled_plugin/references/baseline-auditor.md +18 -0
  16. package/_bundled_plugin/references/core-scan.md +5 -42
  17. package/_bundled_plugin/references/final-report.md +1 -1
  18. package/_bundled_plugin/references/focused-investigator.md +13 -0
  19. package/_bundled_plugin/references/scan-prologue.md +2 -2
  20. package/_bundled_plugin/references/scan-runtime.md +4 -2
  21. package/_bundled_plugin/references/security-guidance.md +14 -1
  22. package/_bundled_plugin/references/validate-scan-findings.md +3 -0
  23. package/_bundled_plugin/scripts/deep_scan_workbench.py +29 -12
  24. package/_bundled_plugin/scripts/dispatch_inventory_tool +7 -0
  25. package/_bundled_plugin/scripts/finalize_scan_contract.py +29 -3
  26. package/_bundled_plugin/scripts/launch_codex_security_mcp +54 -16
  27. package/_bundled_plugin/scripts/posix_scan_local_files.py +26 -1
  28. package/_bundled_plugin/scripts/snapshot_sqlite.py +8 -2
  29. package/_bundled_plugin/scripts/windows_scan_local_files.py +216 -25
  30. package/_bundled_plugin/scripts/workbench/handoff.py +55 -25
  31. package/_bundled_plugin/scripts/workbench/storage.py +25 -5
  32. package/_bundled_plugin/scripts/workbench_cli.py +24 -2
  33. package/_bundled_plugin/scripts/workbench_constants.py +2 -0
  34. package/_bundled_plugin/scripts/workbench_db.py +244 -217
  35. package/_bundled_plugin/scripts/workbench_feedback.py +49 -4
  36. package/_bundled_plugin/scripts/workbench_native_indexes.py +226 -29
  37. package/_bundled_plugin/scripts/workbench_progress.py +159 -3
  38. package/_bundled_plugin/scripts/workbench_publication.py +2 -3
  39. package/_bundled_plugin/scripts/workbench_remediation.py +142 -2
  40. package/_bundled_plugin/scripts/workbench_saved_results.py +48 -8
  41. package/_bundled_plugin/scripts/workbench_scan_history.py +281 -119
  42. package/_bundled_plugin/scripts/workbench_scan_start.py +143 -9
  43. package/_bundled_plugin/scripts/workbench_scan_usage.py +36 -10
  44. package/_bundled_plugin/scripts/workbench_schema.py +220 -14
  45. package/_bundled_plugin/scripts/workbench_setup.py +1 -1
  46. package/_bundled_plugin/scripts/workbench_target.py +471 -84
  47. package/_bundled_plugin/scripts/workbench_target_state.py +1108 -22
  48. package/_bundled_plugin/shared/workbench-history-repairs.json +60 -14
  49. package/_bundled_plugin/shared/workbench-migrations.json +66 -0
  50. package/_bundled_plugin/skills/fix-finding/SKILL.md +1 -0
  51. package/_bundled_plugin/skills/publish-findings/SKILL.md +24 -160
  52. package/_bundled_plugin/skills/publish-findings/agents/openai.yaml +2 -2
  53. package/_bundled_plugin/skills/publish-findings/references/checkmarx-import.md +2 -2
  54. package/_bundled_plugin/skills/publish-findings/scripts/collect_checkmarx.py +3 -58
  55. package/_bundled_plugin/skills/publish-findings/scripts/collect_continuum.py +224 -0
  56. package/_bundled_plugin/skills/publish-findings/scripts/collector_paths.py +63 -0
  57. package/_bundled_plugin/skills/security-scan/SKILL.md +9 -46
  58. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +2 -2
  59. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +3 -21
  60. package/_bundled_plugin/skills/security-scan/references/managed-scan.md +11 -0
  61. package/_bundled_plugin/skills/security-scan/references/scan-results.md +15 -0
  62. package/_bundled_plugin/skills/security-scan/references/scoped-paths.md +23 -0
  63. package/_bundled_plugin/skills/security-scan/references/sdk-files.md +24 -0
  64. package/bin/codex-security.mjs +2 -2
  65. package/dist/api.d.ts +6 -1
  66. package/dist/api.d.ts.map +1 -1
  67. package/dist/api.js +437 -154
  68. package/dist/api.js.map +1 -1
  69. package/dist/armorcode-findings.d.ts +9 -0
  70. package/dist/armorcode-findings.d.ts.map +1 -0
  71. package/dist/armorcode-findings.js +145 -0
  72. package/dist/armorcode-findings.js.map +1 -0
  73. package/dist/artifact-export.d.ts +2 -0
  74. package/dist/artifact-export.d.ts.map +1 -1
  75. package/dist/artifact-export.js +29 -13
  76. package/dist/artifact-export.js.map +1 -1
  77. package/dist/auth.d.ts +6 -2
  78. package/dist/auth.d.ts.map +1 -1
  79. package/dist/auth.js +33 -12
  80. package/dist/auth.js.map +1 -1
  81. package/dist/batch-cost.d.ts +18 -0
  82. package/dist/batch-cost.d.ts.map +1 -0
  83. package/dist/batch-cost.js +41 -0
  84. package/dist/batch-cost.js.map +1 -0
  85. package/dist/blackduck-findings.d.ts +1 -1
  86. package/dist/blackduck-findings.d.ts.map +1 -1
  87. package/dist/blackduck-findings.js +5 -18
  88. package/dist/blackduck-findings.js.map +1 -1
  89. package/dist/bundled-plugin.d.ts +4 -0
  90. package/dist/bundled-plugin.d.ts.map +1 -0
  91. package/dist/bundled-plugin.js +23 -0
  92. package/dist/bundled-plugin.js.map +1 -0
  93. package/dist/classify-scan-severity.d.ts +1 -1
  94. package/dist/classify-scan-severity.d.ts.map +1 -1
  95. package/dist/classify-scan-severity.js +11 -3
  96. package/dist/classify-scan-severity.js.map +1 -1
  97. package/dist/classify-severity.d.ts.map +1 -1
  98. package/dist/classify-severity.js +9 -6
  99. package/dist/classify-severity.js.map +1 -1
  100. package/dist/cli-argument.d.ts +4 -0
  101. package/dist/cli-argument.d.ts.map +1 -0
  102. package/dist/cli-argument.js +17 -0
  103. package/dist/cli-argument.js.map +1 -0
  104. package/dist/cli-help.d.ts +1 -1
  105. package/dist/cli-help.d.ts.map +1 -1
  106. package/dist/cli-help.js +71 -29
  107. package/dist/cli-help.js.map +1 -1
  108. package/dist/cli-hook.d.ts +3 -0
  109. package/dist/cli-hook.d.ts.map +1 -0
  110. package/dist/cli-hook.js +87 -0
  111. package/dist/cli-hook.js.map +1 -0
  112. package/dist/cli-integrations.d.ts +13 -0
  113. package/dist/cli-integrations.d.ts.map +1 -0
  114. package/dist/cli-integrations.js +333 -0
  115. package/dist/cli-integrations.js.map +1 -0
  116. package/dist/cli-mcp.d.ts +15 -0
  117. package/dist/cli-mcp.d.ts.map +1 -0
  118. package/dist/cli-mcp.js +178 -0
  119. package/dist/cli-mcp.js.map +1 -0
  120. package/dist/cli-token-view.d.ts +10 -0
  121. package/dist/cli-token-view.d.ts.map +1 -0
  122. package/dist/cli-token-view.js +41 -0
  123. package/dist/cli-token-view.js.map +1 -0
  124. package/dist/cli.d.ts +5 -3
  125. package/dist/cli.d.ts.map +1 -1
  126. package/dist/cli.js +1763 -894
  127. package/dist/cli.js.map +1 -1
  128. package/dist/cloud-publish.d.ts.map +1 -1
  129. package/dist/cloud-publish.js +33 -31
  130. package/dist/cloud-publish.js.map +1 -1
  131. package/dist/codex-sdk-environment.d.ts +6 -0
  132. package/dist/codex-sdk-environment.d.ts.map +1 -1
  133. package/dist/codex-sdk-environment.js +19 -0
  134. package/dist/codex-sdk-environment.js.map +1 -1
  135. package/dist/command-words.d.ts +3 -0
  136. package/dist/command-words.d.ts.map +1 -0
  137. package/dist/command-words.js +46 -0
  138. package/dist/command-words.js.map +1 -0
  139. package/dist/component-scan.d.ts +3 -1
  140. package/dist/component-scan.d.ts.map +1 -1
  141. package/dist/component-scan.js +40 -7
  142. package/dist/component-scan.js.map +1 -1
  143. package/dist/config.d.ts +1 -1
  144. package/dist/config.d.ts.map +1 -1
  145. package/dist/config.js +30 -1
  146. package/dist/config.js.map +1 -1
  147. package/dist/continuum-findings.d.ts +1 -1
  148. package/dist/continuum-findings.d.ts.map +1 -1
  149. package/dist/continuum-findings.js +93 -31
  150. package/dist/continuum-findings.js.map +1 -1
  151. package/dist/cost.d.ts.map +1 -1
  152. package/dist/cost.js +1 -45
  153. package/dist/cost.js.map +1 -1
  154. package/dist/custom-validation-prompt.d.ts +1 -1
  155. package/dist/custom-validation-prompt.d.ts.map +1 -1
  156. package/dist/custom-validation-prompt.js +29 -19
  157. package/dist/custom-validation-prompt.js.map +1 -1
  158. package/dist/deduplication/local.d.ts +3 -1
  159. package/dist/deduplication/local.d.ts.map +1 -1
  160. package/dist/deduplication/local.js +8 -1
  161. package/dist/deduplication/local.js.map +1 -1
  162. package/dist/deduplication/refusal.d.ts.map +1 -1
  163. package/dist/deduplication/refusal.js +2 -1
  164. package/dist/deduplication/refusal.js.map +1 -1
  165. package/dist/deduplication/scan.d.ts +2 -0
  166. package/dist/deduplication/scan.d.ts.map +1 -1
  167. package/dist/deduplication/scan.js +24 -7
  168. package/dist/deduplication/scan.js.map +1 -1
  169. package/dist/deep-scan.d.ts.map +1 -1
  170. package/dist/deep-scan.js +16 -15
  171. package/dist/deep-scan.js.map +1 -1
  172. package/dist/endor-findings.d.ts +2 -2
  173. package/dist/endor-findings.d.ts.map +1 -1
  174. package/dist/endor-findings.js +6 -23
  175. package/dist/endor-findings.js.map +1 -1
  176. package/dist/errors.d.ts +3 -1
  177. package/dist/errors.d.ts.map +1 -1
  178. package/dist/errors.js +7 -3
  179. package/dist/errors.js.map +1 -1
  180. package/dist/executable-path.d.ts +3 -0
  181. package/dist/executable-path.d.ts.map +1 -1
  182. package/dist/executable-path.js +26 -0
  183. package/dist/executable-path.js.map +1 -1
  184. package/dist/external-findings-import.d.ts.map +1 -1
  185. package/dist/external-findings-import.js +12 -1
  186. package/dist/external-findings-import.js.map +1 -1
  187. package/dist/external-findings-local.d.ts +66 -4
  188. package/dist/external-findings-local.d.ts.map +1 -1
  189. package/dist/external-findings-local.js +234 -53
  190. package/dist/external-findings-local.js.map +1 -1
  191. package/dist/external-findings-publish.d.ts +6 -1
  192. package/dist/external-findings-publish.d.ts.map +1 -1
  193. package/dist/external-findings-publish.js +326 -1633
  194. package/dist/external-findings-publish.js.map +1 -1
  195. package/dist/external-findings-read.d.ts +1 -0
  196. package/dist/external-findings-read.d.ts.map +1 -1
  197. package/dist/external-findings-read.js +31 -51
  198. package/dist/external-findings-read.js.map +1 -1
  199. package/dist/external-findings.d.ts +1 -1
  200. package/dist/external-findings.d.ts.map +1 -1
  201. package/dist/external-findings.js +12 -1
  202. package/dist/external-findings.js.map +1 -1
  203. package/dist/external-import-contract.d.ts +3 -11
  204. package/dist/external-import-contract.d.ts.map +1 -1
  205. package/dist/external-import-contract.js +29 -176
  206. package/dist/external-import-contract.js.map +1 -1
  207. package/dist/external-import-models.d.ts +1 -1
  208. package/dist/external-import-models.d.ts.map +1 -1
  209. package/dist/external-import-models.js.map +1 -1
  210. package/dist/finding-prompt.d.ts.map +1 -1
  211. package/dist/finding-prompt.js +2 -2
  212. package/dist/finding-prompt.js.map +1 -1
  213. package/dist/github-dependabot-findings.d.ts.map +1 -1
  214. package/dist/github-dependabot-findings.js +3 -4
  215. package/dist/github-dependabot-findings.js.map +1 -1
  216. package/dist/github-findings.d.ts.map +1 -1
  217. package/dist/github-findings.js +19 -287
  218. package/dist/github-findings.js.map +1 -1
  219. package/dist/hosted-remediation.d.ts +1 -0
  220. package/dist/hosted-remediation.d.ts.map +1 -1
  221. package/dist/hosted-remediation.js +23 -3
  222. package/dist/hosted-remediation.js.map +1 -1
  223. package/dist/index.d.ts +3 -2
  224. package/dist/index.d.ts.map +1 -1
  225. package/dist/index.js +2 -1
  226. package/dist/index.js.map +1 -1
  227. package/dist/inspector-findings.d.ts.map +1 -1
  228. package/dist/inspector-findings.js +19 -35
  229. package/dist/inspector-findings.js.map +1 -1
  230. package/dist/knowledge-base.d.ts +1 -1
  231. package/dist/knowledge-base.d.ts.map +1 -1
  232. package/dist/knowledge-base.js +34 -27
  233. package/dist/knowledge-base.js.map +1 -1
  234. package/dist/linear.d.ts +11 -0
  235. package/dist/linear.d.ts.map +1 -1
  236. package/dist/linear.js.map +1 -1
  237. package/dist/local-git-metadata.d.ts +5 -2
  238. package/dist/local-git-metadata.d.ts.map +1 -1
  239. package/dist/local-git-metadata.js +8 -4
  240. package/dist/local-git-metadata.js.map +1 -1
  241. package/dist/multiscan.d.ts +4 -0
  242. package/dist/multiscan.d.ts.map +1 -1
  243. package/dist/multiscan.js +79 -37
  244. package/dist/multiscan.js.map +1 -1
  245. package/dist/opengrep-findings.d.ts +4 -2
  246. package/dist/opengrep-findings.d.ts.map +1 -1
  247. package/dist/opengrep-findings.js +39 -22
  248. package/dist/opengrep-findings.js.map +1 -1
  249. package/dist/private-finding-import.d.ts +8 -13
  250. package/dist/private-finding-import.d.ts.map +1 -1
  251. package/dist/private-finding-import.js +69 -129
  252. package/dist/private-finding-import.js.map +1 -1
  253. package/dist/project-config.d.ts.map +1 -1
  254. package/dist/project-config.js +53 -13
  255. package/dist/project-config.js.map +1 -1
  256. package/dist/prompt-files.d.ts +7 -2
  257. package/dist/prompt-files.d.ts.map +1 -1
  258. package/dist/prompt-files.js +42 -20
  259. package/dist/prompt-files.js.map +1 -1
  260. package/dist/provider-profile.d.ts.map +1 -1
  261. package/dist/provider-profile.js +4 -9
  262. package/dist/provider-profile.js.map +1 -1
  263. package/dist/publication.d.ts +1 -1
  264. package/dist/publication.d.ts.map +1 -1
  265. package/dist/publication.js.map +1 -1
  266. package/dist/record.d.ts +1 -5
  267. package/dist/record.d.ts.map +1 -1
  268. package/dist/record.js +3 -51
  269. package/dist/record.js.map +1 -1
  270. package/dist/remediation.d.ts.map +1 -1
  271. package/dist/remediation.js +3 -1
  272. package/dist/remediation.js.map +1 -1
  273. package/dist/runtime.d.ts +35 -7
  274. package/dist/runtime.d.ts.map +1 -1
  275. package/dist/runtime.js +778 -153
  276. package/dist/runtime.js.map +1 -1
  277. package/dist/saved-scan-bootstrap.d.ts +6 -1
  278. package/dist/saved-scan-bootstrap.d.ts.map +1 -1
  279. package/dist/saved-scan-bootstrap.js +267 -115
  280. package/dist/saved-scan-bootstrap.js.map +1 -1
  281. package/dist/scan-archive-path.d.ts +2 -0
  282. package/dist/scan-archive-path.d.ts.map +1 -0
  283. package/dist/scan-archive-path.js +5 -0
  284. package/dist/scan-archive-path.js.map +1 -0
  285. package/dist/scan-comparison.d.ts.map +1 -1
  286. package/dist/scan-comparison.js +6 -2
  287. package/dist/scan-comparison.js.map +1 -1
  288. package/dist/scan-dashboard.d.ts +1 -0
  289. package/dist/scan-dashboard.d.ts.map +1 -1
  290. package/dist/scan-dashboard.js +18 -2
  291. package/dist/scan-dashboard.js.map +1 -1
  292. package/dist/scan-executor.d.ts.map +1 -1
  293. package/dist/scan-executor.js +4 -2
  294. package/dist/scan-executor.js.map +1 -1
  295. package/dist/scan-history-renderer.d.ts +1 -0
  296. package/dist/scan-history-renderer.d.ts.map +1 -1
  297. package/dist/scan-history-renderer.js +25 -9
  298. package/dist/scan-history-renderer.js.map +1 -1
  299. package/dist/scan-logs.d.ts.map +1 -1
  300. package/dist/scan-logs.js +28 -4
  301. package/dist/scan-logs.js.map +1 -1
  302. package/dist/scanner-import.d.ts +5 -11
  303. package/dist/scanner-import.d.ts.map +1 -1
  304. package/dist/scanner-import.js +16 -89
  305. package/dist/scanner-import.js.map +1 -1
  306. package/dist/security-policy.d.ts.map +1 -1
  307. package/dist/security-policy.js +26 -6
  308. package/dist/security-policy.js.map +1 -1
  309. package/dist/semgrep-findings.d.ts.map +1 -1
  310. package/dist/semgrep-findings.js +14 -48
  311. package/dist/semgrep-findings.js.map +1 -1
  312. package/dist/semgrep-platform-findings.d.ts +20 -70
  313. package/dist/semgrep-platform-findings.d.ts.map +1 -1
  314. package/dist/semgrep-platform-findings.js +116 -333
  315. package/dist/semgrep-platform-findings.js.map +1 -1
  316. package/dist/snyk-findings.d.ts +2 -0
  317. package/dist/snyk-findings.d.ts.map +1 -1
  318. package/dist/snyk-findings.js +5 -8
  319. package/dist/snyk-findings.js.map +1 -1
  320. package/dist/snyk-rest-findings.d.ts +3 -20
  321. package/dist/snyk-rest-findings.d.ts.map +1 -1
  322. package/dist/snyk-rest-findings.js +45 -217
  323. package/dist/snyk-rest-findings.js.map +1 -1
  324. package/dist/sonar-findings.d.ts +1 -1
  325. package/dist/sonar-findings.d.ts.map +1 -1
  326. package/dist/sonar-findings.js +2 -4
  327. package/dist/sonar-findings.js.map +1 -1
  328. package/dist/sonar-import.d.ts +3 -0
  329. package/dist/sonar-import.d.ts.map +1 -1
  330. package/dist/sonar-import.js +28 -30
  331. package/dist/sonar-import.js.map +1 -1
  332. package/dist/stored-finding-projection.d.ts +6 -0
  333. package/dist/stored-finding-projection.d.ts.map +1 -0
  334. package/dist/stored-finding-projection.js +104 -0
  335. package/dist/stored-finding-projection.js.map +1 -0
  336. package/dist/stored-findings-publication.d.ts +23 -0
  337. package/dist/stored-findings-publication.d.ts.map +1 -0
  338. package/dist/stored-findings-publication.js +169 -0
  339. package/dist/stored-findings-publication.js.map +1 -0
  340. package/dist/targets.d.ts +6 -1
  341. package/dist/targets.d.ts.map +1 -1
  342. package/dist/targets.js +76 -23
  343. package/dist/targets.js.map +1 -1
  344. package/dist/tenable-findings.d.ts +1 -4
  345. package/dist/tenable-findings.d.ts.map +1 -1
  346. package/dist/tenable-findings.js.map +1 -1
  347. package/dist/trivy-findings.d.ts.map +1 -1
  348. package/dist/trivy-findings.js +0 -11
  349. package/dist/trivy-findings.js.map +1 -1
  350. package/dist/trusted-executable.d.ts +6 -0
  351. package/dist/trusted-executable.d.ts.map +1 -1
  352. package/dist/trusted-executable.js +140 -37
  353. package/dist/trusted-executable.js.map +1 -1
  354. package/dist/veracode-findings.d.ts +1 -3
  355. package/dist/veracode-findings.d.ts.map +1 -1
  356. package/dist/veracode-findings.js +13 -38
  357. package/dist/veracode-findings.js.map +1 -1
  358. package/dist/version.d.ts +3 -1
  359. package/dist/version.d.ts.map +1 -1
  360. package/dist/version.js +184 -32
  361. package/dist/version.js.map +1 -1
  362. package/dist/wiz-findings.d.ts +2 -2
  363. package/dist/wiz-findings.d.ts.map +1 -1
  364. package/dist/wiz-findings.js +14 -92
  365. package/dist/wiz-findings.js.map +1 -1
  366. package/docs/cli.md +373 -106
  367. package/docs/findings-service.md +22 -9
  368. package/docs/hosted-remediation.md +13 -4
  369. package/docs/sdk.md +903 -0
  370. package/package.json +10 -6
  371. package/schemas/external-findings.schema.json +2 -1
  372. package/dist/hosted-scanner-v1.d.ts +0 -6
  373. package/dist/hosted-scanner-v1.d.ts.map +0 -1
  374. package/dist/hosted-scanner-v1.js +0 -60
  375. package/dist/hosted-scanner-v1.js.map +0 -1
  376. package/dist/reader-selection.d.ts +0 -15
  377. package/dist/reader-selection.d.ts.map +0 -1
  378. package/dist/reader-selection.js +0 -89
  379. package/dist/reader-selection.js.map +0 -1
  380. package/dist/semgrep-platform-v1.d.ts +0 -6
  381. package/dist/semgrep-platform-v1.d.ts.map +0 -1
  382. package/dist/semgrep-platform-v1.js +0 -83
  383. package/dist/semgrep-platform-v1.js.map +0 -1
  384. package/dist/snyk-rest-v1.d.ts +0 -28
  385. package/dist/snyk-rest-v1.d.ts.map +0 -1
  386. package/dist/snyk-rest-v1.js +0 -132
  387. package/dist/snyk-rest-v1.js.map +0 -1
@@ -54,6 +54,7 @@ from finalize_scan_contract import (
54
54
  open_scan_local_file_descriptor,
55
55
  )
56
56
  from finding_preview import bounded_finding_details
57
+ from windows_scan_local_files import pin_replay_metadata
57
58
  from workbench import handoff
58
59
  from workbench.storage import (
59
60
  create_private_directory,
@@ -76,7 +77,6 @@ from workbench_constants import (
76
77
  FINDING_SUMMARY_BYTES,
77
78
  FINDING_TITLE_BYTES,
78
79
  FINDINGS_RESULT_LIMIT,
79
- PATCH_PREVIEW_BYTES,
80
80
  SQLITE_RETRY_ATTEMPTS,
81
81
  )
82
82
  from workbench_feedback import get_scan_feedback
@@ -86,6 +86,9 @@ from workbench_scan_start import (
86
86
  archive_scan,
87
87
  insert_running_scan,
88
88
  loaded_plugin_version,
89
+ prepare_cli_scan_target,
90
+ register_windows_resume_output,
91
+ restore_cli_scan_archive,
89
92
  safe_segment,
90
93
  scan_diff_identity,
91
94
  scan_target_identity,
@@ -93,6 +96,8 @@ from workbench_scan_start import (
93
96
  )
94
97
  from workbench_schema import (
95
98
  MIGRATIONS,
99
+ migration_target_paths,
100
+ recorded_git_checkout_roots,
96
101
  )
97
102
  from workbench_schema import (
98
103
  apply_migrations as apply_schema_migrations,
@@ -117,6 +122,7 @@ from workbench_source_scopes import (
117
122
  safe_source_path,
118
123
  )
119
124
  from workbench_target import (
125
+ checked_scan_target,
120
126
  clean_worktree_content_digest,
121
127
  copy_directory_excluding,
122
128
  copy_git_worktree_files,
@@ -130,16 +136,25 @@ from workbench_target import (
130
136
  git_submodule_entries,
131
137
  git_target_metadata,
132
138
  git_worktree_context,
139
+ rejected_checkout_roots,
133
140
  remediation_checkout_snapshot,
134
141
  require_remediation_target,
135
142
  require_scan_target_identity,
136
143
  require_scan_target_unchanged,
137
144
  restore_directory_junctions,
138
145
  scan_target_warning,
146
+ scoped_git_discovery,
147
+ scoped_regular_file_count,
139
148
  worktree_content_digest,
140
149
  worktree_content_digest_for_context,
141
150
  )
142
- from workbench_target_state import backfill_security_targets, ensure_security_target
151
+ from workbench_target_state import (
152
+ RepositoryScanScope,
153
+ backfill_security_targets,
154
+ ensure_security_target,
155
+ register_security_target,
156
+ require_scan_checkout_owner,
157
+ )
143
158
  from workbench_validation import (
144
159
  bounded_output_text,
145
160
  optional_text,
@@ -238,13 +253,21 @@ def release_completion_file_lock(descriptor: int) -> None:
238
253
  windows_file_lock.locking(descriptor, windows_file_lock.LK_UNLCK, 1)
239
254
 
240
255
 
241
- def connect(*, deferred: bool = False) -> sqlite3.Connection:
256
+ def connect(
257
+ *,
258
+ deferred: bool = False,
259
+ discovery_roots: tuple[Path, ...] = (),
260
+ in_memory: bool = False,
261
+ ) -> sqlite3.Connection:
242
262
  """Open the workbench SQLite database and bring its schema up to date.
243
263
 
244
264
  Args:
245
265
  deferred (bool): Let the first migration attempt defer its write lock.
246
266
  Retries after lock contention use an immediate transaction.
247
267
 
268
+ discovery_roots: Additional local paths for bounded target discovery.
269
+ in_memory: Keep a fresh profile read entirely in memory.
270
+
248
271
  Returns:
249
272
  sqlite3.Connection: A caller-owned connection with named rows, foreign
250
273
  keys enabled, and write-ahead logging.
@@ -260,13 +283,14 @@ def connect(*, deferred: bool = False) -> sqlite3.Connection:
260
283
  "the scanned repository."
261
284
  )
262
285
  try:
263
- create_private_directory(path.parent)
286
+ if not in_memory:
287
+ create_private_directory(path.parent)
264
288
  except OSError:
265
289
  print(guidance, file=sys.stderr)
266
290
  raise
267
291
  for attempt in range(SQLITE_RETRY_ATTEMPTS):
268
292
  try:
269
- connection = sqlite3.connect(path, timeout=5)
293
+ connection = sqlite3.connect(":memory:" if in_memory else path, timeout=5)
270
294
  except sqlite3.OperationalError:
271
295
  print(guidance, file=sys.stderr)
272
296
  raise
@@ -275,9 +299,12 @@ def connect(*, deferred: bool = False) -> sqlite3.Connection:
275
299
  connection.execute("PRAGMA foreign_keys = ON")
276
300
  connection.execute("PRAGMA busy_timeout = 5000")
277
301
  # Keep writer admission retries; readers only wait when a repair needs to write.
278
- apply_migrations(connection, immediate=not deferred or attempt > 0)
302
+ apply_migrations(
303
+ connection, immediate=not deferred or attempt > 0, discovery_roots=discovery_roots
304
+ )
279
305
  connection.execute("PRAGMA journal_mode = WAL")
280
- path.chmod(0o600)
306
+ if not in_memory:
307
+ path.chmod(0o600)
281
308
  return connection
282
309
  except sqlite3.OperationalError as exc:
283
310
  connection.close()
@@ -288,9 +315,30 @@ def connect(*, deferred: bool = False) -> sqlite3.Connection:
288
315
  raise AssertionError("SQLite retry loop exhausted unexpectedly.")
289
316
 
290
317
 
291
- def apply_migrations(connection: sqlite3.Connection, *, immediate: bool = False) -> None:
318
+ def begin_immediate_with_retry(connection: sqlite3.Connection) -> None:
319
+ for attempt in range(SQLITE_RETRY_ATTEMPTS):
320
+ try:
321
+ connection.execute("BEGIN IMMEDIATE")
322
+ return
323
+ except sqlite3.OperationalError as exc:
324
+ if attempt == SQLITE_RETRY_ATTEMPTS - 1 or not sqlite_busy(exc):
325
+ raise
326
+ time.sleep(0.05 * (2**attempt))
327
+
328
+
329
+ def apply_migrations(
330
+ connection: sqlite3.Connection,
331
+ *,
332
+ immediate: bool = False,
333
+ discovery_roots: tuple[Path, ...] = (),
334
+ ) -> None:
292
335
  apply_schema_migrations(
293
- connection, MIGRATIONS, now, backfill_security_targets, immediate=immediate
336
+ connection,
337
+ MIGRATIONS,
338
+ now,
339
+ backfill_security_targets,
340
+ immediate=immediate,
341
+ discovery_roots=discovery_roots,
294
342
  )
295
343
 
296
344
 
@@ -342,24 +390,7 @@ def scan_contract(scan: sqlite3.Row) -> dict[str, Any]:
342
390
  }
343
391
 
344
392
 
345
- def expected_coverage_mode(scan: sqlite3.Row) -> str:
346
- """Return the coverage mode implied by the recorded scope, scan mode, and diff target kind."""
347
- if scan["mode"] == "diff":
348
- mode = {
349
- "commit": "commit",
350
- "range": "branch_diff",
351
- "working_tree": "working_tree",
352
- }.get(scan["diff_target_kind"])
353
- if mode is None:
354
- raise SystemExit("This migrated diff scan does not have a validated change set.")
355
- return mode
356
- if scan["scope"] != "." or (
357
- "recipe_json" in scan.keys()
358
- and scan["recipe_json"] is not None
359
- and json.loads(scan["recipe_json"])["target"]["kind"] == "paths"
360
- ):
361
- return "scoped_path"
362
- return "deep_repository" if scan["mode"] == "deep" else "repository"
393
+ expected_coverage_mode = scan_history.expected_coverage_mode
363
394
 
364
395
 
365
396
  def workbench_completion_binding(
@@ -530,6 +561,8 @@ def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -
530
561
  diff_content_digest = (
531
562
  optional_text(args.diff_content_digest, maximum=128) if args.mode == "diff" else None
532
563
  )
564
+ target_path_unvalidated = False
565
+ rejected_roots = None
533
566
  if target_path:
534
567
  try:
535
568
  inspected = inspect_setup_values(
@@ -549,11 +582,17 @@ def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -
549
582
  diff_head_revision = inspected["diffTarget"]["headRevision"]
550
583
  diff_content_digest = inspected["diffTarget"].get("contentDigest")
551
584
  except SystemExit:
552
- # Preserve an incomplete setup so workspace_state can report its validation error.
553
- pass
585
+ # Setup may fail on scope even when the target itself is valid.
586
+ try:
587
+ require_target(target_path)
588
+ except SystemExit:
589
+ target_path_unvalidated = True
590
+ rejected_roots = rejected_checkout_roots(target_path)
554
591
  with connection:
555
592
  target_id = (
556
- ensure_security_target(connection, target_path) if target_path is not None else None
593
+ ensure_security_target(connection, target_path)
594
+ if target_path is not None and not target_path_unvalidated
595
+ else None
557
596
  )
558
597
  connection.execute(
559
598
  """
@@ -561,8 +600,8 @@ def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -
561
600
  id, thread_id, target_id, target_path, target_title, target_summary,
562
601
  default_scope, default_mode,
563
602
  user_context, diff_target_kind, diff_base_revision, diff_head_revision,
564
- diff_content_digest, created_at, updated_at
565
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
603
+ diff_content_digest, created_at, updated_at, target_path_unvalidated, rejected_checkout_roots_json
604
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
566
605
  """,
567
606
  (
568
607
  workspace_id,
@@ -580,6 +619,8 @@ def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -
580
619
  diff_content_digest,
581
620
  timestamp,
582
621
  timestamp,
622
+ target_path_unvalidated,
623
+ json.dumps(rejected_roots) if rejected_roots is not None else None,
583
624
  ),
584
625
  )
585
626
  return workspace_state(connection, workspace_id)
@@ -614,7 +655,10 @@ def save_workspace(connection: sqlite3.Connection, args: argparse.Namespace) ->
614
655
  SET target_id = ?, target_path = ?, target_title = ?, target_summary = ?, default_scope = ?,
615
656
  default_mode = ?, user_context = ?, diff_target_kind = ?,
616
657
  diff_base_revision = ?, diff_head_revision = ?, diff_content_digest = ?,
617
- deep_scan_config_json = ?, submitted = 1, updated_at = ?
658
+ deep_scan_config_json = ?, submitted = 1, updated_at = ?, target_path_unvalidated = 0,
659
+ -- JSON null keeps PATH discovery disabled after a legacy rejection.
660
+ rejected_checkout_roots_json = COALESCE(rejected_checkout_roots_json,
661
+ CASE WHEN target_path_unvalidated = 1 AND target_id IS NULL THEN 'null' END)
618
662
  WHERE id = ? AND active_scan_id IS NULL
619
663
  """,
620
664
  (
@@ -665,7 +709,8 @@ def require_working_tree_unchanged(target: Path, diff_target: dict[str, str] | N
665
709
  and diff_target["kind"] == "working_tree"
666
710
  and (
667
711
  git_revision(target) != diff_target["headRevision"]
668
- or worktree_content_digest(target) != diff_target["contentDigest"]
712
+ or worktree_content_digest(target, expected_digest=diff_target["contentDigest"])
713
+ != diff_target["contentDigest"]
669
714
  )
670
715
  ):
671
716
  raise SystemExit("The selected scan target changed while the scan was starting. Try again.")
@@ -687,6 +732,7 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict
687
732
  (workspace["id"],),
688
733
  ).fetchone()
689
734
  if active is not None:
735
+ require_scan_checkout_owner(connection, active)
690
736
  return workspace_state(connection, workspace["id"], result_scan_id=active["id"])
691
737
  workspace_version = workspace["updated_at"]
692
738
  scan_id = str(uuid.uuid4())
@@ -736,6 +782,7 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict
736
782
  (workspace["id"],),
737
783
  ).fetchone()
738
784
  if active is not None:
785
+ require_scan_checkout_owner(connection, active)
739
786
  if manages_transaction:
740
787
  connection.commit()
741
788
  return workspace_state(connection, workspace["id"], result_scan_id=active["id"])
@@ -762,6 +809,11 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict
762
809
  "This Codex thread already has an active Deep Scan for the selected "
763
810
  "target and scope. Rejoin that scan instead of starting another one."
764
811
  )
812
+ registration = register_security_target(connection, str(current_target))
813
+ if registration.target_id != workspace["target_id"]:
814
+ raise SystemExit(
815
+ "The saved workspace no longer matches the selected repository target."
816
+ )
765
817
  insert_running_scan(
766
818
  connection,
767
819
  scan_id=scan_id,
@@ -770,6 +822,7 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict
770
822
  scope=scope,
771
823
  diff_target=diff_target,
772
824
  target_identity=target_identity,
825
+ repository_generation=registration.repository_generation,
773
826
  source_scopes=source_scopes,
774
827
  target_root=target_root,
775
828
  target_summary=target_summary,
@@ -889,6 +942,7 @@ def _start_prompt_driven_scan(
889
942
  ),
890
943
  ).fetchone()
891
944
  if existing is not None:
945
+ require_scan_checkout_owner(connection, existing)
892
946
  connection.commit()
893
947
  return {
894
948
  **scan_context(connection, existing["id"], model_thread_id=thread_id),
@@ -898,7 +952,8 @@ def _start_prompt_driven_scan(
898
952
  workspace_id = str(uuid.uuid4())
899
953
  scan_id = str(uuid.uuid4())
900
954
  timestamp = now()
901
- target_id = ensure_security_target(connection, target_path)
955
+ registration = register_security_target(connection, target_path)
956
+ target_id = registration.target_id
902
957
  connection.execute(
903
958
  """
904
959
  INSERT INTO workspaces (
@@ -931,6 +986,7 @@ def _start_prompt_driven_scan(
931
986
  scope=scope,
932
987
  diff_target=diff_target,
933
988
  target_identity=target_identity,
989
+ repository_generation=registration.repository_generation,
934
990
  source_scopes=source_scopes,
935
991
  target_root=target_root,
936
992
  target_summary=target_summary,
@@ -1379,6 +1435,7 @@ def complete_scan_locked(
1379
1435
  for kind, filename in ARTIFACTS.items()
1380
1436
  }
1381
1437
  manifest_digest = published_manifest_digest(scan_dir, manifest)
1438
+ reported_count = progress.reported_scope_file_count(_WORKBENCH_DB_CONTEXT, scan)
1382
1439
  if prepare_only:
1383
1440
  connection.execute("BEGIN IMMEDIATE")
1384
1441
  with connection:
@@ -1388,6 +1445,22 @@ def complete_scan_locked(
1388
1445
  )
1389
1446
  if updated.rowcount != 1:
1390
1447
  raise SystemExit("Only a running scan can be prepared for completion.")
1448
+ if reported_count is not None:
1449
+ connection.execute(
1450
+ """
1451
+ UPDATE scan_progress SET scope_file_count = ?, updated_at = ?
1452
+ WHERE scan_id = (SELECT id FROM scans WHERE id = ? AND scan_dir = ?
1453
+ AND handoff_status = ? AND handoff_claim_token IS ?)
1454
+ """,
1455
+ (
1456
+ reported_count,
1457
+ completion_timestamp,
1458
+ scan_id,
1459
+ scan["scan_dir"],
1460
+ scan["handoff_status"],
1461
+ scan["handoff_claim_token"],
1462
+ ),
1463
+ )
1391
1464
  context = scan_context(connection, scan["id"])
1392
1465
  context["targetWarnings"] = target_warnings
1393
1466
  return context
@@ -1430,6 +1503,8 @@ def complete_scan_locked(
1430
1503
  connection.commit()
1431
1504
  return scan_context(connection, scan["id"])
1432
1505
  deep_scan.require_deep_scan_ready_for_parent_completion(connection, scan)
1506
+ if scan["scan_dir"] != str(scan_dir):
1507
+ reported_count = None
1433
1508
  connection.execute("DELETE FROM scan_artifacts WHERE scan_id = ?", (scan["id"],))
1434
1509
  for kind, path in artifacts.items():
1435
1510
  if path is not None:
@@ -1445,10 +1520,17 @@ def complete_scan_locked(
1445
1520
  UPDATE scan_progress
1446
1521
  SET reportable_findings_count = ?, phase_items_total = ?,
1447
1522
  phase_items_completed = ?, phase_progress_unit = 'report_artifacts',
1448
- updated_at = ?
1523
+ scope_file_count = COALESCE(?, scope_file_count), updated_at = ?
1449
1524
  WHERE scan_id = ?
1450
1525
  """,
1451
- (finding_count, len(artifacts), len(artifacts), timestamp, scan["id"]),
1526
+ (
1527
+ finding_count,
1528
+ len(artifacts),
1529
+ len(artifacts),
1530
+ reported_count,
1531
+ timestamp,
1532
+ scan["id"],
1533
+ ),
1452
1534
  )
1453
1535
  updated = connection.execute(
1454
1536
  """
@@ -1498,25 +1580,32 @@ def register_cli_scan(
1498
1580
  *,
1499
1581
  before_archive: Callable[[], None] | None = None,
1500
1582
  ) -> dict[str, Any]:
1501
- """Register a CLI scan and its selected target before execution begins.
1583
+ """Register the scan recipe and target identity, archiving any previous output atomically."""
1584
+ # A selected plugin may replace __main__ while delegating to this workbench.
1585
+ before_output_change = before_archive or getattr(
1586
+ sys, "_codex_security_before_output_change", None
1587
+ )
1588
+
1589
+ def acknowledge_output_change() -> None:
1590
+ nonlocal before_output_change
1591
+ if before_output_change is not None:
1592
+ before_output_change()
1593
+ before_output_change = None
1502
1594
 
1503
- Record the launch recipe and target identity with the new scan. When reusing
1504
- an output directory, coordinate archiving with registration so previous results
1505
- can still be located. Return the scan ID, contract, and target metadata.
1506
- """
1507
1595
  repository = require_target(args.repository)
1508
1596
  require_scannable_target(repository)
1509
- scan_dir = None
1510
1597
  if not args.archive_existing or args.archived_scan_dir is not None:
1511
1598
  # Preserve early output rejection when this call will not move the directory.
1512
- scan_dir = require_cli_scan_directory(repository, args)
1599
+ require_cli_scan_directory(repository, args)
1513
1600
  user_context = None
1514
1601
  workflow_id = None
1602
+ hosted = False
1515
1603
  surface = None
1516
1604
  package_version = None
1517
1605
  if args.registration_json_stdin:
1518
1606
  registration = json.load(sys.stdin)
1519
1607
  recipe_json = json.dumps(registration["recipe"], ensure_ascii=False, separators=(",", ":"))
1608
+ hosted = registration.get("hosted") is True
1520
1609
  user_context = registration.get("userContext")
1521
1610
  workflow_id = registration.get("workflowId")
1522
1611
  if registration.get("surface") in ("cli", "sdk"):
@@ -1554,14 +1643,20 @@ def register_cli_scan(
1554
1643
  raise SystemExit("Working-tree HEAD changed before the scan started.")
1555
1644
  diff_target["contentDigest"] = worktree_content_digest(repository)
1556
1645
  mode = "diff" if diff_target is not None else recipe["mode"]
1557
- target_identity = scan_target_identity(repository, diff_target)
1646
+ target_identity, resume_target = prepare_cli_scan_target(
1647
+ repository, diff_target, mode, launch_kind
1648
+ )
1558
1649
  source_scopes = capture_source_scopes(
1559
1650
  repository,
1560
1651
  target_identity,
1561
1652
  paths or ["."],
1562
1653
  diff_target_kind=diff_target["kind"] if diff_target is not None else None,
1563
1654
  )
1564
- scope_file_count = scan_scope_file_count(repository, paths or ["."], diff_target)
1655
+ scope_file_count = (
1656
+ scoped_regular_file_count(repository, paths)
1657
+ if mode == "standard" and len(paths) > 1
1658
+ else scan_scope_file_count(repository, paths or ["."], diff_target)
1659
+ )
1565
1660
  require_working_tree_unchanged(repository, diff_target)
1566
1661
  parent_scan_id = (
1567
1662
  require_uuid(args.parent_scan_id, "parent-scan-id")
@@ -1577,9 +1672,19 @@ def register_cli_scan(
1577
1672
  with ExitStack() as archive:
1578
1673
  deadline = None
1579
1674
  while True:
1580
- if scan_dir is None:
1581
- # Wait for any previous archive to finish before inspecting its replacement.
1582
- scan_dir = require_cli_scan_directory(repository, args)
1675
+ registration = register_security_target(connection, str(repository))
1676
+ target_id = registration.target_id
1677
+ if parent_scan_id is not None:
1678
+ parent = require_scan(connection, parent_scan_id)
1679
+ parent_scope = RepositoryScanScope(
1680
+ registration.repository_generation, target_id
1681
+ )
1682
+ if not parent_scope.contains(parent):
1683
+ raise SystemExit(
1684
+ "A rerun must belong to the same repository as its parent scan."
1685
+ )
1686
+ # Revalidate the output and its owner under the current write lock.
1687
+ scan_dir = require_cli_scan_directory(repository, args)
1583
1688
  try:
1584
1689
  archived_scan_dir = archive.enter_context(
1585
1690
  archive_scan(
@@ -1588,7 +1693,7 @@ def register_cli_scan(
1588
1693
  scan_dir,
1589
1694
  timestamp,
1590
1695
  require_canonical_scan_directory,
1591
- before_archive=before_archive,
1696
+ before_archive=acknowledge_output_change,
1592
1697
  )
1593
1698
  )
1594
1699
  break
@@ -1607,18 +1712,9 @@ def register_cli_scan(
1607
1712
  if remaining <= 0:
1608
1713
  raise
1609
1714
  connection.rollback()
1610
- before_archive = None # The host already acknowledged this registration.
1611
1715
  scan_dir = None # Revalidate the directory and its owner under the next lock.
1612
1716
  time.sleep(min(0.05, remaining))
1613
1717
  connection.execute("BEGIN IMMEDIATE")
1614
- target_id = ensure_security_target(connection, str(repository))
1615
- if parent_scan_id is not None:
1616
- parent = require_scan(connection, parent_scan_id)
1617
- if parent["target_id"] != target_id:
1618
- raise SystemExit(
1619
- "A rerun must belong to the same repository as its parent scan."
1620
- )
1621
-
1622
1718
  connection.execute(
1623
1719
  """
1624
1720
  INSERT INTO workspaces (
@@ -1648,6 +1744,7 @@ def register_cli_scan(
1648
1744
  scope=scope,
1649
1745
  diff_target=diff_target,
1650
1746
  target_identity=target_identity,
1747
+ repository_generation=registration.repository_generation,
1651
1748
  source_scopes=source_scopes,
1652
1749
  target_root=scan_dir.parent,
1653
1750
  target_summary=None,
@@ -1658,6 +1755,7 @@ def register_cli_scan(
1658
1755
  surface=surface,
1659
1756
  package_version=package_version,
1660
1757
  launch_kind=launch_kind,
1758
+ hosted=hosted,
1661
1759
  )
1662
1760
  connection.execute(
1663
1761
  "UPDATE scans SET recipe_json = ?, parent_scan_id = ?, user_context = ? WHERE id = ?",
@@ -1670,6 +1768,12 @@ def register_cli_scan(
1670
1768
  )
1671
1769
  if workflow_id is not None:
1672
1770
  register_workflow_scan(connection, workflow_id, scan_id, str(scan_dir), timestamp)
1771
+ if resume_target is not None:
1772
+ archive.enter_context(
1773
+ register_windows_resume_output(
1774
+ connection, scan_id, scan_dir, resume_target, acknowledge_output_change
1775
+ )
1776
+ )
1673
1777
  scan = connection.execute(
1674
1778
  "SELECT scans.*, snapshot AS lifecycle_json FROM scans "
1675
1779
  "JOIN scan_lifecycles ON scan_id = scans.id WHERE scans.id = ?",
@@ -1683,6 +1787,12 @@ def register_cli_scan(
1683
1787
  **({"archivedScanDir": str(archived_scan_dir)} if archived_scan_dir is not None else {}),
1684
1788
  "contract": scan_contract(scan),
1685
1789
  "lifecycle": json.loads(scan["lifecycle_json"]),
1790
+ **({"phase": scan["phase"]} if mode == "standard" else {}),
1791
+ **(
1792
+ {"canSaveTimeBudgetStart": True}
1793
+ if "maxTimeMinutes" in recipe and mode in {"standard", "diff"}
1794
+ else {}
1795
+ ),
1686
1796
  "scanDir": str(scan_dir),
1687
1797
  "scanId": scan_id,
1688
1798
  "scopeFileCount": scope_file_count,
@@ -1695,8 +1805,11 @@ def set_scan_thread(connection: sqlite3.Connection, args: argparse.Namespace) ->
1695
1805
  scan = require_scan(connection, args.scan_id)
1696
1806
  with connection:
1697
1807
  connection.execute(
1698
- "UPDATE scans SET continuation_thread_id = ?, updated_at = ? WHERE id = ?",
1699
- (args.thread_id, now(), scan["id"]),
1808
+ """UPDATE scans SET continuation_thread_id = ?1, updated_at = ?2,
1809
+ recipe_json = CASE WHEN ?3 IS NULL THEN recipe_json
1810
+ ELSE json_insert(recipe_json, '$.timeBudgetStartedAt', ?3) END
1811
+ WHERE id = ?4""",
1812
+ (args.thread_id, now(), getattr(args, "time_budget_started_at", None), scan["id"]),
1700
1813
  )
1701
1814
  return {"scanId": scan["id"], "threadId": args.thread_id}
1702
1815
 
@@ -2340,7 +2453,9 @@ def require_reviewed_patch_applied(
2340
2453
  ) -> str | None:
2341
2454
  target = require_scan_target_identity(scan)
2342
2455
  _, content_digest = remediation_checkout_snapshot(
2343
- scan, expected_revision=remediation["base_revision"]
2456
+ scan,
2457
+ expected_revision=remediation["base_revision"],
2458
+ expected_digest=remediation["base_content_digest"],
2344
2459
  )
2345
2460
  if content_digest == remediation["base_content_digest"]:
2346
2461
  raise SystemExit(
@@ -2350,12 +2465,17 @@ def require_reviewed_patch_applied(
2350
2465
  excluded = (Path(scan["scan_dir"]),)
2351
2466
  # Unborn repositories still need their config while metadata junctions are deferred.
2352
2467
  git_dir = git_output(target, "rev-parse", "--absolute-git-dir")
2468
+ metadata = Path(git_dir) if git_dir is not None else None
2353
2469
  if not unversioned:
2354
2470
  repository, pathspec = git_worktree_context(target)
2355
2471
  if git_dir is None:
2356
2472
  raise SystemExit("Could not inspect the selected Git working tree.")
2357
2473
  excluded += tuple(path for path, _ in git_submodule_entries(target))
2358
- with tempfile.TemporaryDirectory(prefix="codex-security-remediation-") as temporary:
2474
+ with (
2475
+ tempfile.TemporaryDirectory(prefix="codex-security-remediation-") as temporary,
2476
+ ExitStack() as pins,
2477
+ ):
2478
+ pinned_metadata = pin_replay_metadata(pins, metadata, Path(temporary))
2359
2479
  reviewed_patch = Path(temporary) / "reviewed.patch"
2360
2480
  digest = hashlib.sha256()
2361
2481
  with open_scan_local_file(Path(scan["scan_dir"]), patch_path) as source:
@@ -2371,36 +2491,30 @@ def require_reviewed_patch_applied(
2371
2491
  junctions = copy_directory_excluding(target, checkout, excluded)
2372
2492
  else:
2373
2493
  _, junctions = copy_git_worktree_files(target, checkout_root, excluded)
2374
- arguments = ["apply", "--reverse", "--whitespace=nowarn"]
2375
- if unversioned:
2376
- arguments.append("--no-index")
2377
- elif pathspec != ".":
2378
- arguments.append(f"--directory={pathspec}")
2379
- arguments.append(str(reviewed_patch))
2380
- applied = git_command(
2381
- checkout if unversioned else checkout_root,
2382
- *arguments,
2383
- text=False,
2384
- git_dir=Path(git_dir) if git_dir is not None else None,
2385
- work_tree=checkout_root if git_dir is not None else None,
2494
+ short, replay_root = remediation_state.reverse_reviewed_patch(
2495
+ target,
2496
+ checkout_root,
2497
+ metadata,
2498
+ pinned_metadata,
2499
+ remediation["patch_digest"],
2500
+ pins,
2501
+ reviewed_patch,
2502
+ None if unversioned else pathspec,
2386
2503
  )
2387
- if applied.returncode != 0:
2388
- raise SystemExit(
2389
- "The selected checkout does not contain the reviewed remediation patch. Apply exactly that patch before recording it as applied."
2390
- )
2391
2504
  restore_directory_junctions(
2392
2505
  target if unversioned else repository,
2393
2506
  checkout if unversioned else checkout_root,
2394
2507
  junctions,
2395
2508
  )
2396
2509
  reverted_digest = (
2397
- directory_content_digest(checkout)
2510
+ directory_content_digest(checkout, replay_git_dir=replay_root)
2398
2511
  if unversioned
2399
2512
  else worktree_content_digest_for_context(
2400
2513
  checkout_root,
2401
2514
  pathspec or ".",
2402
- git_dir=Path(git_dir),
2515
+ git_dir=short or metadata,
2403
2516
  work_tree=checkout_root,
2517
+ expected_digest=remediation["base_content_digest"],
2404
2518
  )
2405
2519
  )
2406
2520
  if reverted_digest != remediation["base_content_digest"] and unversioned:
@@ -2410,12 +2524,16 @@ def require_reviewed_patch_applied(
2410
2524
  checkout,
2411
2525
  "-c",
2412
2526
  "core.autocrlf=input",
2413
- *arguments,
2527
+ "apply",
2528
+ "--reverse",
2529
+ "--whitespace=nowarn",
2530
+ "--no-index",
2531
+ str(reviewed_patch),
2414
2532
  text=True,
2415
2533
  )
2416
2534
  if applied_without_conversion.returncode == 0:
2417
2535
  restore_directory_junctions(target, checkout, junctions)
2418
- reverted_digest = directory_content_digest(checkout)
2536
+ reverted_digest = directory_content_digest(checkout, replay_git_dir=replay_root)
2419
2537
  if reverted_digest != remediation["base_content_digest"]:
2420
2538
  raise SystemExit(
2421
2539
  "The selected checkout contains changes outside the reviewed patch. Remove them before recording the patch as applied."
@@ -2430,9 +2548,6 @@ def require_remediation_checkout_unchanged(
2430
2548
  require_applied_content: bool = False,
2431
2549
  require_base_content: bool = False,
2432
2550
  ) -> None:
2433
- _, content_digest = remediation_checkout_snapshot(
2434
- scan, expected_revision=remediation["base_revision"]
2435
- )
2436
2551
  expected_digest = (
2437
2552
  remediation["applied_content_digest"]
2438
2553
  if require_applied_content
@@ -2440,6 +2555,9 @@ def require_remediation_checkout_unchanged(
2440
2555
  if require_base_content
2441
2556
  else None
2442
2557
  )
2558
+ _, content_digest = remediation_checkout_snapshot(
2559
+ scan, expected_revision=remediation["base_revision"], expected_digest=expected_digest
2560
+ )
2443
2561
  if expected_digest is not None and content_digest != expected_digest:
2444
2562
  raise SystemExit(
2445
2563
  "Working-tree contents changed. Regenerate the remediation patch against the current checkout."
@@ -2608,8 +2726,8 @@ def get_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[s
2608
2726
  ).fetchone()
2609
2727
  if scan is None:
2610
2728
  raise SystemExit("Codex Security scan not found.")
2611
- progress, _ = scan_progress_result(connection, scan)
2612
- return {"scan": {"progress": progress}}
2729
+ progress_result, _ = progress.scan_progress_result(connection, scan)
2730
+ return {"scan": {"progress": progress_result}}
2613
2731
  request_id = getattr(args, "request_id", None)
2614
2732
  action_token = getattr(args, "action_token", None)
2615
2733
  if request_id is not None or action_token is not None:
@@ -2718,45 +2836,6 @@ def list_findings(connection: sqlite3.Connection, args: argparse.Namespace) -> d
2718
2836
  }
2719
2837
 
2720
2838
 
2721
- def scan_progress_result(
2722
- connection: sqlite3.Connection, scan: sqlite3.Row
2723
- ) -> tuple[dict[str, Any], str]:
2724
- independent_reviews = (
2725
- deep_scan.independent_review_progress(
2726
- connection, scan["id"], parent_running=scan["status"] == "running"
2727
- )
2728
- if scan["mode"] == "deep"
2729
- else None
2730
- )
2731
- progress_result = {
2732
- "candidates": {"reportable": scan["reportable_findings_count"]},
2733
- "coverage": {
2734
- "closedRows": scan["review_items_completed"],
2735
- "filesTotal": scan["scope_file_count"],
2736
- "worklistRows": scan["review_items_total"],
2737
- },
2738
- "phase": scan["phase"],
2739
- "phaseProgress": {
2740
- "completed": scan["phase_items_completed"],
2741
- "total": scan["phase_items_total"],
2742
- "unit": scan["phase_progress_unit"],
2743
- },
2744
- "preflightProgress": {
2745
- "completed": scan["preflight_checks_completed"],
2746
- "total": scan["preflight_checks_total"],
2747
- },
2748
- "preflightIssues": json.loads(scan["preflight_issues_json"]),
2749
- "reviewPass": scan["deep_review_pass"],
2750
- "status": "canceled" if scan["canceled_at"] else scan["status"],
2751
- "updatedAt": scan["progress_updated_at"],
2752
- }
2753
- review_updated_at = ""
2754
- if independent_reviews is not None:
2755
- review_updated_at = str(independent_reviews.pop("updatedAt"))
2756
- progress_result["independentReviews"] = independent_reviews
2757
- return progress_result, review_updated_at
2758
-
2759
-
2760
2839
  def scan_result(
2761
2840
  connection: sqlite3.Connection,
2762
2841
  scan: sqlite3.Row,
@@ -2813,7 +2892,7 @@ def scan_result(
2813
2892
  }
2814
2893
  finding_count = sum(severity_counts.values())
2815
2894
  remediation_available, remediation_unavailable_reason = remediation_availability(scan)
2816
- progress_result, review_updated_at = scan_progress_result(connection, scan)
2895
+ progress_result, review_updated_at = progress.scan_progress_result(connection, scan)
2817
2896
  relations = scan_history.finding_relations(
2818
2897
  connection, scan["id"], (row["id"] for row in occurrence_rows)
2819
2898
  )
@@ -2872,7 +2951,8 @@ def remediation_availability(scan: sqlite3.Row) -> tuple[bool, str | None]:
2872
2951
  if scan["status"] != "complete":
2873
2952
  return False, remediation_state.SCAN_STATUS_ERROR
2874
2953
  try:
2875
- current_revision = git_revision(require_scan_target_identity(scan))
2954
+ with checked_scan_target(scan) as target:
2955
+ current_revision = git_revision(target)
2876
2956
  except SystemExit as exc:
2877
2957
  return False, str(exc)
2878
2958
  expected_revision = scan["target_revision"]
@@ -2930,15 +3010,7 @@ def backfill_legacy_finding_details(connection: sqlite3.Connection, scan: sqlite
2930
3010
  if not updates:
2931
3011
  return
2932
3012
 
2933
- # Reads normally avoid writer admission, but legacy details still need a write.
2934
- for attempt in range(SQLITE_RETRY_ATTEMPTS):
2935
- try:
2936
- connection.execute("BEGIN IMMEDIATE")
2937
- break
2938
- except sqlite3.OperationalError as exc:
2939
- if attempt == SQLITE_RETRY_ATTEMPTS - 1 or not sqlite_busy(exc):
2940
- raise
2941
- time.sleep(0.05 * (2**attempt))
3013
+ begin_immediate_with_retry(connection)
2942
3014
  with connection:
2943
3015
  current = require_scan(connection, scan["id"])
2944
3016
  recorded_digest = current["seal_manifest_digest"]
@@ -3137,39 +3209,10 @@ def read_finding_details(value: str) -> dict[str, Any]:
3137
3209
  return details if isinstance(details, dict) else {}
3138
3210
 
3139
3211
 
3140
- def finding_management_updated_at(connection: sqlite3.Connection, scan_id: str) -> str | None:
3141
- return connection.execute(
3142
- """
3143
- SELECT MAX(updated_at)
3144
- FROM (
3145
- SELECT triage.updated_at
3146
- FROM finding_triage AS triage
3147
- JOIN finding_occurrences AS occurrences ON occurrences.id = triage.occurrence_id
3148
- WHERE occurrences.scan_id = ?
3149
- UNION ALL
3150
- SELECT remediation.updated_at
3151
- FROM finding_remediation_attempts AS remediation
3152
- JOIN finding_occurrences AS occurrences ON occurrences.id = remediation.occurrence_id
3153
- WHERE occurrences.scan_id = ?
3154
- )
3155
- """,
3156
- (scan_id, scan_id),
3157
- ).fetchone()[0]
3212
+ finding_management_updated_at = scan_history.finding_management_updated_at
3158
3213
 
3159
3214
 
3160
- def finding_triage_result(connection: sqlite3.Connection, occurrence_id: str) -> dict[str, Any]:
3161
- row = connection.execute(
3162
- "SELECT status, close_reason, note, updated_at FROM finding_triage WHERE occurrence_id = ?",
3163
- (occurrence_id,),
3164
- ).fetchone()
3165
- if row is None:
3166
- return {"status": "open"}
3167
- return {
3168
- "closeReason": row["close_reason"],
3169
- "note": row["note"],
3170
- "status": row["status"],
3171
- "updatedAt": row["updated_at"],
3172
- }
3215
+ finding_triage_result = scan_history.finding_triage_result
3173
3216
 
3174
3217
 
3175
3218
  def finding_remediation_result(
@@ -3219,48 +3262,9 @@ def finding_remediation_result(
3219
3262
  def patch_artifact_preview(
3220
3263
  scan_dir: Path, relative_path: str | None, expected_digest: str | None
3221
3264
  ) -> tuple[str | None, dict[str, int | bool] | None]:
3222
- if relative_path is None or expected_digest is None:
3223
- return None, None
3224
- digest = hashlib.sha256()
3225
- preview = bytearray()
3226
- additions = 0
3227
- deletions = 0
3228
- file_count = 0
3229
- old_headers = 0
3230
- new_headers = 0
3231
- at_line_start = True
3232
- try:
3233
- with open_scan_local_file(scan_dir, relative_path) as patch:
3234
- while chunk := patch.readline(1024 * 1024):
3235
- digest.update(chunk)
3236
- if len(preview) <= PATCH_PREVIEW_BYTES:
3237
- preview.extend(chunk[: PATCH_PREVIEW_BYTES + 1 - len(preview)])
3238
- if at_line_start:
3239
- if chunk.startswith(b"diff --git "):
3240
- file_count += 1
3241
- elif chunk.startswith(b"+++ "):
3242
- new_headers += 1
3243
- elif chunk.startswith(b"--- "):
3244
- old_headers += 1
3245
- elif chunk.startswith(b"+"):
3246
- additions += 1
3247
- elif chunk.startswith(b"-"):
3248
- deletions += 1
3249
- at_line_start = chunk.endswith(b"\n")
3250
- except SystemExit:
3251
- return None, None
3252
- if f"sha256:{digest.hexdigest()}" != expected_digest:
3253
- return None, None
3254
- preview_truncated = len(preview) > PATCH_PREVIEW_BYTES
3255
- preview_text = preview[:PATCH_PREVIEW_BYTES].decode("utf-8", errors="replace")
3256
- if preview_truncated:
3257
- preview_text = f"{preview_text}\n... patch preview truncated ..."
3258
- return preview_text, {
3259
- "additions": additions,
3260
- "deletions": deletions,
3261
- "fileCount": file_count or min(old_headers, new_headers),
3262
- "previewTruncated": preview_truncated,
3263
- }
3265
+ return remediation_state.patch_artifact_preview(
3266
+ scan_dir, relative_path, expected_digest, open_scan_local_file
3267
+ )
3264
3268
 
3265
3269
 
3266
3270
  def available_artifact_path(scan_dir: Path, candidate: Path) -> Path | None:
@@ -3297,7 +3301,7 @@ def require_canonical_scan_directory(scan_dir: Path, *, writable_output: bool =
3297
3301
  try:
3298
3302
  metadata = scan_dir.lstat()
3299
3303
  resolved = scan_dir.resolve(strict=True)
3300
- except OSError as exc:
3304
+ except (OSError, RuntimeError) as exc:
3301
3305
  raise SystemExit(
3302
3306
  "Scan directory must be an existing canonical non-symlink directory."
3303
3307
  ) from exc
@@ -3373,11 +3377,31 @@ def main(*, before_archive: Callable[[], None] | None = None) -> None:
3373
3377
  raise SystemExit(73) from None
3374
3378
  print(json.dumps(result, allow_nan=False, sort_keys=True))
3375
3379
  return
3376
- with closing(
3377
- connect(
3378
- deferred=args.command in {"get-scan", "read-scan-usage", "list-scans", "database-info"}
3379
- )
3380
- ) as connection:
3380
+ command_targets = tuple(
3381
+ Path(value).expanduser()
3382
+ for field in ("target_path", "repository")
3383
+ if (value := getattr(args, field, None))
3384
+ )
3385
+ with (
3386
+ closing(
3387
+ connect(
3388
+ deferred=args.command
3389
+ in {
3390
+ "get-scan",
3391
+ "read-scan-usage",
3392
+ "list-scans",
3393
+ "database-info",
3394
+ "update-progress",
3395
+ },
3396
+ discovery_roots=command_targets,
3397
+ in_memory=scan_history.reads_missing_history(args, database_path()),
3398
+ )
3399
+ ) as connection,
3400
+ scoped_git_discovery(
3401
+ lambda: [*migration_target_paths(connection), *command_targets],
3402
+ recorded_git_roots=lambda: recorded_git_checkout_roots(connection),
3403
+ ),
3404
+ ):
3381
3405
  remediation_state.require_available(connection, args, require_scan)
3382
3406
  handlers = {
3383
3407
  "create-workspace": create_workspace,
@@ -3394,6 +3418,9 @@ def main(*, before_archive: Callable[[], None] | None = None) -> None:
3394
3418
  "record-deep-scan-publication-failure": deep_scan.record_deep_scan_publication_failure,
3395
3419
  "list-scans": scan_history.list_scans,
3396
3420
  "register-cli-scan": partial(register_cli_scan, before_archive=before_archive),
3421
+ "restore-cli-scan-archive": partial(
3422
+ restore_cli_scan_archive, canonical_directory=require_canonical_scan_directory
3423
+ ),
3397
3424
  "set-scan-thread": set_scan_thread,
3398
3425
  "set-scan-cost-limit": set_scan_cost_limit,
3399
3426
  "read-scan-usage": read_scan_usage,