@openai/codex-security 0.8.3 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (658) hide show
  1. package/README.md +36 -746
  2. package/_bundled_plugin/.codex-plugin/plugin.json +2 -0
  3. package/_bundled_plugin/.mcp.json +7 -1
  4. package/_bundled_plugin/examples/completed-scan/findings.json +16 -4
  5. package/_bundled_plugin/examples/completed-scan/report.md +11 -8
  6. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +4 -2
  7. package/_bundled_plugin/mcp/fzstd-LICENSE.txt +21 -0
  8. package/_bundled_plugin/mcp/helpers.mjs +2 -11
  9. package/_bundled_plugin/mcp/helpers.mjs.br +0 -0
  10. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +3 -210
  11. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  12. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  13. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  14. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  15. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  16. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  17. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  18. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  19. package/_bundled_plugin/mcp/package.json +1 -0
  20. package/_bundled_plugin/mcp/permission-profile-preflight.mjs +5 -2
  21. package/_bundled_plugin/mcp/server.mjs +2 -11
  22. package/_bundled_plugin/mcp/server.mjs.br +0 -0
  23. package/_bundled_plugin/mcp/session-decompression.mjs +712 -0
  24. package/_bundled_plugin/references/artifact-storage.md +1 -1
  25. package/_bundled_plugin/references/baseline-auditor.md +18 -0
  26. package/_bundled_plugin/references/core-scan.md +5 -42
  27. package/_bundled_plugin/references/default-severity-rubric.md +9 -4
  28. package/_bundled_plugin/references/final-report.md +5 -3
  29. package/_bundled_plugin/references/finding-detail-fields.md +18 -18
  30. package/_bundled_plugin/references/focused-investigator.md +13 -0
  31. package/_bundled_plugin/references/sarif-adapter.md +8 -2
  32. package/_bundled_plugin/references/scan-artifacts.md +21 -12
  33. package/_bundled_plugin/references/scan-contract.md +27 -33
  34. package/_bundled_plugin/references/scan-prologue.md +2 -2
  35. package/_bundled_plugin/references/scan-runtime.md +4 -2
  36. package/_bundled_plugin/references/security-guidance.md +14 -1
  37. package/_bundled_plugin/references/validate-scan-findings.md +3 -0
  38. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +2 -2
  39. package/_bundled_plugin/scripts/check_deep_scan_target.py +97 -0
  40. package/_bundled_plugin/scripts/codex_profile.mjs +7 -1
  41. package/_bundled_plugin/scripts/deep_scan_config.py +20 -1
  42. package/_bundled_plugin/scripts/deep_scan_workbench.py +192 -352
  43. package/_bundled_plugin/scripts/dispatch_inventory_tool +7 -0
  44. package/_bundled_plugin/scripts/filesystem_identity.py +1 -0
  45. package/_bundled_plugin/scripts/finalize_scan_contract.py +182 -230
  46. package/_bundled_plugin/scripts/finding_preview.py +20 -0
  47. package/_bundled_plugin/scripts/launch_codex_security_mcp +55 -16
  48. package/_bundled_plugin/scripts/legacy_findings.py +148 -0
  49. package/_bundled_plugin/scripts/posix_scan_local_files.py +37 -1
  50. package/_bundled_plugin/scripts/read_codex_session.mjs +21 -0
  51. package/_bundled_plugin/scripts/report_projection.py +81 -43
  52. package/_bundled_plugin/scripts/review_state.py +8 -2
  53. package/_bundled_plugin/scripts/servicenow_avit.py +20 -0
  54. package/_bundled_plugin/scripts/snapshot_sqlite.py +9 -2
  55. package/_bundled_plugin/scripts/threat_model_projection.py +22 -26
  56. package/_bundled_plugin/scripts/validate_scan_contract.py +7 -1
  57. package/_bundled_plugin/scripts/windows_scan_local_files.py +582 -20
  58. package/_bundled_plugin/scripts/workbench/__init__.py +1 -1
  59. package/_bundled_plugin/scripts/workbench/handoff.py +100 -23
  60. package/_bundled_plugin/scripts/workbench/retained_coverage.py +30 -51
  61. package/_bundled_plugin/scripts/workbench/retained_records.py +18 -30
  62. package/_bundled_plugin/scripts/workbench/runtime_toml.py +4 -1
  63. package/_bundled_plugin/scripts/workbench/saved_coverage.py +9 -17
  64. package/_bundled_plugin/scripts/workbench/saved_outputs.py +9 -0
  65. package/_bundled_plugin/scripts/workbench/saved_sources.py +47 -40
  66. package/_bundled_plugin/scripts/workbench/storage.py +91 -7
  67. package/_bundled_plugin/scripts/workbench_cli.py +54 -14
  68. package/_bundled_plugin/scripts/workbench_constants.py +12 -0
  69. package/_bundled_plugin/scripts/workbench_coverage_receipts.py +3 -3
  70. package/_bundled_plugin/scripts/workbench_db.py +562 -303
  71. package/_bundled_plugin/scripts/workbench_feedback.py +57 -11
  72. package/_bundled_plugin/scripts/workbench_finding_index.py +1 -0
  73. package/_bundled_plugin/scripts/workbench_finding_workflows.py +4 -0
  74. package/_bundled_plugin/scripts/workbench_native_indexes.py +238 -41
  75. package/_bundled_plugin/scripts/workbench_progress.py +169 -4
  76. package/_bundled_plugin/scripts/workbench_publication.py +16 -13
  77. package/_bundled_plugin/scripts/workbench_remediation.py +155 -2
  78. package/_bundled_plugin/scripts/workbench_saved_results.py +176 -81
  79. package/_bundled_plugin/scripts/workbench_scan_history.py +398 -174
  80. package/_bundled_plugin/scripts/workbench_scan_start.py +224 -31
  81. package/_bundled_plugin/scripts/workbench_scan_usage.py +675 -73
  82. package/_bundled_plugin/scripts/workbench_schema.py +258 -63
  83. package/_bundled_plugin/scripts/workbench_setup.py +14 -2
  84. package/_bundled_plugin/scripts/workbench_source_excerpt.py +13 -0
  85. package/_bundled_plugin/scripts/workbench_source_scopes.py +18 -0
  86. package/_bundled_plugin/scripts/workbench_target.py +594 -136
  87. package/_bundled_plugin/scripts/workbench_target_state.py +1110 -21
  88. package/_bundled_plugin/scripts/workbench_validation.py +43 -3
  89. package/_bundled_plugin/shared/workbench-history-repairs.json +77 -35
  90. package/_bundled_plugin/shared/workbench-migrations.json +100 -0
  91. package/_bundled_plugin/skills/cloud-findings/SKILL.md +5 -5
  92. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +7 -50
  93. package/_bundled_plugin/skills/fix-finding/SKILL.md +2 -1
  94. package/_bundled_plugin/skills/publish-findings/SKILL.md +24 -153
  95. package/_bundled_plugin/skills/publish-findings/agents/openai.yaml +2 -2
  96. package/_bundled_plugin/skills/publish-findings/references/checkmarx-import.md +37 -0
  97. package/_bundled_plugin/skills/publish-findings/references/wiz-import.md +3 -3
  98. package/_bundled_plugin/skills/publish-findings/scripts/collect_checkmarx.py +409 -0
  99. package/_bundled_plugin/skills/publish-findings/scripts/collect_continuum.py +224 -0
  100. package/_bundled_plugin/skills/publish-findings/scripts/collector_paths.py +63 -0
  101. package/_bundled_plugin/skills/security-scan/SKILL.md +9 -46
  102. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +2 -2
  103. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +3 -21
  104. package/_bundled_plugin/skills/security-scan/references/managed-scan.md +11 -0
  105. package/_bundled_plugin/skills/security-scan/references/scan-results.md +15 -0
  106. package/_bundled_plugin/skills/security-scan/references/scoped-paths.md +23 -0
  107. package/_bundled_plugin/skills/security-scan/references/sdk-files.md +24 -0
  108. package/_bundled_plugin/skills/threat-model-visualize/scripts/build_explorer.py +22 -1
  109. package/_bundled_plugin/skills/triage-finding/references/ticket-intake.md +6 -2
  110. package/bin/codex-security.mjs +2 -2
  111. package/dist/api.d.ts +45 -5
  112. package/dist/api.d.ts.map +1 -1
  113. package/dist/api.js +1192 -427
  114. package/dist/api.js.map +1 -1
  115. package/dist/armorcode-findings.d.ts +9 -0
  116. package/dist/armorcode-findings.d.ts.map +1 -0
  117. package/dist/armorcode-findings.js +145 -0
  118. package/dist/armorcode-findings.js.map +1 -0
  119. package/dist/artifact-export.d.ts +2 -0
  120. package/dist/artifact-export.d.ts.map +1 -1
  121. package/dist/artifact-export.js +29 -13
  122. package/dist/artifact-export.js.map +1 -1
  123. package/dist/auth.d.ts +6 -2
  124. package/dist/auth.d.ts.map +1 -1
  125. package/dist/auth.js +37 -18
  126. package/dist/auth.js.map +1 -1
  127. package/dist/batch-cost.d.ts +18 -0
  128. package/dist/batch-cost.d.ts.map +1 -0
  129. package/dist/batch-cost.js +41 -0
  130. package/dist/batch-cost.js.map +1 -0
  131. package/dist/bedrock-oss-pricing.d.ts +6 -0
  132. package/dist/bedrock-oss-pricing.d.ts.map +1 -0
  133. package/dist/bedrock-oss-pricing.js +58 -0
  134. package/dist/bedrock-oss-pricing.js.map +1 -0
  135. package/dist/bedrock-pricing.d.ts +15 -0
  136. package/dist/bedrock-pricing.d.ts.map +1 -0
  137. package/dist/bedrock-pricing.js +117 -0
  138. package/dist/bedrock-pricing.js.map +1 -0
  139. package/dist/blackduck-findings.d.ts +1 -1
  140. package/dist/blackduck-findings.d.ts.map +1 -1
  141. package/dist/blackduck-findings.js +24 -22
  142. package/dist/blackduck-findings.js.map +1 -1
  143. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  144. package/dist/bulk-scan-discovery.js +4 -4
  145. package/dist/bulk-scan-discovery.js.map +1 -1
  146. package/dist/bundled-plugin.d.ts +4 -0
  147. package/dist/bundled-plugin.d.ts.map +1 -0
  148. package/dist/bundled-plugin.js +23 -0
  149. package/dist/bundled-plugin.js.map +1 -0
  150. package/dist/checkmarx-evidence.d.ts +19 -0
  151. package/dist/checkmarx-evidence.d.ts.map +1 -0
  152. package/dist/checkmarx-evidence.js +36 -0
  153. package/dist/checkmarx-evidence.js.map +1 -0
  154. package/dist/checkmarx-findings.d.ts +4 -0
  155. package/dist/checkmarx-findings.d.ts.map +1 -0
  156. package/dist/checkmarx-findings.js +27 -0
  157. package/dist/checkmarx-findings.js.map +1 -0
  158. package/dist/checkmarx-one.d.ts +4 -0
  159. package/dist/checkmarx-one.d.ts.map +1 -0
  160. package/dist/checkmarx-one.js +53 -0
  161. package/dist/checkmarx-one.js.map +1 -0
  162. package/dist/checkmarx-repository.d.ts +12 -0
  163. package/dist/checkmarx-repository.d.ts.map +1 -0
  164. package/dist/checkmarx-repository.js +181 -0
  165. package/dist/checkmarx-repository.js.map +1 -0
  166. package/dist/checkmarx-xml.d.ts +12 -0
  167. package/dist/checkmarx-xml.d.ts.map +1 -0
  168. package/dist/checkmarx-xml.js +196 -0
  169. package/dist/checkmarx-xml.js.map +1 -0
  170. package/dist/classify-scan-severity.d.ts +1 -1
  171. package/dist/classify-scan-severity.d.ts.map +1 -1
  172. package/dist/classify-scan-severity.js +11 -3
  173. package/dist/classify-scan-severity.js.map +1 -1
  174. package/dist/classify-severity-records.d.ts +1 -9
  175. package/dist/classify-severity-records.d.ts.map +1 -1
  176. package/dist/classify-severity-records.js +3 -13
  177. package/dist/classify-severity-records.js.map +1 -1
  178. package/dist/classify-severity.d.ts.map +1 -1
  179. package/dist/classify-severity.js +11 -10
  180. package/dist/classify-severity.js.map +1 -1
  181. package/dist/cli-argument.d.ts +4 -0
  182. package/dist/cli-argument.d.ts.map +1 -0
  183. package/dist/cli-argument.js +17 -0
  184. package/dist/cli-argument.js.map +1 -0
  185. package/dist/cli-help.d.ts +1 -1
  186. package/dist/cli-help.d.ts.map +1 -1
  187. package/dist/cli-help.js +71 -29
  188. package/dist/cli-help.js.map +1 -1
  189. package/dist/cli-hook.d.ts +3 -0
  190. package/dist/cli-hook.d.ts.map +1 -0
  191. package/dist/cli-hook.js +87 -0
  192. package/dist/cli-hook.js.map +1 -0
  193. package/dist/cli-integrations.d.ts +13 -0
  194. package/dist/cli-integrations.d.ts.map +1 -0
  195. package/dist/cli-integrations.js +333 -0
  196. package/dist/cli-integrations.js.map +1 -0
  197. package/dist/cli-mcp.d.ts +15 -0
  198. package/dist/cli-mcp.d.ts.map +1 -0
  199. package/dist/cli-mcp.js +178 -0
  200. package/dist/cli-mcp.js.map +1 -0
  201. package/dist/cli-token-view.d.ts +10 -0
  202. package/dist/cli-token-view.d.ts.map +1 -0
  203. package/dist/cli-token-view.js +41 -0
  204. package/dist/cli-token-view.js.map +1 -0
  205. package/dist/cli.d.ts +16 -8
  206. package/dist/cli.d.ts.map +1 -1
  207. package/dist/cli.js +3382 -2017
  208. package/dist/cli.js.map +1 -1
  209. package/dist/cloud-publish.d.ts.map +1 -1
  210. package/dist/cloud-publish.js +35 -33
  211. package/dist/cloud-publish.js.map +1 -1
  212. package/dist/codex-sdk-environment.d.ts +6 -0
  213. package/dist/codex-sdk-environment.d.ts.map +1 -1
  214. package/dist/codex-sdk-environment.js +19 -0
  215. package/dist/codex-sdk-environment.js.map +1 -1
  216. package/dist/command-words.d.ts +3 -0
  217. package/dist/command-words.d.ts.map +1 -0
  218. package/dist/command-words.js +46 -0
  219. package/dist/command-words.js.map +1 -0
  220. package/dist/component-scan.d.ts +19 -4
  221. package/dist/component-scan.d.ts.map +1 -1
  222. package/dist/component-scan.js +67 -9
  223. package/dist/component-scan.js.map +1 -1
  224. package/dist/config.d.ts +1 -1
  225. package/dist/config.d.ts.map +1 -1
  226. package/dist/config.js +130 -67
  227. package/dist/config.js.map +1 -1
  228. package/dist/continuum-findings.d.ts +1 -1
  229. package/dist/continuum-findings.d.ts.map +1 -1
  230. package/dist/continuum-findings.js +149 -19
  231. package/dist/continuum-findings.js.map +1 -1
  232. package/dist/contract-values.d.ts +2 -0
  233. package/dist/contract-values.d.ts.map +1 -1
  234. package/dist/contract-values.js +12 -9
  235. package/dist/contract-values.js.map +1 -1
  236. package/dist/cost-model.d.ts +13 -1
  237. package/dist/cost-model.d.ts.map +1 -1
  238. package/dist/cost-model.js +66 -112
  239. package/dist/cost-model.js.map +1 -1
  240. package/dist/cost.d.ts +42 -3
  241. package/dist/cost.d.ts.map +1 -1
  242. package/dist/cost.js +484 -149
  243. package/dist/cost.js.map +1 -1
  244. package/dist/custom-publish.d.ts +4 -0
  245. package/dist/custom-publish.d.ts.map +1 -1
  246. package/dist/custom-publish.js +40 -3
  247. package/dist/custom-publish.js.map +1 -1
  248. package/dist/custom-validation-prompt.d.ts +1 -1
  249. package/dist/custom-validation-prompt.d.ts.map +1 -1
  250. package/dist/custom-validation-prompt.js +29 -19
  251. package/dist/custom-validation-prompt.js.map +1 -1
  252. package/dist/deduplication/local.d.ts +4 -2
  253. package/dist/deduplication/local.d.ts.map +1 -1
  254. package/dist/deduplication/local.js +9 -2
  255. package/dist/deduplication/local.js.map +1 -1
  256. package/dist/deduplication/refusal.d.ts.map +1 -1
  257. package/dist/deduplication/refusal.js +26 -5
  258. package/dist/deduplication/refusal.js.map +1 -1
  259. package/dist/deduplication/scan.d.ts +5 -0
  260. package/dist/deduplication/scan.d.ts.map +1 -1
  261. package/dist/deduplication/scan.js +24 -7
  262. package/dist/deduplication/scan.js.map +1 -1
  263. package/dist/deep-config.d.ts +0 -1
  264. package/dist/deep-config.d.ts.map +1 -1
  265. package/dist/deep-config.js +22 -33
  266. package/dist/deep-config.js.map +1 -1
  267. package/dist/deep-scan-defaults.d.ts +2 -0
  268. package/dist/deep-scan-defaults.d.ts.map +1 -1
  269. package/dist/deep-scan-defaults.js +28 -1
  270. package/dist/deep-scan-defaults.js.map +1 -1
  271. package/dist/deep-scan.d.ts +2 -0
  272. package/dist/deep-scan.d.ts.map +1 -1
  273. package/dist/deep-scan.js +44 -19
  274. package/dist/deep-scan.js.map +1 -1
  275. package/dist/default-severity-rubric.d.ts +1 -1
  276. package/dist/default-severity-rubric.d.ts.map +1 -1
  277. package/dist/default-severity-rubric.js +1 -1
  278. package/dist/default-severity-rubric.js.map +1 -1
  279. package/dist/endor-findings.d.ts +3 -1
  280. package/dist/endor-findings.d.ts.map +1 -1
  281. package/dist/endor-findings.js +86 -45
  282. package/dist/endor-findings.js.map +1 -1
  283. package/dist/errors.d.ts +4 -2
  284. package/dist/errors.d.ts.map +1 -1
  285. package/dist/errors.js +15 -4
  286. package/dist/errors.js.map +1 -1
  287. package/dist/executable-path.d.ts +3 -0
  288. package/dist/executable-path.d.ts.map +1 -1
  289. package/dist/executable-path.js +26 -0
  290. package/dist/executable-path.js.map +1 -1
  291. package/dist/external-findings-import.d.ts +5 -3
  292. package/dist/external-findings-import.d.ts.map +1 -1
  293. package/dist/external-findings-import.js +19 -7
  294. package/dist/external-findings-import.js.map +1 -1
  295. package/dist/external-findings-local.d.ts +69 -5
  296. package/dist/external-findings-local.d.ts.map +1 -1
  297. package/dist/external-findings-local.js +537 -108
  298. package/dist/external-findings-local.js.map +1 -1
  299. package/dist/external-findings-publish.d.ts +13 -6
  300. package/dist/external-findings-publish.d.ts.map +1 -1
  301. package/dist/external-findings-publish.js +895 -1142
  302. package/dist/external-findings-publish.js.map +1 -1
  303. package/dist/external-findings-read.d.ts +21 -2
  304. package/dist/external-findings-read.d.ts.map +1 -1
  305. package/dist/external-findings-read.js +130 -68
  306. package/dist/external-findings-read.js.map +1 -1
  307. package/dist/external-findings.d.ts +15 -3
  308. package/dist/external-findings.d.ts.map +1 -1
  309. package/dist/external-findings.js +54 -2
  310. package/dist/external-findings.js.map +1 -1
  311. package/dist/external-import-contract.d.ts +8 -12
  312. package/dist/external-import-contract.d.ts.map +1 -1
  313. package/dist/external-import-contract.js +51 -184
  314. package/dist/external-import-contract.js.map +1 -1
  315. package/dist/external-import-models.d.ts +1 -1
  316. package/dist/external-import-models.d.ts.map +1 -1
  317. package/dist/external-import-models.js.map +1 -1
  318. package/dist/feedback.d.ts.map +1 -1
  319. package/dist/feedback.js +5 -4
  320. package/dist/feedback.js.map +1 -1
  321. package/dist/finding-prompt.d.ts +5 -0
  322. package/dist/finding-prompt.d.ts.map +1 -0
  323. package/dist/finding-prompt.js +32 -0
  324. package/dist/finding-prompt.js.map +1 -0
  325. package/dist/findings-client.d.ts +1 -0
  326. package/dist/findings-client.d.ts.map +1 -1
  327. package/dist/findings-client.js +27 -3
  328. package/dist/findings-client.js.map +1 -1
  329. package/dist/github-advisories.d.ts.map +1 -1
  330. package/dist/github-advisories.js +0 -2
  331. package/dist/github-advisories.js.map +1 -1
  332. package/dist/github-dependabot-findings.d.ts.map +1 -1
  333. package/dist/github-dependabot-findings.js +18 -8
  334. package/dist/github-dependabot-findings.js.map +1 -1
  335. package/dist/github-findings.d.ts +4 -1
  336. package/dist/github-findings.d.ts.map +1 -1
  337. package/dist/github-findings.js +73 -316
  338. package/dist/github-findings.js.map +1 -1
  339. package/dist/hosted-git-remotes.d.ts +5 -0
  340. package/dist/hosted-git-remotes.d.ts.map +1 -0
  341. package/dist/hosted-git-remotes.js +285 -0
  342. package/dist/hosted-git-remotes.js.map +1 -0
  343. package/dist/hosted-git-repository.d.ts +28 -0
  344. package/dist/hosted-git-repository.d.ts.map +1 -0
  345. package/dist/hosted-git-repository.js +222 -0
  346. package/dist/hosted-git-repository.js.map +1 -0
  347. package/dist/hosted-remediation.d.ts +1 -0
  348. package/dist/hosted-remediation.d.ts.map +1 -1
  349. package/dist/hosted-remediation.js +23 -3
  350. package/dist/hosted-remediation.js.map +1 -1
  351. package/dist/hosted-scan-protocol.js +2 -2
  352. package/dist/hosted-scan-protocol.js.map +1 -1
  353. package/dist/hosted-scan.d.ts.map +1 -1
  354. package/dist/hosted-scan.js +16 -11
  355. package/dist/hosted-scan.js.map +1 -1
  356. package/dist/hosted-scanner-http.d.ts +21 -0
  357. package/dist/hosted-scanner-http.d.ts.map +1 -0
  358. package/dist/hosted-scanner-http.js +204 -0
  359. package/dist/hosted-scanner-http.js.map +1 -0
  360. package/dist/import-scan.d.ts.map +1 -1
  361. package/dist/import-scan.js +3 -0
  362. package/dist/import-scan.js.map +1 -1
  363. package/dist/index.d.ts +21 -9
  364. package/dist/index.d.ts.map +1 -1
  365. package/dist/index.js +12 -3
  366. package/dist/index.js.map +1 -1
  367. package/dist/inspector-findings.d.ts.map +1 -1
  368. package/dist/inspector-findings.js +52 -86
  369. package/dist/inspector-findings.js.map +1 -1
  370. package/dist/knowledge-base.d.ts +1 -1
  371. package/dist/knowledge-base.d.ts.map +1 -1
  372. package/dist/knowledge-base.js +102 -32
  373. package/dist/knowledge-base.js.map +1 -1
  374. package/dist/linear.d.ts +11 -0
  375. package/dist/linear.d.ts.map +1 -1
  376. package/dist/linear.js.map +1 -1
  377. package/dist/local-git-metadata.d.ts +5 -2
  378. package/dist/local-git-metadata.d.ts.map +1 -1
  379. package/dist/local-git-metadata.js +8 -5
  380. package/dist/local-git-metadata.js.map +1 -1
  381. package/dist/multiscan.d.ts +10 -4
  382. package/dist/multiscan.d.ts.map +1 -1
  383. package/dist/multiscan.js +217 -102
  384. package/dist/multiscan.js.map +1 -1
  385. package/dist/native-json-findings.d.ts +2 -1
  386. package/dist/native-json-findings.d.ts.map +1 -1
  387. package/dist/native-json-findings.js +12 -2
  388. package/dist/native-json-findings.js.map +1 -1
  389. package/dist/opengrep-findings.d.ts +5 -2
  390. package/dist/opengrep-findings.d.ts.map +1 -1
  391. package/dist/opengrep-findings.js +54 -33
  392. package/dist/opengrep-findings.js.map +1 -1
  393. package/dist/operation-telemetry.d.ts +104 -0
  394. package/dist/operation-telemetry.d.ts.map +1 -0
  395. package/dist/operation-telemetry.js +293 -0
  396. package/dist/operation-telemetry.js.map +1 -0
  397. package/dist/plugin-python-probe.d.ts +4 -0
  398. package/dist/plugin-python-probe.d.ts.map +1 -0
  399. package/dist/plugin-python-probe.js +10 -0
  400. package/dist/plugin-python-probe.js.map +1 -0
  401. package/dist/private-finding-import.d.ts +99 -9
  402. package/dist/private-finding-import.d.ts.map +1 -1
  403. package/dist/private-finding-import.js +116 -152
  404. package/dist/private-finding-import.js.map +1 -1
  405. package/dist/project-config.d.ts.map +1 -1
  406. package/dist/project-config.js +53 -13
  407. package/dist/project-config.js.map +1 -1
  408. package/dist/prompt-files.d.ts +7 -2
  409. package/dist/prompt-files.d.ts.map +1 -1
  410. package/dist/prompt-files.js +42 -20
  411. package/dist/prompt-files.js.map +1 -1
  412. package/dist/provider-profile.d.ts +1 -1
  413. package/dist/provider-profile.d.ts.map +1 -1
  414. package/dist/provider-profile.js +12 -10
  415. package/dist/provider-profile.js.map +1 -1
  416. package/dist/publication-telemetry.d.ts +45 -0
  417. package/dist/publication-telemetry.d.ts.map +1 -0
  418. package/dist/publication-telemetry.js +50 -0
  419. package/dist/publication-telemetry.js.map +1 -0
  420. package/dist/publication.d.ts +1 -1
  421. package/dist/publication.d.ts.map +1 -1
  422. package/dist/publication.js.map +1 -1
  423. package/dist/publish.d.ts +4 -0
  424. package/dist/publish.d.ts.map +1 -1
  425. package/dist/publish.js +42 -2
  426. package/dist/publish.js.map +1 -1
  427. package/dist/record.d.ts +1 -5
  428. package/dist/record.d.ts.map +1 -1
  429. package/dist/record.js +3 -51
  430. package/dist/record.js.map +1 -1
  431. package/dist/remediation.d.ts +1 -4
  432. package/dist/remediation.d.ts.map +1 -1
  433. package/dist/remediation.js +6 -8
  434. package/dist/remediation.js.map +1 -1
  435. package/dist/request-metadata.d.ts +3 -0
  436. package/dist/request-metadata.d.ts.map +1 -1
  437. package/dist/request-metadata.js +9 -0
  438. package/dist/request-metadata.js.map +1 -1
  439. package/dist/result.d.ts +4 -0
  440. package/dist/result.d.ts.map +1 -1
  441. package/dist/result.js +1 -1
  442. package/dist/result.js.map +1 -1
  443. package/dist/retry-windows-rename.d.ts +8 -0
  444. package/dist/retry-windows-rename.d.ts.map +1 -0
  445. package/dist/retry-windows-rename.js +24 -0
  446. package/dist/retry-windows-rename.js.map +1 -0
  447. package/dist/runtime.d.ts +54 -6
  448. package/dist/runtime.d.ts.map +1 -1
  449. package/dist/runtime.js +1084 -256
  450. package/dist/runtime.js.map +1 -1
  451. package/dist/saved-scan-bootstrap.d.ts +7 -1
  452. package/dist/saved-scan-bootstrap.d.ts.map +1 -1
  453. package/dist/saved-scan-bootstrap.js +269 -114
  454. package/dist/saved-scan-bootstrap.js.map +1 -1
  455. package/dist/scan-activity.d.ts.map +1 -1
  456. package/dist/scan-activity.js +141 -56
  457. package/dist/scan-activity.js.map +1 -1
  458. package/dist/scan-archive-path.d.ts +2 -0
  459. package/dist/scan-archive-path.d.ts.map +1 -0
  460. package/dist/scan-archive-path.js +5 -0
  461. package/dist/scan-archive-path.js.map +1 -0
  462. package/dist/scan-comparison.d.ts +10 -5
  463. package/dist/scan-comparison.d.ts.map +1 -1
  464. package/dist/scan-comparison.js +66 -17
  465. package/dist/scan-comparison.js.map +1 -1
  466. package/dist/scan-dashboard.d.ts +7 -6
  467. package/dist/scan-dashboard.d.ts.map +1 -1
  468. package/dist/scan-dashboard.js +92 -43
  469. package/dist/scan-dashboard.js.map +1 -1
  470. package/dist/scan-executor.d.ts +10 -1
  471. package/dist/scan-executor.d.ts.map +1 -1
  472. package/dist/scan-executor.js +24 -2
  473. package/dist/scan-executor.js.map +1 -1
  474. package/dist/scan-history-renderer.d.ts +1 -0
  475. package/dist/scan-history-renderer.d.ts.map +1 -1
  476. package/dist/scan-history-renderer.js +34 -28
  477. package/dist/scan-history-renderer.js.map +1 -1
  478. package/dist/scan-logs.d.ts +12 -0
  479. package/dist/scan-logs.d.ts.map +1 -1
  480. package/dist/scan-logs.js +131 -78
  481. package/dist/scan-logs.js.map +1 -1
  482. package/dist/scan-measurement.d.ts +26 -0
  483. package/dist/scan-measurement.d.ts.map +1 -0
  484. package/dist/scan-measurement.js +77 -0
  485. package/dist/scan-measurement.js.map +1 -0
  486. package/dist/scan-progress.d.ts +1 -0
  487. package/dist/scan-progress.d.ts.map +1 -1
  488. package/dist/scan-progress.js +3 -0
  489. package/dist/scan-progress.js.map +1 -1
  490. package/dist/scan-sessions.d.ts.map +1 -1
  491. package/dist/scan-sessions.js +4 -1
  492. package/dist/scan-sessions.js.map +1 -1
  493. package/dist/scan-settings.d.ts +1 -1
  494. package/dist/scan-settings.d.ts.map +1 -1
  495. package/dist/scan-settings.js +1 -24
  496. package/dist/scan-settings.js.map +1 -1
  497. package/dist/scanner-import.d.ts +25 -13
  498. package/dist/scanner-import.d.ts.map +1 -1
  499. package/dist/scanner-import.js +216 -97
  500. package/dist/scanner-import.js.map +1 -1
  501. package/dist/scanner-repository-url.d.ts +4 -1
  502. package/dist/scanner-repository-url.d.ts.map +1 -1
  503. package/dist/scanner-repository-url.js +10 -6
  504. package/dist/scanner-repository-url.js.map +1 -1
  505. package/dist/security-policy.d.ts +1 -1
  506. package/dist/security-policy.d.ts.map +1 -1
  507. package/dist/security-policy.js +26 -6
  508. package/dist/security-policy.js.map +1 -1
  509. package/dist/semgrep-findings.d.ts +6 -3
  510. package/dist/semgrep-findings.d.ts.map +1 -1
  511. package/dist/semgrep-findings.js +72 -42
  512. package/dist/semgrep-findings.js.map +1 -1
  513. package/dist/semgrep-guardian-findings.d.ts +38 -0
  514. package/dist/semgrep-guardian-findings.d.ts.map +1 -0
  515. package/dist/semgrep-guardian-findings.js +165 -0
  516. package/dist/semgrep-guardian-findings.js.map +1 -0
  517. package/dist/semgrep-platform-collector.d.ts +26 -0
  518. package/dist/semgrep-platform-collector.d.ts.map +1 -0
  519. package/dist/semgrep-platform-collector.js +108 -0
  520. package/dist/semgrep-platform-collector.js.map +1 -0
  521. package/dist/semgrep-platform-findings.d.ts +157 -6
  522. package/dist/semgrep-platform-findings.d.ts.map +1 -1
  523. package/dist/semgrep-platform-findings.js +766 -103
  524. package/dist/semgrep-platform-findings.js.map +1 -1
  525. package/dist/server/api.d.ts +1 -1
  526. package/dist/server/api.d.ts.map +1 -1
  527. package/dist/server/api.js.map +1 -1
  528. package/dist/server/embedding-tokenizer.cdx.json +33 -0
  529. package/dist/server/embedding-tokenizer.d.ts +2 -0
  530. package/dist/server/embedding-tokenizer.d.ts.map +1 -0
  531. package/dist/server/embedding-tokenizer.js +322 -0
  532. package/dist/server/embedding-tokenizer.js.map +6 -0
  533. package/dist/server/embeddings.d.ts +16 -2
  534. package/dist/server/embeddings.d.ts.map +1 -1
  535. package/dist/server/embeddings.js +35 -5
  536. package/dist/server/embeddings.js.map +1 -1
  537. package/dist/session-lines.d.ts +5 -0
  538. package/dist/session-lines.d.ts.map +1 -0
  539. package/dist/session-lines.js +60 -0
  540. package/dist/session-lines.js.map +1 -0
  541. package/dist/severity-review.d.ts +3 -1
  542. package/dist/severity-review.d.ts.map +1 -1
  543. package/dist/severity-review.js +3 -2
  544. package/dist/severity-review.js.map +1 -1
  545. package/dist/skill-authentication.d.ts +1 -0
  546. package/dist/skill-authentication.d.ts.map +1 -1
  547. package/dist/skill-authentication.js +1 -0
  548. package/dist/skill-authentication.js.map +1 -1
  549. package/dist/snyk-findings.d.ts +9 -2
  550. package/dist/snyk-findings.d.ts.map +1 -1
  551. package/dist/snyk-findings.js +90 -70
  552. package/dist/snyk-findings.js.map +1 -1
  553. package/dist/snyk-rest-findings.d.ts +59 -0
  554. package/dist/snyk-rest-findings.d.ts.map +1 -0
  555. package/dist/snyk-rest-findings.js +879 -0
  556. package/dist/snyk-rest-findings.js.map +1 -0
  557. package/dist/snyk-token-origin.d.ts +4 -0
  558. package/dist/snyk-token-origin.d.ts.map +1 -0
  559. package/dist/snyk-token-origin.js +82 -0
  560. package/dist/snyk-token-origin.js.map +1 -0
  561. package/dist/sonar-collector.d.ts.map +1 -1
  562. package/dist/sonar-collector.js +0 -3
  563. package/dist/sonar-collector.js.map +1 -1
  564. package/dist/sonar-findings.d.ts +1 -1
  565. package/dist/sonar-findings.d.ts.map +1 -1
  566. package/dist/sonar-findings.js +2 -4
  567. package/dist/sonar-findings.js.map +1 -1
  568. package/dist/sonar-import.d.ts +3 -0
  569. package/dist/sonar-import.d.ts.map +1 -1
  570. package/dist/sonar-import.js +30 -34
  571. package/dist/sonar-import.js.map +1 -1
  572. package/dist/stored-finding-projection.d.ts +6 -0
  573. package/dist/stored-finding-projection.d.ts.map +1 -0
  574. package/dist/stored-finding-projection.js +104 -0
  575. package/dist/stored-finding-projection.js.map +1 -0
  576. package/dist/stored-findings-publication.d.ts +23 -0
  577. package/dist/stored-findings-publication.d.ts.map +1 -0
  578. package/dist/stored-findings-publication.js +169 -0
  579. package/dist/stored-findings-publication.js.map +1 -0
  580. package/dist/target-drift.d.ts +9 -0
  581. package/dist/target-drift.d.ts.map +1 -0
  582. package/dist/target-drift.js +27 -0
  583. package/dist/target-drift.js.map +1 -0
  584. package/dist/targets.d.ts +8 -1
  585. package/dist/targets.d.ts.map +1 -1
  586. package/dist/targets.js +131 -42
  587. package/dist/targets.js.map +1 -1
  588. package/dist/tenable-findings.d.ts +6 -0
  589. package/dist/tenable-findings.d.ts.map +1 -0
  590. package/dist/tenable-findings.js +122 -0
  591. package/dist/tenable-findings.js.map +1 -0
  592. package/dist/terminal-stream.d.ts +13 -0
  593. package/dist/terminal-stream.d.ts.map +1 -0
  594. package/dist/terminal-stream.js +35 -0
  595. package/dist/terminal-stream.js.map +1 -0
  596. package/dist/trivy-findings.d.ts +19 -0
  597. package/dist/trivy-findings.d.ts.map +1 -0
  598. package/dist/trivy-findings.js +424 -0
  599. package/dist/trivy-findings.js.map +1 -0
  600. package/dist/trivy-import.d.ts +19 -0
  601. package/dist/trivy-import.d.ts.map +1 -0
  602. package/dist/trivy-import.js +151 -0
  603. package/dist/trivy-import.js.map +1 -0
  604. package/dist/trusted-executable.d.ts +6 -0
  605. package/dist/trusted-executable.d.ts.map +1 -1
  606. package/dist/trusted-executable.js +140 -37
  607. package/dist/trusted-executable.js.map +1 -1
  608. package/dist/validation-records.js +1 -1
  609. package/dist/validation-records.js.map +1 -1
  610. package/dist/veracode-findings.d.ts +1 -1
  611. package/dist/veracode-findings.d.ts.map +1 -1
  612. package/dist/veracode-findings.js +19 -6
  613. package/dist/veracode-findings.js.map +1 -1
  614. package/dist/version.d.ts +3 -1
  615. package/dist/version.d.ts.map +1 -1
  616. package/dist/version.js +184 -32
  617. package/dist/version.js.map +1 -1
  618. package/dist/vertex-pricing.d.ts +8 -0
  619. package/dist/vertex-pricing.d.ts.map +1 -0
  620. package/dist/vertex-pricing.js +20 -0
  621. package/dist/vertex-pricing.js.map +1 -0
  622. package/dist/windows-path.d.ts +1 -0
  623. package/dist/windows-path.d.ts.map +1 -1
  624. package/dist/windows-path.js +26 -1
  625. package/dist/windows-path.js.map +1 -1
  626. package/dist/wiz-findings.d.ts +6 -2
  627. package/dist/wiz-findings.d.ts.map +1 -1
  628. package/dist/wiz-findings.js +65 -89
  629. package/dist/wiz-findings.js.map +1 -1
  630. package/docs/classify-severity-records.md +27 -12
  631. package/docs/cli.md +853 -639
  632. package/docs/dedupe-records.md +44 -24
  633. package/docs/findings-service.md +84 -44
  634. package/docs/hosted-remediation.md +27 -11
  635. package/docs/hosted-scans.md +50 -42
  636. package/docs/sdk.md +903 -0
  637. package/docs/telemetry.md +236 -0
  638. package/docs/validate-records.md +78 -44
  639. package/package.json +23 -16
  640. package/schemas/external-findings.schema.json +4 -1
  641. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  642. package/_bundled_plugin/mcp/helpers.mjs.br.part-001 +0 -0
  643. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  644. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  645. package/_bundled_plugin/mcp/server.mjs.br.part-002 +0 -0
  646. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +0 -96
  647. package/dist/external-imports-feature.d.ts +0 -6
  648. package/dist/external-imports-feature.d.ts.map +0 -1
  649. package/dist/external-imports-feature.js +0 -51
  650. package/dist/external-imports-feature.js.map +0 -1
  651. package/dist/finding-normalization.d.ts +0 -5
  652. package/dist/finding-normalization.d.ts.map +0 -1
  653. package/dist/finding-normalization.js +0 -155
  654. package/dist/finding-normalization.js.map +0 -1
  655. package/dist/reader-selection.d.ts +0 -13
  656. package/dist/reader-selection.d.ts.map +0 -1
  657. package/dist/reader-selection.js +0 -81
  658. package/dist/reader-selection.js.map +0 -1
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import argparse
6
6
  import codecs
