@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
@@ -84,6 +84,28 @@ def _rename_exclusive(parent_fd: int, source: str, destination: str) -> None:
84
84
  if rename(parent_fd, os.fsencode(source), parent_fd, os.fsencode(destination), flag) == 0:
85
85
  return
86
86
  code = ctypes.get_errno()
87
+ elif sys.platform == "linux":
88
+ import sysconfig
89
+
90
+ # musl omits the renameat2 wrapper. Select the syscall for the Python
91
+ # process's ABI, which can differ from the host kernel's architecture.
92
+ arch = (sysconfig.get_config_var("MULTIARCH") or "").partition("-")[0]
93
+ number = {"x86_64": 316, "aarch64": 276}.get(arch)
94
+ syscall = getattr(libc, "syscall", None)
95
+ if number is not None and ctypes.sizeof(ctypes.c_void_p) == 8 and syscall is not None:
96
+ syscall.argtypes = [ctypes.c_long]
97
+ syscall.restype = ctypes.c_long
98
+ result = syscall(
99
+ number,
100
+ ctypes.c_long(parent_fd),
101
+ ctypes.c_char_p(os.fsencode(source)),
102
+ ctypes.c_long(parent_fd),
103
+ ctypes.c_char_p(os.fsencode(destination)),
104
+ ctypes.c_long(flag),
105
+ )
106
+ if result == 0:
107
+ return
108
+ code = ctypes.get_errno()
87
109
  detail = os.strerror(code)
88
110
  if code in {errno.ENOSYS, errno.ENOTSUP, errno.EOPNOTSUPP, errno.EINVAL}:
89
111
  detail = f"cannot publish a new file atomically without hard links or exclusive rename ({detail})"
@@ -168,7 +190,10 @@ def stage_write(
168
190
  if matches:
169
191
  yield lambda _directory=None: (opened, opened.st_ctime_ns)
170
192
  return
171
- candidate = f".{name}.{secrets.token_hex(8)}.tmp"
193
+ # A valid destination may already occupy the filesystem's entire name limit.
194
+ candidate = f".{secrets.token_hex(8)}.tmp"
195
+ if name.casefold() == candidate:
196
+ candidate = "." + candidate
172
197
 
173
198
  with stage_file(parent_fd, candidate, payload, owner_read_write) as staged_fd:
174
199
  staged = os.fstat(staged_fd)
@@ -4,11 +4,18 @@
4
4
  from __future__ import annotations
5
5
 
6
6
  import argparse
7
+ import os
7
8
  import sqlite3
8
9
  from pathlib import Path
9
10
  from urllib.parse import quote
10
11
 
11
12
 
13
+ def readonly_sqlite_uri(path: Path) -> str:
14
+ """Escape the native filename, including separators, without introducing a URI authority."""
15
+ filename = os.fsencode(path) if os.name == "posix" else str(path)
16
+ return f"file:{quote(filename, safe='')}?mode=ro"
17
+
18
+
12
19
  def main() -> None:
13
20
  """Back up the read-only source database into a separate destination using SQLite’s backup API."""
14
21
  parser = argparse.ArgumentParser(description=__doc__)
@@ -21,8 +28,7 @@ def main() -> None:
21
28
  if destination.exists() and destination.samefile(source):
22
29
  parser.error(f"Destination must not be the same file as source: {destination}")
23
30
  destination.parent.mkdir(parents=True, exist_ok=True)
24
- source_uri = f"file:{quote(str(source), safe='')}?mode=ro"
25
- with sqlite3.connect(source_uri, uri=True) as source_connection:
31
+ with sqlite3.connect(readonly_sqlite_uri(source), uri=True) as source_connection:
26
32
  creation_destination = destination.resolve()
27
33
  try:
28
34
  creation_destination.touch(mode=0o600, exist_ok=False)
@@ -71,6 +71,7 @@ _OPEN_EXISTING = 3
71
71
  _FILE_ATTRIBUTE_DIRECTORY = 0x00000010
72
72
  _FILE_ATTRIBUTE_NORMAL = 0x00000080
73
73
  _FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400
74
+ _REPARSE_TAG_NAME_SURROGATE = 0x20000000
74
75
  _FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
75
76
  _FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
76
77
 
@@ -78,6 +79,7 @@ _FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
78
79
  _FILE_RENAME_INFO_CLASS = 3
79
80
  _FILE_DISPOSITION_INFO_CLASS = 4
80
81
  _FILE_ATTRIBUTE_TAG_INFO_CLASS = 9
82
+ _FILE_ID_INFO_CLASS = 18
81
83
 
82
84
  _FILE_TYPE_DISK = 0x0001
83
85
  _FILE_NAME_OPENED = 0x00000008
@@ -130,6 +132,25 @@ class _FileAttributeTagInfo(ctypes.Structure):
130
132
  ]