7
7
  import hashlib
8
+ import json
8
9
  import os
9
10
  import re
10
11
  import shutil
@@ -14,18 +15,22 @@ import subprocess
14
15
  import sys
15
16
  import tempfile
16
17
  import unicodedata
18
+ from collections.abc import Iterable, Iterator
17
19
  from concurrent.futures import ThreadPoolExecutor
20
+ from contextlib import ExitStack, contextmanager
21
+ from contextvars import ContextVar
18
22
  from pathlib import Path, PurePosixPath
19
- from typing import Any, BinaryIO, Callable
23
+ from typing import Any, BinaryIO, Callable, cast
20
24
 
21
25
  # Some plugin hosts launch Python with safe-path isolation enabled.
22
26
  sys.path.insert(0, str(Path(__file__).resolve().parent))
23
- from filesystem_identity import stored_filesystem_identity_matches
24
- from windows_scan_local_files import copy_directory_junction
27
+ from filesystem_identity import serialize_filesystem_identity, stored_filesystem_identity_matches
28
+ from windows_scan_local_files import copy_directory_junction, pinned_root_git_marker
25
29
  from workbench_constants import GIT_REPOSITORY_ENVIRONMENT
26
30
 
27
31
  SOURCE_METADATA_DIRECTORIES = {".git", ".svn"}