131
133
 
132
134
 
135
+ class _FileIdInfo(ctypes.Structure):
136
+ _fields_ = [("VolumeSerialNumber", ctypes.c_uint64), ("FileId", ctypes.c_ubyte * 16)]
137
+
138
+
139
+ class _ByHandleFileInformation(ctypes.Structure):
140
+ _fields_ = [
141
+ ("dwFileAttributes", wintypes.DWORD),
142
+ ("ftCreationTime", wintypes.FILETIME),
143
+ ("ftLastAccessTime", wintypes.FILETIME),
144
+ ("ftLastWriteTime", wintypes.FILETIME),
145
+ ("dwVolumeSerialNumber", wintypes.DWORD),
146
+ ("nFileSizeHigh", wintypes.DWORD),
147
+ ("nFileSizeLow", wintypes.DWORD),
148
+ ("nNumberOfLinks", wintypes.DWORD),
149
+ ("nFileIndexHigh", wintypes.DWORD),
150
+ ("nFileIndexLow", wintypes.DWORD),
151
+ ]
152
+
153
+
133
154
  class _SecurityAttributes(ctypes.Structure):
134
155
  _fields_ = [
135
156
  ("length", wintypes.DWORD),
@@ -230,6 +251,12 @@ if os.name == "nt":
230
251
  wintypes.DWORD,
231
252
  ]
232
253
  _GetFileInformationByHandleEx.restype = wintypes.BOOL
254
+ _GetFileInformationByHandle = _kernel32.GetFileInformationByHandle
255
+ _GetFileInformationByHandle.argtypes = [
256
+ wintypes.HANDLE,
257
+ ctypes.POINTER(_ByHandleFileInformation),
258
+ ]
259
+ _GetFileInformationByHandle.restype = wintypes.BOOL
233
260
 
234
261
  _GetFileType = _kernel32.GetFileType
235
262
  _GetFileType.argtypes = [wintypes.HANDLE]