28
32
  _WINDOWS = os.name == "nt"
33
+ _SCOPED_GIT: ContextVar[Callable[[Path], str] | None] = ContextVar("workbench_git", default=None)
29
34
 
30
35
 
31
36
  class UnreadableLocalFile(SystemExit):
@@ -44,6 +49,11 @@ def committed_diff_snapshot_digest(kind: str, base_revision: str, head_revision:
44
49
 
45
50
 
46
51
  def diff_snapshot_digest(scan: sqlite3.Row, manifest: dict[str, Any] | None) -> str | None:
52
+ """Return the content identity used for a stored diff, or None when unavailable.
53
+
54
+ Working-tree scans use their recorded content digest. Commit and range scans
55
+ reuse the sealed manifest value during recovery or derive a digest from both revisions.
56
+ """
47
57
  if scan["diff_target_kind"] == "working_tree":
48
58
  return scan["diff_content_digest"]
49
59
  if scan["diff_target_kind"] in {"commit", "range"}:
@@ -67,6 +77,7 @@ def git_output(
67
77
  work_tree: Path | None = None,
68
78
  offline: bool = False,
69
79
  ) -> str | None:
80
+ """Return decoded Git stdout with one trailing newline removed, or None on failure or empty output."""
70
81
  completed = git_command(
71
82
  target, *args, text=False, git_dir=git_dir, work_tree=work_tree, offline=offline
72
83
  )
@@ -198,8 +209,10 @@ def _stream_is_binary(output: BinaryIO, size: int, *, drain: bool = False) -> bo
198
209
 
199
210
  def _protected_repository_root(target: Path) -> Path:
200
211
  root = target.resolve()
201
- if root.is_file():
202
- root = root.parent
212
+ return _outer_checkout_root(root.parent if root.is_file() else root)
213
+
214
+
215
+ def _outer_checkout_root(root: Path) -> Path:
203
216
  protected = root
204
217
  for ancestor in (root, *root.parents):
205
218
  try:
@@ -210,9 +223,67 @@ def _protected_repository_root(target: Path) -> Path:
210
223
  return protected
211
224
 
212
225
 
226
+ def rejected_checkout_roots(value: str) -> list[str] | None:
227
+ # Retain both spellings before a checkout marker or symlink can move.
228
+ try:
229
+ lexical = Path(value).expanduser().absolute()
230
+ canonical = lexical.resolve()
231
+ lexical_root = _outer_checkout_root(lexical)
232
+ roots = {
233
+ lexical,
234
+ canonical,
235
+ lexical_root,
236
+ lexical_root.resolve(),
237
+ _protected_repository_root(canonical),
238
+ }
239
+ return sorted(map(str, roots))
240
+ except (OSError, RuntimeError):
241
+ return None
242
+
243
+
244
+ def pin_scoped_git(target: Path) -> str | None:
245
+ scoped = _SCOPED_GIT.get()
246
+ return scoped(target) if scoped is not None else None
247
+
248
+
213
249
  def trusted_git_executable(protected_root: Path) -> str | None:
214
250
  """Validate host-selected Git, or discover Git for a direct plugin invocation."""
215
251
  configured = os.environ.get("CODEX_SECURITY_GIT")
252
+ if configured is None:
253
+ configured = pin_scoped_git(protected_root)
254
+ return _resolve_git_executable(protected_root, configured)
255
+
256
+
257
+ def _historical_repository_roots(target: Path) -> Iterator[Path]:
258
+ try:
259
+ yield _protected_repository_root(target)
260
+ except (OSError, RuntimeError):
261
+ # Keep checking lexical ancestry when the saved path cannot be resolved.
262
+ pass
263
+ # A moved or unavailable descendant still excludes its lexical checkout ancestry.
264
+ root = Path(os.path.abspath(target))
265
+ protected = root
266
+ for ancestor in (root, *root.parents):
267
+ try:
268
+ (ancestor / ".git").lstat()
269
+ except (OSError, RuntimeError):
270
+ continue
271
+ protected = ancestor
272
+ yield protected
273
+ try:
274
+ yield protected.resolve()
275
+ except (OSError, RuntimeError):
276
+ # The lexical root above still excludes tools at an unavailable checkout.
277
+ pass
278
+
279
+
280
+ def _resolve_git_executable(
281
+ protected_root: Path,
282
+ configured: str | None,
283
+ *,
284
+ discovery_roots: Iterable[Path] = (),
285
+ recorded_git_roots: Iterable[Path] | None = (),
286
+ ) -> str | None:
216
287
  windows = sys.platform == "win32"
217
288
  if configured is None:
218
289
  names = ("git.exe", "git.com") if windows else ("git",)
@@ -230,7 +301,22 @@ def trusted_git_executable(protected_root: Path) -> str | None:
230
301
  candidates = iter((candidate,))
231
302
 
232
303
  try:
233
- repository = _protected_repository_root(protected_root)
304
+ repositories = [_protected_repository_root(protected_root)]
305
+ if configured is None:
306
+ # A legacy Git target has no trustworthy boundary to exclude from PATH.
307
+ if recorded_git_roots is None:
308
+ return None
309
+ saved_boundaries = tuple(recorded_git_roots)
310
+ for root in saved_boundaries:
311
+ repositories.extend(_historical_repository_roots(root))
312
+ for root in discovery_roots:
313
+ for repository in _historical_repository_roots(root):
314
+ if not repository.is_dir() and not any(
315
+ repository.is_relative_to(boundary) for boundary in saved_boundaries
316
+ ):
317
+ # Its former checkout is neither discoverable nor already excluded.
318
+ return None
319
+ repositories.append(repository)
234
320
  except (OSError, RuntimeError):
235
321
  return None
236
322
 
@@ -255,6 +341,7 @@ def trusted_git_executable(protected_root: Path) -> str | None:
255
341
  continue
256
342
  if any(
257
343
  path == repository or repository in path.parents
344
+ for repository in repositories
258
345
  for path in (lexical, invocation, canonical)
259
346
  ):
260
347
  if configured is not None:
@@ -264,6 +351,39 @@ def trusted_git_executable(protected_root: Path) -> str | None:
264
351
  return None
265
352
 
266
353
 
354
+ @contextmanager
355
+ def scoped_git_discovery(
356
+ protected_roots: Callable[[], Iterable[Path]],
357
+ *,
358
+ recorded_git_roots: Callable[[], Iterable[Path] | None] = lambda: (),
359
+ ) -> Iterator[None]:
360
+ """Pin ambient Git when an operation first needs to inspect repository targets."""
361
+ if os.environ.get("CODEX_SECURITY_GIT") is not None:
362
+ yield
363
+ return
364
+ executable: str | None = None
365
+
366
+ def resolve_once(target: Path) -> str:
367
+ nonlocal executable
368
+ if executable is None:
369
+ executable = (
370
+ _resolve_git_executable(
371
+ Path.cwd(),
372
+ None,
373
+ discovery_roots=(*protected_roots(), target),
374
+ recorded_git_roots=recorded_git_roots(),
375
+ )
376
+ or ""
377
+ )
378
+ return executable
379
+
380
+ token = _SCOPED_GIT.set(resolve_once)
381
+ try:
382
+ yield
383
+ finally:
384
+ _SCOPED_GIT.reset(token)
385
+
386
+
267
387
  def git_command(
268
388
  target: Path,
269
389
  *args: str,
@@ -273,11 +393,24 @@ def git_command(
273
393
  work_tree: Path | None = None,
274
394
  stdout_file: BinaryIO | None = None,
275
395
  environment_overrides: dict[str, str] | None = None,
396
+ inherit_git_environment: bool = True,
276
397
  offline: bool = False,
277
398
  ) -> subprocess.CompletedProcess[str] | subprocess.CompletedProcess[bytes]:
399
+ """Run Git against target and return the completed process with its exit status.
400
+
401
+ Pass git_dir and work_tree together to select an explicit checkout. Set
402
+ offline to disable transports and lazy fetches. The text flag selects
403
+ decoded or binary output, and stdout_file can redirect it to a file.
404
+ """
278
405
  if (git_dir is None) != (work_tree is None):
279
406
  raise ValueError("git_dir and work_tree must be provided together")
280
- environment = os.environ.copy()
407
+ environment = (
408
+ os.environ.copy()
409
+ if inherit_git_environment
410
+ else {
411
+ name: value for name, value in os.environ.items() if not name.upper().startswith("GIT_")
412
+ }
413
+ )
281
414
  for name in GIT_REPOSITORY_ENVIRONMENT:
282
415
  environment.pop(name, None)
283
416
  environment["GIT_LITERAL_PATHSPECS"] = "1"
@@ -326,7 +459,7 @@ def git_command(
326
459
  return subprocess.CompletedProcess(full_command, 127, empty_output, empty_output)
327
460
 
328
461
 
329
- def run_git_changed_paths(repo: Path, diff_args: list[str]) -> list[tuple[Path, str]]:
462
+ def run_git_changed_paths(repo: Path, diff_args: list[str]) -> list[tuple[str, str, str | None]]:
330
463
  """Return changed regular files from the selected side of each change."""
331
464
  result = git_command(
332
465
  repo,
@@ -345,25 +478,29 @@ def run_git_changed_paths(repo: Path, diff_args: list[str]) -> list[tuple[Path,
345
478
  if fields and not fields[-1]:
346
479
  fields.pop()
347
480
 
348
- changed: list[tuple[Path, str]] = []
481
+ changed: list[tuple[str, str, str | None]] = []
349
482
  index = 0
350
483
  while index < len(fields):
351
484
  metadata = fields[index].split()
352
485
  status = chr(metadata[-1][0])
353
486
  index += 1
487
+ rename_source = os.fsdecode(fields[index]) if status == "R" else None
354
488
  if status in {"C", "R"}:
355
489
  index += 1
356
- path = repo / os.fsdecode(fields[index])
490
+ path = os.fsdecode(fields[index])
357
491
  index += 1
358
492
  selected_mode = metadata[0].removeprefix(b":") if status == "D" else metadata[1]
359
493
  if selected_mode.startswith(b"100"):
360
- changed.append((path, status))
494
+ changed.append((path, status, rename_source))
361
495
  return changed
362
496
 
363
497
 
364
498
  def git_changed_paths(repo: Path, base: str, head: str, mode: str) -> list[tuple[Path, str]]:
365
499
  if mode == "revisions":
366
- return run_git_changed_paths(repo, [f"{base}..{head}"])
500
+ return [
501
+ (repo / name, status)
502
+ for name, status, _ in run_git_changed_paths(repo, [f"{base}..{head}"])
503
+ ]
367
504
  if mode == "local-patch":
368
505
  unstaged = run_git_changed_paths(repo, [base])
369
506
  staged = run_git_changed_paths(repo, ["--cached", base])
@@ -377,26 +514,37 @@ def git_changed_paths(repo: Path, base: str, head: str, mode: str) -> list[tuple
377
514
  offline=True,
378
515
  )
379
516
  untracked.check_returncode()
380
- combined = dict(staged)
381
- combined.update(unstaged)
382
- combined.update(
383
- (repo / os.fsdecode(relative), "A")
384
- for relative in untracked.stdout.split(b"\0")
385
- if relative and not relative.endswith(b"/")
386
- )
387
- selected = []
517
+ combined = {name: (status, source) for name, status, source in [*staged, *unstaged]}
518
+ selected: dict[str, str] = {}
388
519
  linked_prefixes: dict[str, bool] = {}
389
- for path, status in combined.items():
390
- if not SOURCE_METADATA_DIRECTORIES.isdisjoint(path.relative_to(repo).parts):
391
- continue
520
+
521
+ def local_status(name: str, status: str) -> str | None:
522
+ if not SOURCE_METADATA_DIRECTORIES.isdisjoint(PurePosixPath(name).parts):
523
+ return None
524
+ if status == "D":
525
+ return status
526
+ path = repo / name
392
527
  try:
393
- if status == "M" and _directory_link_boundary(repo, path, linked_prefixes) != path:
394
- selected.append((path, "D"))
395
- elif status == "D" or (not path.is_symlink() and path.is_file()):
396
- selected.append((path, status))
528
+ if (
529
+ status in {"M", "R"}
530
+ and _directory_link_boundary(repo, path, linked_prefixes) != path
531
+ ):
532
+ return "D" if status == "M" else None
533
+ return status if stat.S_ISREG(path.lstat().st_mode) else None
397
534
  except (FileNotFoundError, NotADirectoryError):
398
- continue
399
- return sorted(selected)
535
+ return None
536
+
537
+ for name, (status, source) in combined.items():
538
+ if chosen := local_status(name, status):
539
+ selected[name] = chosen
540
+ elif source is not None and local_status(source, "D"):
541
+ selected.setdefault(source, "D")
542
+ for relative in untracked.stdout.split(b"\0"):
543
+ if relative and not relative.endswith(b"/"):
544
+ name = os.fsdecode(relative)
545
+ if local_status(name, "A"):
546
+ selected[name] = "A"
547
+ return sorted((repo / name, status) for name, status in selected.items())
400
548
  raise SystemExit(f"Unknown diff mode: {mode}")
401
549
 
402
550
 
@@ -527,6 +675,19 @@ def update_digest_field(digest: Any, label: bytes, value: bytes) -> None:
527
675
  digest.update(value)
528
676
 
529
677
 
678
+ def _update_regular_file_digest(digest: Any, path: Path, prefix: bytes = b"") -> None:
679
+ """Record the file kind, byte count, and SHA-256 in the snapshot digest."""
680
+ content = hashlib.sha256()
681
+ size = 0
682
+ with path.open("rb") as handle:
683
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
684
+ content.update(chunk)
685
+ size += len(chunk)
686
+ update_digest_field(digest, prefix + b"kind", b"file")
687
+ update_digest_field(digest, prefix + b"size", str(size).encode())
688
+ update_digest_field(digest, prefix + b"content-sha256", content.digest())
689
+
690
+
530
691
  def _visible_git_character(char: str) -> str:
531
692
  if char in "\n\t" or unicodedata.category(char) not in {"Cc", "Cf"}:
532
693
  return char
@@ -535,6 +696,56 @@ def _visible_git_character(char: str) -> str:
535
696
  return ascii(char)[1:-1]
536
697
 
537
698
 
699
+ def _canonical_patch_chunks(output: BinaryIO) -> Iterator[bytes]:
700
+ """Drop Git's optional function label while preserving hunk coordinates and content."""
701
+ line_start = True
702
+ # Limit each read even when source lines are arbitrarily large.
703
+ for part in iter(lambda: output.readline(1024 * 1024), b""):
704
+ next_line_start = part.endswith(b"\n")
705
+ if line_start and part.startswith(b"@@ "):
706
+ coordinates, end, _ = part.partition(b" @@")
707
+ if end:
708
+ part = coordinates + end + b"\n"
709
+ yield part
710
+ line_start = next_line_start
711
+
712
+
713
+ @contextmanager
714
+ def _diff_driver_config(
715
+ target: Path, git_dir: Path | None, work_tree: Path | None
716
+ ) -> Iterator[tuple[str, ...]]:
717
+ names = git_command(
718
+ target,
719
+ "config",
720
+ "--name-only",
721
+ "--null",
722
+ "--get-regexp",
723
+ r"^diff\..+\.binary$",
724
+ text=False,
725
+ git_dir=git_dir,
726
+ work_tree=work_tree,
727
+ environment_overrides={"LC_ALL": "C"},
728
+ )
729
+ if names.returncode == 1: # Git returns 1 when there are no matching keys.
730
+ yield ()
731
+ return
732
+ if names.returncode:
733
+ raise SystemExit(
734
+ os.fsdecode(names.stderr) or "Could not inspect Git diff-driver configuration."
735
+ )
736
+ # A private command-scope include preserves case and arbitrary driver-name bytes
737
+ # without putting an unbounded number of keys on the command line.
738
+ with tempfile.TemporaryDirectory(prefix="codex-security-diff-") as directory:
739
+ config = Path(directory) / "drivers"
740
+ with config.open("wb") as stream:
741
+ for key in names.stdout.split(b"\0"):
742
+ if key:
743
+ driver = key.removeprefix(b"diff.").removesuffix(b".binary")
744
+ escaped = driver.replace(b"\\", b"\\\\").replace(b'"', b'\\"')
745
+ stream.write(b'[diff "' + escaped + b'"]\n\tbinary = auto\n')
746
+ yield "-c", f"include.path={config}"
747
+
748
+
538
749
  def _update_digest_field_from_git(
539
750
  digest: Any,
540
751
  label: bytes,
@@ -542,15 +753,24 @@ def _update_digest_field_from_git(
542
753
  *args: str,
543
754
  git_dir: Path | None = None,
544
755
  work_tree: Path | None = None,
756
+ environment_overrides: dict[str, str] | None = None,
757
+ stable_display: bool = False,
545
758
  ) -> None:
546
- with tempfile.TemporaryFile() as output:
759
+ with tempfile.TemporaryFile() as output, ExitStack() as stack:
760
+ driver_config = (
761
+ stack.enter_context(_diff_driver_config(target, git_dir, work_tree))
762
+ if stable_display
763
+ else ()
764
+ )
547
765
  completed = git_command(
548
766
  target,
767
+ *driver_config,
549
768
  *args,
550
769
  text=False,
551
770
  git_dir=git_dir,
552
771
  work_tree=work_tree,
553
772
  stdout_file=output,
773
+ environment_overrides=environment_overrides,
554
774
  )
555
775
  if completed.returncode != 0:
556
776
  detail = completed.stderr.decode("utf-8", errors="backslashreplace").replace(
@@ -560,39 +780,52 @@ def _update_digest_field_from_git(
560
780
  raise SystemExit(
561
781
  f"Could not snapshot the selected working-tree changes.\n{detail}".rstrip("\n")
562
782
  )
563
- output.seek(0, os.SEEK_END)
564
- value_size = output.tell()
783
+ if stable_display:
784
+ output.seek(0)
785
+ value_size = sum(len(part) for part in _canonical_patch_chunks(output))
786
+ else:
787
+ value_size = output.seek(0, os.SEEK_END)
565
788
  _update_digest_field_header(digest, label, value_size)
566
789
  output.seek(0)
567
- for chunk in iter(lambda: output.read(1024 * 1024), b""):
790
+ chunks = (
791
+ _canonical_patch_chunks(output)
792
+ if stable_display
793
+ else iter(lambda: output.read(1024 * 1024), b"")
794
+ )
795
+ for chunk in chunks:
568
796
  digest.update(chunk)
569
797
 
570
798
 
571
- def worktree_content_digest(target: Path) -> str:
799
+ def worktree_content_digest(target: Path, *, expected_digest: str | None = None) -> str:
800
+ """Return the worktree digest for the selected path after checking the state of its submodules."""
572
801
  require_clean_submodule_worktrees(target)
573
802
  repository, pathspec = git_worktree_context(target)
574
- return worktree_content_digest_for_context(repository, pathspec)
803
+ return worktree_content_digest_for_context(
804
+ repository, pathspec, expected_digest=expected_digest
805
+ )
575
806
 
576
807
 
577
808
  def remediation_checkout_snapshot(
578
809
  scan: sqlite3.Row,
579
810
  *,
580
811
  expected_revision: str | None = None,
812
+ expected_digest: str | None = None,
581
813
  head_changed_message: str = (
582
814
  "Repository HEAD changed. Regenerate the remediation patch against the current checkout."
583
815
  ),
584
816
  ) -> tuple[str, str | None]:
585
- target = require_scan_target_identity(scan)
586
- revision = git_revision(target)
587
- required_revision = expected_revision or scan["target_revision"]
588
- if revision != required_revision:
589
- raise SystemExit(head_changed_message)
590
- content_digest = (
591
- worktree_content_digest(target)
592
- if revision != "unversioned"
593
- else directory_content_digest(target, excluded=(Path(scan["scan_dir"]),))
594
- )
595
- return revision, content_digest
817
+ """Return the current revision and content digest after verifying the recorded checkout identity and required revision."""
818
+ with checked_scan_target(scan) as target:
819
+ revision = git_revision(target)
820
+ required_revision = expected_revision or scan["target_revision"]
821
+ if revision != required_revision:
822
+ raise SystemExit(head_changed_message)
823
+ content_digest = (
824
+ worktree_content_digest(target, expected_digest=expected_digest)
825
+ if revision != "unversioned"
826
+ else directory_content_digest(target, excluded=(Path(scan["scan_dir"]),))
827
+ )
828
+ return revision, content_digest
596
829
 
597
830
 
598
831
  def require_scan_target_unchanged(scan: sqlite3.Row) -> None:
@@ -604,28 +837,33 @@ def require_scan_target_unchanged(scan: sqlite3.Row) -> None:
604
837
  and scan["target_revision"] != "unversioned"
605
838
  ):
606
839
  # Legacy Git records bind only the revision, not working-tree contents.
607
- target = require_scan_target_identity(scan)
608
- if git_revision(target) != scan["target_revision"]:
609
- raise SystemExit(head_changed_message)
610
- require_clean_submodule_worktrees(target)
840
+ with checked_scan_target(scan) as target:
841
+ if git_revision(target) != scan["target_revision"]:
842
+ raise SystemExit(head_changed_message)
843
+ require_clean_submodule_worktrees(target)
611
844
  return
612
- _, current_digest = remediation_checkout_snapshot(
613
- scan, head_changed_message=head_changed_message
614
- )
615
845
  if scan["diff_target_kind"] == "working_tree":
616
846
  expected_digest = scan["diff_content_digest"]
617
847
  elif scan["diff_target_kind"] in {"commit", "range"}:
618
- tracked = git_bytes(Path(scan["target_path"]), "ls-files", "-t", "-z")
848
+ expected_digest = clean_worktree_content_digest()
849
+ else:
850
+ expected_digest = scan["target_snapshot_digest"]
851
+ _, current_digest = remediation_checkout_snapshot(
852
+ scan, expected_digest=expected_digest, head_changed_message=head_changed_message
853
+ )
854
+ if scan["diff_target_kind"] in {"commit", "range"}:
855
+ target = Path(scan["target_path"])
856
+ tracked = git_bytes(target, "ls-files", "-v", "-z")
619
857
  if tracked is None:
620
858
  raise SystemExit("Could not inspect tracked files in the scan target.")
621
- if any(entry.startswith(b"S ") for entry in tracked.split(b"\0")):
859
+ entries = tracked.split(b"\0")
860
+ if any(entry.startswith((b"S ", b"s ")) for entry in entries):
622
861
  raise SystemExit(
623
862
  "Committed-diff scans require a full repository checkout. "
624
863
  "Sparse checkouts are not supported; materialize skipped tracked files and retry."
625
864
  )
626
- expected_digest = clean_worktree_content_digest()
627
- else:
628
- expected_digest = scan["target_snapshot_digest"]
865
+ if any(entry.startswith(b"h ") for entry in entries):
866
+ verify_assumed_unchanged_files(target)
629
867
  if current_digest != expected_digest:
630
868
  raise SystemExit(
631
869
  "Scan target contents changed since the scan. "
@@ -633,12 +871,67 @@ def require_scan_target_unchanged(scan: sqlite3.Row) -> None:
633
871
  )
634
872
 
635
873
 
874
+ def verify_assumed_unchanged_files(target: Path) -> None:
875
+ index = git_output(target, "rev-parse", "--path-format=absolute", "--git-path", "index")
876
+ if index is None:
877
+ raise SystemExit("Could not locate the Git index for the scan target.")
878
+ with tempfile.TemporaryDirectory(prefix="codex-security-git-index-") as directory:
879
+ # Refresh a private index without running checkout hooks or updating its shared index.
880
+ index_copy = Path(directory) / "index"
881
+ shutil.copyfile(index, index_copy)
882
+ result = git_command(
883
+ target,
884
+ "-c",
885
+ f"core.hooksPath={directory}",
886
+ "-c",
887
+ "core.splitIndex=false",
888
+ "update-index",
889
+ "--really-refresh",
890
+ text=False,
891
+ environment_overrides={"GIT_INDEX_FILE": str(index_copy)},
892
+ # A repository's clean filter can run while Git compares working-tree bytes.
893
+ inherit_git_environment=False,
894
+ offline=True,
895
+ )
896
+ if result.returncode == 1:
897
+ raise SystemExit(
898
+ "A tracked file marked assume-unchanged changed since the scan. "
899
+ "Run a new scan before validating its findings."
900
+ )
901
+ if result.returncode != 0:
902
+ raise SystemExit(
903
+ os.fsdecode(result.stderr) or "Could not refresh the scan target's Git index."
904
+ )
905
+
906
+
636
907
  def worktree_content_digest_for_context(
637
908
  repository: Path,
638
909
  pathspec: str,
639
910
  *,
640
911
  git_dir: Path | None = None,
641
912
  work_tree: Path | None = None,
913
+ expected_digest: str | None = None,
914
+ ) -> str:
915
+ def calculate(stable_display: bool) -> str:
916
+ return _git_content_digest(repository, pathspec, git_dir, work_tree, stable_display)
917
+
918
+ current = calculate(True)
919
+ # Older sealed snapshots may have included the user's Git display settings.
920
+ if (
921
+ expected_digest is not None
922
+ and current != expected_digest
923
+ and calculate(False) == expected_digest
924
+ ):
925
+ return expected_digest
926
+ return current
927
+
928
+
929
+ def _git_content_digest(
930
+ repository: Path,
931
+ pathspec: str,
932
+ git_dir: Path | None,
933
+ work_tree: Path | None,
934
+ stable_display: bool,
642
935
  ) -> str:
643
936
  digest = hashlib.sha256()
644
937
  update_digest_field(digest, b"format", b"codex-security-snapshot/v1")
@@ -647,12 +940,44 @@ def worktree_content_digest_for_context(
647
940
  ":(top,glob,exclude)**/.svn",
648
941
  ":(top,glob,exclude)**/.svn/**",
649
942
  ]
943
+ config = (
944
+ (
945
+ "-c",
946
+ "core.quotePath=true",
947
+ "-c",
948
+ "diff.suppressBlankEmpty=false",
949
+ "-c",
950
+ "core.compression=1", # Git uses the fastest zlib level for binary patches by default.
951
+ )
952
+ if stable_display
953
+ else ()
954
+ )
955
+ display = (
956
+ (
957
+ "--no-color",
958
+ "--src-prefix=a/",
959
+ "--dst-prefix=b/",
960
+ "--unified=3",
961
+ "--diff-algorithm=myers",
962
+ "--indent-heuristic",
963
+ "--inter-hunk-context=0",
964
+ "--find-renames=50%",
965
+ "-l1000", # Git's default inexact rename limit.
966
+ "--submodule=short",
967
+ "-O",
968
+ os.devnull,
969
+ )
970
+ if stable_display
971
+ else ()
972
+ )
650
973
  _update_digest_field_from_git(
651
974
  digest,
652
975
  b"tracked-diff",
653
976
  repository,
977
+ *config,
654
978
  "--no-literal-pathspecs",
655
979
  "diff",
980
+ *display,
656
981
  "--binary",
657
982
  "--full-index",
658
983
  "--no-ext-diff",
@@ -663,6 +988,9 @@ def worktree_content_digest_for_context(
663
988
  *source_pathspecs,
664
989
  git_dir=git_dir,
665
990
  work_tree=work_tree,
991
+ # GIT_DIFF_OPTS overrides even an explicit --unified option.
992
+ environment_overrides={"GIT_DIFF_OPTS": ""} if stable_display else None,
993
+ stable_display=stable_display,
666
994
  )
667
995
  untracked = git_bytes(
668
996
  repository,
@@ -706,26 +1034,10 @@ def worktree_content_digest_for_context(
706
1034
  directory_content_digest(path.resolve()).encode(),
707
1035
  )
708
1036
  elif stat.S_ISREG(metadata.st_mode):
709
- content_digest = hashlib.sha256()
710
- content_size = 0
711
1037
  try:
712
- with path.open("rb") as handle:
713
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
714
- content_digest.update(chunk)
715
- content_size += len(chunk)
1038
+ _update_regular_file_digest(digest, path, prefix=b"untracked-")
716
1039
  except OSError as exc:
717
1040
  raise SystemExit(f"Could not read untracked file: {relative_path}") from exc
718
- update_digest_field(digest, b"untracked-kind", b"file")
719
- update_digest_field(
720
- digest,
721
- b"untracked-size",
722
- str(content_size).encode(),
723
- )
724
- update_digest_field(
725
- digest,
726
- b"untracked-content-sha256",
727
- content_digest.digest(),
728
- )
729
1041
  else:
730
1042
  raise SystemExit(f"Unsupported untracked file type: {relative_path}")
731
1043
  return f"codex-security-snapshot/v1:sha256:{digest.hexdigest()}"
@@ -835,11 +1147,64 @@ def _directory_link_boundary(target: Path, path: Path, linked_prefixes: dict[str
835
1147
  return path
836
1148
 
837
1149
 
838
- def git_directory_snapshot_paths(target: Path) -> list[Path] | None:
839
- repository_root = git_output(target, "rev-parse", "--show-toplevel")
840
- if repository_root is None:
841
- return None
842
- repository, pathspec = git_worktree_context(target)
1150
+ def _windows_inventory_query(
1151
+ target: Path,
1152
+ *args: str,
1153
+ git_dir: Path,
1154
+ work_tree: Path,
1155
+ input_data: bytes | None = None,
1156
+ environment_overrides: dict[str, str] | None = None,
1157
+ ) -> subprocess.CompletedProcess[bytes]:
1158
+ """Retry an inventory's metadata length error with its verified worktree marker."""
1159
+
1160
+ def query(
1161
+ directory: Path, environment: dict[str, str] | None
1162
+ ) -> subprocess.CompletedProcess[bytes]:
1163
+ return cast(
1164
+ subprocess.CompletedProcess[bytes],
1165
+ git_command(
1166
+ target,
1167
+ *args,
1168
+ text=False,
1169
+ git_dir=directory,
1170
+ work_tree=work_tree,
1171
+ input_data=input_data,
1172
+ environment_overrides=environment,
1173
+ ),
1174
+ )
1175
+
1176
+ result = query(git_dir, environment_overrides)
1177
+ if (
1178
+ result.returncode != 128
1179
+ or result.stdout
1180
+ or not target.is_relative_to(work_tree)
1181
+ or b"GIT_DIR" not in result.stderr
1182
+ ):
1183
+ return result
1184
+ diagnostic = b"fatal: '$GIT_DIR' too big"
1185
+ if diagnostic not in result.stderr.splitlines():
1186
+ # Confirm translated diagnostics without changing the actual inventory's environment.
1187
+ probe = query(git_dir, {**(environment_overrides or {}), "LC_ALL": "C", "LANGUAGE": "C"})
1188
+ if probe.returncode != 128 or probe.stdout or diagnostic not in probe.stderr.splitlines():
1189
+ return result
1190
+ with pinned_root_git_marker(target, git_dir, work_tree=work_tree) as marker:
1191
+ if marker is not None:
1192
+ retry = query(marker, environment_overrides)
1193
+ if retry.returncode == 0 or (retry.returncode == 1 and "check-ignore" in args):
1194
+ return retry
1195
+ return result
1196
+
1197
+
1198
+ def git_directory_snapshot_paths(
1199
+ target: Path, *, replay_git_dir: Path | None = None
1200
+ ) -> list[Path] | None:
1201
+ if replay_git_dir is None:
1202
+ if git_output(target, "rev-parse", "--show-toplevel") is None:
1203
+ return None
1204
+ repository, pathspec = git_worktree_context(target)
1205
+ else:
1206
+ # The temporary copy of an unborn repository uses the selected Git config and index.
1207
+ repository, pathspec = target, "."
843
1208
  scope = repository / pathspec
844
1209
  scope_depth = len(Path(pathspec).parts)
845
1210
  matching_prefixes: dict[str, bool] = {}
@@ -867,6 +1232,8 @@ def git_directory_snapshot_paths(target: Path) -> list[Path] | None:
867
1232
  "-z",
868
1233
  "--",
869
1234
  inventory_pathspec,
1235
+ git_dir=replay_git_dir,
1236
+ work_tree=repository if replay_git_dir else None,
870
1237
  )
871
1238
  if listed is None:
872
1239
  raise SystemExit("Could not inspect files in the selected Git working tree.")
@@ -925,10 +1292,10 @@ def git_directory_snapshot_paths(target: Path) -> list[Path] | None:
925
1292
  if _WINDOWS:
926
1293
  # Git omits empty untracked directories from its file listing. Inventory
927
1294
  # junction identities independently of whether their targets contain files.
928
- git_directory = git_output(target, "rev-parse", "--absolute-git-dir")
1295
+ git_directory = replay_git_dir or git_output(target, "rev-parse", "--absolute-git-dir")
929
1296
  if git_directory is None:
930
1297
  raise SystemExit("Could not inspect the selected Git working tree.")
931
- directories = git_bytes(
1298
+ directories = _windows_inventory_query(
932
1299
  target,
933
1300
  "--no-literal-pathspecs",
934
1301
  "ls-files",
@@ -942,9 +1309,9 @@ def git_directory_snapshot_paths(target: Path) -> list[Path] | None:
942
1309
  git_dir=Path(git_directory),
943
1310
  work_tree=repository,
944
1311
  )
945
- if directories is None:
1312
+ if directories.returncode != 0:
946
1313
  raise SystemExit("Could not inspect directories in the selected Git working tree.")
947
- pending = [target / os.fsdecode(path) for path in directories.split(b"\0") if path]
1314
+ pending = [target / os.fsdecode(path) for path in directories.stdout.split(b"\0") if path]
948
1315
  while pending:
949
1316
  children: list[Path] = []
950
1317
  for path in pending:
@@ -983,13 +1350,12 @@ def git_directory_snapshot_paths(target: Path) -> list[Path] | None:
983
1350
  if not candidates:
984
1351
  break
985
1352
  # Filter a directory level at once, retaining the outer repository context.
986
- ignored = git_command(
1353
+ ignored = _windows_inventory_query(
987
1354
  repository,
988
1355
  "--no-literal-pathspecs",
989
1356
  "check-ignore",
990
1357
  "-z",
991
1358
  "--stdin",
992
- text=False,
993
1359
  input_data=b"\0".join(candidates) + b"\0",
994
1360
  git_dir=Path(git_directory),
995
1361
  work_tree=repository,
@@ -1043,6 +1409,7 @@ def directory_content_digest(
1043
1409
  excluded: tuple[Path, ...] = (),
1044
1410
  include_ignored: bool = False,
1045
1411
  include_git_metadata: bool = False,
1412
+ replay_git_dir: Path | None = None,
1046
1413
  ) -> str:
1047
1414
  def raise_walk_error(error: OSError) -> None:
1048
1415
  raise error
@@ -1055,7 +1422,7 @@ def directory_content_digest(
1055
1422
  target, excluded, include_git_metadata=include_git_metadata, onerror=raise_walk_error
1056
1423
  )
1057
1424
  if include_ignored
1058
- else git_directory_snapshot_paths(target)
1425
+ else git_directory_snapshot_paths(target, replay_git_dir=replay_git_dir)
1059
1426
  )
1060
1427
  if paths is None:
1061
1428
  paths = source_directory_snapshot_paths(target, excluded)
@@ -1084,36 +1451,46 @@ def directory_content_digest(
1084
1451
  elif stat.S_ISDIR(mode):
1085
1452
  update_digest_field(digest, b"kind", b"directory")
1086
1453
  elif stat.S_ISREG(mode):
1087
- content_digest = hashlib.sha256()
1088
- content_size = 0
1089
1454
  try:
1090
- with path.open("rb") as handle:
1091
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
1092
- content_digest.update(chunk)
1093
- content_size += len(chunk)
1455
+ _update_regular_file_digest(digest, path)
1094
1456
  except OSError as exc:
1095
1457
  raise UnreadableLocalFile(f"Could not read local file: {relative_path}") from exc
1096
- update_digest_field(digest, b"kind", b"file")
1097
- update_digest_field(digest, b"size", str(content_size).encode())
1098
- update_digest_field(digest, b"content-sha256", content_digest.digest())
1099
1458
  else:
1100
1459
  raise UnsupportedLocalFileType(f"Unsupported local file type: {relative_path}")
1101
1460
  return f"codex-security-snapshot/v1:sha256:{digest.hexdigest()}"
1102
1461
 
1103
1462
 
1104
- def directory_snapshot_regular_file_count(target: Path) -> int:
1463
+ def directory_snapshot_regular_files(target: Path) -> Iterator[Path]:
1105
1464
  paths = git_directory_snapshot_paths(target)
1106
1465
  if paths is None:
1107
1466
  paths = source_directory_snapshot_paths(target)
1108
- count = 0
1109
1467
  for path in paths:
1110
1468
  try:
1111
1469
  metadata = path.lstat()
1112
1470
  except OSError as exc:
1113
1471
  raise SystemExit(f"Could not inspect local file: {path.relative_to(target)}") from exc
1114
1472
  if stat.S_ISREG(metadata.st_mode):
1115
- count += 1
1116
- return count
1473
+ yield path
1474
+
1475
+
1476
+ def directory_snapshot_regular_file_count(target: Path) -> int:
1477
+ return sum(1 for _ in directory_snapshot_regular_files(target))
1478
+
1479
+
1480
+ def scoped_regular_file_count(repository: Path, scopes: list[str]) -> int:
1481
+ # Count directory entries once while retaining explicitly requested ignored files.
1482
+ names: set[str] = set()
1483
+ for scope in scopes:
1484
+ selected = (repository / scope).resolve(strict=True)
1485
+ if not selected.is_relative_to(repository):
1486
+ raise SystemExit("Requested scope must be inside the repository.")
1487
+ if not SOURCE_METADATA_DIRECTORIES.isdisjoint(selected.relative_to(repository).parts):
1488
+ continue
1489
+ if selected.is_file():
1490
+ names.add(selected.as_posix())
1491
+ elif selected.is_dir():
1492
+ names.update(path.as_posix() for path in directory_snapshot_regular_files(selected))
1493
+ return len(names)
1117
1494
 
1118
1495
 
1119
1496
  def copy_directory_excluding(
@@ -1213,7 +1590,12 @@ def copy_git_worktree_files(
1213
1590
  destination_path = destination / relative
1214
1591
  destination_path.parent.mkdir(parents=True, exist_ok=True)
1215
1592
  if stat.S_ISLNK(metadata.st_mode):
1216
- destination_path.symlink_to(os.readlink(source_path))
1593
+ directory_link = bool(
1594
+ getattr(metadata, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_DIRECTORY
1595
+ )
1596
+ destination_path.symlink_to(
1597
+ os.readlink(source_path), target_is_directory=directory_link
1598
+ )
1217
1599
  elif stat.S_ISREG(metadata.st_mode):
1218
1600
  shutil.copy2(source_path, destination_path, follow_symlinks=False)
1219
1601
  elif stat.S_ISDIR(metadata.st_mode):
@@ -1299,7 +1681,10 @@ def require_remediation_target(value: str) -> Path:
1299
1681
  raise SystemExit("Remediation target must be an absolute local directory path.")
1300
1682
  try:
1301
1683
  resolved = stored.resolve(strict=True)
1302
- except (FileNotFoundError, OSError) as exc:
1684
+ except NotADirectoryError:
1685
+ # A component of the recorded checkout path now names a non-directory.
1686
+ resolved = None
1687
+ except OSError as exc:
1303
1688
  raise SystemExit(
1304
1689
  "Remediation is unavailable because the selected checkout is no longer accessible."
1305
1690
  ) from exc
@@ -1310,8 +1695,78 @@ def require_remediation_target(value: str) -> Path:
1310
1695
  return stored
1311
1696
 
1312
1697
 
1313
- def require_scan_target_identity(scan: sqlite3.Row) -> Path:
1698
+ @contextmanager
1699
+ def verified_windows_checkout(
1700
+ scan: sqlite3.Row, target: Path, *, replaced_message: str
1701
+ ) -> Iterator[None]:
1702
+ """Bind a Windows Deep checkout for the full operation, including legacy stat-width changes."""
1703
+ from windows_scan_local_files import pinned_resume_checkout
1704
+
1705
+ binding = scan["windows_resume_target_identity"]
1706
+ stored = (scan["target_device"], scan["target_inode"])
1707
+ if binding is None:
1708
+
1709
+ def stat_identity() -> tuple[int | str, int | str]:
1710
+ try:
1711
+ metadata = target.stat()
1712
+ except OSError as exc:
1713
+ raise SystemExit(f"Cannot verify the original Windows checkout: {exc}") from exc
1714
+ return serialize_filesystem_identity(metadata.st_dev), serialize_filesystem_identity(
1715
+ metadata.st_ino
1716
+ )
1717
+
1718
+ if stat_identity() == stored:
1719
+ yield
1720
+ if stat_identity() != stored:
1721
+ raise SystemExit(replaced_message)
1722
+ return
1723
+
1724
+ with pinned_resume_checkout(target) as native:
1725
+ if binding is not None:
1726
+ if native is None:
1727
+ raise SystemExit("Cannot verify the original Windows checkout identity.")
1728
+ if list(native) != json.loads(binding):
1729
+ raise SystemExit(replaced_message)
1730
+ # Legacy stat returned at most a 32-bit volume and 64-bit file index.
1731
+ elif (
1732
+ native is None
1733
+ or (native[0] < 1 << 32 and native[1] < 1 << 64)
1734
+ or tuple(map(serialize_filesystem_identity, native)) != stored
1735
+ ):
1736
+ raise SystemExit(
1737
+ "Cannot verify the saved Windows checkout identity with this Python runtime. "
1738
+ "Use its original Python runtime or start a new scan with "
1739
+ f"'codex-security scans rerun {scan['id']}'."
1740
+ )
1741
+ yield
1742
+
1743
+
1744
+ @contextmanager
1745
+ def checked_scan_target(scan: sqlite3.Row) -> Iterator[Path]:
1746
+ """Keep any recorded Windows checkout binding intact while a caller reads the target."""
1314
1747
  target = require_remediation_target(scan["target_path"])
1748
+ replaced = "Remediation is unavailable because the selected checkout path was replaced. Start a new scan."
1749
+ if (
1750
+ os.name == "nt"
1751
+ and "windows_resume_target_identity" in scan.keys()
1752
+ and (
1753
+ scan["windows_resume_target_identity"] is not None
1754
+ or (
1755
+ scan["mode"] == "deep"
1756
+ and scan["launch_kind"] == "scan"
1757
+ and scan["recipe_json"] is not None
1758
+ )
1759
+ )
1760
+ ):
1761
+ with ExitStack() as pins:
1762
+ try:
1763
+ pins.enter_context(
1764
+ verified_windows_checkout(scan, target, replaced_message=replaced)
1765
+ )
1766
+ except OSError as exc:
1767
+ raise SystemExit(f"Cannot verify the original Windows checkout: {exc}") from exc
1768
+ yield target
1769
+ return
1315
1770
  expected_inode = scan["target_inode"]
1316
1771
  if expected_inode is None:
1317
1772
  raise SystemExit(
@@ -1325,11 +1780,14 @@ def require_scan_target_identity(scan: sqlite3.Row) -> Path:
1325
1780
  "Remediation is unavailable because the selected checkout is no longer accessible."
1326
1781
  ) from exc
1327
1782
  if not stored_filesystem_identity_matches(expected_inode, metadata.st_ino):
1328
- raise SystemExit(
1329
- "Remediation is unavailable because the selected checkout path was replaced. "
1330
- "Start a new scan."
1331
- )
1332
- return target
1783
+ raise SystemExit(replaced)
1784
+ yield target
1785
+
1786
+
1787
+ def require_scan_target_identity(scan: sqlite3.Row) -> Path:
1788
+ """Return the recorded checkout path after checking its filesystem identity."""
1789
+ with checked_scan_target(scan) as target:
1790
+ return target
1333
1791
 
1334
1792
 
1335
1793
  def require_git_worktree_head(target: Path) -> str:
@@ -1343,37 +1801,37 @@ def scan_target_warning(scan: sqlite3.Row) -> str | None:
1343
1801
  if scan["diff_target_kind"] != "working_tree" and not scan["target_snapshot_digest"]:
1344
1802
  return None
1345
1803
  try:
1346
- target = require_scan_target_identity(scan)
1347
- if scan["target_revision"] == "unversioned":
1348
- if (
1349
- directory_content_digest(target, excluded=(Path(scan["scan_dir"]),))
1350
- != scan["target_snapshot_digest"]
1351
- ):
1804
+ with checked_scan_target(scan) as target:
1805
+ if scan["target_revision"] == "unversioned":
1806
+ if (
1807
+ directory_content_digest(target, excluded=(Path(scan["scan_dir"]),))
1808
+ != scan["target_snapshot_digest"]
1809
+ ):
1810
+ return (
1811
+ "Directory contents changed while the scan was running; "
1812
+ "results were saved for the original snapshot."
1813
+ )
1814
+ return None
1815
+ if git_revision(target) == "unversioned":
1352
1816
  return (
1353
- "Directory contents changed while the scan was running; "
1354
- "results were saved for the original snapshot."
1817
+ "The scanned Git repository became unavailable while the scan was running; "
1818
+ "results were saved for the original revision."
1355
1819
  )
1356
- return None
1357
- if git_revision(target) == "unversioned":
1358
- return (
1359
- "The scanned Git repository became unavailable while the scan was running; "
1360
- "results were saved for the original revision."
1361
- )
1362
- working_tree = scan["diff_target_kind"] == "working_tree"
1363
- expected_head = scan["diff_head_revision"] if working_tree else scan["target_revision"]
1364
- if require_git_worktree_head(target) != expected_head:
1365
- return (
1366
- "Repository HEAD changed while the scan was running; "
1367
- "results were saved for the original revision."
1368
- )
1369
- expected_digest = (
1370
- scan["diff_content_digest"] if working_tree else scan["target_snapshot_digest"]
1371
- )
1372
- if worktree_content_digest(target) != expected_digest:
1373
- return (
1374
- "Working-tree contents changed while the scan was running; "
1375
- "results were saved for the original snapshot."
1820
+ working_tree = scan["diff_target_kind"] == "working_tree"
1821
+ expected_head = scan["diff_head_revision"] if working_tree else scan["target_revision"]
1822
+ if require_git_worktree_head(target) != expected_head:
1823
+ return (
1824
+ "Repository HEAD changed while the scan was running; "
1825
+ "results were saved for the original revision."
1826
+ )
1827
+ expected_digest = (
1828
+ scan["diff_content_digest"] if working_tree else scan["target_snapshot_digest"]
1376
1829
  )
1830
+ if worktree_content_digest(target, expected_digest=expected_digest) != expected_digest:
1831
+ return (
1832
+ "Working-tree contents changed while the scan was running; "
1833
+ "results were saved for the original snapshot."
1834
+ )
1377
1835
  except (OSError, SystemExit) as error:
1378
1836
  return (
1379
1837
  f"Could not verify the scan target after scanning: {error}; "