@@ -442,9 +469,11 @@ def _verify_handle_path(handle: int, expected_path: Path, *, opened_name: bool =
442
469
  raise _invalid_path(expected_path, "opened file resolved outside its verified scan path")
443
470
 
444
471
 
445
- def _verify_directory(handle: int, expected_path: Path) -> None:
472
+ def _verify_directory(handle: int, expected_path: Path, checkout: bool = False) -> None:
446
473
  info = _attributes(handle)
447
- if info.FileAttributes & _FILE_ATTRIBUTE_REPARSE_POINT:
474
+ if info.FileAttributes & _FILE_ATTRIBUTE_REPARSE_POINT and (
475
+ not checkout or not info.ReparseTag or info.ReparseTag & _REPARSE_TAG_NAME_SURROGATE
476
+ ):
448
477
  raise _invalid_path(expected_path, "scan-local directories must not be reparse points")
449
478
  if not info.FileAttributes & _FILE_ATTRIBUTE_DIRECTORY:
450
479
  raise _invalid_path(expected_path, "expected a scan-local directory")
@@ -480,6 +509,7 @@ def _open_directory(
480
509
  missing_ok: bool = False,
481
510
  missing_is_path_error: bool = True,
482
511
  movable: bool = False,
512
+ checkout: bool = False,
483
513
  ) -> _OwnedHandle | None:
484
514
  try:
485
515
  handle = _create_file(
@@ -500,7 +530,7 @@ def _open_directory(
500
530
  if handle is not None:
501
531
  try:
502
532
  assert handle.value is not None
503
- _verify_directory(handle.value, path)
533
+ _verify_directory(handle.value, path, checkout)
504
534
  except BaseException:
505
535
  handle.close()
506
536
  raise
@@ -550,7 +580,7 @@ def _current_user_sid() -> str:
550
580
  return _sid_text(wintypes.LPVOID.from_buffer(user))
551
581
 
552
582
 
553
- def _output_directory_grants(handle: int, path: Path) -> int:
583
+ def _output_directory_grants(handle: int, path: Path, *, expected_descriptor=None) -> int:
554
584
  """Inspect the descriptor of the opened directory, even if its pathname changes."""
555
585
  owner, acl, descriptor = wintypes.LPVOID(), wintypes.LPVOID(), wintypes.LPVOID()
556
586
  status = _advapi32.GetSecurityInfo(
@@ -566,6 +596,10 @@ def _output_directory_grants(handle: int, path: Path) -> int:
566
596
  if status:
567
597
  raise ctypes.WinError(status)
568
598
  try:
599
+ if expected_descriptor is not None and _generated_directory_policy(
600
+ descriptor
601
+ ) != _generated_directory_policy(expected_descriptor):
602
+ raise _invalid_path(path, "new scan directory lacks its private owner or DACL")
569
603
  trusted = {
570
604
  _current_user_sid(),
571
605
  "S-1-5-18",
@@ -651,8 +685,8 @@ def _require_stable_output(path: Path, parent_grants: int, child_grants: int = 0
651
685
 
652
686
 
653
687
  @contextlib.contextmanager
654
- def _checked_output_directory(path: Path) -> Iterator[tuple[int, int]]:
655
- """Hold the checked canonical chain and expose its final directory handle and grants."""
688
+ def _checked_output_directory(path: Path) -> Iterator[tuple[int | None, int, int]]:
689
+ """Hold the checked chain and expose its parent, final directory handle and grants."""
656
690
  parent_grants = 0
657
691
  parent = None
658
692
  with contextlib.ExitStack() as pins:
@@ -678,18 +712,77 @@ def _checked_output_directory(path: Path) -> Iterator[tuple[int, int]]:
678
712
  _verify_directory(handle.value, directory)
679
713
  grants = _output_directory_grants(handle.value, directory)
680
714
  _require_stable_output(directory, parent_grants, grants)
681
- parent, parent_grants = handle.value, grants
682
- yield parent, parent_grants
715
+ containing, parent, parent_grants = parent, handle.value, grants
716
+ yield containing, parent, parent_grants
683
717
 
684
718
 
685
719
  def require_windows_output_path(path: Path, *, writable_output: bool = False) -> None:
686
- with _checked_output_directory(path) as (_, grants):
720
+ with _checked_output_directory(path) as (_, _, grants):
687
721
  if writable_output and grants & _SET_REPARSE_POINT:
688
722
  raise _invalid_path(
689
723
  path, "Another user can turn the output directory into a reparse point when empty."
690
724
  )
691
725
 
692
726
 
727
+ DEEP_RESUME_DIRECTORY = ".codex-security-resume"
728
+
729
+
730
+ def deep_resume_output_identity(scan_dir: Path) -> list[int]:
731
+ """Bind the output and its protected child while every directory is pinned."""
732
+ retained = scan_dir / DEEP_RESUME_DIRECTORY
733
+ with _checked_output_directory(retained) as (parent, child, grants):
734
+ assert parent is not None
735
+ return _pinned_resume_identity(parent, child, retained, grants)
736
+
737
+
738
+ def _full_directory_id(handle: int, path: Path) -> tuple[int, int] | None:
739
+ info = _FileIdInfo()
740
+ if not _GetFileInformationByHandleEx(
741
+ handle, _FILE_ID_INFO_CLASS, ctypes.byref(info), ctypes.sizeof(info)
742
+ ):
743
+ if ctypes.get_last_error() in {50, 87}: # ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER.
744
+ return None
745
+ _raise_last_error("GetFileInformationByHandleEx(FileIdInfo)", path)
746
+ file_id = int.from_bytes(info.FileId, "little")
747
+ if not file_id:
748
+ raise _invalid_path(path, "The resume directory has no stable file identity.")
749
+ return info.VolumeSerialNumber, file_id
750
+
751
+
752
+ def _resume_directory_id(handle: int, path: Path) -> tuple[int, int]:
753
+ if (identity := _full_directory_id(handle, path)) is not None:
754
+ return identity
755
+ # Some filesystems expose only the legacy 64-bit file index.
756
+ legacy = _ByHandleFileInformation()
757
+ if not _GetFileInformationByHandle(handle, ctypes.byref(legacy)):
758
+ _raise_last_error("GetFileInformationByHandle", path)
759
+ file_id = (legacy.nFileIndexHigh << 32) | legacy.nFileIndexLow
760
+ if not file_id:
761
+ raise _invalid_path(path, "The resume directory has no stable file identity.")
762
+ return legacy.dwVolumeSerialNumber, file_id
763
+
764
+
765
+ @contextlib.contextmanager
766
+ def pinned_resume_checkout(target: Path) -> Iterator[tuple[int, int] | None]:
767
+ """Keep the canonical checkout fixed while reading its full native identity and snapshot."""
768
+ with contextlib.ExitStack() as pins:
769
+ for directory in (*reversed(target.parents), target):
770
+ # A source provider directory may carry a reparse tag without redirecting its name.
771
+ handle = _open_directory(directory, checkout=True)
772
+ assert handle is not None
773
+ pins.enter_context(handle)
774
+ assert handle.value is not None
775
+ yield _full_directory_id(handle.value, target)
776
+
777
+
778
+ def _pinned_resume_identity(parent: int, child: int, retained: Path, grants: int) -> list[int]:
779
+ # A nonreplaceable, protected child keeps the scan root nonempty after
780
+ # the sandbox receives Modify there. The caller holds both directories.
781
+ if grants:
782
+ raise _invalid_path(retained, "The retained resume directory must be protected.")
783
+ return [*_resume_directory_id(parent, retained.parent), *_resume_directory_id(child, retained)]
784
+
785
+
693
786
  class _UnicodeString(ctypes.Structure):
694
787
  _fields_ = [
695
788
  ("length", wintypes.USHORT),
@@ -710,7 +803,7 @@ class _ObjectAttributes(ctypes.Structure):
710
803
 
711
804
 
712
805
  def _relative_output_directory(
713
- parent: int, basename: str, descriptor=None
806
+ parent: int, basename: str, descriptor=None, *, rollback_handle: bool = False
714
807
  ) -> tuple[int, int | None]:
715
808
  """Open or create one component relative to its checked parent without reparsing it."""
716
809
  size = len(basename.encode("utf-16-le", errors="surrogatepass"))
@@ -729,12 +822,16 @@ def _relative_output_directory(
729
822
  io_status = (ctypes.c_void_p * 2)() # IO_STATUS_BLOCK
730
823
  status = _ntdll.NtCreateFile(
731
824
  ctypes.byref(handle),
732
- _FILE_TRAVERSE | _FILE_READ_ATTRIBUTES | _READ_CONTROL | 0x100000,
825
+ _FILE_TRAVERSE
826
+ | _FILE_READ_ATTRIBUTES
827
+ | _READ_CONTROL
828
+ | 0x100000
829
+ | (_DELETE if rollback_handle else 0),
733
830
  ctypes.byref(attributes),
734
831
  ctypes.byref(io_status),
735
832
  None,
736
833
  _FILE_ATTRIBUTE_NORMAL,
737
- _FILE_SHARE_READ | _FILE_SHARE_WRITE,
834
+ 0 if rollback_handle else _FILE_SHARE_READ | _FILE_SHARE_WRITE,
738
835
  1 if descriptor is None else 2, # FILE_OPEN or FILE_CREATE
739
836
  0x200021, # FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT | FILE_DIRECTORY_FILE
740
837
  None,
@@ -744,7 +841,7 @@ def _relative_output_directory(
744
841
 
745
842
 
746
843
  def create_windows_output_directory(path: Path, descriptor: wintypes.LPVOID) -> int:
747
- with _checked_output_directory(path.parent) as (parent, grants):
844
+ with _checked_output_directory(path.parent) as (_, parent, grants):
748
845
  _require_stable_output(path, grants)
749
846
  error, handle = _relative_output_directory(parent, path.name, descriptor)
750
847
  if not error:
@@ -752,8 +849,8 @@ def create_windows_output_directory(path: Path, descriptor: wintypes.LPVOID) ->
752
849
  return error
753
850
 
754
851
 
755
- def create_private_directory(path: Path, *, exist_ok: bool, scan_output: bool) -> Path:
756
- """Create one Windows directory with a protected inheritable DACL."""
852
+ @contextlib.contextmanager
853
+ def _private_directory_descriptor(path: Path, *, explicit_owner: bool) -> Iterator[wintypes.LPVOID]:
757
854
  _require_windows()
758
855
  # Older supported Python releases ignore mkdir's 0700 mode on Windows.
759
856
  # Apply the same owner/SYSTEM/Administrators policy at creation so a
@@ -770,7 +867,7 @@ def create_private_directory(path: Path, *, exist_ok: bool, scan_output: bool) -
770
867
  raise ValueError("Select a directory on a Windows volume that supports ACLs.")
771
868
 
772
869
  sid = _current_user_sid()
773
- owner = "" if exist_ok else f"O:{sid}"
870
+ owner = f"O:{sid}" if explicit_owner else ""
774
871
  dacl = f"{owner}D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;{sid})"
775
872
 
776
873
  descriptor = wintypes.LPVOID()
@@ -779,6 +876,14 @@ def create_private_directory(path: Path, *, exist_ok: bool, scan_output: bool) -
779
876
  ):
780
877
  raise ctypes.WinError(ctypes.get_last_error())
781
878
  try:
879
+ yield descriptor
880
+ finally:
881
+ _kernel32.LocalFree(descriptor)
882
+
883
+
884
+ def create_private_directory(path: Path, *, exist_ok: bool, scan_output: bool) -> Path:
885
+ """Create one Windows directory with a protected inheritable DACL."""
886
+ with _private_directory_descriptor(path, explicit_owner=not exist_ok) as descriptor:
782
887
  if scan_output:
783
888
  error = create_windows_output_directory(path, descriptor)
784
889
  else:
@@ -795,8 +900,34 @@ def create_private_directory(path: Path, *, exist_ok: bool, scan_output: bool) -
795
900
  require_windows_output_path(path)
796
901
  return path
797
902
  raise ctypes.WinError(error)
798
- finally:
799
- _kernel32.LocalFree(descriptor)
903
+
904
+
905
+ @contextlib.contextmanager
906
+ def create_deep_resume_output(scan_dir: Path, committed: Callable[[], bool]) -> Iterator[list[int]]:
907
+ """Retain the exact creation handle through verification and database commit."""
908
+ retained = scan_dir / DEEP_RESUME_DIRECTORY
909
+ with (
910
+ _private_directory_descriptor(retained, explicit_owner=True) as descriptor,
911
+ _checked_output_directory(scan_dir) as (_, parent, grants),
912
+ ):
913
+ _require_stable_output(retained, grants)
914
+ error, child = _relative_output_directory(
915
+ parent, retained.name, descriptor, rollback_handle=True
916
+ )
917
+ if error:
918
+ raise ctypes.WinError(error)
919
+ assert child is not None
920
+ with _OwnedHandle(child):
921
+ try:
922
+ _verify_directory(child, retained)
923
+ child_grants = _output_directory_grants(
924
+ child, retained, expected_descriptor=descriptor
925
+ )
926
+ yield _pinned_resume_identity(parent, child, retained, child_grants)
927
+ except BaseException:
928
+ if not committed():
929
+ _mark_handle_for_deletion(child)
930
+ raise
800
931
 
801
932
 
802
933
  def create_directory_with_same_dacl(path: Path, source: Path) -> None:
@@ -903,16 +1034,22 @@ def scan_root_identity(scan_dir: Path) -> tuple[Path, tuple[int, int]]:
903
1034
 
904
1035
 
905
1036
  @contextlib.contextmanager
906
- def pinned_root_git_marker(cwd: Path, metadata: Path) -> Iterator[Path | None]:
907
- """Bind a canonical worktree beneath a fixed-drive root to its exact .git marker."""
1037
+ def pinned_root_git_marker(
1038
+ cwd: Path, metadata: Path, *, work_tree: Path | None = None
1039
+ ) -> Iterator[Path | None]:
1040
+ """Return a short explicit worktree marker while its cwd and Git metadata are pinned."""
1041
+ if work_tree is None:
1042
+ work_tree = cwd
908
1043
  if (
909
1044
  not cwd.is_absolute()
910
1045
  or not metadata.is_absolute()
911
1046
  or len(cwd.drive) != 2
912
- or cwd.drive != metadata.drive
913
- or len(cwd.parts) < 2
1047
+ or len(metadata.drive) != 2
1048
+ or len(work_tree.parts) < 2
1049
+ or cwd.parts[: len(work_tree.parts)] != work_tree.parts
914
1050
  or len(metadata.parts) < 2
915
1051
  or _GetDriveTypeW(cwd.anchor) != _DRIVE_FIXED
1052
+ or _GetDriveTypeW(metadata.anchor) != _DRIVE_FIXED
916
1053
  ):
917
1054
  yield None
918
1055
  return
@@ -930,9 +1067,11 @@ def pinned_root_git_marker(cwd: Path, metadata: Path) -> Iterator[Path | None]:
930
1067
  assert handle.value is not None
931
1068
  if _final_path(handle.value) != _extended_path(path):
932
1069
  raise ValueError("the selected Git directory spelling is not canonical")
933
- if str(cwd / ".git") != str(metadata):
1070
+ root_marker = work_tree / ".git"
1071
+ reference = Path(os.path.relpath(root_marker, cwd))
1072
+ if str(root_marker) != str(metadata):
934
1073
  # The literal canonical root is already pinned before opening its regular file.
935
- fd, leaf = open_read_fd_with_path(cwd, ".git", "Git metadata pointer")
1074
+ fd, leaf = open_read_fd_with_path(work_tree, ".git", "Git metadata pointer")
936
1075
  pointer = pins.enter_context(os.fdopen(fd, "rb"))
937
1076
  if leaf != ".git":
938
1077
  raise ValueError("the root marker name does not match .git")
@@ -940,12 +1079,64 @@ def pinned_root_git_marker(cwd: Path, metadata: Path) -> Iterator[Path | None]:
940
1079
  value = pointer.read(len(expected) + 3).removesuffix(b"\n").removesuffix(b"\r")
941
1080
  if value.replace(b"/", b"\\") != expected:
942
1081
  raise ValueError("the root marker does not name the selected Git directory")
943
- marker = Path(".git")
1082
+ # A deep scope can make the relative spelling longer than the gitfile itself.
1083
+ if len(os.fsencode(root_marker)) < len(os.fsencode(reference)):
1084
+ reference = root_marker
1085
+ marker = reference
944
1086
  except (OSError, ValueError):
945
1087
  pins.close()
946
1088
  yield marker
947
1089
 
948
1090
 
1091
+ def pin_replay_metadata(
1092
+ pins: contextlib.ExitStack, metadata: Path | None, scratch: Path
1093
+ ) -> Path | None:
1094
+ """Bind the selected metadata and fresh private Windows scratch before copying into it."""
1095
+ if os.name != "nt" or metadata is None:
1096
+ return None
1097
+ try:
1098
+ with contextlib.ExitStack() as checked:
1099
+ checked.enter_context(_locked_parent(metadata, "HEAD", create=False))
1100
+ checked.enter_context(_locked_parent(scratch.parent, scratch.name, create=False))
1101
+ directory = _create_file(
1102
+ scratch,
1103
+ access=_FILE_TRAVERSE | _FILE_READ_ATTRIBUTES | _READ_CONTROL,
1104
+ share=_FILE_SHARE_READ | _FILE_SHARE_WRITE,
1105
+ disposition=_OPEN_EXISTING,
1106
+ flags=_FILE_FLAG_BACKUP_SEMANTICS | _FILE_FLAG_OPEN_REPARSE_POINT,
1107
+ )
1108
+ assert directory is not None and directory.value is not None
1109
+ checked.enter_context(directory)
1110
+ _verify_directory(directory.value, scratch)
1111
+ if _output_directory_grants(directory.value, scratch):
1112
+ return None
1113
+ pins.enter_context(checked.pop_all())
1114
+ except (OSError, ValueError):
1115
+ return None
1116
+ return metadata
1117
+
1118
+
1119
+ @contextlib.contextmanager
1120
+ def pinned_replay_gitfile(checkout: Path, metadata: Path) -> Iterator[Path]:
1121
+ """Keep Git's short metadata pointer outside the replay and immutable while Git uses it."""
1122
+ with _locked_parent(checkout, ".git", create=False):
1123
+ # Git reads this path relative to its unchanged worktree cwd. Both volumes'
1124
+ # literal ancestors are pinned, including the temporary directory above checkout.
1125
+ marker = checkout.parent / "reviewed.git"
1126
+ handle = _create_file(
1127
+ marker,
1128
+ access=_GENERIC_WRITE | _FILE_READ_ATTRIBUTES,
1129
+ share=_FILE_SHARE_READ,
1130
+ disposition=_CREATE_NEW,
1131
+ flags=_FILE_ATTRIBUTE_NORMAL | _FILE_FLAG_OPEN_REPARSE_POINT,
1132
+ )
1133
+ assert handle is not None and handle.value is not None
1134
+ with handle:
1135
+ _verify_regular_file(handle.value, marker)
1136
+ _write_all(handle.value, f"gitdir: {metadata.as_posix()}\n".encode("utf-8"))
1137
+ yield Path("..") / marker.name
1138
+
1139
+
949
1140
  def open_read_fd(scan_dir: Path, relative_path: str, context: str) -> int:
950
1141
  """Open a verified regular file and return an owned binary read descriptor."""
951
1142
 
@@ -38,9 +38,8 @@ def require_tokenless_scan_owner(
38
38
  "SELECT thread_id FROM workspaces WHERE id = ?", (scan["workspace_id"],)
39
39
  ).fetchone()[0]
40
40
  if owner is None:
41
- # Only a completed import is intentionally ownerless among registered scans.
42
41
  completed_import = scan["launch_kind"] == "import" and scan["status"] == "complete"
43
- if scan["recipe_json"] is not None and not completed_import:
42
+ if not completed_import:
44
43
  raise SystemExit("This scan is awaiting its owning Codex thread.")
45
44
  elif owner != model_thread_id:
46
45
  raise SystemExit("This scan requires its owning Codex thread.")
@@ -231,30 +230,61 @@ def mark_handoff_delivered(
231
230
  raise SystemExit(
232
231
  "Codex Security handoff delivery is owned by another continuation."
233
232
  )
234
- connection.commit()
235
- return wb.workspace_state(connection, scan["workspace_id"])
236
- updated = connection.execute(
237
- """
238
- UPDATE scans
239
- SET handoff_status = 'delivered', handoff_claimed_at = NULL,
240
- updated_at = ?
241
- WHERE id = ? AND handoff_status = 'pending'
242
- AND handoff_claim_token = ?
243
- """,
244
- (timestamp, scan["id"], claim_token),
245
- )
246
- if updated.rowcount != 1:
247
- raise SystemExit("Codex Security handoff delivery could not be recorded.")
248
- if scan["mode"] != "deep":
249
- connection.execute(
233
+ else:
234
+ updated = connection.execute(
250
235
  """
251
- UPDATE scan_progress
252
- SET phase_items_total = 0, phase_items_completed = 0,
253
- phase_progress_unit = 'checks',
254
- preflight_checks_total = 0, preflight_checks_completed = 0,
236
+ UPDATE scans
237
+ SET handoff_status = 'delivered', handoff_claimed_at = NULL,
255
238
  updated_at = ?
256
- WHERE scan_id = ?
239
+ WHERE id = ? AND handoff_status = 'pending'
240
+ AND handoff_claim_token = ?
257
241
  """,
258
- (timestamp, scan["id"]),
242
+ (timestamp, scan["id"], claim_token),
259
243
  )
260
- return wb.workspace_state(connection, scan["workspace_id"])
244
+ if updated.rowcount != 1:
245
+ raise SystemExit("Codex Security handoff delivery could not be recorded.")
246
+ if scan["mode"] != "deep":
247
+ connection.execute(
248
+ """
249
+ UPDATE scan_progress
250
+ SET phase_items_total = 0, phase_items_completed = 0,
251
+ phase_progress_unit = 'checks',
252
+ preflight_checks_total = 0, preflight_checks_completed = 0,
253
+ updated_at = ?
254
+ WHERE scan_id = ?
255
+ """,
256
+ (timestamp, scan["id"]),
257
+ )
258
+ began_review = (
259
+ args.return_context
260
+ and thread_id is not None
261
+ and args.occurrence_id is None
262
+ and scan["mode"] == "standard"
263
+ and scan["status"] == "running"
264
+ and scan["canceled_at"] is None
265
+ and scan["phase"] == "preflight"
266
+ )
267
+ if began_review:
268
+ connection.execute(
269
+ "UPDATE scans SET phase = 'threat_model', updated_at = ? WHERE id = ?",
270
+ (timestamp, scan_id),
271
+ )
272
+ connection.execute(
273
+ """UPDATE scan_progress SET phase_items_total = 0, phase_items_completed = 0,
274
+ phase_progress_unit = NULL, updated_at = ? WHERE scan_id = ?""",
275
+ (timestamp, scan_id),
276
+ )
277
+ if not args.return_context:
278
+ return wb.workspace_state(connection, scan["workspace_id"])
279
+ context = wb.get_scan(
280
+ connection,
281
+ argparse.Namespace(
282
+ scan_id=scan_id,
283
+ occurrence_id=args.occurrence_id,
284
+ model_thread_id=thread_id or "",
285
+ context_claim_token=claim_token,
286
+ ),
287
+ )
288
+ if began_review:
289
+ context["beganStandardReview"] = True
290
+ return context
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import hashlib
5
6
  import os
6
7
  import sqlite3
7
8
  import tempfile
@@ -35,18 +36,37 @@ def worker_usage_directory(scan_id: str) -> Path:
35
36
  return state_dir() / "codex-home" / "worker-usage" / scan_id
36
37
 
37
38
 
39
+ def short_archive_prefix(original_name: str) -> str:
40
+ """Bind a short archive name to the complete original filename."""
41
+ return f".previous-{hashlib.sha256(os.fsencode(original_name)).hexdigest()}-"
42
+
43
+
44
+ def archive_source_directory(archive: Path, source: Path) -> Path | None:
45
+ """Return the original sibling when the archived name identifies it."""
46
+ if not source.is_relative_to(archive.parent):
47
+ return None
48
+ parts = source.relative_to(archive.parent).parts
49
+ if not parts or ".." in parts:
50
+ return None
51
+ name = parts[0]
52
+ if archive.name.startswith(f"{name}.previous-") or (
53
+ archive.name.startswith(".previous-")
54
+ and archive.name.startswith(short_archive_prefix(name))
55
+ ):
56
+ return archive.parent / name
57
+ return None
58
+
59
+
38
60
  def archived_deep_path(scan_dir: Path, value: str | None) -> str | None:
39
61
  """Resolve old archive rows that still name the original sibling output."""
40
62
  if value is None or ".previous-" not in scan_dir.name:
41
63
  return value
42
64
  path = Path(value)
43
- if not path.is_relative_to(scan_dir.parent):
44
- return value
45
- parts = path.relative_to(scan_dir.parent).parts
46
- if not parts or ".." in parts or not scan_dir.name.startswith(f"{parts[0]}.previous-"):
65
+ original = archive_source_directory(scan_dir, path)
66
+ if original is None:
47
67
  return value
48
68
  # Keep missing files inside the archive too. Never follow the replacement scan's output.
49
- return str(scan_dir.joinpath(*parts[1:]))
69
+ return str(scan_dir / path.relative_to(original))
50
70
 
51
71
 
52
72
  def saved_deep_workers(connection: sqlite3.Connection, scan: sqlite3.Row) -> list[Any]: