@openai/codex-security 0.9.1 → 0.10.1

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 (444) hide show
  1. package/README.md +37 -788
  2. package/_bundled_plugin/.codex-plugin/plugin.json +2 -0
  3. package/_bundled_plugin/.mcp.json +3 -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/access-advisory.md +1 -1
  15. package/_bundled_plugin/references/artifact-storage.md +1 -1
  16. package/_bundled_plugin/references/baseline-auditor.md +18 -0
  17. package/_bundled_plugin/references/core-scan.md +5 -42
  18. package/_bundled_plugin/references/final-report.md +1 -1
  19. package/_bundled_plugin/references/focused-investigator.md +13 -0
  20. package/_bundled_plugin/references/scan-prologue.md +2 -2
  21. package/_bundled_plugin/references/scan-runtime.md +4 -2
  22. package/_bundled_plugin/references/security-guidance.md +14 -1
  23. package/_bundled_plugin/references/threat-model.md +1 -0
  24. package/_bundled_plugin/references/validate-scan-findings.md +3 -0
  25. package/_bundled_plugin/scripts/deep_scan_workbench.py +30 -12
  26. package/_bundled_plugin/scripts/dispatch_inventory_tool +7 -0
  27. package/_bundled_plugin/scripts/finalize_scan_contract.py +47 -9
  28. package/_bundled_plugin/scripts/launch_codex_security_mcp +54 -16
  29. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +2 -0
  30. package/_bundled_plugin/scripts/posix_scan_local_files.py +26 -1
  31. package/_bundled_plugin/scripts/snapshot_sqlite.py +8 -2
  32. package/_bundled_plugin/scripts/windows_scan_local_files.py +216 -25
  33. package/_bundled_plugin/scripts/workbench/handoff.py +55 -25
  34. package/_bundled_plugin/scripts/workbench/storage.py +25 -5
  35. package/_bundled_plugin/scripts/workbench_cli.py +24 -2
  36. package/_bundled_plugin/scripts/workbench_constants.py +2 -0
  37. package/_bundled_plugin/scripts/workbench_db.py +257 -268
  38. package/_bundled_plugin/scripts/workbench_feedback.py +49 -4
  39. package/_bundled_plugin/scripts/workbench_native_indexes.py +226 -29
  40. package/_bundled_plugin/scripts/workbench_progress.py +159 -3
  41. package/_bundled_plugin/scripts/workbench_publication.py +2 -3
  42. package/_bundled_plugin/scripts/workbench_remediation.py +142 -2
  43. package/_bundled_plugin/scripts/workbench_saved_results.py +48 -8
  44. package/_bundled_plugin/scripts/workbench_scan_history.py +291 -134
  45. package/_bundled_plugin/scripts/workbench_scan_start.py +208 -11
  46. package/_bundled_plugin/scripts/workbench_scan_usage.py +36 -10
  47. package/_bundled_plugin/scripts/workbench_schema.py +220 -14
  48. package/_bundled_plugin/scripts/workbench_setup.py +1 -1
  49. package/_bundled_plugin/scripts/workbench_source_scopes.py +8 -0
  50. package/_bundled_plugin/scripts/workbench_target.py +486 -85
  51. package/_bundled_plugin/scripts/workbench_target_state.py +1108 -22
  52. package/_bundled_plugin/shared/workbench-history-repairs.json +64 -14
  53. package/_bundled_plugin/shared/workbench-migrations.json +66 -0
  54. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +4 -2
  55. package/_bundled_plugin/skills/attack-path-analysis/references/severity-policy.md +2 -2
  56. package/_bundled_plugin/skills/fix-finding/SKILL.md +1 -0
  57. package/_bundled_plugin/skills/publish-findings/SKILL.md +26 -160
  58. package/_bundled_plugin/skills/publish-findings/agents/openai.yaml +2 -2
  59. package/_bundled_plugin/skills/publish-findings/references/checkmarx-import.md +2 -2
  60. package/_bundled_plugin/skills/publish-findings/scripts/collect_checkmarx.py +3 -58
  61. package/_bundled_plugin/skills/publish-findings/scripts/collector_paths.py +63 -0
  62. package/_bundled_plugin/skills/security-scan/SKILL.md +9 -46
  63. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +2 -2
  64. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +3 -21
  65. package/_bundled_plugin/skills/security-scan/references/managed-scan.md +11 -0
  66. package/_bundled_plugin/skills/security-scan/references/scan-results.md +15 -0
  67. package/_bundled_plugin/skills/security-scan/references/scoped-paths.md +23 -0
  68. package/_bundled_plugin/skills/security-scan/references/sdk-files.md +24 -0
  69. package/bin/codex-security.mjs +2 -2
  70. package/dist/api.d.ts +7 -1
  71. package/dist/api.d.ts.map +1 -1
  72. package/dist/api.js +459 -157
  73. package/dist/api.js.map +1 -1
  74. package/dist/armorcode-findings.d.ts +9 -0
  75. package/dist/armorcode-findings.d.ts.map +1 -0
  76. package/dist/armorcode-findings.js +145 -0
  77. package/dist/armorcode-findings.js.map +1 -0
  78. package/dist/artifact-export.d.ts +2 -0
  79. package/dist/artifact-export.d.ts.map +1 -1
  80. package/dist/artifact-export.js +29 -13
  81. package/dist/artifact-export.js.map +1 -1
  82. package/dist/auth.d.ts +6 -2
  83. package/dist/auth.d.ts.map +1 -1
  84. package/dist/auth.js +33 -12
  85. package/dist/auth.js.map +1 -1
  86. package/dist/batch-cost.d.ts +18 -0
  87. package/dist/batch-cost.d.ts.map +1 -0
  88. package/dist/batch-cost.js +41 -0
  89. package/dist/batch-cost.js.map +1 -0
  90. package/dist/blackduck-findings.d.ts +1 -1
  91. package/dist/blackduck-findings.d.ts.map +1 -1
  92. package/dist/blackduck-findings.js +5 -18
  93. package/dist/blackduck-findings.js.map +1 -1
  94. package/dist/bundled-plugin.d.ts +4 -0
  95. package/dist/bundled-plugin.d.ts.map +1 -0
  96. package/dist/bundled-plugin.js +23 -0
  97. package/dist/bundled-plugin.js.map +1 -0
  98. package/dist/classify-scan-severity.d.ts +1 -1
  99. package/dist/classify-scan-severity.d.ts.map +1 -1
  100. package/dist/classify-scan-severity.js +11 -3
  101. package/dist/classify-scan-severity.js.map +1 -1
  102. package/dist/classify-severity-diagnostics.d.ts +10 -0
  103. package/dist/classify-severity-diagnostics.d.ts.map +1 -0
  104. package/dist/classify-severity-diagnostics.js +57 -0
  105. package/dist/classify-severity-diagnostics.js.map +1 -0
  106. package/dist/classify-severity-records.d.ts +4 -0
  107. package/dist/classify-severity-records.d.ts.map +1 -1
  108. package/dist/classify-severity-records.js +35 -8
  109. package/dist/classify-severity-records.js.map +1 -1
  110. package/dist/classify-severity.d.ts.map +1 -1
  111. package/dist/classify-severity.js +9 -6
  112. package/dist/classify-severity.js.map +1 -1
  113. package/dist/cli-argument.d.ts +4 -0
  114. package/dist/cli-argument.d.ts.map +1 -0
  115. package/dist/cli-argument.js +17 -0
  116. package/dist/cli-argument.js.map +1 -0
  117. package/dist/cli-help.d.ts +1 -1
  118. package/dist/cli-help.d.ts.map +1 -1
  119. package/dist/cli-help.js +71 -29
  120. package/dist/cli-help.js.map +1 -1
  121. package/dist/cli-hook.d.ts +3 -0
  122. package/dist/cli-hook.d.ts.map +1 -0
  123. package/dist/cli-hook.js +87 -0
  124. package/dist/cli-hook.js.map +1 -0
  125. package/dist/cli-integrations.d.ts +13 -0
  126. package/dist/cli-integrations.d.ts.map +1 -0
  127. package/dist/cli-integrations.js +333 -0
  128. package/dist/cli-integrations.js.map +1 -0
  129. package/dist/cli-mcp.d.ts +15 -0
  130. package/dist/cli-mcp.d.ts.map +1 -0
  131. package/dist/cli-mcp.js +178 -0
  132. package/dist/cli-mcp.js.map +1 -0
  133. package/dist/cli-token-view.d.ts +10 -0
  134. package/dist/cli-token-view.d.ts.map +1 -0
  135. package/dist/cli-token-view.js +41 -0
  136. package/dist/cli-token-view.js.map +1 -0
  137. package/dist/cli.d.ts +8 -3
  138. package/dist/cli.d.ts.map +1 -1
  139. package/dist/cli.js +1860 -903
  140. package/dist/cli.js.map +1 -1
  141. package/dist/cloud-publish.d.ts.map +1 -1
  142. package/dist/cloud-publish.js +33 -31
  143. package/dist/cloud-publish.js.map +1 -1
  144. package/dist/codex-sdk-environment.d.ts +6 -0
  145. package/dist/codex-sdk-environment.d.ts.map +1 -1
  146. package/dist/codex-sdk-environment.js +19 -0
  147. package/dist/codex-sdk-environment.js.map +1 -1
  148. package/dist/command-words.d.ts +3 -0
  149. package/dist/command-words.d.ts.map +1 -0
  150. package/dist/command-words.js +46 -0
  151. package/dist/command-words.js.map +1 -0
  152. package/dist/component-plan.d.ts.map +1 -1
  153. package/dist/component-plan.js +3 -3
  154. package/dist/component-plan.js.map +1 -1
  155. package/dist/component-scan.d.ts +3 -1
  156. package/dist/component-scan.d.ts.map +1 -1
  157. package/dist/component-scan.js +40 -7
  158. package/dist/component-scan.js.map +1 -1
  159. package/dist/config.d.ts +1 -1
  160. package/dist/config.d.ts.map +1 -1
  161. package/dist/config.js +30 -1
  162. package/dist/config.js.map +1 -1
  163. package/dist/continuum-aws.d.ts +6 -0
  164. package/dist/continuum-aws.d.ts.map +1 -0
  165. package/dist/continuum-aws.js +202 -0
  166. package/dist/continuum-aws.js.map +1 -0
  167. package/dist/continuum-collector.d.ts +44 -0
  168. package/dist/continuum-collector.d.ts.map +1 -0
  169. package/dist/continuum-collector.js +266 -0
  170. package/dist/continuum-collector.js.map +1 -0
  171. package/dist/continuum-findings.d.ts +31 -2
  172. package/dist/continuum-findings.d.ts.map +1 -1
  173. package/dist/continuum-findings.js +497 -59
  174. package/dist/continuum-findings.js.map +1 -1
  175. package/dist/contract.d.ts +1 -0
  176. package/dist/contract.d.ts.map +1 -1
  177. package/dist/contract.js +3 -0
  178. package/dist/contract.js.map +1 -1
  179. package/dist/cost.d.ts.map +1 -1
  180. package/dist/cost.js +1 -45
  181. package/dist/cost.js.map +1 -1
  182. package/dist/crowdstrike-findings.d.ts +7 -0
  183. package/dist/crowdstrike-findings.d.ts.map +1 -0
  184. package/dist/crowdstrike-findings.js +210 -0
  185. package/dist/crowdstrike-findings.js.map +1 -0
  186. package/dist/custom-validation-prompt.d.ts +1 -1
  187. package/dist/custom-validation-prompt.d.ts.map +1 -1
  188. package/dist/custom-validation-prompt.js +29 -19
  189. package/dist/custom-validation-prompt.js.map +1 -1
  190. package/dist/deduplication/local.d.ts +3 -1
  191. package/dist/deduplication/local.d.ts.map +1 -1
  192. package/dist/deduplication/local.js +8 -1
  193. package/dist/deduplication/local.js.map +1 -1
  194. package/dist/deduplication/refusal.d.ts.map +1 -1
  195. package/dist/deduplication/refusal.js +2 -1
  196. package/dist/deduplication/refusal.js.map +1 -1
  197. package/dist/deduplication/scan.d.ts +2 -0
  198. package/dist/deduplication/scan.d.ts.map +1 -1
  199. package/dist/deduplication/scan.js +24 -7
  200. package/dist/deduplication/scan.js.map +1 -1
  201. package/dist/deep-scan.d.ts.map +1 -1
  202. package/dist/deep-scan.js +16 -15
  203. package/dist/deep-scan.js.map +1 -1
  204. package/dist/endor-findings.d.ts +2 -2
  205. package/dist/endor-findings.d.ts.map +1 -1
  206. package/dist/endor-findings.js +6 -23
  207. package/dist/endor-findings.js.map +1 -1
  208. package/dist/errors.d.ts +3 -1
  209. package/dist/errors.d.ts.map +1 -1
  210. package/dist/errors.js +7 -3
  211. package/dist/errors.js.map +1 -1
  212. package/dist/executable-path.d.ts +3 -0
  213. package/dist/executable-path.d.ts.map +1 -1
  214. package/dist/executable-path.js +26 -0
  215. package/dist/executable-path.js.map +1 -1
  216. package/dist/external-findings-import.d.ts.map +1 -1
  217. package/dist/external-findings-import.js +12 -1
  218. package/dist/external-findings-import.js.map +1 -1
  219. package/dist/external-findings-local.d.ts +66 -4
  220. package/dist/external-findings-local.d.ts.map +1 -1
  221. package/dist/external-findings-local.js +258 -59
  222. package/dist/external-findings-local.js.map +1 -1
  223. package/dist/external-findings-publish.d.ts +6 -1
  224. package/dist/external-findings-publish.d.ts.map +1 -1
  225. package/dist/external-findings-publish.js +330 -1633
  226. package/dist/external-findings-publish.js.map +1 -1
  227. package/dist/external-findings-read.d.ts +11 -2
  228. package/dist/external-findings-read.d.ts.map +1 -1
  229. package/dist/external-findings-read.js +56 -53
  230. package/dist/external-findings-read.js.map +1 -1
  231. package/dist/external-findings.d.ts +1 -1
  232. package/dist/external-findings.d.ts.map +1 -1
  233. package/dist/external-findings.js +12 -1
  234. package/dist/external-findings.js.map +1 -1
  235. package/dist/external-import-contract.d.ts +6 -11
  236. package/dist/external-import-contract.d.ts.map +1 -1
  237. package/dist/external-import-contract.js +35 -177
  238. package/dist/external-import-contract.js.map +1 -1
  239. package/dist/external-import-models.d.ts +1 -1
  240. package/dist/external-import-models.d.ts.map +1 -1
  241. package/dist/external-import-models.js.map +1 -1
  242. package/dist/finding-prompt.d.ts.map +1 -1
  243. package/dist/finding-prompt.js +2 -2
  244. package/dist/finding-prompt.js.map +1 -1
  245. package/dist/github-dependabot-findings.d.ts.map +1 -1
  246. package/dist/github-dependabot-findings.js +3 -4
  247. package/dist/github-dependabot-findings.js.map +1 -1
  248. package/dist/github-findings.d.ts.map +1 -1
  249. package/dist/github-findings.js +19 -287
  250. package/dist/github-findings.js.map +1 -1
  251. package/dist/host-protocol.d.ts +6 -0
  252. package/dist/host-protocol.d.ts.map +1 -1
  253. package/dist/host-protocol.js +11 -1
  254. package/dist/host-protocol.js.map +1 -1
  255. package/dist/host-records-protocol.d.ts +2 -0
  256. package/dist/host-records-protocol.d.ts.map +1 -1
  257. package/dist/host-records-protocol.js +4 -0
  258. package/dist/host-records-protocol.js.map +1 -1
  259. package/dist/hosted-remediation.d.ts +1 -0
  260. package/dist/hosted-remediation.d.ts.map +1 -1
  261. package/dist/hosted-remediation.js +23 -3
  262. package/dist/hosted-remediation.js.map +1 -1
  263. package/dist/index.d.ts +5 -3
  264. package/dist/index.d.ts.map +1 -1
  265. package/dist/index.js +3 -1
  266. package/dist/index.js.map +1 -1
  267. package/dist/inspector-findings.d.ts.map +1 -1
  268. package/dist/inspector-findings.js +19 -35
  269. package/dist/inspector-findings.js.map +1 -1
  270. package/dist/knowledge-base.d.ts +1 -1
  271. package/dist/knowledge-base.d.ts.map +1 -1
  272. package/dist/knowledge-base.js +34 -27
  273. package/dist/knowledge-base.js.map +1 -1
  274. package/dist/linear.d.ts +11 -0
  275. package/dist/linear.d.ts.map +1 -1
  276. package/dist/linear.js.map +1 -1
  277. package/dist/local-git-metadata.d.ts +5 -2
  278. package/dist/local-git-metadata.d.ts.map +1 -1
  279. package/dist/local-git-metadata.js +8 -4
  280. package/dist/local-git-metadata.js.map +1 -1
  281. package/dist/multiscan.d.ts +4 -0
  282. package/dist/multiscan.d.ts.map +1 -1
  283. package/dist/multiscan.js +83 -39
  284. package/dist/multiscan.js.map +1 -1
  285. package/dist/opengrep-findings.d.ts +4 -2
  286. package/dist/opengrep-findings.d.ts.map +1 -1
  287. package/dist/opengrep-findings.js +39 -22
  288. package/dist/opengrep-findings.js.map +1 -1
  289. package/dist/private-finding-import.d.ts +8 -13
  290. package/dist/private-finding-import.d.ts.map +1 -1
  291. package/dist/private-finding-import.js +69 -129
  292. package/dist/private-finding-import.js.map +1 -1
  293. package/dist/project-config-schema.d.ts +2 -0
  294. package/dist/project-config-schema.d.ts.map +1 -1
  295. package/dist/project-config-schema.js +1 -0
  296. package/dist/project-config-schema.js.map +1 -1
  297. package/dist/project-config.d.ts +1 -0
  298. package/dist/project-config.d.ts.map +1 -1
  299. package/dist/project-config.js +56 -13
  300. package/dist/project-config.js.map +1 -1
  301. package/dist/prompt-files.d.ts +7 -2
  302. package/dist/prompt-files.d.ts.map +1 -1
  303. package/dist/prompt-files.js +42 -20
  304. package/dist/prompt-files.js.map +1 -1
  305. package/dist/provider-profile.d.ts.map +1 -1
  306. package/dist/provider-profile.js +4 -9
  307. package/dist/provider-profile.js.map +1 -1
  308. package/dist/publication.d.ts +1 -1
  309. package/dist/publication.d.ts.map +1 -1
  310. package/dist/publication.js.map +1 -1
  311. package/dist/record.d.ts +1 -5
  312. package/dist/record.d.ts.map +1 -1
  313. package/dist/record.js +3 -51
  314. package/dist/record.js.map +1 -1
  315. package/dist/remediation.d.ts.map +1 -1
  316. package/dist/remediation.js +3 -1
  317. package/dist/remediation.js.map +1 -1
  318. package/dist/runtime.d.ts +35 -7
  319. package/dist/runtime.d.ts.map +1 -1
  320. package/dist/runtime.js +782 -153
  321. package/dist/runtime.js.map +1 -1
  322. package/dist/saved-scan-bootstrap.d.ts +6 -1
  323. package/dist/saved-scan-bootstrap.d.ts.map +1 -1
  324. package/dist/saved-scan-bootstrap.js +267 -115
  325. package/dist/saved-scan-bootstrap.js.map +1 -1
  326. package/dist/scan-archive-path.d.ts +2 -0
  327. package/dist/scan-archive-path.d.ts.map +1 -0
  328. package/dist/scan-archive-path.js +5 -0
  329. package/dist/scan-archive-path.js.map +1 -0
  330. package/dist/scan-comparison.d.ts +20 -2
  331. package/dist/scan-comparison.d.ts.map +1 -1
  332. package/dist/scan-comparison.js +26 -5
  333. package/dist/scan-comparison.js.map +1 -1
  334. package/dist/scan-dashboard.d.ts +1 -0
  335. package/dist/scan-dashboard.d.ts.map +1 -1
  336. package/dist/scan-dashboard.js +18 -2
  337. package/dist/scan-dashboard.js.map +1 -1
  338. package/dist/scan-executor.d.ts.map +1 -1
  339. package/dist/scan-executor.js +4 -2
  340. package/dist/scan-executor.js.map +1 -1
  341. package/dist/scan-history-renderer.d.ts +1 -0
  342. package/dist/scan-history-renderer.d.ts.map +1 -1
  343. package/dist/scan-history-renderer.js +25 -9
  344. package/dist/scan-history-renderer.js.map +1 -1
  345. package/dist/scan-logs.d.ts.map +1 -1
  346. package/dist/scan-logs.js +28 -4
  347. package/dist/scan-logs.js.map +1 -1
  348. package/dist/scan-settings.d.ts +1 -0
  349. package/dist/scan-settings.d.ts.map +1 -1
  350. package/dist/scan-settings.js +1 -0
  351. package/dist/scan-settings.js.map +1 -1
  352. package/dist/scanner-import.d.ts +5 -11
  353. package/dist/scanner-import.d.ts.map +1 -1
  354. package/dist/scanner-import.js +16 -89
  355. package/dist/scanner-import.js.map +1 -1
  356. package/dist/security-policy.d.ts.map +1 -1
  357. package/dist/security-policy.js +26 -6
  358. package/dist/security-policy.js.map +1 -1
  359. package/dist/semgrep-findings.d.ts.map +1 -1
  360. package/dist/semgrep-findings.js +14 -48
  361. package/dist/semgrep-findings.js.map +1 -1
  362. package/dist/semgrep-platform-findings.d.ts +20 -70
  363. package/dist/semgrep-platform-findings.d.ts.map +1 -1
  364. package/dist/semgrep-platform-findings.js +116 -333
  365. package/dist/semgrep-platform-findings.js.map +1 -1
  366. package/dist/severity-review.d.ts.map +1 -1
  367. package/dist/severity-review.js +1 -0
  368. package/dist/severity-review.js.map +1 -1
  369. package/dist/snyk-findings.d.ts +2 -0
  370. package/dist/snyk-findings.d.ts.map +1 -1
  371. package/dist/snyk-findings.js +5 -8
  372. package/dist/snyk-findings.js.map +1 -1
  373. package/dist/snyk-rest-findings.d.ts +3 -20
  374. package/dist/snyk-rest-findings.d.ts.map +1 -1
  375. package/dist/snyk-rest-findings.js +45 -217
  376. package/dist/snyk-rest-findings.js.map +1 -1
  377. package/dist/sonar-findings.d.ts +1 -1
  378. package/dist/sonar-findings.d.ts.map +1 -1
  379. package/dist/sonar-findings.js +2 -4
  380. package/dist/sonar-findings.js.map +1 -1
  381. package/dist/sonar-import.d.ts +3 -0
  382. package/dist/sonar-import.d.ts.map +1 -1
  383. package/dist/sonar-import.js +28 -30
  384. package/dist/sonar-import.js.map +1 -1
  385. package/dist/stored-finding-projection.d.ts +6 -0
  386. package/dist/stored-finding-projection.d.ts.map +1 -0
  387. package/dist/stored-finding-projection.js +129 -0
  388. package/dist/stored-finding-projection.js.map +1 -0
  389. package/dist/stored-findings-publication.d.ts +23 -0
  390. package/dist/stored-findings-publication.d.ts.map +1 -0
  391. package/dist/stored-findings-publication.js +169 -0
  392. package/dist/stored-findings-publication.js.map +1 -0
  393. package/dist/targets.d.ts +8 -1
  394. package/dist/targets.d.ts.map +1 -1
  395. package/dist/targets.js +103 -23
  396. package/dist/targets.js.map +1 -1
  397. package/dist/tenable-findings.d.ts +1 -4
  398. package/dist/tenable-findings.d.ts.map +1 -1
  399. package/dist/tenable-findings.js.map +1 -1
  400. package/dist/trivy-findings.d.ts.map +1 -1
  401. package/dist/trivy-findings.js +0 -11
  402. package/dist/trivy-findings.js.map +1 -1
  403. package/dist/trusted-executable.d.ts +7 -0
  404. package/dist/trusted-executable.d.ts.map +1 -1
  405. package/dist/trusted-executable.js +148 -37
  406. package/dist/trusted-executable.js.map +1 -1
  407. package/dist/value.js +3 -1
  408. package/dist/value.js.map +1 -1
  409. package/dist/veracode-findings.d.ts +1 -3
  410. package/dist/veracode-findings.d.ts.map +1 -1
  411. package/dist/veracode-findings.js +13 -38
  412. package/dist/veracode-findings.js.map +1 -1
  413. package/dist/version.d.ts +3 -1
  414. package/dist/version.d.ts.map +1 -1
  415. package/dist/version.js +184 -32
  416. package/dist/version.js.map +1 -1
  417. package/dist/wiz-findings.d.ts +2 -2
  418. package/dist/wiz-findings.d.ts.map +1 -1
  419. package/dist/wiz-findings.js +14 -92
  420. package/dist/wiz-findings.js.map +1 -1
  421. package/docs/classify-severity-records.md +30 -0
  422. package/docs/cli.md +537 -124
  423. package/docs/findings-service.md +22 -9
  424. package/docs/hosted-remediation.md +13 -4
  425. package/docs/sdk.md +918 -0
  426. package/package.json +15 -6
  427. package/schemas/external-findings.schema.json +2 -1
  428. package/schemas/project-config.schema.json +5 -0
  429. package/dist/hosted-scanner-v1.d.ts +0 -6
  430. package/dist/hosted-scanner-v1.d.ts.map +0 -1
  431. package/dist/hosted-scanner-v1.js +0 -60
  432. package/dist/hosted-scanner-v1.js.map +0 -1
  433. package/dist/reader-selection.d.ts +0 -15
  434. package/dist/reader-selection.d.ts.map +0 -1
  435. package/dist/reader-selection.js +0 -89
  436. package/dist/reader-selection.js.map +0 -1
  437. package/dist/semgrep-platform-v1.d.ts +0 -6
  438. package/dist/semgrep-platform-v1.d.ts.map +0 -1
  439. package/dist/semgrep-platform-v1.js +0 -83
  440. package/dist/semgrep-platform-v1.js.map +0 -1
  441. package/dist/snyk-rest-v1.d.ts +0 -28
  442. package/dist/snyk-rest-v1.d.ts.map +0 -1
  443. package/dist/snyk-rest-v1.js +0 -132
  444. package/dist/snyk-rest-v1.js.map +0 -1
package/dist/cli.js CHANGED
@@ -20,53 +20,58 @@ import { execFile as execFileCallback, execFileSync, spawn, } from "node:child_p
20
20
  import { createHash, randomUUID } from "node:crypto";
21
21
  import { errorMonitor } from "node:events";
22
22
  import { accessSync, constants, createReadStream, existsSync, lstatSync, realpathSync, writeSync, } from "node:fs";
23
- import { chmod, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rm, writeFile, } from "node:fs/promises";
23
+ import { chmod, lstat, mkdtemp, open, readFile, readdir, readlink, realpath, rm, writeFile, } from "node:fs/promises";
24
24
  import { tmpdir } from "node:os";
25
- import { basename, dirname, isAbsolute, join, parse, relative, resolve, win32, } from "node:path";
25
+ import { basename, dirname, extname, isAbsolute, join, parse, relative, resolve, sep, win32, } from "node:path";
26
26
  import { cwd } from "node:process";
27
27
  import { createInterface } from "node:readline";
28
28
  import { Readable, Writable as NodeWritable } from "node:stream";
29
29
  import { fileURLToPath, pathToFileURL } from "node:url";
30
30
  import { isDeepStrictEqual, parseArgs, promisify, stripVTControlCharacters, } from "node:util";
31
31
  import { Cli, Formatter, z } from "incur";
32
+ import { completeCli, completionShell, serveIntegration, } from "./cli-integrations.js";
32
33
  import stringWidth from "string-width";
33
34
  import Ajv2020 from "ajv/dist/2020.js";
34
35
  import { formatCliHelp } from "./cli-help.js";
35
- import { formatCoverageScope } from "./coverage-presentation.js";
36
+ import { formatJsonTokenView } from "./cli-token-view.js";
37
+ import { formatCoverageScope, formatScopePath, } from "./coverage-presentation.js";
36
38
  import { resolveSkillAuthentication } from "./skill-authentication.js";
37
39
  import { scanLogsJson } from "./cli-scan-logs-json.js";
38
- import { ARTIFACT_EXPORT_FILENAMES, exportEnvironment, resolveArtifactFormat, resolveArtifactExportOutput, resolveSavedArtifactDirectory, runArtifactExport, writeArtifactOutput as writeCliOutput, } from "./artifact-export.js";
40
+ import { ARTIFACT_EXPORT_FILENAMES, exportEnvironment, resolveArtifactFormat, artifactSourceProtectionRoots, resolveArtifactExportOutput, resolveSavedArtifactDirectory, runArtifactExport, writeArtifactOutput as writeCliOutput, } from "./artifact-export.js";
39
41
  export { exportEnvironment } from "./artifact-export.js";
40
42
  import { parse as parseToml } from "smol-toml";
41
- import { classifyConnectionFailure, CodexSecurity, environmentValue, formatEnvironmentVariableRemovalGuidance, initialCredentialsAvailable, scanCodexHome, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, runtimeScanAuthentication, selectedScanEnvironment, } from "./api.js";
42
- import { accountStatus, CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, configuredCodexHome, environmentEntry, readCodexHomeConfig, withoutOpenAiApiKeys, } from "./auth.js";
43
+ import { classifyConnectionFailure, connectionAdviceDetail, CodexSecurity, environmentValue, formatEnvironmentVariableRemovalGuidance, initialCredentialsAvailable, scanCodexHome, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, runtimeScanAuthentication, selectedScanEnvironment, } from "./api.js";
44
+ import { accountStatus, nativeLogoutArgs, prepareLoginConfig, NO_CREDENTIALS_MESSAGE, configuredCodexHome, environmentEntry, readCodexHomeConfig, withoutOpenAiApiKeys, } from "./auth.js";
43
45
  import { loadContract, sha256Text } from "./contract.js";
44
46
  import { formatDeepScanReviews, } from "./scan-progress.js";
45
- import { isRecord as isJsonObject } from "./record.js";
47
+ import { asRecord, isRecord as isJsonObject } from "./record.js";
46
48
  import { suggestOwnersInternal } from "./suggest-owners.js";
47
49
  import { parseImportedFindings } from "./findings-import.js";
48
50
  import { publishScanToCustom } from "./custom-publish.js";
49
51
  import { ExternalPublicationError, prepareExternalPublication, } from "./external-findings-publish.js";
50
52
  import { prepareLocalExternalImport } from "./external-findings-import.js";
53
+ import { collectContinuumFinding, collectContinuumIssues, continuumEnvironmentId, continuumFindingId, continuumImportOutput, } from "./continuum-collector.js";
51
54
  import { validateInspectorProjectMapping } from "./inspector-findings.js";
52
- import { listLocalExternalFindings, } from "./external-findings-local.js";
55
+ import { readLocalExternalFindings, } from "./external-findings-local.js";
53
56
  import { prepareSonarImport } from "./sonar-import.js";
54
57
  import { EXTERNAL_FINDINGS_PROVIDERS, EXTERNAL_FINDINGS_READERS, requireCloudReader, } from "./external-findings-read.js";
55
58
  import { externalImportDisposition, NoPublishableFindingsError, } from "./external-findings.js";
56
59
  import { publishPatchReview, resolvePatchReviewPublisher, } from "./patch-publication.js";
57
60
  import { DEFAULT_DEDUPE_CONCURRENCY } from "./deduplication/deduplication.js";
58
- import { savedScanWorkbench } from "./saved-scan-bootstrap.js";
61
+ import { savedCheckoutBoundaries, savedDiscoveryRoots, savedScanWorkbench, } from "./saved-scan-bootstrap.js";
59
62
  import { deduplicateScanInternal } from "./deduplication/scan.js";
63
+ import { createSeverityDiagnostics, severityDiagnosticsEnabled, } from "./classify-severity-diagnostics.js";
60
64
  import { runHostRecordsProtocol } from "./host-records-protocol.js";
61
65
  import { runHostedScanProtocol } from "./hosted-scan-protocol.js";
62
66
  import { runHostedRemediationProtocol } from "./hosted-remediation-protocol.js";
63
- import { FindingPatchSchema as findingPatchSchema, parseFindingVerifications, remediationPrompt, verificationBatches, VerificationModeSchema, } from "./remediation.js";
67
+ import { FindingPatchSchema as findingPatchSchema, parseFindingVerifications, remediationPrompt, verificationBatches, VerificationModeSchema, FindingPatchSchema, FindingVerificationSchema, } from "./remediation.js";
64
68
  import { classifyScanSeverityInternal, classifyScanDirectorySeverityInternal, } from "./classify-scan-severity.js";
65
69
  import { resolveCompletedScan, resolveWorkflowScan, } from "./saved-scan.js";
66
70
  import { publishFindingsCsvToCloud, publishScanToCloud, } from "./cloud-publish.js";
67
71
  import { createBulkScanDiscoveryDependencies, createTerminalPrompt, runBulkScanWizard, } from "./bulk-scan-discovery.js";
68
- import { DEFAULT_CODEX_CONFIG, deepMerge, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergeCodexOverrides, hasCommandAuth, inlineToml, quoteTomlString, modelProviderConfigOverride, resolveCommandAuthConfig, resolveCodexProfile, mergedCodexConfig, readCodexFileProfile, scanPricingContext, scanModel, scanModelConfiguration, scanModelProvider, scanProviderEnvKey, writeCodexConfig, } from "./config.js";
72
+ import { CODEX_AUTH_CONFIG_KEYS, DEFAULT_CODEX_CONFIG, deepMerge, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergeCodexOverrides, hasCommandAuth, inlineToml, quoteTomlString, modelProviderConfigOverride, resolveCommandAuthConfig, resolveCodexProfile, mergedCodexConfig, readCodexAuthConfig, readCodexFileProfile, scanPricingContext, scanModel, scanModelConfiguration, scanModelProvider, scanProviderEnvKey, writeCodexConfig, } from "./config.js";
69
73
  import { formatUsd } from "./cost.js";
74
+ import { batchScanBudget } from "./batch-cost.js";
70
75
  import { formatScanCost, formatScanCostTokens, formatTokenUsage, } from "./cost-model.js";
71
76
  import { readRegularInputFile, resolveScanPrompts } from "./prompt-files.js";
72
77
  import { prepareFindingPrompt } from "./finding-prompt.js";
@@ -87,8 +92,8 @@ import { componentPlanSchema } from "./component-plan.js";
87
92
  import { runComponentScans, } from "./component-scan.js";
88
93
  import { checkScanPublication, forceTerminatePublicationProcesses as terminatePublishers, publishScanInternal, } from "./publish.js";
89
94
  import { importScan } from "./import-scan.js";
90
- import { bundledPluginRoot, cleanupSdkDirectory, createIsolatedHome, resolvePluginPath, acquireCodexSecurityCredentialHomeLock, withCredentialHomeLock, requireOutputOutsideRepositories, canonicalizeModelSafePath, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, logoutCredentialHome, executablePathForSpawn, environmentWithGit, expandHome, prepareCodexSecurityCredentialHome, resolveCodexCommand, resolvePluginPython, pluginMetadata, runWorkbench, workbenchEnvironment, sameFile, setCodexSecurityCredentialLogout, } from "./runtime.js";
91
- import { comparisonFindingGroups, selectedComparisonContext, comparisonForScan, matchScanFindingsInternal, unionFindingGroups, } from "./scan-comparison.js";
95
+ import { bundledPluginRoot, runCodexCommand, cleanupSdkDirectory, createIsolatedHome, resolvePluginPath, acquireCodexSecurityCredentialHomeLock, withCredentialHomeLock, writeCredentialHomeConfig, requireOutputOutsideRepositories, canonicalizeModelSafePath, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, logoutCredentialHome, executablePathForSpawn, environmentWithGit, isPythonPathCandidate, expandHome, resolveInputPath, resolveParentTraversal, prepareCodexSecurityCredentialHome, resolveCodexCommand, resolvePluginPython, pluginMetadata, runWorkbench, workbenchEnvironment, setCodexSecurityCredentialLogout, } from "./runtime.js";
96
+ import { comparisonFindingGroups, resolveMatchingBatch, selectedComparisonContext, comparisonForScan, matchScanFindingsInternal, unionFindingGroups, } from "./scan-comparison.js";
92
97
  import { scanActivitiesFromEvent } from "./scan-activity.js";
93
98
  import { OperationTelemetry, } from "./operation-telemetry.js";
94
99
  import { codexSecurityRequestContext } from "./request-metadata.js";
@@ -101,12 +106,14 @@ import { fitCell, graphemes } from "./terminal-columns.js";
101
106
  import { TerminalErrorListener, } from "./terminal-stream.js";
102
107
  import { ACCOUNT_LIMITS_UNAVAILABLE, formatAccountLimits, formatUsageFreshness, isChatGptAuthentication, USAGE_TIME_UNAVAILABLE, } from "./scan-usage-display.js";
103
108
  import { policyDisplayData, runPolicyCommand, } from "./security-policy-cli.js";
109
+ import { installManagedHook } from "./cli-hook.js";
110
+ import { cliShellLabel, quoteCliPath } from "./cli-argument.js";
104
111
  import { formatSecurityPolicyText as escapeTerminalText } from "./security-policy.js";
105
112
  import { commandGitProtectionRoots } from "./local-git-metadata.js";
106
113
  import { scanPhaseLabel as scanPhase, scanProgressCount, } from "./worker-progress.js";
107
- import { abortable, DiffTarget, enclosingGitWorktreeRoots, gitMarkerRoot, normalizeRepository, trustedGitCommand, UNSUPPORTED_GIT_ENVIRONMENT, relativePathIsOutside as isOutsidePath, } from "./targets.js";
114
+ import { abortable, DiffTarget, resolveRepositoryPath, enclosingGitWorktreeRoots, gitMarkerRoot, normalizeRepository, trustedGitCommand, relativePathIsOutside as isOutsidePath, } from "./targets.js";
108
115
  import { inspectTrustedExecutable, resolveTrustedExecutable, } from "./trusted-executable.js";
109
- import { BUNDLED_PLUGIN_VERSION, checkForUpdate, CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION, formatUpdateNotice, updateNoticeEnabled, VERSION, } from "./version.js";
116
+ import { BUNDLED_PLUGIN_VERSION, checkForUpdate, CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION, formatUpdateNotice, installUpdate, invokedWithNpx, updateNoticeEnabled, VERSION, } from "./version.js";
110
117
  import { readProjectConfig, resolveScanSettings, projectScopeTarget, configurationSources, projectConfigStarter, } from "./project-config.js";
111
118
  import { resolveConfigPath } from "./config-path.js";
112
119
  import { deepScanOptions, resolveDeepScanConfig } from "./deep-config.js";
@@ -122,6 +129,14 @@ const FRAMEWORK_VALUE_OPTIONS = new Set([
122
129
  "--token-limit",
123
130
  "--token-offset",
124
131
  ]);
132
+ const INSPECTION_FLAGS = [
133
+ "-h",
134
+ "--help",
135
+ "--schema",
136
+ "--version",
137
+ "--llms",
138
+ "--llms-full",
139
+ ];
125
140
  const OUTPUT_OPTION = /^--(?:format|filter-output|full-output|token-count|token-limit|token-offset)(?:=|$)/u;
126
141
  const HIDE_CURSOR = "\u001B[?25l";
127
142
  const SHOW_CURSOR = "\u001B[?25h";
@@ -129,7 +144,12 @@ const CHILD_TERMINATION_GRACE_MS = 1_000;
129
144
  const DUPLICATE_SIGNAL_WINDOW_MS = 500;
130
145
  const DEFAULT_SCAN_MODEL_CONFIGURATION = scanModelConfiguration(DEFAULT_CODEX_CONFIG);
131
146
  const MODEL_OPTIONS = modelOptions();
132
- const MATCHING_MODEL_OPTIONS = modelOptions("Model for finding matching (default: Codex's configured model).", "Matching reasoning effort (default: medium).");
147
+ const MATCHING_OPTIONS = modelOptions("Model for finding matching (default: Codex's configured model).", "Matching reasoning effort (default: medium).").extend({
148
+ force: z
149
+ .boolean()
150
+ .default(false)
151
+ .describe("Recompute saved finding matches."),
152
+ });
133
153
  const SKILL_CODEX_OVERRIDE_DESCRIPTION = 'Repeat TOML model="gpt-5.6-terra", model_reasoning_effort="high", model_provider="gateway", model_providers.<name>.<key>=VALUE, daybreak=true, or analytics.enabled=false.';
134
154
  const SKILL_CONFIG_OPTIONS = MODEL_OPTIONS.extend({
135
155
  codex: z
@@ -185,7 +205,13 @@ const ASSESS_PATCH_RISK_OPTION = z
185
205
  .default(false)
186
206
  .describe("Assess the completed patch and return the risk report.");
187
207
  function optionValue(flag) {
188
- return z.string().min(1, `${flag} must not be empty.`);
208
+ return z
209
+ .string({
210
+ error: (issue) => issue.input === undefined
211
+ ? `Missing required option ${flag}.`
212
+ : undefined,
213
+ })
214
+ .min(1, `${flag} must not be empty.`);
189
215
  }
190
216
  function remediationInputOptions(verb) {
191
217
  return z.object({
@@ -220,7 +246,10 @@ function linearApiKeyOption() {
220
246
  .describe("Linear personal API key; defaults to CODEX_SECURITY_LINEAR_API_KEY.");
221
247
  }
222
248
  const PUBLICATION_DESTINATION_OPTIONS = z.object({
223
- to: z.literal("linear").describe("Publication destination."),
249
+ to: z
250
+ .literal("linear")
251
+ .default("linear")
252
+ .describe("Publication destination."),
224
253
  linearTeam: optionValue("--linear-team")
225
254
  .optional()
226
255
  .describe("Linear team ID; defaults to CODEX_SECURITY_LINEAR_TEAM."),
@@ -714,15 +743,84 @@ const DEEP_SCAN_OPTION_SCHEMAS = Object.fromEntries(DEEP_SCAN_SETTINGS.flatMap((
714
743
  export function resolveCliPath(directory, value) {
715
744
  return resolveConfigPath(directory, value);
716
745
  }
746
+ const jsonDocument = z.record(z.string(), z.unknown());
747
+ const scanArtifactFields = {
748
+ manifest: jsonDocument,
749
+ findings: jsonDocument,
750
+ review: jsonDocument,
751
+ scanDir: z.string(),
752
+ reportPath: z.string(),
753
+ };
754
+ const retainedScanOutput = z.object({
755
+ ...scanArtifactFields,
756
+ mode: z.string(),
757
+ });
758
+ const completedScanOutput = z.looseObject({
759
+ ...scanArtifactFields,
760
+ artifactsDir: z.string(),
761
+ sarifPath: z.string().nullable(),
762
+ threadId: z.string(),
763
+ turn: jsonDocument,
764
+ cost: jsonDocument.nullable(),
765
+ threatModel: jsonDocument.nullable(),
766
+ threatModelPath: z.string().nullable(),
767
+ repositoryFindings: z.array(jsonDocument).optional(),
768
+ ownerSuggestionsPath: z.string().optional(),
769
+ ownerSuggestionsError: z.string().optional(),
770
+ validation: jsonDocument.optional(),
771
+ warnings: z.array(z.string()).optional(),
772
+ patchSeverity: FailureSeveritySchema.optional(),
773
+ patches: z.array(FindingPatchSchema).optional(),
774
+ pullRequest: jsonDocument.optional(),
775
+ });
776
+ const scanPreflightOutput = z.looseObject({
777
+ ...DeepScanSettingsSchema.shape,
778
+ dryRun: z.literal(true),
779
+ repository: z.string(),
780
+ target: z.object({
781
+ kind: z.enum(["repository", "paths", "refs", "working_tree"]),
782
+ paths: z.array(z.string()),
783
+ base: z.string().optional(),
784
+ head: z.string().optional(),
785
+ baseRef: z.string().optional(),
786
+ headRef: z.string().optional(),
787
+ }),
788
+ mode: ScanSettingsSchema.shape.mode.unwrap(),
789
+ model: z.string(),
790
+ reasoningEffort: z.string(),
791
+ modelProvider: z.string().optional(),
792
+ outputDir: z.string().nullable(),
793
+ stateDirectory: z.string().optional(),
794
+ archiveDir: z.string().optional(),
795
+ authentication: z.looseObject({
796
+ method: z.string(),
797
+ verified: z.literal(false),
798
+ }),
799
+ maxTimeMinutes: ScanSettingsSchema.shape.maxTimeMinutes,
800
+ maxCostUsd: ScanSettingsSchema.shape.maxCostUsd,
801
+ costLimitNote: z.string().optional(),
802
+ knowledgeBasePaths: ScanSettingsSchema.shape.knowledgeBasePaths,
803
+ excludePaths: ScanSettingsSchema.shape.excludePaths,
804
+ scanPromptFile: ScanSettingsSchema.shape.scanPromptFile,
805
+ validationPromptFile: ScanSettingsSchema.shape.validationPromptFile,
806
+ failOnSeverity: FailureSeveritySchema.optional(),
807
+ projectConfig: jsonDocument.optional(),
808
+ deepScanSources: jsonDocument.optional(),
809
+ });
810
+ function cliFailureSchema(...codes) {
811
+ return z.object({
812
+ status: z.literal("failed"),
813
+ code: z.literal(codes),
814
+ message: z.string(),
815
+ });
816
+ }
717
817
  function scanOutputSchema(...codes) {
718
818
  return z
719
819
  .union([
720
- z.record(z.string(), z.unknown()),
721
- z.object({
722
- status: z.literal("failed"),
723
- code: z.literal(codes),
724
- message: z.string(),
725
- }),
820
+ completedScanOutput,
821
+ retainedScanOutput,
822
+ scanPreflightOutput,
823
+ cliFailureSchema(...codes),
726
824
  ])
727
825
  .optional();
728
826
  }
@@ -802,9 +900,11 @@ const DEFAULT_DEPENDENCIES = {
802
900
  exportFindings: runArtifactExport,
803
901
  runWorkbench: async (args, input, signal, pythonPath, protectedRoot, gitProtectedRoots = [], pluginPath) => {
804
902
  const checkingTarget = args[0] === "get-scan" && args.includes("--check-target");
903
+ const configuredGit = environmentEntry(process.env, "CODEX_SECURITY_GIT");
805
904
  let environment = !checkingTarget || protectedRoot === undefined
806
905
  ? {
807
906
  ...exportEnvironment(),
907
+ CODEX_SECURITY_GIT: configuredGit,
808
908
  CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
809
909
  }
810
910
  : workbenchEnvironment(process.env);
@@ -813,18 +913,30 @@ const DEFAULT_DEPENDENCIES = {
813
913
  : typeof protectedRoot === "string"
814
914
  ? [protectedRoot]
815
915
  : protectedRoot).map(async (root) => (await gitMarkerRoot(root, signal, "outermost")) ?? root));
916
+ const configuredPython = pythonPath ?? environmentEntry(environment, "PYTHON");
917
+ const boundaries = configuredPython && isPythonPathCandidate(configuredPython)
918
+ ? undefined
919
+ : await savedCheckoutBoundaries(environment);
816
920
  const python = await resolvePluginPython({
817
921
  configuredPath: pythonPath,
818
922
  environment,
819
923
  signal,
820
924
  protectedRoot: protectedRoot === undefined ? undefined : protectedRoots,
925
+ discoveryProtectedRoots: boundaries
926
+ ? await savedDiscoveryRoots(boundaries, [...boundaries.byTarget.keys()], signal)
927
+ : undefined,
928
+ allowPathLookup: boundaries?.complete,
821
929
  });
822
- if (checkingTarget && protectedRoot !== undefined) {
823
- const git = await inspectTrustedExecutable("git", environment, [
824
- ...protectedRoots,
825
- ...gitProtectedRoots,
826
- ]);
827
- environment = environmentWithGit(git.environment, git);
930
+ if (checkingTarget &&
931
+ gitProtectedRoots.length > 0 &&
932
+ (configuredGit === undefined || isAbsolute(configuredGit))) {
933
+ const git = await inspectTrustedExecutable(configuredGit ?? "git", environment, [...protectedRoots, ...gitProtectedRoots]);
934
+ // Filter knowledge-base tools, then let the workbench choose ambient Git
935
+ // after it also knows the boundaries recorded in the history database.
936
+ environment =
937
+ configuredGit !== undefined || git.executable === null
938
+ ? environmentWithGit(git.environment, git)
939
+ : git.environment;
828
940
  }
829
941
  const workspace = pluginPath === undefined
830
942
  ? undefined
@@ -851,6 +963,8 @@ function signalHandlers(dependencies, operation, interrupt, terminate) {
851
963
  dependencies[`${operation}SignalListener`]("SIGINT", interrupt);
852
964
  dependencies[`${operation}SignalListener`]("SIGTERM", terminate);
853
965
  }
966
+ // Login and status must not load configuration from the caller's checkout.
967
+ const NEUTRAL_CODEX_CWD = parse(process.execPath).root;
854
968
  export async function runCodexSkillCommand(args, output, command = resolveCodexCommand(), processEnvironment = process.env, input) {
855
969
  let journal = null;
856
970
  if (output !== undefined) {
@@ -967,7 +1081,7 @@ async function runCodexSkillProcess(args, output, command, processEnvironment, i
967
1081
  credentialConfig["model_providers"] = {
968
1082
  [provider]: providerConfiguration,
969
1083
  };
970
- await writeCodexConfig(join(codexHome, "config.toml"), credentialConfig);
1084
+ await writeCredentialHomeConfig(codexHome, credentialConfig);
971
1085
  credentialsAvailable = await initialCredentialsAvailable(selected, configuredCodexHome(selected), codexHome);
972
1086
  selected = {
973
1087
  ...selected,
@@ -1050,11 +1164,9 @@ async function runCodexSkillProcess(args, output, command, processEnvironment, i
1050
1164
  output?.signal?.throwIfAborted();
1051
1165
  const invocation = spawn(executablePathForSpawn(command.command), [...args], {
1052
1166
  env: environment,
1053
- cwd: output?.appServer?.directory ?? parse(process.execPath).root,
1167
+ cwd: output?.appServer?.directory ?? NEUTRAL_CODEX_CWD,
1054
1168
  stdio: output === undefined
1055
- ? input === undefined
1056
- ? "inherit"
1057
- : ["pipe", "inherit", "inherit"]
1169
+ ? [input === undefined ? "inherit" : "pipe", "inherit", "pipe"]
1058
1170
  : [
1059
1171
  output.appServer !== undefined || input !== undefined
1060
1172
  ? "pipe"
@@ -1111,13 +1223,19 @@ async function runCodexSkillProcess(args, output, command, processEnvironment, i
1111
1223
  process.on("SIGTERM", onTerminate);
1112
1224
  try {
1113
1225
  let diagnostic = "";
1114
- invocation.stderr?.setEncoding("utf8").on("data", (chunk) => {
1115
- diagnostic += chunk;
1116
- });
1117
- const captured = output === undefined || invocation.stdout === null
1118
- ? Promise.resolve(undefined)
1119
- : Promise.race([
1120
- readSkillCommandOutput(invocation.stdout, output.appServer === undefined
1226
+ let forwarded;
1227
+ if (output === undefined && invocation.stderr) {
1228
+ forwarded = forwardSignInHints(invocation.stderr, processEnvironment);
1229
+ }
1230
+ else {
1231
+ invocation.stderr?.setEncoding("utf8").on("data", (chunk) => {
1232
+ diagnostic += chunk;
1233
+ });
1234
+ }
1235
+ const captured = Promise.race([
1236
+ output === undefined || invocation.stdout === null
1237
+ ? forwarded?.then(() => undefined)
1238
+ : readSkillCommandOutput(invocation.stdout, output.appServer === undefined
1121
1239
  ? undefined
1122
1240
  : {
1123
1241
  ...output.appServer,
@@ -1126,10 +1244,10 @@ async function runCodexSkillProcess(args, output, command, processEnvironment, i
1126
1244
  onThreadStarted: releaseCredentialHome,
1127
1245
  input: invocation.stdin,
1128
1246
  }),
1129
- new Promise((resolve) => {
1130
- forceCaptureCompletion = () => resolve(undefined);
1131
- }),
1132
- ]);
1247
+ new Promise((resolve) => {
1248
+ forceCaptureCompletion = () => resolve(undefined);
1249
+ }),
1250
+ ]);
1133
1251
  invocationStatus = new Promise((resolve, reject) => {
1134
1252
  const complete = (code, signal) => {
1135
1253
  resolve(requestedSignal === "SIGINT" || signal === "SIGINT"
@@ -1178,6 +1296,10 @@ async function runCodexSkillProcess(args, output, command, processEnvironment, i
1178
1296
  invocation.stderr?.destroy();
1179
1297
  requestTermination("SIGTERM");
1180
1298
  await invocationStatus?.catch(() => undefined);
1299
+ // The sign-in diagnostic stream is closed; a second diagnostic cannot be delivered.
1300
+ if (output === undefined &&
1301
+ error?.code === "EPIPE")
1302
+ return 1;
1181
1303
  throw error;
1182
1304
  }
1183
1305
  finally {
@@ -1194,6 +1316,32 @@ async function runCodexSkillProcess(args, output, command, processEnvironment, i
1194
1316
  await releaseCredentialHome?.();
1195
1317
  }
1196
1318
  }
1319
+ /** Forward native prompts immediately, including commands split across stderr writes. */
1320
+ async function forwardSignInHints(stderr, environment) {
1321
+ const cli = invokedWithNpx(environment)
1322
+ ? "npx @openai/codex-security"
1323
+ : "codex-security";
1324
+ const hints = ["`codex login", "| codex login"];
1325
+ const rewrite = (text) => text.replace(/(`|\| )codex login(?=[\s`]|$)/gu, `$1${cli} login`);
1326
+ let pending = "";
1327
+ for await (const chunk of stderr.setEncoding("utf8")) {
1328
+ let text = pending + chunk;
1329
+ pending = "";
1330
+ // Hold only a partial command at the end of this chunk.
1331
+ const start = Math.max(text.lastIndexOf("`"), text.lastIndexOf("|"));
1332
+ if (start >= 0) {
1333
+ const tail = text.slice(start);
1334
+ if (hints.some((hint) => hint.startsWith(tail))) {
1335
+ pending = tail;
1336
+ text = text.slice(0, start);
1337
+ }
1338
+ }
1339
+ if (text)
1340
+ await writeCliOutput(process.stderr, rewrite(text));
1341
+ }
1342
+ if (pending)
1343
+ await writeCliOutput(process.stderr, rewrite(pending));
1344
+ }
1197
1345
  /**
1198
1346
  * Stored auth switches homes. Native origins preserve ambient settings at
1199
1347
  * app-server startup, including telemetry controls and model discovery gates.
@@ -1340,76 +1488,41 @@ function handleDisconnectedResize(error) {
1340
1488
  process.stderr.once("error", () => { });
1341
1489
  }
1342
1490
  }
1343
- export async function main(argv = process.argv.slice(2), output = process.stdout, errorOutput = process.stderr, dependencies = DEFAULT_DEPENDENCIES) {
1344
- const remediationOperation = argv[0] === "patch"
1345
- ? "patch"
1346
- : argv[0] === "verify-fix"
1347
- ? "verify"
1348
- : undefined;
1349
- const recordsCommand = argv[0] === "dedupe" ||
1350
- argv[0] === "validate" ||
1351
- argv[0] === "classify-severity"
1352
- ? argv[0]
1353
- : undefined;
1354
- const hostedCommand = argv[0] === "scan" || remediationOperation !== undefined;
1355
- if (((recordsCommand !== undefined && argv.includes("--records")) ||
1356
- (hostedCommand &&
1357
- argv.some((arg) => arg === "--host" || arg.startsWith("--host=")))) &&
1358
- !argv.includes("--help") &&
1359
- !argv.includes("-h") &&
1360
- !argv.includes("--schema")) {
1361
- let classificationRuns;
1362
- if (argv[0] === "classify-severity") {
1363
- try {
1364
- const { values } = parseArgs({
1365
- args: argv.slice(1),
1366
- options: {
1367
- records: { type: "boolean" },
1368
- runs: { type: "string" },
1369
- },
1370
- });
1371
- if (values.runs !== undefined)
1372
- classificationRuns = reviewRunsOption.parse(Number(values.runs));
1373
- }
1374
- catch {
1375
- errorOutput.write(`codex-security: Use --records with only --runs (an integer from 1 to 10; default: ${DEFAULT_REVIEW_RUNS}).\n`);
1376
- return 2;
1377
- }
1378
- }
1379
- else if (argv.length !== 2 || (hostedCommand && argv[1] !== "--host")) {
1380
- errorOutput.write(hostedCommand
1381
- ? `codex-security: --host must be used alone with ${argv[0]}.\n`
1382
- : `codex-security: --records must be used alone with ${argv[0]}.\n`);
1383
- return 2;
1384
- }
1385
- const controller = new AbortController();
1386
- const removeSignals = listenForAbort(dependencies, controller);
1387
- let exitCode;
1388
- try {
1389
- const input = dependencies.recordsInput ?? process.stdin;
1390
- const code = recordsCommand !== undefined
1391
- ? await runHostRecordsProtocol(recordsCommand, input, output, {
1392
- signal: controller.signal,
1393
- classificationRuns,
1394
- })
1395
- : remediationOperation !== undefined
1396
- ? await runHostedRemediationProtocol(input, output, controller.signal, remediationOperation)
1397
- : await runHostedScanProtocol(input, output, controller.signal);
1398
- exitCode =
1399
- controller.signal.reason === "SIGINT"
1400
- ? 130
1401
- : controller.signal.reason === "SIGTERM"
1402
- ? 143
1403
- : code;
1404
- }
1405
- finally {
1406
- removeSignals();
1407
- }
1408
- // Protocol writes have flushed or been canceled. Node's stdout ignores destroy().
1409
- if (output === process.stdout)
1410
- process.exit(exitCode);
1411
- return exitCode;
1412
- }
1491
+ /** Run the standalone CLI, which owns the process and its stdio. */
1492
+ export async function runCli() {
1493
+ let signInInterrupted = false;
1494
+ const exitCode = await main(process.argv.slice(2), process.stdout, process.stderr, DEFAULT_DEPENDENCIES, () => {
1495
+ signInInterrupted = true;
1496
+ });
1497
+ // Managed output and child cleanup are complete. An interrupted prompt may
1498
+ // still have a write pending on stderr if its reader stopped draining.
1499
+ if (signInInterrupted)
1500
+ process.exit(exitCode);
1501
+ return exitCode;
1502
+ }
1503
+ export async function main(argv = process.argv.slice(2), output = process.stdout, errorOutput = process.stderr, dependencies = DEFAULT_DEPENDENCIES, onInterruptedSignIn) {
1504
+ // Build the command tree with no executable arguments for shell callbacks.
1505
+ // Completion words, including literal action flags, belong to the shell.
1506
+ const completion = completionShell.safeParse(process.env["COMPLETE"]);
1507
+ const shellArgv = argv;
1508
+ if (completion.success)
1509
+ argv = [];
1510
+ const separator = argv.indexOf("--");
1511
+ const literalArgs = separator < 0 ? [] : argv.slice(separator + 1);
1512
+ if (separator >= 0)
1513
+ argv = argv.slice(0, separator);
1514
+ const inspection = argv.some((arg) => INSPECTION_FLAGS.includes(arg));
1515
+ const actionFlags = argv.filter((arg) => arg === "--mcp" || arg === "--update");
1516
+ const actionOptions = argv.filter((arg) => arg !== actionFlags[0]);
1517
+ const mixedAction = actionFlags.length > 0 &&
1518
+ (actionFlags.length !== 1 ||
1519
+ literalArgs.length > 0 ||
1520
+ firstNonGlobal(actionOptions, 0) < actionOptions.length ||
1521
+ (actionFlags[0] === "--mcp" && !inspection && actionOptions.length > 0));
1522
+ if (!mixedAction && actionFlags[0] === "--update")
1523
+ argv = ["update", ...actionOptions];
1524
+ if (!mixedAction && actionFlags[0] === "--mcp" && inspection)
1525
+ argv = actionOptions;
1413
1526
  const positionals = [];
1414
1527
  let exitCode = 0;
1415
1528
  let frameworkExit;
@@ -1422,7 +1535,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1422
1535
  let renderedOutput;
1423
1536
  let structuredError = false;
1424
1537
  let failedResultOutput;
1425
- let filteredScanFailure;
1538
+ let unfilteredFailure;
1426
1539
  const includeFailureResults = (format) => argv.includes("--full-output") &&
1427
1540
  (format === "json" ||
1428
1541
  format === "jsonl" ||
@@ -1440,8 +1553,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1440
1553
  const message = errorMessage(outcome.error);
1441
1554
  if (!argv.includes("--full-output")) {
1442
1555
  const data = { status: "failed", code, message };
1443
- if (frameworkFlags.filterOutput)
1444
- filteredScanFailure = { format, data };
1556
+ if (frameworkFlags.filters.length)
1557
+ unfilteredFailure = data;
1445
1558
  return data;
1446
1559
  }
1447
1560
  // Incur would wrap returned data in an ok: true envelope.
@@ -1463,7 +1576,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1463
1576
  const runImport = (options) => withTerminalErrorsHandled(errorOutput, () => runScanImport(options, errorOutput, dependencies));
1464
1577
  const history = async (args, select = (value) => value, pythonPath, protectedRoot) => {
1465
1578
  try {
1466
- return await select(await dependencies.runWorkbench(args, undefined, undefined, pythonPath, protectedRoot));
1579
+ return await select(await (typeof args === "function"
1580
+ ? args()
1581
+ : dependencies.runWorkbench(args, undefined, undefined, pythonPath, protectedRoot)));
1467
1582
  }
1468
1583
  catch (error) {
1469
1584
  errorOutput.write(`codex-security: ${diagnosticLines(error)}\n`);
@@ -1471,9 +1586,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1471
1586
  throw error;
1472
1587
  }
1473
1588
  };
1474
- const latestScans = async (count = 1, status = "complete", pythonPath, protectedRoot) => {
1589
+ const latestScans = async (count = 1, status = "complete", options = {}) => {
1475
1590
  const result = await history(workbenchArgs("list-scans", {
1476
1591
  repository: dependencies.currentDirectory(),
1592
+ preferWorktree: options.preferWorktree,
1477
1593
  status: status === "complete" ? "complete" : undefined,
1478
1594
  limit: String(count),
1479
1595
  }), (value) => {
@@ -1484,9 +1600,22 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1484
1600
  : `At least ${count} ${kind} scans are required for the current repository.`);
1485
1601
  }
1486
1602
  return value;
1487
- }, pythonPath, protectedRoot);
1603
+ }, options.pythonPath, options.protectedRoot);
1488
1604
  return result?.["scans"];
1489
1605
  };
1606
+ const preferredScan = async (repository, status) => {
1607
+ const result = await dependencies.runWorkbench(workbenchArgs("list-scans", {
1608
+ repository,
1609
+ preferWorktree: true,
1610
+ status,
1611
+ limit: 1,
1612
+ }));
1613
+ return result["scans"][0];
1614
+ };
1615
+ const historyId = z.string().min(1).optional();
1616
+ const resolveHistoryId = async (id, status) => id === "latest"
1617
+ ? (await latestScans(1, status, { preferWorktree: true }))?.[0]?.scanId
1618
+ : id;
1490
1619
  const runMatching = async (operation, selection) => {
1491
1620
  const controller = new AbortController();
1492
1621
  const removeListeners = listenForAbort(dependencies, controller, (signal) => dependencies.forceExit(signal));
@@ -1557,9 +1686,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1557
1686
  color: dependencies.environment["NO_COLOR"] === undefined &&
1558
1687
  dependencies.environment["TERM"] !== "dumb",
1559
1688
  now: dependencies.now(),
1560
- repository: settings.repository,
1561
- scanRoot: settings.scanRoot,
1562
- showLinkedFindings: settings.showLinkedFindings,
1689
+ ...settings,
1563
1690
  });
1564
1691
  return result;
1565
1692
  };
@@ -1580,7 +1707,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1580
1707
  const findingFeedback = Cli.create("findings", {
1581
1708
  description: "Review saved findings (default: list).",
1582
1709
  }).command("false-positive", {
1710
+ usage: [{ suffix: "OCCURRENCE_ID --reason TEXT" }],
1583
1711
  description: "Mark a finding as a false positive for future scans.",
1712
+ examples: [
1713
+ {
1714
+ args: { occurrenceId: "occurrence_abc123" },
1715
+ options: { reason: "unreachable" },
1716
+ description: "Use the occurrence ID from findings list and explain why it does not apply.",
1717
+ },
1718
+ ],
1719
+ hint: "Future scans of the repository can reuse the reason while it applies. Read the occurrence’s triage.note in codex-security scans show SCAN_ID --json.",
1584
1720
  destructive: true,
1585
1721
  args: z.object({
1586
1722
  occurrenceId: z
@@ -1614,6 +1750,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1614
1750
  });
1615
1751
  findingFeedback.command("list", {
1616
1752
  description: "List open findings for a repository across its scans.",
1753
+ examples: [{ args: { repository: "." } }],
1754
+ hint: "Use findings false-positive to record a triage decision for an occurrence.",
1617
1755
  args: z.object({
1618
1756
  repository: z
1619
1757
  .string()
@@ -1622,38 +1760,40 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1622
1760
  }),
1623
1761
  output: z.record(z.string(), z.unknown()).optional(),
1624
1762
  async run({ args, format }) {
1625
- const requestedRepository = resolveCliPath(dependencies.currentDirectory(), args.repository ?? ".");
1626
- const repository = await realpath(requestedRepository).catch(() => requestedRepository);
1627
- return presentHistory(await history(["list-repositories", "--status", "scanned"], async (value) => {
1628
- const repositories = value["repositories"];
1629
- let target = repositories.find((entry) => entry["targetPath"] === requestedRepository);
1630
- const canonicalTarget = repositories.find((entry) => entry["targetPath"] === repository);
1631
- if (target === undefined &&
1632
- canonicalTarget !== undefined &&
1633
- (await sameFile(canonicalTarget["targetPath"], requestedRepository))) {
1634
- target = canonicalTarget;
1635
- }
1636
- if (target === undefined) {
1637
- for (const entry of repositories) {
1638
- const storedPath = entry["targetPath"];
1639
- if (await sameFile(storedPath, requestedRepository)) {
1640
- target = entry;
1641
- break;
1642
- }
1643
- }
1644
- }
1645
- const findings = target === undefined
1646
- ? []
1647
- : await listRepositoryFindings(dependencies.runWorkbench, target["targetId"]);
1648
- return {
1763
+ const requestedPath = resolveInputPath(args.repository ?? ".", dependencies.currentDirectory());
1764
+ const storedPath = await resolveParentTraversal(requestedPath).catch(() => undefined);
1765
+ const canonicalPath = storedPath === undefined
1766
+ ? undefined
1767
+ : await realpath(storedPath).catch(() => undefined);
1768
+ const requestedRepository = canonicalPath === undefined
1769
+ ? (storedPath ?? requestedPath)
1770
+ : requestedPath;
1771
+ return await history(async () => {
1772
+ const findings = await listRepositoryFindings(dependencies.runWorkbench, {
1649
1773
  repository: requestedRepository,
1650
- findings: findings ?? [],
1651
- };
1652
- }), "findings", format, { repository: requestedRepository });
1774
+ });
1775
+ if (findings === undefined) {
1776
+ throw new CodexSecurityError("Repository findings are unavailable for the requested checkout.");
1777
+ }
1778
+ let missingRepositoryHistory = false;
1779
+ if (findings.length === 0 && useInteractiveHistory(format)) {
1780
+ const saved = await dependencies.runWorkbench(workbenchArgs("list-scans", {
1781
+ repository: requestedRepository,
1782
+ limit: "1",
1783
+ }));
1784
+ missingRepositoryHistory =
1785
+ saved["scans"].length === 0;
1786
+ }
1787
+ return presentHistory({ repository: requestedRepository, findings }, "findings", format, {
1788
+ missingRepositoryHistory,
1789
+ });
1790
+ });
1653
1791
  },
1654
1792
  });
1655
1793
  findingFeedback.command("imported", {
1656
1794
  description: "List imported vendor evidence for a local repository.",
1795
+ examples: [{ args: { repository: "." } }],
1796
+ hint: "Use publish findings FILE --to local to save a vendor report. See publish findings --help for its required selectors.",
1657
1797
  args: z.object({
1658
1798
  repository: z
1659
1799
  .string()
@@ -1665,14 +1805,15 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1665
1805
  const controller = new AbortController();
1666
1806
  const removeSignals = listenForAbort(dependencies, controller);
1667
1807
  try {
1668
- const repository = resolveCliPath(dependencies.currentDirectory(), args.repository ?? ".");
1669
- const findings = await (dependencies.listLocalExternalFindings ?? listLocalExternalFindings)({ repository }, {
1808
+ const repository = resolveInputPath(args.repository ?? ".", dependencies.currentDirectory());
1809
+ controller.signal.throwIfAborted();
1810
+ const result = await (dependencies.readLocalExternalFindings ?? readLocalExternalFindings)({ repository }, {
1670
1811
  environment: dependencies.environment,
1671
1812
  signal: controller.signal,
1672
1813
  });
1673
1814
  if (useInteractiveHistory(format))
1674
- renderedOutput = renderImportedFindings(repository, findings, output.columns || 96);
1675
- return { repository, findings };
1815
+ renderedOutput = renderImportedFindings(result.repository, result.findings, output.columns || 96);
1816
+ return result;
1676
1817
  }
1677
1818
  catch (error) {
1678
1819
  if (controller.signal.aborted) {
@@ -1700,6 +1841,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1700
1841
  })
1701
1842
  .command("list", {
1702
1843
  description: "List saved scans for a repository or scan root.",
1844
+ examples: [{ args: { repository: "." } }],
1845
+ hint: "Use scans show SCAN_ID for results or scans logs SCAN_ID for activity.",
1703
1846
  args: z.object({
1704
1847
  repository: z
1705
1848
  .string()
@@ -1719,10 +1862,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1719
1862
  ? undefined
1720
1863
  : process.platform === "win32"
1721
1864
  ? await canonicalizeModelSafePath(resolveCliPath(directory, options.scanRoot))
1722
- : resolveCliPath(directory, options.scanRoot);
1865
+ : await resolveParentTraversal(resolveInputPath(options.scanRoot, directory), { allowMissing: true });
1723
1866
  const repository = scanRoot !== undefined && args.repository === undefined
1724
1867
  ? undefined
1725
- : resolveCliPath(directory, args.repository ?? directory);
1868
+ : resolveInputPath(args.repository ?? directory, directory);
1726
1869
  return presentHistory(await history(workbenchArgs("list-scans", {
1727
1870
  repository,
1728
1871
  scanRoot,
@@ -1736,11 +1879,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1736
1879
  description: "Show the results and saved configuration for a scan.",
1737
1880
  hint: "Without an ID, show selects the latest completed scan; logs selects the latest scan of any status. Pass the same ID to inspect one run.",
1738
1881
  args: z.object({
1739
- scanId: z
1740
- .string()
1741
- .min(1)
1742
- .optional()
1743
- .describe("Scan ID or unique prefix (default: latest completed)."),
1882
+ scanId: historyId.describe("Scan ID, unique prefix, or latest (default: latest completed)."),
1744
1883
  }),
1745
1884
  options: z.object({
1746
1885
  showLinkedFindings: z
@@ -1756,24 +1895,22 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1756
1895
  },
1757
1896
  ],
1758
1897
  output: z.record(z.string(), z.unknown()).optional(),
1759
- async run({ args, format, options }) {
1760
- let scanId = args.scanId;
1761
- if (scanId === undefined) {
1762
- try {
1763
- scanId = (await latestScans())?.[0]?.scanId;
1764
- }
1765
- catch (error) {
1766
- if (useDefaultOutput(format)) {
1767
- errorOutput.write("Use codex-security scans list to find failed or active scans, then pass a scan ID to scans show and scans logs.\n");
1768
- }
1769
- throw error;
1898
+ async run({ args: { scanId: requestedId = "latest" }, format, options }) {
1899
+ let scanId;
1900
+ try {
1901
+ scanId = await resolveHistoryId(requestedId, "complete");
1902
+ }
1903
+ catch (error) {
1904
+ if (useDefaultOutput(format)) {
1905
+ errorOutput.write("Use codex-security scans list to find failed or active scans, then pass a scan ID to scans show and scans logs.\n");
1770
1906
  }
1907
+ throw error;
1771
1908
  }
1772
1909
  if (scanId === undefined)
1773
1910
  return;
1774
1911
  return presentHistory(await history(["get-scan", "--scan-id", scanId], async (value) => {
1775
1912
  const { scan, recipe, parentScanId } = value;
1776
- await showHistoryNavigation(scan, format, args.scanId === undefined ? "latest completed scan" : undefined);
1913
+ await showHistoryNavigation(scan, format, requestedId === "latest" ? "latest completed scan" : undefined);
1777
1914
  return {
1778
1915
  ...scan,
1779
1916
  ...(recipe === undefined ? {} : { recipe }),
@@ -1786,11 +1923,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1786
1923
  description: "Show saved activity for a scan and its workers.",
1787
1924
  hint: "Without an ID, logs selects the latest scan, including failed and active runs; show selects the latest completed scan. Pass the same ID to inspect one run.",
1788
1925
  args: z.object({
1789
- scanId: z
1790
- .string()
1791
- .min(1)
1792
- .optional()
1793
- .describe("Scan identifier or unique prefix (default: latest, any status)."),
1926
+ scanId: historyId.describe("Scan ID, unique prefix, or latest (default: latest, any status)."),
1794
1927
  }),
1795
1928
  examples: [
1796
1929
  { args: {}, description: "Show activity from the latest scan." },
@@ -1800,13 +1933,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1800
1933
  },
1801
1934
  ],
1802
1935
  output: z.record(z.string(), z.unknown()).optional(),
1803
- async run({ args, format }) {
1804
- const scanId = args.scanId ?? (await latestScans(1, "any"))?.[0]?.scanId;
1936
+ async run({ args: { scanId: requestedId = "latest" }, format }) {
1937
+ const scanId = await resolveHistoryId(requestedId, "any");
1805
1938
  if (scanId === undefined)
1806
1939
  return;
1807
1940
  const result = await history(["get-scan", "--scan-id", scanId], async (value) => {
1808
1941
  const scan = value["scan"];
1809
- await showHistoryNavigation(scan, format, args.scanId === undefined
1942
+ await showHistoryNavigation(scan, format, requestedId === "latest"
1810
1943
  ? "latest scan, including failed and active runs"
1811
1944
  : undefined);
1812
1945
  const logs = await readSavedScanLogs(scan, [
@@ -1829,10 +1962,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1829
1962
  },
1830
1963
  })
1831
1964
  .command("resume", {
1832
- description: "Resume an interrupted Deep Scan in its original session.",
1965
+ description: "Resume an interrupted Standard or Deep Scan in its original session.",
1966
+ examples: [{ args: { scanId: "SCAN_ID" } }],
1833
1967
  hint: "Execution failures keep available scan results under data in failed full-output JSON, JSONL, YAML, or TOON envelopes.",
1834
1968
  args: z.object({
1835
- scanId: z.string().min(1).describe("Interrupted Deep Scan identifier."),
1969
+ scanId: z.string().min(1).describe("Interrupted scan identifier."),
1836
1970
  }),
1837
1971
  options: z.object({
1838
1972
  showCost: SHOW_COST_OPTION,
@@ -1874,7 +2008,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1874
2008
  },
1875
2009
  })
1876
2010
  .command("rerun", {
1877
- description: "Start a new scan using saved settings and current checkout/context files.",
2011
+ description: "Start a new scan using saved settings and the current files at its saved checkout.",
2012
+ examples: [{ args: { scanId: "SCAN_ID" } }],
1878
2013
  hint: "Execution failures keep available scan results under data in failed full-output JSON, JSONL, YAML, or TOON envelopes.",
1879
2014
  destructive: true,
1880
2015
  args: z.object({
@@ -1882,7 +2017,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1882
2017
  .string()
1883
2018
  .min(1)
1884
2019
  .optional()
1885
- .describe("Saved scan identifier (default: latest completed scan)."),
2020
+ .describe("Saved scan identifier (default: latest completed in this worktree)."),
1886
2021
  }),
1887
2022
  options: z.object({
1888
2023
  showCost: SHOW_COST_OPTION,
@@ -1905,20 +2040,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1905
2040
  exitCode = 2;
1906
2041
  throw error;
1907
2042
  }
1908
- let scanId;
1909
- try {
1910
- scanId = args.scanId ?? (await latestScans())?.[0]?.scanId;
1911
- }
1912
- catch (error) {
1913
- const message = errorMessage(error);
1914
- if (exitCode === 0)
1915
- errorOutput.write(`codex-security: ${diagnosticLines(message)}\n`);
1916
- return finishScanCommand({ exitCode: 2, error: message }, format, incurError, "SCAN_REPLAY_UNAVAILABLE");
1917
- }
1918
- if (scanId === undefined)
1919
- return;
1920
2043
  let scanArguments;
1921
2044
  try {
2045
+ let scanId = args.scanId;
2046
+ let localScan;
2047
+ if (scanId === undefined) {
2048
+ localScan = await preferredScan(dependencies.currentDirectory(), "complete");
2049
+ if (!localScan)
2050
+ throw new CodexSecurityError("No completed scans found for the current repository.");
2051
+ scanId = localScan.scanId;
2052
+ if (!localScan.inCurrentWorktree)
2053
+ throw new CodexSecurityError(`No completed scan in this worktree. Scan ${scanId} used ${localScan.targetPath} (revision ${localScan["targetRevision"] ?? "unknown"}). To rerun there, use codex-security scans rerun ${scanId}.`);
2054
+ }
1922
2055
  const saved = await dependencies.runWorkbench(workbenchArgs("get-scan-recipe", { scanId }));
1923
2056
  const recipe = saved["recipe"];
1924
2057
  const parentScanId = saved["scanId"];
@@ -1946,7 +2079,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1946
2079
  });
1947
2080
  return finishScanCommand(outcome, format, incurError, "SCAN_IMPORT_FAILED");
1948
2081
  }
1949
- scanArguments = await prepareScanArgumentsFromRecipe(saved, "rerun", dependencies.currentDirectory(), dependencies.environment, options);
2082
+ const replay = localScan && isJsonObject(recipe)
2083
+ ? {
2084
+ ...saved,
2085
+ recipe: {
2086
+ ...recipe,
2087
+ repository: localScan.targetPath,
2088
+ },
2089
+ }
2090
+ : saved;
2091
+ scanArguments = await prepareScanArgumentsFromRecipe(replay, "rerun", dependencies.currentDirectory(), dependencies.environment, options);
1950
2092
  scanArguments.verbose = options.verbose;
1951
2093
  scanArguments.showCost = options.showCost;
1952
2094
  scanArguments.parentScanId = parentScanId;
@@ -1961,7 +2103,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1961
2103
  },
1962
2104
  })
1963
2105
  .command("match", {
1964
- description: "Match findings by root cause across saved scans.",
2106
+ description: "Match findings across completed scans. Uncached matches can use the model and save decisions.",
2107
+ usage: [{ suffix: "--all [options]" }],
2108
+ examples: [{ options: { all: true } }],
2109
+ hint: "For a pair, use scans compare BEFORE AFTER. The older scans match BEFORE AFTER spelling also works.",
1965
2110
  destructive: true,
1966
2111
  args: z.object({
1967
2112
  beforeId: z
@@ -1980,22 +2125,31 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1980
2125
  .boolean()
1981
2126
  .default(false)
1982
2127
  .describe("Match all completed scans of the current repository."),
1983
- force: z
1984
- .boolean()
1985
- .default(false)
1986
- .describe("Recompute an existing semantic finding comparison."),
1987
- ...MATCHING_MODEL_OPTIONS.shape,
2128
+ ...MATCHING_OPTIONS.shape,
1988
2129
  }),
1989
2130
  output: z.record(z.string(), z.unknown()).optional(),
1990
2131
  async run({ args, format, options }) {
1991
2132
  if (options.all) {
2133
+ if (args.beforeId !== undefined || args.afterId !== undefined) {
2134
+ throw new CodexSecurityError("scans match --all does not accept scan identifiers.");
2135
+ }
1992
2136
  return presentHistory(await runMatching((matchingOptions) => matchAllScans(dependencies, options.force, matchingOptions), options), "match-all", format);
1993
2137
  }
2138
+ if (args.beforeId === undefined || args.afterId === undefined) {
2139
+ throw new CodexSecurityError("scans match requires two scan identifiers or --all.");
2140
+ }
1994
2141
  return presentHistory(await matchScanPair(args.beforeId, args.afterId, options), "compare", format);
1995
2142
  },
1996
2143
  })
1997
2144
  .command("compare", {
1998
- description: "Match and compare findings between scans.",
2145
+ description: "Compare findings from two scans. Uncached matches can use the model and save matching decisions.",
2146
+ examples: [
2147
+ {
2148
+ args: { beforeId: "BEFORE", afterId: "AFTER" },
2149
+ description: "Compare two scans, using the model and saving decisions on a cache miss.",
2150
+ },
2151
+ { args: {}, description: "Compare the latest two completed scans." },
2152
+ ],
1999
2153
  destructive: true,
2000
2154
  args: z.object({
2001
2155
  beforeId: z
@@ -2009,7 +2163,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2009
2163
  .optional()
2010
2164
  .describe("Later saved scan identifier (default: latest completed)."),
2011
2165
  }),
2012
- options: MATCHING_MODEL_OPTIONS,
2166
+ options: MATCHING_OPTIONS,
2013
2167
  output: z.record(z.string(), z.unknown()).optional(),
2014
2168
  async run({ args, format, options }) {
2015
2169
  let { beforeId, afterId } = args;
@@ -2045,10 +2199,25 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2045
2199
  const publication = Cli.create("publish", {
2046
2200
  description: "Publish Codex Security findings.",
2047
2201
  }).command("scan", {
2048
- description: "Publish findings from a completed scan, or a CSV for internal publication.",
2049
- hint: "Examples:\n" +
2050
- " codex-security publish scan --to linear --scan latest --linear-team TEAM_ID --dry-run\n" +
2051
- " codex-security publish scan --to custom --scan latest --findings-url http://localhost:3000",
2202
+ description: "Publish findings from a completed scan.",
2203
+ examples: [
2204
+ {
2205
+ args: { scanDir: "../scan-results" },
2206
+ options: {
2207
+ to: "linear",
2208
+ linearTeam: "TEAM_ID",
2209
+ dryRun: true,
2210
+ },
2211
+ },
2212
+ {
2213
+ options: {
2214
+ to: "custom",
2215
+ scan: ["latest"],
2216
+ findingsUrl: "http://localhost:3000",
2217
+ },
2218
+ },
2219
+ ],
2220
+ hint: "Use --dry-run to preview the selected findings before publishing.",
2052
2221
  destructive: true,
2053
2222
  args: z.object({
2054
2223
  scanDir: z
@@ -2071,7 +2240,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2071
2240
  scanDir: z
2072
2241
  .array(optionValue("--scan-dir"))
2073
2242
  .default([])
2074
- .describe("External completed scan directory; Linear and custom accept one scan."),
2243
+ .describe("Use the positional directory for one scan. Repeat this flag for destinations that accept multiple scans."),
2075
2244
  // Cloud remains an internal destination, omitted from public discovery.
2076
2245
  to: z
2077
2246
  .string()
@@ -2165,22 +2334,24 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2165
2334
  const csvPath = options.csv === undefined
2166
2335
  ? undefined
2167
2336
  : resolveCliPath(currentDirectory, options.csv);
2168
- const directories = [
2169
- ...new Set([
2170
- ...(args.scanDir === undefined ? [] : [args.scanDir]),
2171
- ...options.scanDir,
2172
- ].map((directory) => resolveCliPath(currentDirectory, directory))),
2337
+ const directoryInputs = [
2338
+ ...(args.scanDir === undefined ? [] : [args.scanDir]),
2339
+ ...options.scanDir,
2173
2340
  ];
2174
- if (directories.length > 1 && options.to !== "cloud") {
2175
- throw new CodexSecurityError("Multiple scan directories are only supported with --to cloud.");
2176
- }
2177
- if (options.scan.length > 0 && directories.length > 0) {
2341
+ const uniqueDirectories = (paths) => {
2342
+ const directories = [...new Set(paths)];
2343
+ if (directories.length > 1 && options.to !== "cloud") {
2344
+ throw new CodexSecurityError("Multiple scan directories are only supported with --to cloud.");
2345
+ }
2346
+ return directories;
2347
+ };
2348
+ // Reject conflicting selectors before reading their path components.
2349
+ uniqueDirectories(directoryInputs.map((value) => resolveCliPath(currentDirectory, value)));
2350
+ if (options.scan.length > 0 && directoryInputs.length > 0) {
2178
2351
  throw new CodexSecurityError("Use --scan or scan directory inputs, not both.");
2179
2352
  }
2180
2353
  if (csvPath !== undefined &&
2181
- (args.scanDir !== undefined ||
2182
- options.scan.length > 0 ||
2183
- options.scanDir.length > 0)) {
2354
+ (directoryInputs.length > 0 || options.scan.length > 0)) {
2184
2355
  throw new CodexSecurityError("Use --csv or scan directory and ID inputs, not both.");
2185
2356
  }
2186
2357
  if (csvPath !== undefined && options.to !== "cloud") {
@@ -2228,6 +2399,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2228
2399
  currentDirectory: dependencies.currentDirectory,
2229
2400
  runWorkbench: (args, input) => dependencies.runWorkbench(args, input, controller.signal),
2230
2401
  };
2402
+ const directories = uniqueDirectories(await Promise.all(directoryInputs.map((value) => resolveParentTraversal(resolveInputPath(value, currentDirectory), { allowMissing: true }))));
2231
2403
  const selectedScans = directories.map((scanDir) => ({ scanDir }));
2232
2404
  for (const requestedId of new Set(options.scan)) {
2233
2405
  controller.signal.throwIfAborted();
@@ -2515,7 +2687,31 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2515
2687
  publication
2516
2688
  .command("findings", {
2517
2689
  description: "Preview and import a saved scanner report locally or to Cloud.",
2518
- hint: "Choose your scanner with --provider. Reuse --source-key for later imports from the same source. See the scanner import guide for supported formats, repository setup, and export examples: https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md. Gzip files are supported. Use --to local to save unassessed findings without a Cloud login. Use --full-output with --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
2690
+ usage: [
2691
+ {
2692
+ args: { file: true },
2693
+ options: {
2694
+ to: true,
2695
+ repository: true,
2696
+ provider: true,
2697
+ sourceKey: true,
2698
+ },
2699
+ suffix: "[options]",
2700
+ },
2701
+ ],
2702
+ examples: [
2703
+ {
2704
+ args: { file: "selected-wiz.json" },
2705
+ options: {
2706
+ to: "local",
2707
+ repository: "./project",
2708
+ provider: "wiz",
2709
+ sourceKey: "tenant/vulnerability-finding",
2710
+ dryRun: true,
2711
+ },
2712
+ },
2713
+ ],
2714
+ hint: "Choose your scanner with --provider. Reuse --source-key for later imports from the same source. For findings already in the workbench, use the SDK's prepareStoredFindingsPublication. The installed @openai/codex-security package includes the workflow in docs/sdk.md under Import external findings. See the scanner import guide for supported formats, repository setup, and export examples: https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md. Gzip files are supported. Use --to local to save unassessed findings without a Cloud login. Use --full-output with --format json or --format jsonl.",
2519
2715
  destructive: true,
2520
2716
  args: z.object({
2521
2717
  file: z
@@ -2529,7 +2725,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2529
2725
  repository: optionValue("--repository").describe("Local repository path for --to local; authorized repository ID or URL for --to cloud."),
2530
2726
  provider: z
2531
2727
  .enum(EXTERNAL_FINDINGS_READERS)
2532
- .describe("Select the file reader for this report. OpenGrep findings use the semgrep storage provider. Tenable requires --to local and --source-repository-url."),
2728
+ .describe("Select the file reader for this report. OpenGrep findings use the semgrep storage provider. Tenable requires --to local and --source-repository-url. CrowdStrike requires --to local."),
2533
2729
  sourceRepositoryUrl: optionValue("--source-repository-url")
2534
2730
  .optional()
2535
2731
  .describe("Source repository URL when required by the selected reader. Checked against the Cloud destination or configured local Git remotes."),
@@ -2564,6 +2760,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2564
2760
  exitCode,
2565
2761
  });
2566
2762
  }
2763
+ if (options.sourceRepositoryUrl !== undefined)
2764
+ writeDiagnostic("codex-security: warning: Use --source-repository-url only after verifying that every finding belongs to the repository you specify.\n");
2567
2765
  const controller = new AbortController();
2568
2766
  const removeSignals = listenForAbort(dependencies, controller);
2569
2767
  const structured = formatExplicit && format !== "toon";
@@ -2637,9 +2835,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2637
2835
  inspectorProjectMap = new Map([[inspectorProjectArn, url]]);
2638
2836
  }
2639
2837
  const directory = dependencies.currentDirectory();
2640
- const report = resolveCliPath(directory, args.file);
2838
+ const report = resolveInputPath(args.file, directory);
2641
2839
  const repository = options.to === "local"
2642
- ? resolveCliPath(directory, options.repository)
2840
+ ? resolveInputPath(options.repository, directory)
2643
2841
  : options.repository;
2644
2842
  const publicationOptions = {
2645
2843
  ...readerOptions,
@@ -2659,7 +2857,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2659
2857
  showExclusions(preview.excluded);
2660
2858
  for (const finding of preview.findings.slice(0, 5))
2661
2859
  writeDiagnostic(` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`);
2662
- writeDiagnostic(`Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\nUse --dry-run --format json to inspect all normalized findings and complete evidence before storing them.\n`);
2860
+ writeDiagnostic(`Evidence file: ${diagnosticValue(report)}\nImported evidence remains not assessed by Codex.\nUse --dry-run --format json to inspect all normalized findings and complete evidence before storing them.\n`);
2663
2861
  };
2664
2862
  const disposition = externalImportDisposition(preview);
2665
2863
  if (disposition === "excluded" || disposition === "failed")
@@ -2682,7 +2880,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2682
2880
  exitCode = 1;
2683
2881
  const summary = disposition === "empty"
2684
2882
  ? "The report contains no findings. Nothing was stored.\n"
2685
- : `Local import complete.\nCreated: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Excluded: ${result.excluded.length}\nImported evidence remains not assessed by Codex.\nRead stored evidence with codex-security findings imported REPOSITORY.\n`;
2883
+ : `Local import complete.\nCreated: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Excluded: ${result.excluded.length}\nImported evidence remains not assessed by Codex.\n${importedFindingsCommand(preview.repository)}\n`;
2686
2884
  if (humanSummary)
2687
2885
  renderedOutput = summary;
2688
2886
  else if (!structured)
@@ -2703,7 +2901,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2703
2901
  if (preview.cloudUrl)
2704
2902
  writeDiagnostic(`Cloud app: ${diagnosticValue(preview.cloudUrl)}\n`);
2705
2903
  showExclusions(preview.excluded);
2706
- writeDiagnostic(`Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\n`);
2904
+ writeDiagnostic(`Evidence file: ${diagnosticValue(report)}\nImported evidence remains not assessed by Codex.\n`);
2707
2905
  const severities = new Map();
2708
2906
  for (const finding of preview.findings)
2709
2907
  severities.set(finding.evidence.severity, (severities.get(finding.evidence.severity) ?? 0) + 1);
@@ -2787,8 +2985,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2787
2985
  };
2788
2986
  if (machineFormat &&
2789
2987
  (!argv.includes("--full-output") || selection !== undefined) &&
2790
- frameworkFlags.filterOutput)
2791
- filteredScanFailure = { format, data: failure };
2988
+ frameworkFlags.filters.length)
2989
+ unfilteredFailure = failure;
2792
2990
  return structured ? failure : undefined;
2793
2991
  }
2794
2992
  finally {
@@ -2799,6 +2997,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2799
2997
  })
2800
2998
  .command("check", {
2801
2999
  description: "Check saved scan history and Linear access without creating issues.",
3000
+ examples: [
3001
+ {
3002
+ args: { scanDir: "../scan-results" },
3003
+ options: { linearTeam: "TEAM_ID" },
3004
+ },
3005
+ ],
3006
+ hint: "Use publish scan --dry-run to preview a publication offline.",
2802
3007
  args: z.object({
2803
3008
  scanDir: z.string().describe("Completed scan directory."),
2804
3009
  }),
@@ -2809,10 +3014,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2809
3014
  const controller = new AbortController();
2810
3015
  const removeSignals = listenForAbort(dependencies, controller);
2811
3016
  try {
2812
- const result = await (dependencies.checkScanPublication ?? checkScanPublication)(resolveCliPath(dependencies.currentDirectory(), args.scanDir), {
2813
- ...publicationDestination(options, dependencies.environment),
2814
- signal: controller.signal,
3017
+ const input = resolveInputPath(args.scanDir, dependencies.currentDirectory());
3018
+ const destination = publicationDestination(options, dependencies.environment);
3019
+ const directory = await resolveParentTraversal(input, {
3020
+ allowMissing: true,
2815
3021
  });
3022
+ const result = await (dependencies.checkScanPublication ?? checkScanPublication)(directory, { ...destination, signal: controller.signal });
2816
3023
  controller.signal.throwIfAborted();
2817
3024
  return { ...result };
2818
3025
  }
@@ -2827,8 +3034,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2827
3034
  },
2828
3035
  });
2829
3036
  const imports = Cli.create("import", {
2830
- description: "Import Sonar security issues or read hosted Semgrep, Snyk, and GitHub findings.",
3037
+ description: "Collect findings from Continuum, GitHub, Semgrep, Snyk or Sonar.",
2831
3038
  }).command("github", {
3039
+ examples: [{ args: { repository: "owner/repo" } }],
2832
3040
  description: "Read GitHub code scanning alerts without changing GitHub.",
2833
3041
  hint: "Save complete --format json output for publish findings --provider github. This command reads code-scanning alerts; Dependabot and secret-scanning alerts are not supported. To save CSV or JSON findings as a local scan, use codex-security scan import --help.",
2834
3042
  destructive: false,
@@ -2860,7 +3068,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2860
3068
  alert: z.record(z.string(), z.unknown()),
2861
3069
  }))
2862
3070
  .optional(),
2863
- async run({ args, options }) {
3071
+ async run({ args, options, error: fail }) {
2864
3072
  const controller = new AbortController();
2865
3073
  const removeSignals = listenForAbort(dependencies, controller);
2866
3074
  try {
@@ -2885,7 +3093,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2885
3093
  exitCode = 2;
2886
3094
  errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);
2887
3095
  }
2888
- throw error;
3096
+ return fail({
3097
+ code: "GITHUB_IMPORT_FAILED",
3098
+ message: errorMessage(error),
3099
+ exitCode,
3100
+ });
2889
3101
  }
2890
3102
  finally {
2891
3103
  removeSignals();
@@ -2905,9 +3117,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2905
3117
  const diagnostic = interrupted
2906
3118
  ? `${provider} import ${interrupted === 130 ? "canceled" : "terminated"}.`
2907
3119
  : message;
2908
- const terminalDiagnostic = provider === "Semgrep" || provider === "Snyk"
2909
- ? escapeTerminalText(diagnostic)
2910
- : diagnostic;
3120
+ const terminalDiagnostic = provider === "GitHub advisory"
3121
+ ? diagnostic
3122
+ : escapeTerminalText(diagnostic);
2911
3123
  errorOutput.write(`codex-security: ${terminalDiagnostic}\n`);
2912
3124
  if (argv.includes("--full-output")) {
2913
3125
  structuredError = true;
@@ -2929,12 +3141,78 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2929
3141
  environment: dependencies.environment,
2930
3142
  fetch: dependencies.hostedScannerFetch,
2931
3143
  };
2932
- function setHostedOutputFormat(format) {
3144
+ function setTerminalOutputFormat(format) {
2933
3145
  escapeFrameworkOutput =
2934
3146
  format === "md" || (format === "toon" && output.isTTY === true);
2935
3147
  }
2936
3148
  imports
3149
+ .command("continuum", {
3150
+ examples: [
3151
+ { args: { environmentId: "abc123" } },
3152
+ {
3153
+ args: { environmentId: "abc123" },
3154
+ options: {
3155
+ findingId: "def456",
3156
+ sourceRoot: "/absolute/path/to/checkout",
3157
+ repositoryName: "example/project",
3158
+ },
3159
+ },
3160
+ ],
3161
+ description: "Read all AWS Continuum issues or collect one finding with its matching validation evidence and patches.",
3162
+ hint: "Requires AWS CLI v2.38.5 or later installed outside the checkout. Bulk collection requires exactly one Git repository and allows S3 sources. For one finding, pass --finding-id and --source-root. The CLI checks for one Git repository and no S3 sources when --repository-name is omitted. Save --format json output for publish findings --provider continuum.",
3163
+ destructive: false,
3164
+ args: z.object({ environmentId: continuumEnvironmentId }),
3165
+ options: z
3166
+ .object({
3167
+ awsProfile: optionValue("--aws-profile")
3168
+ .optional()
3169
+ .describe("AWS CLI profile (default: use the AWS CLI's configured credentials)."),
3170
+ awsRegion: optionValue("--aws-region")
3171
+ .optional()
3172
+ .describe("AWS Region (default: use the AWS CLI's configured Region)."),
3173
+ findingId: continuumFindingId.optional(),
3174
+ sourceRoot: optionValue("--source-root")
3175
+ .refine(isAbsolute, {
3176
+ message: "--source-root must be an absolute path.",
3177
+ })
3178
+ .optional()
3179
+ .describe("Absolute path of the selected checkout for --finding-id."),
3180
+ repositoryName: optionValue("--repository-name")
3181
+ .optional()
3182
+ .describe("Exact AWS source name for the selected finding's repository. Required unless the environment has one Git repository and no S3 sources."),
3183
+ })
3184
+ .refine((options) => options.findingId !== undefined ||
3185
+ (options.sourceRoot === undefined &&
3186
+ options.repositoryName === undefined), {
3187
+ message: "--source-root and --repository-name require --finding-id.",
3188
+ })
3189
+ .refine((options) => options.findingId === undefined || options.sourceRoot !== undefined, { message: "--finding-id requires --source-root." }),
3190
+ output: continuumImportOutput.optional(),
3191
+ run: ({ args, options, error, format }) => {
3192
+ setTerminalOutputFormat(format);
3193
+ return collectHostedFindings("Continuum", error, (signal) => {
3194
+ const selection = {
3195
+ environmentId: args.environmentId,
3196
+ profile: options.awsProfile,
3197
+ region: options.awsRegion,
3198
+ cwd: dependencies.currentDirectory(),
3199
+ environment: dependencies.environment,
3200
+ signal,
3201
+ };
3202
+ if (options.findingId === undefined)
3203
+ return (dependencies.collectContinuumIssues ?? collectContinuumIssues)(selection);
3204
+ return (dependencies.collectContinuumFinding ?? collectContinuumFinding)({
3205
+ ...selection,
3206
+ findingId: options.findingId,
3207
+ sourceRoot: options.sourceRoot,
3208
+ repositoryName: options.repositoryName,
3209
+ warn: (message) => errorOutput.write(`codex-security: ${escapeTerminalText(message)}\n`),
3210
+ });
3211
+ });
3212
+ },
3213
+ })
2937
3214
  .command("github-advisories", {
3215
+ examples: [{ args: { repository: "owner/repo" } }],
2938
3216
  description: "Read GitHub security advisories without changing GitHub.",
2939
3217
  hint: "Defaults to published repository advisories. Use --github-advisory-source global with explicit --github-advisory IDs to select public database entries. Advisories do not establish an installed dependency or applicability to the selected repository.",
2940
3218
  destructive: false,
@@ -2981,14 +3259,30 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2981
3259
  })),
2982
3260
  })
2983
3261
  .command("snyk", {
3262
+ usage: [
3263
+ {
3264
+ args: { project: true },
3265
+ options: { org: true, sourceRepositoryUrl: true },
3266
+ suffix: "[options]",
3267
+ },
3268
+ ],
2984
3269
  description: "Read Snyk Open Source or Code issues for one monitored project.",
3270
+ examples: [
3271
+ {
3272
+ args: { project: "PROJECT_ID" },
3273
+ options: {
3274
+ org: "ORG_ID",
3275
+ sourceRepositoryUrl: "https://github.com/example/project",
3276
+ },
3277
+ },
3278
+ ],
2985
3279
  hint: "Requires SNYK_TOKEN. Save the complete --format json output. Use publish findings --provider snyk with --to local or --to cloud.",
2986
3280
  destructive: false,
2987
3281
  args: z.object({
2988
3282
  project: z.string().min(1).describe("Snyk project ID."),
2989
3283
  }),
2990
3284
  options: z.object({
2991
- snykOrg: optionValue("--snyk-org").describe("Snyk organization ID."),
3285
+ org: optionValue("--org").describe("Snyk organization ID (alias: --snyk-org)."),
2992
3286
  snykProduct: z
2993
3287
  .enum(["open-source", "code"])
2994
3288
  .default("open-source")
@@ -3017,10 +3311,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3017
3311
  })
3018
3312
  .optional(),
3019
3313
  run: ({ args, options, error, format }) => {
3020
- setHostedOutputFormat(format);
3314
+ setTerminalOutputFormat(format);
3021
3315
  return collectHostedFindings("Snyk", error, (signal) => collectSnykIssues({
3022
3316
  projectId: args.project,
3023
- organizationId: options.snykOrg,
3317
+ organizationId: options.org,
3024
3318
  product: options.snykProduct,
3025
3319
  apiOrigin: options.snykApiOrigin,
3026
3320
  sourceRepositoryUrl: options.sourceRepositoryUrl,
@@ -3029,7 +3323,23 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3029
3323
  },
3030
3324
  })
3031
3325
  .command("semgrep", {
3326
+ usage: [
3327
+ {
3328
+ args: { project: true },
3329
+ options: { deployment: true, ref: true },
3330
+ suffix: "[options]",
3331
+ },
3332
+ ],
3032
3333
  description: "Read a full Semgrep Platform project and ref through the Web API.",
3334
+ examples: [
3335
+ {
3336
+ args: { project: "owner/project" },
3337
+ options: {
3338
+ deployment: "DEPLOYMENT",
3339
+ ref: "refs/heads/main",
3340
+ },
3341
+ },
3342
+ ],
3033
3343
  hint: "Requires SEMGREP_APP_TOKEN with Web API access. Import the saved --format json output with publish findings --provider semgrep and --to local or --to cloud. Selected Guardian MCP captures also support both destinations.",
3034
3344
  destructive: false,
3035
3345
  args: z.object({
@@ -3039,8 +3349,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3039
3349
  .describe("Exact Semgrep project name, typically owner/repository."),
3040
3350
  }),
3041
3351
  options: z.object({
3042
- semgrepDeployment: optionValue("--semgrep-deployment").describe("Semgrep deployment slug."),
3043
- semgrepRef: optionValue("--semgrep-ref").describe("Exact source ref, for example refs/heads/main."),
3352
+ deployment: optionValue("--deployment").describe("Semgrep deployment slug (alias: --semgrep-deployment)."),
3353
+ ref: optionValue("--ref").describe("Exact source ref, for example refs/heads/main (alias: --semgrep-ref)."),
3044
3354
  semgrepProduct: z
3045
3355
  .enum(SEMGREP_PLATFORM_PRODUCTS)
3046
3356
  .default("sast")
@@ -3068,11 +3378,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3068
3378
  })
3069
3379
  .optional(),
3070
3380
  run: ({ args, options, error, format }) => {
3071
- setHostedOutputFormat(format);
3381
+ setTerminalOutputFormat(format);
3072
3382
  return collectHostedFindings("Semgrep", error, (signal) => collectSemgrepPlatformFindings({
3073
3383
  project: args.project,
3074
- deployment: options.semgrepDeployment,
3075
- ref: options.semgrepRef,
3384
+ deployment: options.deployment,
3385
+ ref: options.ref,
3076
3386
  product: options.semgrepProduct,
3077
3387
  sourceRepositoryUrl: options.sourceRepositoryUrl,
3078
3388
  signal,
@@ -3080,8 +3390,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3080
3390
  },
3081
3391
  })
3082
3392
  .command("sonar", {
3393
+ usage: [
3394
+ { suffix: "[--sonar-project KEY] [options]" },
3395
+ { suffix: "CAPTURE [options]" },
3396
+ ],
3083
3397
  description: "Collect Sonar security findings or replay a saved capture into the local workbench.",
3084
- hint: "Uses the active sonar CLI login. --to cloud also publishes the locally imported selection to the connected Cloud repository. --dry-run saves a live capture for review without importing findings.",
3398
+ examples: [
3399
+ { options: { sonarProject: "PROJECT_KEY", dryRun: true } },
3400
+ { args: { capture: "../reports/sonar.json" } },
3401
+ ],
3402
+ hint: "Uses the active sonar CLI login. --to cloud also publishes the locally imported selection to the connected Cloud repository. --dry-run saves a private evidence copy for live and saved inputs and prints its path for confirmation.",
3085
3403
  destructive: true,
3086
3404
  args: z.object({
3087
3405
  capture: z
@@ -3114,7 +3432,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3114
3432
  dryRun: z
3115
3433
  .boolean()
3116
3434
  .default(false)
3117
- .describe("Preview destinations and evidence without storing or publishing findings."),
3435
+ .describe("Save a private evidence copy and preview the selected findings and destinations."),
3118
3436
  yes: z
3119
3437
  .boolean()
3120
3438
  .default(false)
@@ -3234,7 +3552,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3234
3552
  note("Cloud repository: " + diagnosticValue(result.cloud.cloudUrl));
3235
3553
  if (humanSummary) {
3236
3554
  const { created, updated, unchanged } = result.local.counts;
3237
- renderedOutput = `Local import: ${created} created, ${updated} updated, ${unchanged} unchanged.\n`;
3555
+ renderedOutput = `Local import: ${created} created, ${updated} updated, ${unchanged} unchanged.\n${importedFindingsCommand(info.repository)}\n`;
3238
3556
  if (result.cloud)
3239
3557
  renderedOutput += renderExternalPublicationSummary(result.cloud);
3240
3558
  }
@@ -3256,9 +3574,14 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3256
3574
  });
3257
3575
  },
3258
3576
  });
3577
+ const withLoginEnvironment = async (run) => {
3578
+ const home = await prepareCodexSecurityCredentialHome(dependencies.environment);
3579
+ return withCredentialHomeLock(home, () => run({ ...dependencies.environment, CODEX_HOME: home }));
3580
+ };
3259
3581
  const infoOutput = z.object({
3260
3582
  sdkVersion: z.string(),
3261
3583
  bundledPluginVersion: z.string(),
3584
+ bundledPluginAvailable: z.boolean(),
3262
3585
  scanMcp: z.literal(false),
3263
3586
  cancellationNote: z.string(),
3264
3587
  cliVersion: z.string(),
@@ -3271,6 +3594,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3271
3594
  });
3272
3595
  const cliOptions = {
3273
3596
  aliases: ["cs"],
3597
+ update: false,
3274
3598
  description: "Find, review, and fix security issues in your code.",
3275
3599
  version: VERSION,
3276
3600
  mcp: {
@@ -3280,6 +3604,27 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3280
3604
  },
3281
3605
  };
3282
3606
  const cli = Cli.create("codex-security", cliOptions)
3607
+ .command("update", {
3608
+ description: "Update the CLI or show the command for this installation.",
3609
+ destructive: true,
3610
+ async run({ format, error }) {
3611
+ try {
3612
+ await installUpdate(dependencies.environment);
3613
+ }
3614
+ catch (cause) {
3615
+ return error({
3616
+ code: "UPDATE_FAILED",
3617
+ message: errorMessage(cause),
3618
+ exitCode: 2,
3619
+ });
3620
+ }
3621
+ const name = "@openai/codex-security";
3622
+ if (output.isTTY && useDefaultOutput(format))
3623
+ renderedOutput = `✓ Updated ${name}\n`;
3624
+ return { name };
3625
+ },
3626
+ })
3627
+ .command(scanHistory)
3283
3628
  .command("policy", {
3284
3629
  description: "Draft SECURITY.md for review.",
3285
3630
  destructive: true,
@@ -3321,7 +3666,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3321
3666
  hint: "Review the diff and notes. Edit the draft, then copy only SECURITY.md to the Policy target shown.\n" +
3322
3667
  "Your existing policy stays unchanged until you replace it.\n\n" +
3323
3668
  "Save a draft without answering questions:\n" +
3324
- " codex-security policy . --headless --output-dir /path/outside/repository/policy --json",
3669
+ " codex-security policy . --output-dir ../policy-draft --json",
3325
3670
  output: z
3326
3671
  .union([z.record(z.string(), z.unknown()), z.string()])
3327
3672
  .optional(),
@@ -3344,7 +3689,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3344
3689
  const directory = dependencies.currentDirectory();
3345
3690
  const codexOverrides = await parseScanCodexOverrides(options, dependencies.environment);
3346
3691
  const outcome = await withTerminalErrorsHandled(errorOutput, () => runPolicyCommand({
3347
- repository: resolveCliPath(directory, args.repository ?? "."),
3692
+ repository: resolveInputPath(args.repository ?? ".", directory),
3348
3693
  config: {
3349
3694
  pluginPath: options.pluginPath,
3350
3695
  pythonPath: options.python,
@@ -3410,214 +3755,302 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3410
3755
  return fail(message, 2);
3411
3756
  }
3412
3757
  },
3413
- })
3414
- .command("scan", {
3415
- description: "Scan a repository, selected paths, or Git changes.",
3416
- hint: "Examples:\n" +
3417
- " codex-security scan .\n" +
3418
- " codex-security scan . --path src --path tests\n" +
3419
- " codex-security scan . --working-tree\n" +
3420
- " codex-security scan . --diff origin/main\n" +
3421
- " codex-security scan . --mode deep\n\n" +
3422
- "Import existing findings without security analysis:\n" +
3423
- " codex-security scan import --csv findings.csv\n" +
3424
- " codex-security scan import --json findings.json\n" +
3425
- "Use ./import to scan a repository named import.\n" +
3426
- "Execution failures in JSON/JSONL --full-output return ok: false and keep scan results under data.",
3427
- destructive: true,
3428
- alias: { config: "c" },
3429
- args: z.object({
3430
- repository: z
3431
- .string()
3432
- .optional()
3433
- .describe("Repository root to scan (default: current directory)."),
3434
- }),
3435
- options: z
3436
- .object({
3437
- config: PROJECT_CONFIG_OPTION,
3438
- host: z
3439
- .boolean()
3440
- .default(false)
3441
- .describe("Run one hosted Standard scan over JSON-RPC stdin/stdout; use alone."),
3442
- workflowId: optionValue("--workflow-id")
3443
- .optional()
3444
- .describe("Reuse completed work in the named local findings workflow."),
3445
- cyberAccessProgram: ScanSettingsSchema.shape.cyberAccessProgram,
3446
- auth: ScanSettingsSchema.shape.auth.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication (default: auto)."),
3447
- verbose: z
3448
- .boolean()
3449
- .default(false)
3450
- .describe("Print additional scan diagnostics to stderr."),
3451
- safetyIdentifier: optionValue("--safety-identifier")
3452
- .optional()
3453
- .describe("Stable hashed end-user ID for this scan's model requests (1–64 characters)."),
3454
- path: z
3455
- .array(optionValue("--path"))
3456
- .optional()
3457
- .meta({ default: [] })
3458
- .describe("Scan only PATH; repeat for multiple repository-relative paths."),
3459
- knowledgeBase: z
3460
- .array(optionValue("--knowledge-base"))
3461
- .optional()
3462
- .meta({ default: [] })
3463
- .describe("Add security-context files or directories; repeat for multiple paths."),
3464
- rubric: optionValue("--rubric")
3465
- .optional()
3466
- .describe("Use this Markdown file to grade findings. Takes precedence over the default severity rubric."),
3467
- scanPromptFile: optionValue("--scan-prompt-file")
3468
- .optional()
3469
- .describe("Append scan instructions from FILE."),
3470
- validationPromptFile: optionValue("--validation-prompt-file")
3471
- .optional()
3472
- .describe("Replace final validation with the workflow in FILE (not Deep)."),
3473
- postScanPromptFile: optionValue("--post-scan-prompt-file")
3474
- .optional()
3475
- .describe("Run FILE after each scan, including failures."),
3476
- diff: optionValue("--diff")
3477
- .optional()
3478
- .describe("Scan committed Git changes from BASE to --head."),
3479
- workingTree: z
3480
- .boolean()
3481
- .optional()
3482
- .meta({ default: false })
3483
- .describe("Scan staged and unstaged changes against --base."),
3484
- head: optionValue("--head")
3485
- .optional()
3486
- .describe("Git head ref for --diff (default: HEAD)."),
3487
- base: optionValue("--base")
3488
- .optional()
3489
- .describe("Git base ref for --working-tree (default: HEAD)."),
3490
- mode: ScanSettingsSchema.shape.mode.describe("Scan mode (default: standard); deep supports repository and path targets."),
3491
- maxTime: ScanSettingsSchema.shape.maxTimeMinutes,
3492
- ...DEEP_SCAN_OPTION_SCHEMAS,
3493
- ...modelOptions(`OpenAI model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`).shape,
3494
- provider: PROVIDER_OPTION,
3495
- outputDir: optionValue("--output-dir")
3496
- .optional()
3497
- .describe("Artifact directory outside the repository (default: Codex Security state; CODEX_SECURITY_STATE_DIR)."),
3498
- archiveExisting: z
3499
- .boolean()
3500
- .default(false)
3501
- .describe("Archive existing results; requires --output-dir."),
3502
- ...RUNTIME_OPTION_SCHEMAS,
3503
- failOnSeverity: FailureSeveritySchema.optional().describe("Exit 1 for findings at or above LEVEL."),
3504
- patch: z
3505
- .boolean()
3506
- .default(false)
3507
- .describe("Patch and verify confirmed findings after the scan."),
3508
- validate: z
3509
- .boolean()
3510
- .default(false)
3511
- .describe("Run standalone finding validation after the scan."),
3512
- patchSeverity: z
3513
- .enum(REPORTABLE_SEVERITIES)
3514
- .optional()
3515
- .describe("Patch findings at or above LEVEL; requires --patch."),
3516
- createPr: CREATE_PR_OPTION.describe("Create a draft pull request or merge request after verified patches; requires --patch."),
3517
- maxCost: ScanSettingsSchema.shape.maxCostUsd.describe("Stop above AMOUNT in estimated USD; the dashboard offers increases near the limit."),
3518
- ownerSuggestions: ScanSettingsSchema.shape.ownerSuggestions,
3519
- showCost: SHOW_COST_OPTION,
3520
- headless: z
3521
- .boolean()
3522
- .default(false)
3523
- .describe("Use plain text progress instead of the interactive dashboard."),
3524
- dryRun: z
3525
- .boolean()
3526
- .default(false)
3527
- .describe("Validate local scan inputs without starting a scan."),
3528
- mock: z
3529
- .boolean()
3530
- .default(false)
3531
- .describe("Save synthetic Standard scan findings without calling an LLM."),
3532
- })
3533
- .refine((options) => options.patchSeverity === undefined || options.patch, {
3534
- message: "--patch-severity requires --patch.",
3535
- })
3536
- .refine((options) => !options.createPr || options.patch, {
3537
- message: "--create-pr requires --patch.",
3538
- })
3539
- .refine((options) => !options.patch || !options.dryRun, {
3540
- message: "--patch cannot be combined with --dry-run.",
3541
- })
3542
- .refine((options) => !options.validate || !options.dryRun, {
3543
- message: "--validate cannot be combined with --dry-run.",
3544
- })
3545
- .refine((options) => !options.mock ||
3546
- (!options.dryRun && !options.patch && !options.validate), {
3547
- message: "--mock cannot be combined with --dry-run, --patch, or --validate.",
3548
- }),
3549
- output: scanOutputSchema("SCAN_FAILED"),
3550
- async run({ args, error: incurError, format, options }) {
3551
- if (options.host)
3552
- throw new CodexSecurityError("Use scan --host alone.");
3553
- if (format === "md") {
3554
- const error = new CodexSecurityError("Markdown output is not supported for scan results.");
3555
- errorOutput.write(`codex-security: ${diagnosticLines(error)}\n`);
3556
- exitCode = 2;
3557
- throw error;
3558
- }
3559
- let outcome;
3560
- try {
3561
- const directory = dependencies.currentDirectory();
3562
- const project = await selectedProjectConfig(options.config, dependencies);
3563
- const scope = resolveCliScope(project?.input.scan?.scope, {
3564
- paths: options.path,
3565
- diff: options.diff,
3566
- workingTree: options.workingTree,
3567
- head: options.head,
3568
- base: options.base,
3569
- });
3570
- const { config, options: settings, projectConfig: provenance, } = resolveScanSettings(project, {
3571
- ...pickScanSettings(options),
3572
- target: scope.target,
3573
- knowledgeBasePaths: options.knowledgeBase,
3574
- failureSeverity: options.failOnSeverity,
3575
- maxCostUsd: options.maxCost,
3576
- maxTimeMinutes: options.maxTime,
3577
- codexOverrides: await parseScanCodexOverrides(options, dependencies.environment, project?.input.codex),
3578
- }, directory, scope.sources);
3579
- if (options.archiveExisting && settings.outputDir === undefined) {
3580
- throw new CodexSecurityError("--archive-existing requires --output-dir.");
3758
+ });
3759
+ function createScanCommands() {
3760
+ return Cli.create("scan", {
3761
+ description: "Scan a repository, selected paths, or Git changes.",
3762
+ usage: [
3763
+ {
3764
+ suffix: "[repository] [--path PATH | --diff REF | --working-tree] [options]",
3765
+ },
3766
+ { suffix: "--host" },
3767
+ { suffix: "import (--csv FILE | --json FILE) [options]" },
3768
+ ],
3769
+ examples: [
3770
+ { args: { repository: "." }, options: { dryRun: true } },
3771
+ { args: { repository: "." } },
3772
+ { args: { repository: "." }, options: { path: ["src", "tests"] } },
3773
+ { args: { repository: "." }, options: { workingTree: true } },
3774
+ { args: { repository: "." }, options: { diff: "origin/main" } },
3775
+ { args: { repository: "." }, options: { mode: "deep" } },
3776
+ ],
3777
+ hint: "Import existing findings without security analysis with scan import --help. Use ./import to scan a repository named import. Execution failures in JSON/JSONL --full-output return ok: false and keep scan results under data.",
3778
+ destructive: true,
3779
+ alias: { config: "c" },
3780
+ args: z.object({
3781
+ repository: z
3782
+ .string()
3783
+ .optional()
3784
+ .describe("Repository root to scan (default: current directory)."),
3785
+ }),
3786
+ options: z
3787
+ .object({
3788
+ config: PROJECT_CONFIG_OPTION,
3789
+ host: z
3790
+ .boolean()
3791
+ .default(false)
3792
+ .describe("Run one hosted Standard scan over JSON-RPC stdin/stdout; use alone."),
3793
+ workflowId: optionValue("--workflow-id")
3794
+ .optional()
3795
+ .describe("Reuse completed work in the named local findings workflow."),
3796
+ cyberAccessProgram: ScanSettingsSchema.shape.cyberAccessProgram,
3797
+ auth: ScanSettingsSchema.shape.auth.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication (default: auto)."),
3798
+ verbose: z
3799
+ .boolean()
3800
+ .default(false)
3801
+ .describe("Print additional scan diagnostics to stderr."),
3802
+ safetyIdentifier: optionValue("--safety-identifier")
3803
+ .optional()
3804
+ .describe("Stable hashed end-user ID for model requests (1–64 characters). Requires a compatible Codex runtime."),
3805
+ path: z
3806
+ .array(optionValue("--path"))
3807
+ .optional()
3808
+ .meta({ default: [] })
3809
+ .describe("Scan only PATH; repeat for multiple repository-relative paths."),
3810
+ excludePath: z
3811
+ .array(optionValue("--exclude-path"))
3812
+ .optional()
3813
+ .meta({ default: [] })
3814
+ .describe("Exclude a literal repository-relative file or directory; repeat for multiple paths."),
3815
+ knowledgeBase: z
3816
+ .array(optionValue("--knowledge-base"))
3817
+ .optional()
3818
+ .meta({ default: [] })
3819
+ .describe("Add security-context files or directories; repeat for multiple paths."),
3820
+ rubric: optionValue("--rubric")
3821
+ .optional()
3822
+ .describe("Use this Markdown file to grade findings. Takes precedence over the default severity rubric."),
3823
+ scanPromptFile: optionValue("--scan-prompt-file")
3824
+ .optional()
3825
+ .describe("Append scan instructions from FILE."),
3826
+ validationPromptFile: optionValue("--validation-prompt-file")
3827
+ .optional()
3828
+ .describe("Replace final validation with the workflow in FILE (not Deep)."),
3829
+ postScanPromptFile: optionValue("--post-scan-prompt-file")
3830
+ .optional()
3831
+ .describe("Run FILE after each scan, including failures."),
3832
+ diff: optionValue("--diff")
3833
+ .optional()
3834
+ .describe("Scan committed Git changes from BASE to --head."),
3835
+ workingTree: z
3836
+ .boolean()
3837
+ .optional()
3838
+ .meta({ default: false })
3839
+ .describe("Scan staged and unstaged changes against --base."),
3840
+ head: optionValue("--head")
3841
+ .optional()
3842
+ .describe("Git head ref for --diff (default: HEAD)."),
3843
+ base: optionValue("--base")
3844
+ .optional()
3845
+ .describe("Git base ref for --working-tree (default: HEAD)."),
3846
+ mode: ScanSettingsSchema.shape.mode.describe("Scan mode (default: standard); deep supports repository and path targets."),
3847
+ maxTime: ScanSettingsSchema.shape.maxTimeMinutes,
3848
+ ...DEEP_SCAN_OPTION_SCHEMAS,
3849
+ ...modelOptions(`OpenAI model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`).shape,
3850
+ provider: PROVIDER_OPTION,
3851
+ outputDir: optionValue("--output-dir")
3852
+ .optional()
3853
+ .describe("Artifact directory outside the repository (default: Codex Security state; CODEX_SECURITY_STATE_DIR)."),
3854
+ archiveExisting: z
3855
+ .boolean()
3856
+ .default(false)
3857
+ .describe("Archive existing results; requires --output-dir."),
3858
+ ...RUNTIME_OPTION_SCHEMAS,
3859
+ failOnSeverity: FailureSeveritySchema.optional().describe("Exit 1 for findings at or above LEVEL."),
3860
+ patch: z
3861
+ .boolean()
3862
+ .default(false)
3863
+ .describe("Patch and verify findings after a scan without a cost limit."),
3864
+ validate: z
3865
+ .boolean()
3866
+ .default(false)
3867
+ .describe("Run standalone finding validation after the scan."),
3868
+ patchSeverity: z
3869
+ .enum(REPORTABLE_SEVERITIES)
3870
+ .optional()
3871
+ .describe("Patch findings at or above LEVEL; requires --patch."),
3872
+ createPr: CREATE_PR_OPTION.describe("Create a draft pull request or merge request after verified patches; requires --patch."),
3873
+ maxCost: ScanSettingsSchema.shape.maxCostUsd.describe("Stop above AMOUNT in estimated USD; the dashboard offers increases near the limit."),
3874
+ ownerSuggestions: ScanSettingsSchema.shape.ownerSuggestions,
3875
+ showCost: SHOW_COST_OPTION,
3876
+ headless: z
3877
+ .boolean()
3878
+ .default(false)
3879
+ .describe("Use plain text progress instead of the interactive dashboard."),
3880
+ dryRun: z
3881
+ .boolean()
3882
+ .default(false)
3883
+ .describe("Validate local scan inputs without starting a scan."),
3884
+ mock: z
3885
+ .boolean()
3886
+ .default(false)
3887
+ .describe("Save synthetic Standard scan findings without calling an LLM."),
3888
+ })
3889
+ .refine((options) => options.patchSeverity === undefined || options.patch, {
3890
+ message: "--patch-severity requires --patch.",
3891
+ })
3892
+ .refine((options) => !options.createPr || options.patch, {
3893
+ message: "--create-pr requires --patch.",
3894
+ })
3895
+ .refine((options) => !options.patch || !options.dryRun, {
3896
+ message: "--patch cannot be combined with --dry-run.",
3897
+ })
3898
+ .refine((options) => !options.validate || !options.dryRun, {
3899
+ message: "--validate cannot be combined with --dry-run.",
3900
+ })
3901
+ .refine((options) => !options.mock ||
3902
+ (!options.dryRun && !options.patch && !options.validate), {
3903
+ message: "--mock cannot be combined with --dry-run, --patch, or --validate.",
3904
+ }),
3905
+ output: scanOutputSchema("SCAN_FAILED"),
3906
+ async run({ args, error: incurError, format, options }) {
3907
+ if (options.host)
3908
+ throw new CodexSecurityError("Use scan --host alone.");
3909
+ if (format === "md") {
3910
+ const error = new CodexSecurityError("Markdown output is not supported for scan results.");
3911
+ errorOutput.write(`codex-security: ${diagnosticLines(error)}\n`);
3912
+ exitCode = 2;
3913
+ throw error;
3914
+ }
3915
+ let outcome;
3916
+ try {
3917
+ const directory = dependencies.currentDirectory();
3918
+ const project = await selectedProjectConfig(options.config, dependencies);
3919
+ const scope = resolveCliScope(project?.input.scan?.scope, {
3920
+ paths: options.path,
3921
+ diff: options.diff,
3922
+ workingTree: options.workingTree,
3923
+ head: options.head,
3924
+ base: options.base,
3925
+ });
3926
+ const { config, options: settings, projectConfig: provenance, } = resolveScanSettings(project, {
3927
+ ...pickScanSettings(options),
3928
+ target: scope.target,
3929
+ excludePaths: options.excludePath,
3930
+ knowledgeBasePaths: options.knowledgeBase,
3931
+ failureSeverity: options.failOnSeverity,
3932
+ maxCostUsd: options.maxCost,
3933
+ maxTimeMinutes: options.maxTime,
3934
+ codexOverrides: await parseScanCodexOverrides(options, dependencies.environment, project?.input.codex),
3935
+ }, directory, scope.sources);
3936
+ if (options.archiveExisting && settings.outputDir === undefined) {
3937
+ throw new CodexSecurityError("--archive-existing requires --output-dir.");
3938
+ }
3939
+ if (options.validate && settings.maxCostUsd !== undefined) {
3940
+ throw new CodexSecurityError("--validate cannot be combined with a scan cost limit because standalone validation is not cost-tracked.");
3941
+ }
3942
+ outcome = await runScan(format, {
3943
+ ...settings,
3944
+ rubricPath: options.rubric === undefined
3945
+ ? undefined
3946
+ : resolveCliPath(directory, options.rubric),
3947
+ codexOverrides: config.codexOverrides,
3948
+ projectConfig: provenance,
3949
+ workflowId: options.workflowId,
3950
+ safetyIdentifier: options.safetyIdentifier,
3951
+ verbose: options.verbose,
3952
+ repository: args.repository,
3953
+ archiveExisting: options.archiveExisting,
3954
+ pluginPath: options.pluginPath,
3955
+ pythonPath: options.python,
3956
+ patch: options.patch,
3957
+ validate: options.validate,
3958
+ patchSeverity: options.patchSeverity,
3959
+ createPr: options.createPr,
3960
+ showCost: options.showCost,
3961
+ headless: options.headless,
3962
+ dryRun: options.dryRun,
3963
+ mock: options.mock,
3964
+ });
3581
3965
  }
3582
- if (options.validate && settings.maxCostUsd !== undefined) {
3583
- throw new CodexSecurityError("--validate cannot be combined with a scan cost limit because standalone validation is not cost-tracked.");
3966
+ catch (error) {
3967
+ const message = errorMessage(error);
3968
+ errorOutput.write(`${diagnosticLines(message)}\n`);
3969
+ outcome = { exitCode: 2, error: message };
3584
3970
  }
3585
- outcome = await runScan(format, {
3586
- ...settings,
3587
- rubricPath: options.rubric === undefined
3971
+ return options.dryRun
3972
+ ? finishScan(outcome, format, incurError)
3973
+ : finishScanCommand(outcome, format, incurError);
3974
+ },
3975
+ }).command("import", {
3976
+ usage: [{ suffix: "FILE [options]" }],
3977
+ description: "Save CSV or JSON findings as a completed scan without security analysis.",
3978
+ destructive: true,
3979
+ args: z.object({
3980
+ file: z
3981
+ .string({ error: "Provide a findings file to import." })
3982
+ .min(1)
3983
+ .describe("Findings file to import."),
3984
+ }),
3985
+ options: z
3986
+ .object({
3987
+ inputFormat: z
3988
+ .enum(["csv", "json"])
3989
+ .optional()
3990
+ .describe("Input format (default: inferred from .csv or .json)."),
3991
+ outputDir: optionValue("--output-dir")
3992
+ .optional()
3993
+ .describe("Artifact directory (default: Codex Security state; CODEX_SECURITY_STATE_DIR)."),
3994
+ archiveExisting: z
3995
+ .boolean()
3996
+ .default(false)
3997
+ .describe("Archive existing results; requires --output-dir."),
3998
+ dryRun: z
3999
+ .boolean()
4000
+ .default(false)
4001
+ .describe("Validate the input without saving a scan."),
4002
+ })
4003
+ .refine((options) => !options.archiveExisting || options.outputDir !== undefined, { message: "--archive-existing requires --output-dir." }),
4004
+ examples: [
4005
+ { args: { file: "findings.csv" } },
4006
+ { args: { file: "report" }, options: { inputFormat: "json" } },
4007
+ ],
4008
+ hint: "Each input row is retained, including duplicates. Use FILE --json for JSON output. Legacy --csv FILE and --json FILE still select the input format.",
4009
+ output: z.record(z.string(), z.unknown()).optional(),
4010
+ async run({ args, options, format, error: incurError }) {
4011
+ const directory = dependencies.currentDirectory();
4012
+ const inputFormat = options.inputFormat ?? extname(args.file).slice(1).toLowerCase();
4013
+ if (inputFormat !== "csv" && inputFormat !== "json") {
4014
+ exitCode = 2;
4015
+ const message = "Cannot infer input format. Use --input-format csv or --input-format json.";
4016
+ errorOutput.write(`codex-security: ${message}\n`);
4017
+ return incurError({
4018
+ code: "INVALID_INPUT_FORMAT",
4019
+ message,
4020
+ exitCode,
4021
+ });
4022
+ }
4023
+ const outcome = await runImport({
4024
+ sourcePath: resolveCliPath(directory, args.file),
4025
+ format: inputFormat,
4026
+ outputDir: options.outputDir === undefined
3588
4027
  ? undefined
3589
- : resolveCliPath(directory, options.rubric),
3590
- codexOverrides: config.codexOverrides,
3591
- projectConfig: provenance,
3592
- workflowId: options.workflowId,
3593
- safetyIdentifier: options.safetyIdentifier,
3594
- verbose: options.verbose,
3595
- repository: args.repository,
4028
+ : resolveCliPath(directory, options.outputDir),
3596
4029
  archiveExisting: options.archiveExisting,
3597
- pluginPath: options.pluginPath,
3598
- pythonPath: options.python,
3599
- patch: options.patch,
3600
- validate: options.validate,
3601
- patchSeverity: options.patchSeverity,
3602
- createPr: options.createPr,
3603
- showCost: options.showCost,
3604
- headless: options.headless,
3605
4030
  dryRun: options.dryRun,
3606
- mock: options.mock,
3607
4031
  });
3608
- }
3609
- catch (error) {
3610
- const message = errorMessage(error);
3611
- errorOutput.write(`${diagnosticLines(message)}\n`);
3612
- outcome = { exitCode: 2, error: message };
3613
- }
3614
- return options.dryRun
3615
- ? finishScan(outcome, format, incurError)
3616
- : finishScanCommand(outcome, format, incurError);
3617
- },
3618
- })
4032
+ exitCode = outcome.exitCode;
4033
+ if (outcome.error !== undefined) {
4034
+ return incurError({
4035
+ code: "SCAN_IMPORT_FAILED",
4036
+ message: outcome.error,
4037
+ exitCode,
4038
+ });
4039
+ }
4040
+ if (!options.dryRun && useDefaultOutput(format)) {
4041
+ return;
4042
+ }
4043
+ return outcome.data;
4044
+ },
4045
+ });
4046
+ }
4047
+ cli
4048
+ .command(createScanCommands())
3619
4049
  .command("install-hook", {
3620
- description: "Install a local pre-commit hook that blocks on scan errors or findings at the selected severity threshold.",
4050
+ description: "Install a pre-commit hook that scans staged and unstaged working-tree changes and blocks on errors or findings at the selected severity.",
4051
+ examples: [
4052
+ { args: { repository: "." }, options: { failOnSeverity: "high" } },
4053
+ ],
3621
4054
  hint: "Require a passing scan in CI to enforce a scan before merging.",
3622
4055
  destructive: true,
3623
4056
  args: z.object({
@@ -3641,43 +4074,26 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3641
4074
  async run({ args, options }) {
3642
4075
  try {
3643
4076
  const cwd = dependencies.currentDirectory();
3644
- const repository = resolveCliPath(cwd, args.repository ?? ".");
3645
4077
  const environment = dependencies.environment;
3646
- const git = await trustedGitCommand(repository, true, environment, await commandGitProtectionRoots(repository, environment, undefined, cwd));
3647
- const hook = execFileSync(git.executable, [
4078
+ const requested = resolveInputPath(args.repository ?? ".", cwd, environment);
4079
+ const repository = await resolveParentTraversal(requested);
4080
+ const git = await trustedGitCommand(repository, true, environment, await commandGitProtectionRoots(repository, environment, undefined, { cwd, requestedPaths: [resolve(requested)] }));
4081
+ const hooksDirectory = execFileSync(git.executable, [
3648
4082
  "-C",
3649
4083
  repository,
3650
4084
  "rev-parse",
3651
4085
  "--path-format=absolute",
3652
4086
  "--git-path",
3653
- "hooks/pre-commit",
3654
- ], { encoding: "utf8", env: git.environment }).trim();
4087
+ "hooks",
4088
+ ], { encoding: "utf8", env: git.environment }).replace(/\r?\n$/u, "");
4089
+ const hook = join(hooksDirectory, "pre-commit");
3655
4090
  const command = [
3656
4091
  realpathSync(process.execPath),
3657
4092
  realpathSync(fileURLToPath(import.meta.url)),
3658
4093
  ]
3659
4094
  .map((path) => `'${path.replaceAll("'", `'"'"'`)}'`)
3660
4095
  .join(" ");
3661
- const invocation = `exec ${command} scan . --working-tree --fail-on-severity ${options.failOnSeverity}\n`;
3662
- const contents = `#!/bin/sh\nset -eu\nunset ${[...UNSUPPORTED_GIT_ENVIRONMENT].join(" ")}\n${invocation}`;
3663
- const previousScopedContents = `#!/bin/sh\nset -eu\nunset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE\n${invocation}`;
3664
- const previousContents = `#!/bin/sh\nset -eu\n${invocation}`;
3665
- const legacyContents = `#!/bin/sh\nset -eu\nexec npx --no-install codex-security scan . --working-tree --fail-on-severity ${options.failOnSeverity}\n`;
3666
- const existing = await readFile(hook, "utf8").catch(() => null);
3667
- if (existing !== null &&
3668
- existing !== contents &&
3669
- existing !== previousScopedContents &&
3670
- existing !== previousContents &&
3671
- existing !== legacyContents) {
3672
- throw new Error(`A pre-commit hook already exists at ${hook}.`);
3673
- }
3674
- if (existing === null) {
3675
- await mkdir(dirname(hook), { recursive: true });
3676
- await writeFile(hook, contents, { flag: "wx", mode: 0o755 });
3677
- }
3678
- else if (existing !== contents) {
3679
- await writeFile(hook, contents, { flag: "w" });
3680
- }
4096
+ await installManagedHook(hook, command, options.failOnSeverity);
3681
4097
  return {
3682
4098
  hook,
3683
4099
  failOnSeverity: options.failOnSeverity,
@@ -3690,10 +4106,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3690
4106
  }
3691
4107
  },
3692
4108
  })
3693
- .command(scanHistory)
3694
4109
  .command(findingFeedback)
3695
4110
  .command(publication)
3696
4111
  .command("suggest-owners", {
4112
+ examples: [{ args: { findings: "findings.json" } }],
3697
4113
  description: "Suggest finding owners from CODEOWNERS and Git history.",
3698
4114
  destructive: false,
3699
4115
  args: z.object({
@@ -3714,7 +4130,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3714
4130
  const removeSignals = listenForAbort(dependencies, controller);
3715
4131
  try {
3716
4132
  const directory = dependencies.currentDirectory();
3717
- const repository = resolveCliPath(directory, options.sourceRoot ?? ".");
4133
+ const repository = resolveInputPath(options.sourceRoot ?? ".", directory);
3718
4134
  const findings = await parseImportedFindings(await readRegularInputFile(resolveCliPath(directory, args.findings), repository), "json", await bundledPluginRoot());
3719
4135
  const result = await (dependencies.suggestOwners ?? suggestOwnersInternal)(repository, findings, {
3720
4136
  environment: dependencies.environment,
@@ -3739,14 +4155,19 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3739
4155
  })
3740
4156
  .command("classify-severity", {
3741
4157
  description: "Assess severity for saved findings or canonical records.",
3742
- hint: "For saved findings, use --rubric for your own policy or set CODEX_SECURITY_ENABLE_REMOTE_SEVERITY_RUBRIC=1 for the Statsig default. For host-provided reviews, use --records.",
4158
+ usage: [
4159
+ { suffix: "(--scan ID | --scan-dir DIR) [options]" },
4160
+ { suffix: "--records [--runs COUNT]" },
4161
+ ],
4162
+ examples: [{ options: { scan: "latest" } }],
4163
+ hint: `Use the built-in severity rubric or select --rubric FILE. Each uncached finding receives ${DEFAULT_REVIEW_RUNS} model reviews by default. Use --reprocess to replace saved assessments. --records accepts host-provided reviews over JSON-RPC.`,
3743
4164
  destructive: true,
3744
4165
  options: z.object({
3745
4166
  runs: reviewRunsOption.describe(`Number of independent classification runs (1–10; default: ${DEFAULT_REVIEW_RUNS}).`),
3746
4167
  records: z
3747
4168
  .boolean()
3748
4169
  .default(false)
3749
- .describe("Classify canonical records through host-provided reviews over version 1 JSON-RPC; accepts --runs."),
4170
+ .describe("Classify canonical records through host-provided reviews over version 1 JSON-RPC. Accepts --runs. Hosts can enable CLI diagnostics with the Node condition codex-security-records-logs-v1."),
3750
4171
  reprocess: z
3751
4172
  .boolean()
3752
4173
  .default(false)
@@ -3821,8 +4242,14 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3821
4242
  },
3822
4243
  })
3823
4244
  .command("dedupe", {
3824
- description: "Identify duplicate findings in a saved scan.",
3825
- hint: "Use --records alone for host-provided reviews over JSON-RPC.",
4245
+ description: "Find duplicates against the saved findings corpus.",
4246
+ usage: [
4247
+ { suffix: "--scan ID [--workflow-id ID] [options]" },
4248
+ { suffix: "--workflow-id ID [options]" },
4249
+ { suffix: "--records" },
4250
+ ],
4251
+ examples: [{ options: { scan: "latest" } }],
4252
+ hint: "Service-backed deduplication can save duplicate groups to the selected findings service. Use --records alone for host-provided reviews over JSON-RPC.",
3826
4253
  destructive: true,
3827
4254
  options: z.object({
3828
4255
  concurrency: positiveInteger
@@ -3852,6 +4279,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3852
4279
  .object({
3853
4280
  scanId: z.string(),
3854
4281
  uniqueFindingIds: z.array(z.string()),
4282
+ scanRepresentativeFindingIds: z.array(z.string()),
3855
4283
  duplicateGroups: z.array(z.array(z.string())),
3856
4284
  deduplicationStatus: z.enum(["completed", "completed_with_refusals"]),
3857
4285
  refusals: z
@@ -3968,7 +4396,30 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3968
4396
  })
3969
4397
  .command(imports)
3970
4398
  .command("scan-components", {
3971
- description: "Scan project components and combine results.",
4399
+ description: "Scan project components independently and combine their results.",
4400
+ usage: [
4401
+ {
4402
+ suffix: "[repository] (--component PATH | --components-file FILE | --auto) --output-dir DIR [options]",
4403
+ },
4404
+ ],
4405
+ examples: [
4406
+ {
4407
+ args: { repository: "." },
4408
+ options: {
4409
+ component: ["services/api"],
4410
+ outputDir: "../component-results",
4411
+ },
4412
+ },
4413
+ {
4414
+ args: { repository: "." },
4415
+ options: {
4416
+ auto: true,
4417
+ planOnly: true,
4418
+ outputDir: "../component-plan",
4419
+ },
4420
+ },
4421
+ ],
4422
+ hint: "Supply --output-dir or configure output.directory. Automatic planning can call a model even with --plan-only. A per-component --max-cost does not cover planning.",
3972
4423
  destructive: true,
3973
4424
  alias: { config: "c" },
3974
4425
  args: z.object({
@@ -3997,7 +4448,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3997
4448
  planOnly: z
3998
4449
  .boolean()
3999
4450
  .default(false)
4000
- .describe("Save components.json without starting scans."),
4451
+ .describe("Save components.json and print a command to run it. Explicit plans work offline."),
4001
4452
  headless: z
4002
4453
  .boolean()
4003
4454
  .default(false)
@@ -4022,6 +4473,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4022
4473
  ...modelOptions("Model for planning and component scans.").shape,
4023
4474
  provider: PROVIDER_OPTION,
4024
4475
  maxCost: ScanSettingsSchema.shape.maxCostUsd.describe("Stop each component scan if estimated USD cost exceeds AMOUNT."),
4476
+ maxTotalCost: ScanSettingsSchema.shape.maxCostUsd.describe("Divide estimated USD among explicit components for this invocation. Skips model-based finding matching and owner suggestions."),
4025
4477
  showCost: SHOW_COST_OPTION,
4026
4478
  ...RUNTIME_OPTION_SCHEMAS,
4027
4479
  })
@@ -4047,7 +4499,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4047
4499
  signalHandlers(dependencies, "add", onInterrupt, onTerminate);
4048
4500
  try {
4049
4501
  const directory = dependencies.currentDirectory();
4050
- const repository = resolveCliPath(directory, args.repository ?? ".");
4502
+ const repository = resolveInputPath(args.repository ?? ".", directory);
4051
4503
  const project = await selectedProjectConfig(options.config, dependencies);
4052
4504
  const resolved = resolveScanSettings(project, {
4053
4505
  ...pickScanSettings({ ...options, workers: undefined }),
@@ -4080,6 +4532,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4080
4532
  pricingContext: scanPricingContext(dashboardConfig, dependencies.environment),
4081
4533
  mode: settings.mode,
4082
4534
  maxCostUsd: settings.maxCostUsd,
4535
+ maxTotalCostUsd: options.maxTotalCost,
4083
4536
  showCost: options.showCost,
4084
4537
  clock: dependencies,
4085
4538
  color: dependencies.environment["NO_COLOR"] === undefined,
@@ -4099,6 +4552,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4099
4552
  outputDir: settings.outputDir,
4100
4553
  ...(options.auto ? { auto: true } : { components }),
4101
4554
  planOnly: options.planOnly,
4555
+ maxTotalCostUsd: options.maxTotalCost,
4102
4556
  workers: options.workers,
4103
4557
  config,
4104
4558
  scanOptions: {
@@ -4109,6 +4563,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4109
4563
  planComponents: dependencies.planComponents,
4110
4564
  matchFindings: dependencies.matchFindings,
4111
4565
  onPlan: (components) => {
4566
+ if (dashboard === null && options.maxTotalCost !== undefined)
4567
+ errorOutput.write(`codex-security: ${formatUsd(options.maxTotalCost)} total limit for this invocation. Model-based finding matching and owner suggestions are skipped.\n`);
4112
4568
  for (const component of components)
4113
4569
  componentNames.set(component.id, component.name);
4114
4570
  dashboard?.setComponents(components);
@@ -4117,7 +4573,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4117
4573
  ? (event) => {
4118
4574
  const componentName = diagnosticValue(componentNames.get(event.componentId) ??
4119
4575
  event.componentId);
4120
- const line = componentScanEventLine(componentName, event, options.showCost || settings.maxCostUsd !== undefined, settings.auth);
4576
+ const line = componentScanEventLine(componentName, event, options.showCost ||
4577
+ settings.maxCostUsd !== undefined ||
4578
+ options.maxTotalCost !== undefined, settings.auth);
4121
4579
  if (line !== null)
4122
4580
  errorOutput.write(line);
4123
4581
  }
@@ -4133,17 +4591,54 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4133
4591
  onProgress: (component) => {
4134
4592
  if (dashboard !== null)
4135
4593
  dashboard.updateComponent(component);
4136
- else
4137
- errorOutput.write(`codex-security: ${diagnosticValue(component.name)} ${component.status}${component.error === undefined ? "" : `: ${diagnosticValue(component.error)}`}\n`);
4594
+ else {
4595
+ const budget = component.status === "started" &&
4596
+ component.maxCostUsd !== undefined
4597
+ ? ` (${formatUsd(component.maxCostUsd)} per component)`
4598
+ : "";
4599
+ errorOutput.write(`codex-security: ${diagnosticValue(component.name)} ${component.status}${budget}${component.error === undefined ? "" : `: ${diagnosticValue(component.error)}`}\n`);
4600
+ }
4138
4601
  },
4139
4602
  onComplete: (result) => {
4140
4603
  dashboard?.finishComponents(result);
4141
4604
  stopDashboard();
4142
- errorOutput.write(`Component scans: ${result.completed} complete, ${result.failed} failed.\n${result.sourceFindingCount} findings → ${result.findingCount} groups${result.deduplication?.status === "failed" ? " (matching failed)" : ""}.\nReport: ${errorMessage(result.reportPath)}\n`);
4605
+ errorOutput.write(`Component scans: ${result.completed} complete, ${result.failed} failed.\n${result.sourceFindingCount} findings → ${result.findingCount} groups${result.deduplication?.status === "failed" ? " (matching failed)" : result.deduplication?.status === "skipped" ? " (matching skipped under total cost limit)" : ""}.\nReport: ${errorMessage(result.reportPath)}\n`);
4143
4606
  if (result.retryPlanPath !== undefined)
4144
4607
  errorOutput.write(`Retry with --components-file ${JSON.stringify(errorMessage(result.retryPlanPath))} and a new --output-dir.\n`);
4145
4608
  },
4146
4609
  });
4610
+ if (options.planOnly) {
4611
+ const { auto, component, componentsFile, planOnly, outputDir, config, codex, ...scanOptions } = options;
4612
+ const supplied = new Set(argv.map((arg) => arg.split("=", 1)[0]));
4613
+ const overrides = Object.fromEntries(Object.entries(scanOptions).filter(([key]) => {
4614
+ const flag = cliOptionFlag(key);
4615
+ return (supplied.has(flag) ||
4616
+ supplied.has(`--${key}`) ||
4617
+ supplied.has(`--no-${flag.slice(2)}`));
4618
+ }));
4619
+ const nextCommand = [
4620
+ "codex-security",
4621
+ "scan-components",
4622
+ quoteCliPath(repository),
4623
+ ...cliOptionTokens({
4624
+ componentsFile: result.planPath,
4625
+ outputDir: join(dirname(result.planPath), "results"),
4626
+ config: project?.path,
4627
+ ...overrides,
4628
+ }),
4629
+ ].join(" ");
4630
+ const nextCommandNote = codex.length > 0
4631
+ ? "Reapply your --codex overrides when running this command."
4632
+ : undefined;
4633
+ errorOutput.write(`Run this plan: ${diagnosticValue(nextCommand)}\n`);
4634
+ if (nextCommandNote)
4635
+ errorOutput.write(`${nextCommandNote}\n`);
4636
+ return {
4637
+ ...result,
4638
+ nextCommand,
4639
+ ...(nextCommandNote && { nextCommandNote }),
4640
+ };
4641
+ }
4147
4642
  exitCode =
4148
4643
  interruptedExitCode(controller.signal) ??
4149
4644
  (result.failed || result.deduplication?.status === "failed"
@@ -4186,7 +4681,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4186
4681
  .string()
4187
4682
  .min(1, "--output-dir must not be empty.")
4188
4683
  .optional()
4189
- .describe("Resumable results directory; required with a repository CSV."),
4684
+ .describe("Results directory. Required with a CSV and used as the initial directory in the wizard."),
4190
4685
  knowledgeBase: z
4191
4686
  .array(optionValue("--knowledge-base"))
4192
4687
  .optional()
@@ -4209,20 +4704,27 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4209
4704
  provider: PROVIDER_OPTION,
4210
4705
  maxAttempts: positiveInteger
4211
4706
  .default(1)
4212
- .describe("Maximum scan attempts per repository."),
4707
+ .describe("Try each CSV row up to this many times per run."),
4213
4708
  maxCost: ScanSettingsSchema.shape.maxCostUsd.describe("Stop each repository attempt if estimated USD cost exceeds AMOUNT."),
4709
+ maxTotalCost: ScanSettingsSchema.shape.maxCostUsd.describe("Divide estimated USD among pending repository attempts, including retries, for this invocation. Skips model-based finding matching and owner suggestions."),
4214
4710
  ...runtimeOptions(() => z.string().min(1)),
4215
4711
  }),
4712
+ usage: [
4713
+ { suffix: "[options]" },
4714
+ { suffix: "repositories.csv --output-dir DIR [options]" },
4715
+ { suffix: "repositories.csv --recover --output-dir DIR [options]" },
4716
+ ],
4216
4717
  examples: [
4217
4718
  {
4218
- args: {},
4219
- options: { model: "gpt-5.6-terra", effort: "high" },
4719
+ args: { input: "repositories.csv" },
4720
+ options: { outputDir: "../campaign", workers: 4, maxAttempts: 3 },
4721
+ },
4722
+ {
4723
+ args: { input: "repositories.csv" },
4724
+ options: { recover: true, outputDir: "../campaign" },
4220
4725
  },
4221
4726
  ],
4222
- hint: "CSV example:\n" +
4223
- " codex-security bulk-scan repositories.csv " +
4224
- "--output-dir /path/outside/repositories/results " +
4225
- "--workers 4 --max-attempts 3",
4727
+ hint: "Omit the CSV to select repositories interactively. A configured output.directory can supply the results directory; --max-cost applies per repository attempt.",
4226
4728
  output: z.record(z.string(), z.unknown()).optional(),
4227
4729
  async run({ args, options }) {
4228
4730
  const controller = new AbortController();
@@ -4244,9 +4746,6 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4244
4746
  let outputDir;
4245
4747
  let githubHost;
4246
4748
  if (args.input === undefined) {
4247
- if (options.outputDir !== undefined) {
4248
- throw new Error("--output-dir can only be used with a repository CSV; omit it to choose an output directory interactively.");
4249
- }
4250
4749
  const wizard = await runBulkScanWizard(dependencies.bulkScan ??
4251
4750
  createBulkScanDiscoveryDependencies({
4252
4751
  output: errorOutput,
@@ -4263,7 +4762,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4263
4762
  if (settings.outputDir === undefined) {
4264
4763
  throw new Error("--output-dir is required with a repository CSV.");
4265
4764
  }
4266
- inputPath = resolveCliPath(currentDirectory, args.input);
4765
+ inputPath = resolveInputPath(args.input, currentDirectory);
4267
4766
  outputDir = settings.outputDir;
4268
4767
  }
4269
4768
  const scanOptionsByMode = project === undefined
@@ -4272,6 +4771,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4272
4771
  mode,
4273
4772
  resolveScanSettings(project, { ...overrides, mode }, currentDirectory).options,
4274
4773
  ]));
4774
+ if (options.maxTotalCost !== undefined)
4775
+ errorOutput.write(`codex-security: ${formatUsd(options.maxTotalCost)} total limit for this invocation. Model-based finding matching and owner suggestions are skipped.\n`);
4275
4776
  const result = await runMultiscan({
4276
4777
  inputPath,
4277
4778
  outputDir,
@@ -4279,6 +4780,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4279
4780
  workers: options.workers,
4280
4781
  mode: settings.mode,
4281
4782
  maxAttempts: options.maxAttempts,
4783
+ maxTotalCostUsd: options.maxTotalCost,
4282
4784
  ...(settings.maxCostUsd === undefined
4283
4785
  ? {}
4284
4786
  : { maxCostUsd: settings.maxCostUsd }),
@@ -4308,6 +4810,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4308
4810
  signal: controller.signal,
4309
4811
  });
4310
4812
  return {
4813
+ alreadyCompleted: true,
4311
4814
  manifest: contract.manifest,
4312
4815
  findings: contract.findings,
4313
4816
  cost: scan["cost"] ??
@@ -4341,6 +4844,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4341
4844
  try {
4342
4845
  return await security.run(recipe.repository, {
4343
4846
  ...pickScanSettings(recipe),
4847
+ ...batchScanBudget(prompts.maxTotalCostShareUsd, recipe),
4344
4848
  knowledgeBaseSnapshot: prompts.knowledgeBaseSnapshot,
4345
4849
  telemetryContext: prompts.telemetryContext,
4346
4850
  onTelemetry: prompts.onTelemetry,
@@ -4359,9 +4863,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4359
4863
  }
4360
4864
  : {}),
4361
4865
  signal: controller.signal,
4362
- onProgress: ({ repository, status, attempt, error, warning }) => {
4866
+ onProgress: ({ repository, status, attempt, maxCostUsd, error, warning, }) => {
4363
4867
  const detail = error ?? warning;
4364
- errorOutput.write(`codex-security: ${repository} ${status} (attempt ${attempt})${detail === undefined ? "" : `: ${diagnosticValue(detail)}`}\n`);
4868
+ const budget = maxCostUsd === undefined
4869
+ ? ""
4870
+ : `, ${formatUsd(maxCostUsd)} per repository attempt`;
4871
+ errorOutput.write(`codex-security: ${repository} ${status} (attempt ${attempt}${budget})${detail === undefined ? "" : `: ${diagnosticValue(detail)}`}\n`);
4365
4872
  },
4366
4873
  });
4367
4874
  exitCode =
@@ -4390,6 +4897,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4390
4897
  " codex-security export --export-format json --output -\n" +
4391
4898
  " codex-security export ../scan-results --export-format csv\n" +
4392
4899
  " codex-security export --artifact threat-model --output -\n\n" +
4900
+ "Implicit filenames: results.sarif, findings.json, findings.csv, servicenow-avit.csv, or threatmodel.md.\n" +
4393
4901
  "Use --export-format for artifact format. The global --format option controls\n" +
4394
4902
  "framework output such as --schema; it does not change exported files.",
4395
4903
  destructive: true,
@@ -4417,7 +4925,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4417
4925
  .describe("Per-application CSV template required for servicenow-avit exports."),
4418
4926
  output: optionValue("--output")
4419
4927
  .optional()
4420
- .describe("FILE or '-' for stdout (default: results.sarif, findings.json, findings.csv, servicenow-avit.csv, or threatmodel.md)."),
4928
+ .describe("FILE to replace or '-' for raw stdout. Default filenames are created only if absent."),
4421
4929
  sourceRoot: optionValue("--source-root")
4422
4930
  .optional()
4423
4931
  .describe("Repository checkout used for SARIF source-line fingerprints."),
@@ -4434,6 +4942,26 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4434
4942
  async run({ args, options }) {
4435
4943
  rawExportOutput = options.output === "-";
4436
4944
  try {
4945
+ if (rawExportOutput) {
4946
+ const responseFlag = frameworkFlags.filters.length
4947
+ ? "--filter-output"
4948
+ : frameworkFlags.fullOutput
4949
+ ? "--full-output"
4950
+ : frameworkFlags.tokenArguments[0];
4951
+ if (responseFlag) {
4952
+ throw new CodexSecurityError(`${responseFlag} cannot be used with raw artifact stdout. Omit it to pipe the complete artifact.`);
4953
+ }
4954
+ const markdown = options.artifact === "threat-model" ||
4955
+ options.exportFormat === "md";
4956
+ const csv = options.exportFormat === "csv" ||
4957
+ options.exportFormat === "servicenow-avit";
4958
+ const expectedFormat = markdown ? "md" : csv ? undefined : "json";
4959
+ const incompatible = frameworkFlags.formats.find((value) => value !== expectedFormat);
4960
+ if (incompatible !== undefined) {
4961
+ const label = markdown ? "Markdown" : csv ? "CSV" : "JSON";
4962
+ throw new CodexSecurityError(`${label} stdout cannot be combined with --format ${incompatible}. Omit the response format to pipe the complete artifact.`);
4963
+ }
4964
+ }
4437
4965
  const currentDirectory = dependencies.currentDirectory();
4438
4966
  if (args.scanDir !== undefined && options.scan !== undefined) {
4439
4967
  throw new CodexSecurityError("--scan cannot be combined with a result directory.");
@@ -4441,15 +4969,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4441
4969
  const format = resolveArtifactFormat(options.artifact, options.exportFormat, options.avitTemplate);
4442
4970
  const sourceRoot = options.sourceRoot === undefined
4443
4971
  ? undefined
4444
- : resolveCliPath(currentDirectory, options.sourceRoot);
4445
- const protectedRoot = sourceRoot === undefined
4446
- ? undefined
4447
- : [currentDirectory, sourceRoot];
4972
+ : resolveInputPath(options.sourceRoot, currentDirectory);
4973
+ const protectedRoot = await artifactSourceProtectionRoots(sourceRoot, currentDirectory);
4448
4974
  let scanDir = args.scanDir;
4449
4975
  if (scanDir === undefined) {
4450
4976
  let scanId = options.scan;
4451
4977
  if (!scanId || scanId === "latest") {
4452
- const scans = await latestScans(1, "complete", options.python, protectedRoot);
4978
+ const scans = await latestScans(1, "complete", {
4979
+ pythonPath: options.python,
4980
+ protectedRoot,
4981
+ });
4453
4982
  scanId = scans?.[0]?.scanId;
4454
4983
  }
4455
4984
  if (scanId === undefined)
@@ -4461,10 +4990,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4461
4990
  ? "-"
4462
4991
  : resolveCliPath(currentDirectory, destination);
4463
4992
  const prepared = await resolveArtifactExportOutput({
4464
- scanDir: resolveCliPath(currentDirectory, scanDir),
4993
+ scanDir: resolveInputPath(scanDir, currentDirectory),
4465
4994
  artifact: options.artifact,
4466
4995
  format,
4467
4996
  output: outputPath,
4997
+ noClobber: options.output === undefined,
4468
4998
  sourceRoot,
4469
4999
  avitTemplate: options.avitTemplate,
4470
5000
  pythonPath: options.python,
@@ -4490,6 +5020,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4490
5020
  },
4491
5021
  })
4492
5022
  .command("validate", {
5023
+ usage: [{ suffix: "<findings...> [options]" }, { suffix: "--records" }],
5024
+ examples: [{ args: { "findings...": "findings.json" } }],
4493
5025
  hint: "Use --records alone for host-provided reviews over JSON-RPC.",
4494
5026
  description: "Assess candidate security findings using source evidence only.",
4495
5027
  destructive: false,
@@ -4497,7 +5029,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4497
5029
  "findings...": z
4498
5030
  .string()
4499
5031
  .min(1, "A finding must not be empty.")
4500
- .describe("Finding text or a file containing findings."),
5032
+ .describe("Finding text, a local file path or file URL. Use text:VALUE to pass path-shaped prose."),
4501
5033
  }),
4502
5034
  options: z.object({
4503
5035
  records: z
@@ -4526,7 +5058,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4526
5058
  if (options.records)
4527
5059
  throw new CodexSecurityError("Use validate --records alone.");
4528
5060
  if (options.knowledgeBase.length > 0) {
4529
- knowledgeBase = await prepareKnowledgeBase(options.knowledgeBase.map((path) => resolveCliPath(dependencies.currentDirectory(), path)));
5061
+ const directory = dependencies.currentDirectory();
5062
+ const checkout = await gitMarkerRoot(directory, undefined, "nearest");
5063
+ const paths = options.knowledgeBase.map((path) => resolveCliPath(directory, path));
5064
+ const snapshot = await readKnowledgeBaseSnapshot(paths, undefined, checkout ? [checkout] : []);
5065
+ knowledgeBase = await prepareKnowledgeBase(snapshot);
4530
5066
  }
4531
5067
  exitCode = await runSkill("validation", positionals, options, output, errorOutput, dependencies, {
4532
5068
  auth: options.auth,
@@ -4549,6 +5085,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4549
5085
  },
4550
5086
  })
4551
5087
  .command("verify-fix", {
5088
+ usage: [
5089
+ { suffix: "FINDING... [options]" },
5090
+ { suffix: "--scan ID [--severity LEVEL] [options]" },
5091
+ { suffix: "(--linear-issue ID | --linear-project PROJECT) [options]" },
5092
+ { suffix: "--host" },
5093
+ ],
4552
5094
  description: "Verify existing security fixes without changing the repository.",
4553
5095
  destructive: false,
4554
5096
  args: z.object({
@@ -4556,7 +5098,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4556
5098
  .string()
4557
5099
  .min(1, "A finding must not be empty.")
4558
5100
  .optional()
4559
- .describe("Finding text, a file, or a saved finding identifier."),
5101
+ .describe("Finding text, a local file path or URL, or a saved finding identifier. Use text:VALUE to pass path-shaped prose."),
4560
5102
  }),
4561
5103
  options: z.object({
4562
5104
  host: z
@@ -4579,13 +5121,22 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4579
5121
  description: "Verify a fix described in a file.",
4580
5122
  },
4581
5123
  ],
4582
- output: z.record(z.string(), z.unknown()).optional(),
5124
+ output: z
5125
+ .union([
5126
+ z.object({
5127
+ repository: z.string(),
5128
+ scanId: z.string().optional(),
5129
+ results: z.array(FindingVerificationSchema),
5130
+ }),
5131
+ cliFailureSchema("VERIFICATION_FAILED"),
5132
+ ])
5133
+ .optional(),
4583
5134
  async run({ format, options, error: incurError }) {
4584
5135
  let workerDiagnostic;
4585
5136
  const structured = format === "json" || format === "jsonl";
4586
5137
  const reportDiagnostic = async (chunk) => {
4587
5138
  if (structured) {
4588
- if (!batchedVerification || frameworkFlags.tokenArguments.length)
5139
+ if (!batchedVerification || frameworkFlags.tokenView)
4589
5140
  deferredVerificationDiagnostic = chunk;
4590
5141
  }
4591
5142
  else {
@@ -4705,7 +5256,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4705
5256
  return undefined;
4706
5257
  }
4707
5258
  }
4708
- if (structured) {
5259
+ if (!useDefaultOutput(format)) {
5260
+ setTerminalOutputFormat(format);
4709
5261
  return {
4710
5262
  repository,
4711
5263
  ...(selected === undefined ? {} : { scanId: selected.scanId }),
@@ -4728,6 +5280,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4728
5280
  },
4729
5281
  })
4730
5282
  .command("patch", {
5283
+ usage: [
5284
+ { suffix: "ISSUE... [options]" },
5285
+ { suffix: "--scan ID [--severity LEVEL] [options]" },
5286
+ { suffix: "(--linear-issue ID | --linear-project PROJECT) [options]" },
5287
+ { suffix: "--resume-pr BRANCH" },
5288
+ { suffix: "--host" },
5289
+ ],
4731
5290
  description: "Patch one or more security issues.",
4732
5291
  destructive: true,
4733
5292
  args: z.object({
@@ -4735,7 +5294,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4735
5294
  .string()
4736
5295
  .min(1, "An issue must not be empty.")
4737
5296
  .optional()
4738
- .describe("Issue text, a file, or a saved finding identifier."),
5297
+ .describe("Issue text, a local file path or URL, or a saved finding identifier. Use text:VALUE to pass path-shaped prose."),
4739
5298
  }),
4740
5299
  options: z.object({
4741
5300
  host: z
@@ -4971,24 +5530,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4971
5530
  }
4972
5531
  },
4973
5532
  })
4974
- .command("login", {
5533
+ .command(Cli.create("login", {
4975
5534
  description: "Sign in with ChatGPT or store credentials.",
4976
- hint: "For remote login, use --device-auth if your workspace allows it.\n" +
4977
- "If device auth is disabled, sign in over SSH:\n" +
4978
- " On your local machine (replace user@remote):\n" +
4979
- " ssh -L 1455:localhost:1455 user@remote\n" +
4980
- " In that SSH session:\n" +
4981
- " codex-security login\n" +
4982
- " Open the sign-in URL in your local browser.\n" +
4983
- " Keep SSH connected until login finishes.\n" +
4984
- "Docs: https://learn.chatgpt.com/docs/auth?surface=cli#cli-fallback-forward-the-localhost-callback-over-ssh",
5535
+ hint: "Check the effective sign-in with codex-security login status. For a remote machine use --device-auth if your workspace permits it. For SSH, on your local machine run:\n ssh -L 1455:localhost:1455 user@remote\nThen, in that SSH session:\n codex-security login\nOpen the sign-in URL locally and keep SSH connected until login finishes.\nhttps://learn.chatgpt.com/docs/auth?surface=cli#cli-fallback-forward-the-localhost-callback-over-ssh",
4985
5536
  destructive: true,
4986
- args: z.object({
4987
- action: z
4988
- .enum(["status"])
4989
- .optional()
4990
- .describe("Use status to inspect credentials; omit to sign in."),
4991
- }),
4992
5537
  options: z.object({
4993
5538
  deviceAuth: z
4994
5539
  .boolean()
@@ -5004,74 +5549,103 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
5004
5549
  .describe("Read an access token from stdin."),
5005
5550
  }),
5006
5551
  examples: [
5007
- { args: {}, description: "Sign in with ChatGPT." },
5008
- { args: { action: "status" }, description: "Check authentication." },
5552
+ { options: {}, description: "Sign in using the browser." },
5553
+ {
5554
+ options: { deviceAuth: true },
5555
+ description: "Sign in from a headless machine with device auth.",
5556
+ },
5557
+ {
5558
+ options: { withApiKey: true },
5559
+ description: "Pipe an API key on stdin from your credential source.",
5560
+ },
5009
5561
  ],
5010
- async run({ args, options }) {
5011
- const credentialHome = await prepareCodexSecurityCredentialHome(dependencies.environment);
5562
+ async run({ options }) {
5012
5563
  const authentication = scanAuthentication(dependencies.environment);
5013
- if (args.action === "status" && authentication.method !== "api_key") {
5014
- const ambientHome = scanCodexHome(dependencies.environment);
5015
- await withCredentialHomeLock(credentialHome, () => initialCredentialsAvailable(dependencies.environment, ambientHome, credentialHome));
5564
+ exitCode = await withLoginEnvironment(async (environment) => {
5565
+ await prepareLoginConfig(environment.CODEX_HOME, await readCodexAuthConfig(scanCodexHome(dependencies.environment), true));
5566
+ const status = await dependencies.runCodex([
5567
+ "login",
5568
+ ...(options.deviceAuth ? ["--device-auth"] : []),
5569
+ ...(options.withApiKey ? ["--with-api-key"] : []),
5570
+ ...(options.withAccessToken ? ["--with-access-token"] : []),
5571
+ ], undefined, environment);
5572
+ if (status === 0)
5573
+ await setCodexSecurityCredentialLogout(environment.CODEX_HOME, false);
5574
+ return status;
5575
+ });
5576
+ if (exitCode === 0 &&
5577
+ !options.withApiKey &&
5578
+ authentication.method === "api_key") {
5579
+ const configuredApiKeyVariables = Object.keys(dependencies.environment).filter((name) => ["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase()) && dependencies.environment[name]?.trim());
5580
+ const loginWarning = options.withAccessToken
5581
+ ? `Access-token login succeeded, but noninteractive scans will use ${authentication.source}.\n`
5582
+ : "ChatGPT login succeeded. Interactive scans will ask which account to use; " +
5583
+ `noninteractive scans will use ${authentication.source}.\n`;
5584
+ const storedCredentials = options.withAccessToken
5585
+ ? "your stored credentials"
5586
+ : "your ChatGPT sign-in";
5587
+ errorOutput.write(loginWarning +
5588
+ `To use ${storedCredentials}, pass '--auth chatgpt' or ` +
5589
+ `${formatEnvironmentVariableRemovalGuidance(configuredApiKeyVariables)}.\n`);
5016
5590
  }
5017
- const authenticationEnvironment = {
5018
- ...dependencies.environment,
5019
- CODEX_HOME: credentialHome,
5020
- };
5021
- exitCode = await dependencies.runCodex([
5022
- "login",
5023
- ...(args.action === undefined ? [] : [args.action]),
5024
- ...(options.deviceAuth ? ["--device-auth"] : []),
5025
- ...(options.withApiKey ? ["--with-api-key"] : []),
5026
- ...(options.withAccessToken ? ["--with-access-token"] : []),
5027
- ], undefined, authenticationEnvironment);
5028
- if (args.action === undefined && exitCode === 0) {
5029
- await setCodexSecurityCredentialLogout(credentialHome, false);
5030
- }
5031
- if (args.action === "status") {
5032
- if (authentication.method === "api_key" &&
5033
- (exitCode === 0 || exitCode === 1)) {
5034
- exitCode = 0;
5035
- errorOutput.write(`Effective scan authentication: API key from ${authentication.source}.\n`);
5036
- errorOutput.write(`To use a ChatGPT sign-in, ${formatEnvironmentVariableRemovalGuidance(["OPENAI_API_KEY", "CODEX_API_KEY"])}.\n`);
5037
- }
5038
- }
5039
- else if (exitCode === 0 && !options.withApiKey) {
5040
- if (authentication.method === "api_key") {
5041
- const configuredApiKeyVariables = Object.entries(dependencies.environment).flatMap(([name, value]) => value?.trim() &&
5042
- (name.toUpperCase() === "OPENAI_API_KEY" ||
5043
- name.toUpperCase() === "CODEX_API_KEY")
5044
- ? name
5045
- : []);
5046
- const loginWarning = options.withAccessToken
5047
- ? `Access-token login succeeded, but noninteractive scans will use ${authentication.source}.\n`
5048
- : "ChatGPT login succeeded. Interactive scans will ask which account to use; " +
5049
- `noninteractive scans will use ${authentication.source}.\n`;
5050
- const storedCredentials = options.withAccessToken
5051
- ? "your stored credentials"
5052
- : "your ChatGPT sign-in";
5053
- errorOutput.write(loginWarning +
5054
- `To use ${storedCredentials}, pass '--auth chatgpt' or ` +
5055
- `${formatEnvironmentVariableRemovalGuidance(configuredApiKeyVariables)}.\n`);
5056
- }
5591
+ },
5592
+ }).command("status", {
5593
+ description: "Check effective scan authentication.",
5594
+ hint: "Use codex-security login status --json for automation. With stored credentials, the first check can import an existing Codex sign-in.",
5595
+ output: z
5596
+ .object({
5597
+ authenticated: z.boolean(),
5598
+ method: z.enum(["api_key", "stored_credentials"]),
5599
+ source: z.string().optional(),
5600
+ })
5601
+ .optional(),
5602
+ async run({ format }) {
5603
+ const structured = !useDefaultOutput(format);
5604
+ const authentication = scanAuthentication(dependencies.environment);
5605
+ if (authentication.method === "api_key") {
5606
+ errorOutput.write(`API key configured via ${authentication.source} (offline check).\n`);
5607
+ errorOutput.write("Stored sign-in status:\n");
5608
+ }
5609
+ exitCode = await withLoginEnvironment(async (environment) => {
5610
+ if (authentication.method !== "api_key")
5611
+ await initialCredentialsAvailable(dependencies.environment, scanCodexHome(dependencies.environment), environment.CODEX_HOME);
5612
+ if (!structured)
5613
+ return await dependencies.runCodex(["login", "status"], undefined, environment);
5614
+ const native = await runCodexCommand(resolveCodexCommand(environment), ["login", "status"], environment, undefined, undefined, { cwd: NEUTRAL_CODEX_CWD });
5615
+ for (const diagnostic of [native.stdout, native.stderr]) {
5616
+ if (diagnostic.trim())
5617
+ errorOutput.write(`${diagnosticLines(diagnostic.trimEnd())}\n`);
5618
+ }
5619
+ return native.exitCode ?? 2;
5620
+ });
5621
+ if (authentication.method === "api_key" &&
5622
+ (exitCode === 0 || exitCode === 1)) {
5623
+ exitCode = 0;
5624
+ errorOutput.write(`To use a ChatGPT sign-in, ${formatEnvironmentVariableRemovalGuidance(["OPENAI_API_KEY", "CODEX_API_KEY"])}.\n`);
5057
5625
  }
5626
+ if (structured)
5627
+ return {
5628
+ authenticated: exitCode === 0,
5629
+ ...(authentication.method === "api_key"
5630
+ ? {
5631
+ method: authentication.method,
5632
+ source: authentication.source,
5633
+ }
5634
+ : { method: "stored_credentials" }),
5635
+ };
5058
5636
  },
5059
- })
5637
+ }))
5060
5638
  .command("logout", {
5061
- description: "Remove the stored sign-in.",
5639
+ description: "Remove the stored Codex Security sign-in.",
5640
+ hint: "Check the effective account with codex-security login status. Scans can still use an API key configured in your environment.",
5062
5641
  destructive: true,
5063
5642
  async run() {
5064
- const credentialHome = await prepareCodexSecurityCredentialHome(dependencies.environment);
5065
- const runLogout = () => dependencies.runCodex(["logout"], undefined, {
5066
- ...dependencies.environment,
5067
- CODEX_HOME: credentialHome,
5068
- });
5069
- exitCode = await withCredentialHomeLock(credentialHome, () => logoutCredentialHome(credentialHome, scanCodexHome(dependencies.environment), runLogout));
5643
+ exitCode = await withLoginEnvironment((environment) => logoutCredentialHome(environment.CODEX_HOME, scanCodexHome(dependencies.environment), (store) => dependencies.runCodex(nativeLogoutArgs(store), undefined, environment)));
5070
5644
  },
5071
5645
  })
5072
5646
  .command("init", {
5073
5647
  description: "Create a starter project configuration.",
5074
- hint: "Existing files are never overwritten.",
5648
+ hint: "Use the generated file with scan . -c FILE --dry-run. Existing files are never overwritten.",
5075
5649
  destructive: true,
5076
5650
  args: z.object({
5077
5651
  file: z
@@ -5081,24 +5655,36 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
5081
5655
  .describe("YAML or JSON destination (default: codex-security.yaml)."),
5082
5656
  }),
5083
5657
  output: z.object({ path: z.string() }).optional(),
5084
- async run({ args }) {
5658
+ async run({ args, format }) {
5659
+ let preview;
5085
5660
  try {
5086
5661
  const directory = dependencies.currentDirectory();
5087
5662
  const path = resolveCliPath(directory, args.file ?? "codex-security.yaml");
5663
+ preview = `${PREVIEW_LABEL}: ${projectPreviewCommand(directory, path)}`;
5088
5664
  await writeFile(path, projectConfigStarter(path, directory), {
5089
5665
  flag: "wx",
5090
5666
  mode: 0o600,
5091
5667
  });
5668
+ if (useDefaultOutput(format)) {
5669
+ if (output.isTTY)
5670
+ renderedOutput = `Created ${escapeTerminalText(path)}\n${preview}\n`;
5671
+ else
5672
+ errorOutput.write(`${preview}\n`);
5673
+ }
5092
5674
  return { path };
5093
5675
  }
5094
5676
  catch (error) {
5095
5677
  exitCode = 2;
5096
5678
  errorOutput.write(`codex-security: ${diagnosticLines(error)}\n`);
5679
+ if (error.code === "EEXIST" && preview)
5680
+ errorOutput.write(`${preview}\n`);
5097
5681
  throw error;
5098
5682
  }
5099
5683
  },
5100
5684
  })
5101
5685
  .command("feedback", {
5686
+ usage: [{ suffix: "[scan-id] --reason TEXT [--include-logs]" }],
5687
+ examples: [{ options: { reason: "unexpected-result" } }],
5102
5688
  description: "Send feedback to OpenAI and return a feedback ID.",
5103
5689
  destructive: true,
5104
5690
  args: z.object({
@@ -5175,7 +5761,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
5175
5761
  },
5176
5762
  },
5177
5763
  output: infoOutput,
5178
- async run({ options }) {
5764
+ async run({ options, format }) {
5179
5765
  const directory = dependencies.currentDirectory();
5180
5766
  const project = await selectedProjectConfig(options.config, dependencies);
5181
5767
  const resolved = resolveScanSettings(project, {}, directory);
@@ -5184,125 +5770,240 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
5184
5770
  const deep = resolved.options.mode === "deep"
5185
5771
  ? await resolveDeepScanConfig(resolved.options, join(scanCodexHome(dependencies.environment), "codex-security", "config.toml"))
5186
5772
  : undefined;
5773
+ const model = scanModelConfiguration(codex);
5774
+ const sources = configurationSources(resolved.sources, deep?.sources);
5775
+ const nextStep = projectPreviewCommand(directory, project?.path);
5776
+ const bundledPluginAvailable = Boolean(await bundledPluginRoot().catch(() => undefined));
5777
+ if (output.isTTY && useDefaultOutput(format)) {
5778
+ const overrides = Object.entries(sources)
5779
+ .filter(([, source]) => source !== "default")
5780
+ .map(([key, source]) => `${key} (${source})`);
5781
+ const { mode, auth, target, maxCostUsd, excludePaths } = resolved.options;
5782
+ renderedOutput =
5783
+ [
5784
+ `${PREVIEW_LABEL}: ${nextStep}`,
5785
+ `Configuration: ${project?.path ?? "defaults"}`,
5786
+ `Scope: ${typeof target === "string" ? target : JSON.stringify(target)}`,
5787
+ ...(excludePaths?.length
5788
+ ? [
5789
+ `Excluded paths: ${excludePaths.map(formatScopePath).join(", ")}`,
5790
+ ]
5791
+ : []),
5792
+ `Scan: ${mode} · ${model.model} (${model.reasoningEffort}) · auth ${auth}`,
5793
+ ...(maxCostUsd === undefined
5794
+ ? []
5795
+ : [`Cost limit: $${maxCostUsd}`]),
5796
+ `Bundled plugin: ${BUNDLED_PLUGIN_VERSION} (${bundledPluginAvailable ? "available" : "missing"})`,
5797
+ ...(overrides.length
5798
+ ? [`Overrides: ${overrides.join(", ")}`]
5799
+ : []),
5800
+ ]
5801
+ .map((line) => escapeTerminalText(line))
5802
+ .join("\n") + "\n";
5803
+ }
5187
5804
  return {
5188
5805
  sdkVersion: VERSION,
5189
5806
  bundledPluginVersion: BUNDLED_PLUGIN_VERSION,
5807
+ bundledPluginAvailable,
5190
5808
  scanMcp: false,
5191
5809
  cancellationNote: "Scans are CLI-only because the MCP transport cannot cancel active commands.",
5192
5810
  cliVersion: VERSION,
5193
5811
  codexVersion: CODEX_EXECUTABLE_VERSION,
5194
5812
  codexSdkVersion: CODEX_SDK_VERSION,
5195
- ...scanModelConfiguration(codex),
5196
- nextStep: project
5197
- ? "Run codex-security scan . -c FILE --dry-run, replacing FILE with the project configuration you selected."
5198
- : "codex-security scan . --dry-run",
5813
+ ...model,
5814
+ nextStep,
5199
5815
  configuration: {
5200
5816
  ...(project?.path === undefined ? {} : { path: project.path }),
5201
5817
  settings: { ...resolved.options, ...deep?.settings },
5202
- sources: configurationSources(resolved.sources, deep?.sources),
5818
+ sources,
5203
5819
  },
5204
5820
  };
5205
5821
  },
5206
5822
  });
5823
+ if (completion.success) {
5824
+ await writeCliOutput(output, completeCli(cli, cliOptions, completion.data, shellArgv));
5825
+ return 0;
5826
+ }
5207
5827
  const commands = Cli.toCommands.get(cli);
5828
+ prepareCliExamples(commands);
5208
5829
  const valueOptions = cliValueOptions(commands);
5209
- const commandIndex = argv.findIndex((value, index) => {
5210
- if (value.startsWith("-"))
5211
- return false;
5212
- return index === 0 || !valueOptions.has(argv[index - 1]);
5213
- });
5830
+ const isPositional = (value, index) => (value === "-" || !value.startsWith("-")) &&
5831
+ (index === 0 || !valueOptions.has(argv[index - 1]));
5832
+ // A leading terminator still permits a positional command name.
5833
+ let commandIndex = argv.findIndex(isPositional);
5834
+ if (commandIndex < 0 &&
5835
+ !actionFlags.length &&
5836
+ literalArgs[0] &&
5837
+ !literalArgs[0].startsWith("-") &&
5838
+ firstNonGlobal(argv, 0) === argv.length) {
5839
+ commandIndex = argv.length;
5840
+ const name = literalArgs.shift();
5841
+ const group = commands.get(name);
5842
+ const verb = literalArgs[0];
5843
+ argv = [...argv, name];
5844
+ if (group && "_group" in group && verb && group.commands.has(verb))
5845
+ argv = [...argv, literalArgs.shift()];
5846
+ }
5847
+ if (argv[commandIndex] === "codex-security") {
5848
+ argv = argv.toSpliced(commandIndex, 1);
5849
+ commandIndex = argv.findIndex(isPositional);
5850
+ }
5214
5851
  const command = argv[commandIndex];
5215
- const following = argv[commandIndex + 1];
5852
+ const entry = command === undefined ? undefined : commands.get(command);
5853
+ const verbIndex = firstNonGlobal(argv, commandIndex + 1);
5854
+ let following = argv[verbIndex];
5216
5855
  const scanImport = command === "scan" && following === "import";
5856
+ const importArgs = normalizeImportArguments(argv, verbIndex, command, following);
5857
+ argv = importArgs.args;
5858
+ if (command === "scan" &&
5859
+ !scanImport &&
5860
+ (literalArgs.length ||
5861
+ argv.some((value, index) => index > commandIndex && isPositional(value, index)))) {
5862
+ // A repository such as "imports" or "./import" is a positional even when
5863
+ // shared options precede it. Bypass Incur's subcommand typo suggestions.
5864
+ if (entry && "_group" in entry && entry.root)
5865
+ commands.set(command, entry.root);
5866
+ }
5217
5867
  if ((command === "scans" || command === "findings") &&
5218
5868
  !argv.includes("--help") &&
5219
5869
  !argv.includes("-h") &&
5870
+ !argv.some((arg) => arg === "--llms" || arg === "--llms-full") &&
5220
5871
  (following === undefined || following.startsWith("-"))) {
5221
- argv = argv.toSpliced(commandIndex + 1, 0, "list");
5222
- }
5872
+ argv = argv.toSpliced(verbIndex, 0, "list");
5873
+ following = "list";
5874
+ }
5875
+ const nested = entry &&
5876
+ "_group" in entry &&
5877
+ following !== undefined &&
5878
+ entry.commands.has(following);
5879
+ const subcommand = nested ? following : undefined;
5880
+ const selected = entry && "_group" in entry
5881
+ ? subcommand
5882
+ ? entry.commands.get(subcommand)
5883
+ : entry.root
5884
+ : entry;
5885
+ const protocolFlag = ["scan", "patch", "verify-fix"].includes(command ?? "") && !scanImport
5886
+ ? "--host"
5887
+ : ["validate", "classify-severity", "dedupe"].includes(command ?? "")
5888
+ ? "--records"
5889
+ : undefined;
5890
+ let protocol = false;
5891
+ let classificationRuns;
5223
5892
  function validateCliArguments() {
5224
- if (argv.includes("--help") || argv.includes("-h"))
5225
- return undefined;
5226
- if (command === undefined || !commands.has(command))
5227
- return undefined;
5228
- const structuredOutput = argv.some((value, index) => value === "--json" ||
5229
- ((value === "--format" ||
5230
- value === "--format=json" ||
5231
- value === "--format=jsonl") &&
5232
- (value.endsWith("=json") ||
5233
- value.endsWith("=jsonl") ||
5234
- argv[index + 1] === "json" ||
5235
- argv[index + 1] === "jsonl")));
5236
- if (structuredOutput &&
5237
- ["validate", "login", "logout"].includes(command) &&
5238
- !argv.includes("--schema")) {
5239
- return `${command} does not support noninteractive JSON output; run it without --json, --format json, or --format jsonl.`;
5240
- }
5241
- if (command === "export" && structuredOutput) {
5242
- const hasValue = (flag, value) => argv.some((arg, index) => arg === `${flag}=${value}` ||
5243
- (arg === flag && argv[index + 1] === value));
5244
- if (hasValue("--output", "-")) {
5245
- if (["csv", "servicenow-avit"].some((format) => hasValue("--export-format", format) ||
5246
- hasValue("--exportFormat", format))) {
5247
- return "CSV stdout cannot be combined with JSON output; write CSV to a file or omit --json.";
5248
- }
5249
- if (hasValue("--artifact", "threat-model") ||
5250
- hasValue("--export-format", "md")) {
5251
- return "Markdown stdout cannot be combined with JSON output; write Markdown to a file or omit --json.";
5893
+ if (argv.includes("--incur-update-check"))
5894
+ return "Unknown flag: --incur-update-check";
5895
+ if (mixedAction)
5896
+ return `${actionFlags.join(" and ")} must be used alone.`;
5897
+ if (command === undefined && literalArgs.length)
5898
+ return "Select a command before --.";
5899
+ if (importArgs.error)
5900
+ return importArgs.error;
5901
+ if (frameworkFlags.argumentError)
5902
+ return frameworkFlags.argumentError;
5903
+ if (command === undefined)
5904
+ return frameworkFlags.tokenError;
5905
+ if (!entry) {
5906
+ if (["skills", "skill", "mcp", "completions"].includes(command))
5907
+ return frameworkFlags.tokenError;
5908
+ if (inspection)
5909
+ return `Unknown command ${diagnosticValue(command)}. Use codex-security --help.`;
5910
+ return frameworkFlags.tokenError;
5911
+ }
5912
+ if ("_group" in entry &&
5913
+ !entry.root &&
5914
+ following &&
5915
+ !following.startsWith("-") &&
5916
+ !subcommand)
5917
+ // Discovery otherwise widens an unknown path to its parent. Execution
5918
+ // already reports unknown verbs with Incur's spelling suggestions.
5919
+ return inspection
5920
+ ? `Unknown command ${diagnosticValue(command + " " + following)}. Use codex-security ${command} --help.`
5921
+ : undefined;
5922
+ if (protocolFlag && !inspection) {
5923
+ const negative = "--no-" + protocolFlag.slice(2);
5924
+ const flags = argv.filter((arg) => arg === protocolFlag ||
5925
+ arg.startsWith(protocolFlag + "=") ||
5926
+ arg === negative);
5927
+ const last = flags.at(-1);
5928
+ protocol = last === protocolFlag || last === protocolFlag + "=true";
5929
+ if (protocol) {
5930
+ const rest = argv.filter((arg, index) => index !== commandIndex && !flags.includes(arg));
5931
+ if (command === "classify-severity" &&
5932
+ commandIndex === 0 &&
5933
+ !literalArgs.length) {
5934
+ try {
5935
+ const { values } = parseArgs({
5936
+ args: rest,
5937
+ options: { runs: { type: "string" } },
5938
+ });
5939
+ if (values.runs !== undefined)
5940
+ classificationRuns = reviewRunsOption.parse(Number(values.runs));
5941
+ }
5942
+ catch {
5943
+ return `Use --records with only --runs (an integer from 1 to 10; default: ${DEFAULT_REVIEW_RUNS}).`;
5944
+ }
5252
5945
  }
5946
+ else if (rest.length || literalArgs.length || commandIndex !== 0)
5947
+ return `${protocolFlag} must be used alone with ${command}.`;
5253
5948
  }
5254
5949
  }
5255
- if (command === "scan" && !argv.includes("--schema")) {
5256
- if (argv.some((value) => value === "--filter-output" || value.startsWith("--filter-output="))) {
5950
+ const structuredOutput = frameworkFlags.formats.some(isJsonFormat);
5951
+ if (structuredOutput &&
5952
+ (["validate", "logout"].includes(command) ||
5953
+ (command === "login" && following !== "status")) &&
5954
+ !inspection) {
5955
+ return `${command} does not support noninteractive JSON output; run it without --json, --format json, or --format jsonl.`;
5956
+ }
5957
+ if (command === "scan" && !inspection) {
5958
+ if (frameworkFlags.filters.length) {
5257
5959
  return "--filter-output is not supported for scan results.";
5258
5960
  }
5259
- if (argv.some((value, index) => value === "--format=md" ||
5260
- (value === "--format" && argv[index + 1] === "md"))) {
5961
+ if (frameworkFlags.formats.includes("md")) {
5261
5962
  return "Markdown output is not supported for scan results.";
5262
5963
  }
5263
5964
  }
5264
- const nestedCommand = scanImport ||
5265
- command === "scans" ||
5266
- command === "findings" ||
5267
- command === "publish" ||
5268
- command === "import";
5269
- const subcommand = nestedCommand ? argv[commandIndex + 1] : undefined;
5270
- if (command === "import" &&
5271
- subcommand !== "sonar" &&
5272
- frameworkFlags.rawCollector) {
5273
- // Incur's skill-sync notice turns a saved collector array into an object.
5965
+ if (frameworkFlags.rawStructuredOutput &&
5966
+ !(command === "scans" && subcommand === "logs")) {
5967
+ // Saved logs include the framework's CTA after streamed events. Other
5968
+ // raw result objects and arrays keep notices in full-output metadata.
5274
5969
  cliOptions.sync = false;
5275
5970
  }
5276
5971
  if (command === "info") {
5277
- for (let index = 0; index < argv.length; index += 1) {
5278
- const argument = argv[index];
5279
- if (argument !== "--filter-output" &&
5280
- !argument.startsWith("--filter-output=")) {
5972
+ for (const selector of frameworkFlags.filters) {
5973
+ if (selector === undefined)
5281
5974
  continue;
5282
- }
5283
- const selector = argument.includes("=")
5284
- ? argument.slice(argument.indexOf("=") + 1)
5285
- : argv[index + 1];
5286
- if (selector !== undefined &&
5287
- !selector
5288
- .split(",")
5289
- .every((field) => Object.hasOwn(infoOutput.shape, field))) {
5975
+ const valid = selector.split(/,(?!\d+\])/u).every((field) => {
5976
+ const match = /^([\w-]+)(?:\.[\w-]+|\[\d+,\d+\])*$/u.exec(field);
5977
+ return match !== null && Object.hasOwn(infoOutput.shape, match[1]);
5978
+ });
5979
+ if (!valid)
5290
5980
  return "--filter-output must select an info metadata field.";
5291
- }
5292
5981
  }
5293
5982
  }
5294
- for (let index = commandIndex + (nestedCommand ? 2 : 1); index < argv.length; index += 1) {
5983
+ let lastPositionalIndex = -1;
5984
+ for (let index = nested ? verbIndex + 1 : commandIndex + 1; index < argv.length; index += 1) {
5295
5985
  const value = argv[index];
5296
- if (!value.startsWith("-")) {
5986
+ if (value === "-" || !value.startsWith("-")) {
5297
5987
  positionals.push(value);
5988
+ lastPositionalIndex = index;
5298
5989
  continue;
5299
5990
  }
5300
5991
  const equals = value.indexOf("=");
5301
5992
  const option = equals < 0 ? value : value.slice(0, equals);
5302
5993
  const canonicalOption = option.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
5303
- if (equals >= 0 ||
5304
- (!valueOptions.has(canonicalOption) &&
5305
- !(scanImport && option === "--json")))
5994
+ if (equals >= 0 && selected && "options" in selected) {
5995
+ const name = option
5996
+ .slice(2)
5997
+ .replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
5998
+ const shape = selected.options?.shape;
5999
+ const field = shape && Object.hasOwn(shape, name) ? shape[name] : undefined;
6000
+ if (field &&
6001
+ z.toJSONSchema(field, { io: "input" }).type === "boolean" &&
6002
+ !["true", "false"].includes(value.slice(equals + 1))) {
6003
+ return `Invalid boolean value for ${option}: ${diagnosticValue(value.slice(equals + 1))}. Use ${option}, ${option}=true, or ${option}=false.`;
6004
+ }
6005
+ }
6006
+ if (equals >= 0 || !valueOptions.has(canonicalOption))
5306
6007
  continue;
5307
6008
  const next = argv[index + 1];
5308
6009
  if (next === undefined || next.startsWith("--") || next === "-h") {
@@ -5310,178 +6011,153 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
5310
6011
  }
5311
6012
  index += 1;
5312
6013
  }
5313
- if (subcommand === "match" &&
5314
- !argv.some((value) => ["--schema", "--llms", "--llms-full"].includes(value))) {
5315
- if (argv.includes("--all") && positionals.length > 0) {
5316
- return "scans match --all does not accept scan identifiers.";
5317
- }
5318
- if (!argv.includes("--all") && positionals.length !== 2) {
5319
- return "scans match requires two scan identifiers or --all.";
5320
- }
6014
+ const beforeDelimiter = positionals.length;
6015
+ positionals.push(...literalArgs);
6016
+ if (command === "login" && !subcommand && positionals.length)
6017
+ return "Use login to sign in or login status to inspect authentication.";
6018
+ // Incur's global flag extractor doesn't recognize --. Supply literal
6019
+ // arguments to the positional schema as inputs so its normal validation
6020
+ // still applies and no layer can reinterpret a value as a framework flag.
6021
+ if (literalArgs.length && selected && "args" in selected && selected.args) {
6022
+ const shape = {};
6023
+ for (const [index, key] of Object.keys(selected.args.shape).entries()) {
6024
+ const literal = literalArgs[index - beforeDelimiter];
6025
+ if (literal !== undefined)
6026
+ shape[key] = selected.args.shape[key].prefault(literal);
6027
+ }
6028
+ selected.args = selected.args.extend(shape);
5321
6029
  }
5322
6030
  if (command !== "validate" &&
5323
6031
  command !== "verify-fix" &&
5324
6032
  command !== "patch" &&
5325
6033
  positionals.length >
5326
- (scanImport || command === "logout" || command === "info"
5327
- ? 0
5328
- : subcommand === "compare" || subcommand === "match"
5329
- ? 2
5330
- : 1)) {
5331
- return `Unexpected positional argument for ${command}${subcommand === undefined ? "" : ` ${subcommand}`}.`;
5332
- }
5333
- }
5334
- const firstImportOption = scanImport ? commandIndex + 2 : argv.length;
5335
- const frameworkArgv = [];
5336
- for (let index = 0; index < argv.length; index++) {
5337
- const argument = argv[index];
5338
- const next = argv[index + 1];
5339
- const separator = argument.indexOf("=");
5340
- if (index >= firstImportOption &&
5341
- argument === "--json" &&
5342
- next !== undefined &&
5343
- !next.startsWith("--") &&
5344
- next !== "-h") {
5345
- // Incur reserves bare --json for output, but parses --json=FILE normally.
5346
- frameworkArgv.push(`--json=${next}`);
5347
- index++;
5348
- }
5349
- else if (separator >= 0 &&
5350
- FRAMEWORK_VALUE_OPTIONS.has(argument.slice(0, separator))) {
5351
- frameworkArgv.push(argument.slice(0, separator), argument.slice(separator + 1));
6034
+ (selected && "args" in selected && selected.args
6035
+ ? Object.keys(selected.args.shape).length
6036
+ : 0)) {
6037
+ const previous = argv[lastPositionalIndex - 1]?.split("=", 1)[0];
6038
+ const hint = previous?.startsWith("-")
6039
+ ? ` Check the flag ${diagnosticValue(previous)} and whether it takes a value.`
6040
+ : "";
6041
+ return `Unexpected positional argument for ${command}${subcommand === undefined ? "" : ` ${subcommand}`}.${hint}`;
6042
+ }
6043
+ return frameworkFlags.tokenError;
6044
+ }
6045
+ const frameworkFlags = parseFrameworkArguments(argv);
6046
+ const frameworkArgv = frameworkFlags.args;
6047
+ const { jsonFormat } = frameworkFlags;
6048
+ const policyFullOutput = command === "policy" &&
6049
+ frameworkFlags.fullOutput &&
6050
+ !mixedAction &&
6051
+ !argv.includes("--incur-update-check");
6052
+ const envelopeFormat = frameworkFlags.fullOutput ? jsonFormat : undefined;
6053
+ const commandPath = subcommand
6054
+ ? `${command} ${subcommand}`
6055
+ : (command ?? "codex-security");
6056
+ const argumentFailure = (message, code = commandPath === "scan"
6057
+ ? "SCAN_FAILED"
6058
+ : command === "policy"
6059
+ ? "POLICY_FAILED"
6060
+ : "INVALID_ARGUMENTS") => Formatter.format({ ok: false, error: { code, message }, meta: { command: commandPath } }, envelopeFormat) + "\n";
6061
+ const reportError = async (message, code) => {
6062
+ errorOutput.write(`codex-security: ${diagnosticLines(message)}\n`);
6063
+ if (envelopeFormat)
6064
+ await writeCliOutput(output, argumentFailure(message, code));
6065
+ return 2;
6066
+ };
6067
+ const argumentError = validateCliArguments();
6068
+ if (argumentError !== undefined && (!policyFullOutput || envelopeFormat))
6069
+ return reportError(argumentError);
6070
+ if (protocol) {
6071
+ const recordsCommand = command === "dedupe" ||
6072
+ command === "validate" ||
6073
+ command === "classify-severity"
6074
+ ? command
6075
+ : undefined;
6076
+ const remediationOperation = command === "patch"
6077
+ ? "patch"
6078
+ : command === "verify-fix"
6079
+ ? "verify"
6080
+ : undefined;
6081
+ const controller = new AbortController();
6082
+ const removeSignals = listenForAbort(dependencies, controller);
6083
+ let exitCode;
6084
+ try {
6085
+ const input = dependencies.recordsInput ?? process.stdin;
6086
+ const code = recordsCommand !== undefined
6087
+ ? await runHostRecordsProtocol(recordsCommand, input, output, {
6088
+ signal: controller.signal,
6089
+ classificationRuns,
6090
+ diagnostics: recordsCommand === "classify-severity" &&
6091
+ severityDiagnosticsEnabled()
6092
+ ? createSeverityDiagnostics(() => dependencies.now())
6093
+ : undefined,
6094
+ })
6095
+ : remediationOperation !== undefined
6096
+ ? await runHostedRemediationProtocol(input, output, controller.signal, remediationOperation)
6097
+ : await runHostedScanProtocol(input, output, controller.signal);
6098
+ exitCode =
6099
+ controller.signal.reason === "SIGINT"
6100
+ ? 130
6101
+ : controller.signal.reason === "SIGTERM"
6102
+ ? 143
6103
+ : code;
5352
6104
  }
5353
- else {
5354
- frameworkArgv.push(argument);
6105
+ finally {
6106
+ removeSignals();
5355
6107
  }
5356
- }
5357
- const frameworkFlags = frameworkOutputFlags(frameworkArgv);
5358
- const policyFullOutput = command === "policy" && argv.includes("--full-output");
5359
- const argumentError = validateCliArguments();
5360
- if (argumentError !== undefined && !policyFullOutput) {
5361
- errorOutput.write(`codex-security: ${argumentError}\n`);
5362
- return 2;
6108
+ // Protocol writes have flushed or been canceled. Node's stdout ignores destroy().
6109
+ if (output === process.stdout)
6110
+ process.exit(exitCode);
6111
+ return exitCode;
5363
6112
  }
5364
6113
  const updateController = new AbortController();
5365
6114
  const pendingUpdate = errorOutput.isTTY === true &&
5366
6115
  argv.length > 0 &&
5367
- argv[0] !== "completions" &&
5368
- !argv.some((argument) => [
5369
- "--help",
5370
- "-h",
5371
- "--version",
5372
- "--llms",
5373
- "--llms-full",
5374
- "--schema",
5375
- "--dry-run",
5376
- ].includes(argument)) &&
6116
+ command !== "completions" &&
6117
+ command !== "update" &&
6118
+ !process.env["COMPLETE"] &&
6119
+ !argv.some((argument) => [...INSPECTION_FLAGS, "--dry-run", "--mcp"].includes(argument)) &&
5377
6120
  updateNoticeEnabled(dependencies.environment)
5378
6121
  ? dependencies
5379
6122
  .checkForUpdate(updateController.signal)
5380
6123
  .catch(() => undefined)
5381
6124
  : undefined;
5382
- // Incur cannot mount a command with both a handler and subcommands.
5383
- // Select the nested import route while preserving scan [repository].
5384
- if (scanImport) {
5385
- cli.command(Cli.create("scan", {
5386
- description: "Run or import a saved scan.",
5387
- }).command("import", {
5388
- description: "Save CSV or JSON findings as a completed scan without security analysis.",
5389
- destructive: true,
5390
- options: z
5391
- .object({
5392
- csv: optionValue("--csv")
5393
- .optional()
5394
- .describe("Findings CSV in the codex-security export format."),
5395
- json: optionValue("--json")
5396
- .optional()
5397
- .describe("Findings JSON document or object with a findings array."),
5398
- outputDir: optionValue("--output-dir")
5399
- .optional()
5400
- .describe("Artifact directory (default: Codex Security state; CODEX_SECURITY_STATE_DIR)."),
5401
- archiveExisting: z
5402
- .boolean()
5403
- .default(false)
5404
- .describe("Archive existing results; requires --output-dir."),
5405
- dryRun: z
5406
- .boolean()
5407
- .default(false)
5408
- .describe("Validate the input without saving a scan."),
5409
- })
5410
- .refine((options) => Number(options.csv !== undefined) +
5411
- Number(options.json !== undefined) ===
5412
- 1, { message: "Provide exactly one of --csv FILE or --json FILE." })
5413
- .refine((options) => !options.archiveExisting || options.outputDir !== undefined, { message: "--archive-existing requires --output-dir." }),
5414
- examples: [
5415
- { options: { csv: "findings.csv" } },
5416
- { options: { json: "findings.json" } },
5417
- ],
5418
- hint: "Each input row is retained, including duplicates. --json selects the input file; use --format json for JSON output.",
5419
- output: z.record(z.string(), z.unknown()).optional(),
5420
- async run({ options, format, error: incurError }) {
5421
- const directory = dependencies.currentDirectory();
5422
- const outcome = await runImport({
5423
- sourcePath: resolveCliPath(directory, options.csv ?? options.json),
5424
- format: options.csv === undefined ? "json" : "csv",
5425
- outputDir: options.outputDir === undefined
5426
- ? undefined
5427
- : resolveCliPath(directory, options.outputDir),
5428
- archiveExisting: options.archiveExisting,
5429
- dryRun: options.dryRun,
5430
- });
5431
- exitCode = outcome.exitCode;
5432
- if (outcome.error !== undefined) {
5433
- return incurError({
5434
- code: "SCAN_IMPORT_FAILED",
5435
- message: outcome.error,
5436
- exitCode,
5437
- });
5438
- }
5439
- if (!options.dryRun && useDefaultOutput(format)) {
5440
- return;
5441
- }
5442
- return outcome.data;
5443
- },
5444
- }));
5445
- }
5446
6125
  let notice;
6126
+ if (argv.includes("--schema") || argv.includes("--llms-full")) {
6127
+ describeCommandInputs(commands);
6128
+ }
5447
6129
  try {
5448
- await cli.serve(frameworkArgv, {
6130
+ const serveOptions = {
5449
6131
  stdout: frameworkCapture.stream.write,
5450
6132
  exit: (code) => {
5451
6133
  frameworkExit = code;
5452
6134
  },
5453
- });
6135
+ };
6136
+ if (!(await serveIntegration(frameworkArgv, cli, cliOptions, serveOptions, command, literalArgs))) {
6137
+ await cli.serve(frameworkArgv, serveOptions);
6138
+ }
5454
6139
  if (pendingUpdate !== undefined) {
5455
6140
  notice = await Promise.race([pendingUpdate, undefined]);
5456
6141
  }
5457
6142
  }
6143
+ catch (error) {
6144
+ return reportError(errorMessage(error), "COMMAND_FAILED");
6145
+ }
5458
6146
  finally {
5459
6147
  updateController.abort();
5460
6148
  }
6149
+ if ((command === "login" || command === "logout") &&
6150
+ (exitCode === 130 || exitCode === 143))
6151
+ onInterruptedSignIn?.();
5461
6152
  let frameworkOutput = frameworkCapture.text();
5462
- if (filteredScanFailure !== undefined) {
5463
- // Success-field filters do not apply to diagnostics. Reuse Incur's format
5464
- // and token controls without running the saved scan a second time.
5465
- const failureOutput = captureOutput();
5466
- const failureArguments = [
5467
- "render",
5468
- "--format",
5469
- filteredScanFailure.format,
5470
- ...frameworkFlags.tokenArguments,
5471
- ];
5472
- if (failedResultOutput)
5473
- failureArguments.push("--full-output");
5474
- const failure = filteredScanFailure.data;
5475
- await Cli.create("codex-security-scan-error")
5476
- .command("render", { run: () => failure })
5477
- .serve(failureArguments, {
5478
- stdout: failureOutput.stream.write,
5479
- exit: () => undefined,
5480
- });
5481
- if (failedResultOutput)
5482
- frameworkOutput = failureOutput.text();
5483
- else
5484
- renderedOutput = failureOutput.text();
6153
+ if (command !== undefined &&
6154
+ (argv.includes("--help") || argv.includes("-h")) &&
6155
+ frameworkOutput.includes("\nUsage: codex-security <command>\n")) {
6156
+ // Incur returns the root menu for unresolved application help paths.
6157
+ const parent = commands.get(command);
6158
+ const group = parent && "_group" in parent ? command : undefined;
6159
+ const path = group && following ? `${group} ${following}` : command;
6160
+ return reportError(`Unknown command ${diagnosticValue(path)}. Use codex-security${group ? ` ${group}` : ""} --help.`, "COMMAND_NOT_FOUND");
5485
6161
  }
5486
6162
  if (escapeFrameworkOutput)
5487
6163
  frameworkOutput = escapeTerminalText(frameworkOutput, true);
@@ -5496,22 +6172,68 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
5496
6172
  if (deferredVerificationDiagnostic === undefined)
5497
6173
  writeUpdateNotice();
5498
6174
  if (frameworkExit !== undefined) {
5499
- if (policyFullOutput || structuredError) {
6175
+ // A canceled command can deliberately finish without a result.
6176
+ if (!structuredError &&
6177
+ !policyFullOutput &&
6178
+ (exitCode === 130 || exitCode === 143))
6179
+ return exitCode;
6180
+ if (!envelopeFormat && (policyFullOutput || structuredError)) {
5500
6181
  if (exitCode === 0)
5501
6182
  exitCode = 2;
5502
6183
  }
5503
6184
  else {
5504
- if (exitCode !== 0)
6185
+ if (exitCode !== 0 && !envelopeFormat)
5505
6186
  return exitCode;
5506
- errorOutput.write(`codex-security: ${diagnosticLines(await incurErrorMessage(frameworkOutput))}\n`);
5507
- return 2;
6187
+ const envelope = jsonFormat
6188
+ ? parseJson(() => frameworkOutput)
6189
+ : undefined;
6190
+ const record = asRecord(envelope);
6191
+ const error = record?.["ok"] === false ? asRecord(record["error"]) : record;
6192
+ const validationError = error?.["code"] === "VALIDATION_ERROR";
6193
+ const structuredFailure = Boolean(envelopeFormat || validationError);
6194
+ let message = structuredFailure && typeof error?.["message"] === "string"
6195
+ ? error["message"]
6196
+ : await incurErrorMessage(frameworkOutput);
6197
+ if (validationError && Array.isArray(error["fieldErrors"])) {
6198
+ const entry = command ? commands.get(command) : undefined;
6199
+ const leaf = entry && "_group" in entry
6200
+ ? (entry.commands.get(following ?? "") ?? entry.root)
6201
+ : entry;
6202
+ const options = leaf && "options" in leaf ? leaf.options?.shape : undefined;
6203
+ const messages = error["fieldErrors"].map((field) => {
6204
+ if (!isJsonObject(field) || typeof field["path"] !== "string")
6205
+ return message;
6206
+ const detail = typeof field["message"] === "string" ? field["message"] : message;
6207
+ if (options && Object.hasOwn(options, field["path"])) {
6208
+ const flag = field["path"].replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
6209
+ return field["missing"]
6210
+ ? `Missing required option --${flag}.`
6211
+ : `Invalid value for --${flag}: ${detail}`;
6212
+ }
6213
+ return detail;
6214
+ });
6215
+ message = messages.join("\n");
6216
+ error["message"] = message;
6217
+ frameworkOutput = Formatter.format(envelope, jsonFormat) + "\n";
6218
+ }
6219
+ // Handlers that set an exit code have already reported the execution error.
6220
+ if (exitCode === 0)
6221
+ errorOutput.write(`codex-security: ${diagnosticLines(message)}\n`);
6222
+ if (!structuredFailure)
6223
+ return 2;
6224
+ if (exitCode === 0)
6225
+ exitCode = 2;
6226
+ // Incur parses its built-in flags before selecting a format.
6227
+ if (envelopeFormat && record?.["ok"] !== false)
6228
+ frameworkOutput = argumentFailure(message);
5508
6229
  }
5509
6230
  }
5510
6231
  if (rawExportOutput)
5511
6232
  return exitCode;
5512
6233
  if (frameworkOutput.length === 0 &&
6234
+ !(jsonFormat && frameworkFlags.tokenView?.count && exitCode === 0) &&
5513
6235
  streamedLogs === undefined &&
5514
- filteredScanFailure === undefined &&
6236
+ unfilteredFailure === undefined &&
5515
6237
  deferredVerificationDiagnostic === undefined)
5516
6238
  return exitCode;
5517
6239
  try {
@@ -5537,19 +6259,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
5537
6259
  }
5538
6260
  else if (failedResultOutput !== undefined) {
5539
6261
  const envelope = JSON.parse(frameworkOutput);
5540
- // Token-count output is a number, not a full-output envelope.
5541
6262
  if (isJsonObject(envelope) && envelope["ok"] === true) {
5542
- // Re-rendered failures carry the unfiltered page, but the command's
5543
- // original metadata describes the actual invocation.
5544
- const meta = filteredScanFailure && isJsonObject(envelope["meta"])
5545
- ? {
5546
- ...JSON.parse(frameworkCapture.text()).meta,
5547
- nextOffset: envelope["meta"]["nextOffset"],
5548
- }
5549
- : envelope["meta"];
5550
6263
  frameworkOutput = `${JSON.stringify({
5551
6264
  ...envelope,
5552
- meta,
6265
+ ...(unfilteredFailure && { data: unfilteredFailure }),
5553
6266
  ok: false,
5554
6267
  error: {
5555
6268
  code: failedResultOutput.code ?? "SCAN_FAILED",
@@ -5558,9 +6271,23 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
5558
6271
  }, null, failedResultOutput.format === "json" ? 2 : undefined)}\n`;
5559
6272
  }
5560
6273
  }
5561
- await writeCliOutput(output, logOutput ??
5562
- renderedOutput ??
5563
- formatCliHelp(frameworkOutput, output.columns));
6274
+ const help = formatCliHelp(frameworkOutput, output.columns);
6275
+ let response = renderedOutput ?? help ?? frameworkOutput;
6276
+ // Incur writes menus and completion scripts directly as plain text.
6277
+ if (jsonFormat &&
6278
+ !inspection &&
6279
+ exitCode === 0 &&
6280
+ (help !== undefined || command === "completions")) {
6281
+ response =
6282
+ Formatter.format(frameworkFlags.fullOutput
6283
+ ? { ok: true, data: response, meta: { command: commandPath } }
6284
+ : response, jsonFormat) + "\n";
6285
+ }
6286
+ if (jsonFormat && unfilteredFailure && !failedResultOutput)
6287
+ response = Formatter.format(unfilteredFailure, jsonFormat) + "\n";
6288
+ if (jsonFormat && frameworkFlags.tokenView && !inspection)
6289
+ response = formatJsonTokenView(response, jsonFormat, frameworkFlags.fullOutput, frameworkFlags.tokenView);
6290
+ await writeCliOutput(output, logOutput ?? response);
5564
6291
  return exitCode;
5565
6292
  }
5566
6293
  catch (error) {
@@ -5571,7 +6298,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
5571
6298
  if (deferredVerificationDiagnostic !== undefined) {
5572
6299
  // Token output can omit the diagnostic. Otherwise a buffered stderr
5573
6300
  // write is optional once the complete structured failure is on stdout.
5574
- if (frameworkFlags.tokenArguments.length) {
6301
+ if (frameworkFlags.tokenView) {
5575
6302
  await writeCliOutput(errorOutput, deferredVerificationDiagnostic).catch(() => { });
5576
6303
  }
5577
6304
  else {
@@ -5678,6 +6405,7 @@ async function prepareScanArgumentsFromRecipe({ recipe, userContext }, operation
5678
6405
  const failureSeverity = readSetting("failOnSeverity", fields.failureSeverity, "severity policy");
5679
6406
  const maxCostUsd = readSetting("maxCostUsd", fields.maxCostUsd, "cost limit");
5680
6407
  const maxTimeMinutes = readSetting("maxTimeMinutes", fields.maxTimeMinutes, "investigation time limit");
6408
+ const excludePaths = readSetting("excludePaths", fields.excludePaths, "excluded paths");
5681
6409
  const deepScan = DeepScanSettingsSchema.optional().safeParse(recipe["deepScan"]);
5682
6410
  if (!deepScan.success) {
5683
6411
  throw new CodexSecurityError("The saved scan recipe contains invalid deep scan settings.");
@@ -5716,6 +6444,7 @@ async function prepareScanArgumentsFromRecipe({ recipe, userContext }, operation
5716
6444
  auth: auth ?? DEFAULT_SCAN_AUTH,
5717
6445
  cyberAccessProgram,
5718
6446
  ownerSuggestions,
6447
+ excludePaths,
5719
6448
  ...(severityRubric === undefined ? {} : { severityRubric }),
5720
6449
  // Saved scopes contain literal repository names, not home-relative inputs.
5721
6450
  target: paths.length > 0
@@ -5727,7 +6456,7 @@ async function prepareScanArgumentsFromRecipe({ recipe, userContext }, operation
5727
6456
  : kind === "working_tree"
5728
6457
  ? DiffTarget.workingTree({ base: reference ?? "HEAD" })
5729
6458
  : "repository",
5730
- knowledgeBasePaths: knowledgeBasePaths.map((path) => resolveCliPath(directory, path)),
6459
+ knowledgeBasePaths: knowledgeBasePaths.map((path) => resolveInputPath(path, directory)),
5731
6460
  ...prompts,
5732
6461
  safetyIdentifier,
5733
6462
  postScanPrompt,
@@ -5751,45 +6480,230 @@ async function prepareScanArgumentsFromRecipe({ recipe, userContext }, operation
5751
6480
  : undefined,
5752
6481
  };
5753
6482
  }
5754
- function frameworkOutputFlags(argv) {
5755
- let fullOutput = false;
5756
- let rawCollector = false;
5757
- const tokenArguments = [];
5758
- let filterOutput = false;
5759
- for (let index = 0; index < argv.length; index++) {
6483
+ /** Incur describes parsed Zod outputs by default. Callers supply the inputs,
6484
+ * which may omit fields populated by CLI defaults. Keep the runtime defaults. */
6485
+ function describeCommandInputs(commands) {
6486
+ for (const entry of commands.values()) {
6487
+ if ("_group" in entry)
6488
+ describeCommandInputs(entry.commands);
6489
+ const command = "_group" in entry ? entry.root : entry;
6490
+ if (command && "options" in command && command.options) {
6491
+ const input = z.toJSONSchema(command.options, { io: "input" });
6492
+ command.options = command.options.meta({
6493
+ required: input.required ?? [],
6494
+ });
6495
+ }
6496
+ }
6497
+ }
6498
+ function isJsonFormat(format) {
6499
+ return format === "json" || format === "jsonl";
6500
+ }
6501
+ /** Skip recognized global options and their operands while locating a command. */
6502
+ function firstNonGlobal(argv, start) {
6503
+ let index = start;
6504
+ while (index < argv.length) {
5760
6505
  const value = argv[index];
5761
- if (value === "--full-output")
5762
- fullOutput = true;
5763
- if (value === "--json")
5764
- rawCollector = true;
5765
- if (value === "--token-count")
5766
- tokenArguments.push(value);
5767
- if (FRAMEWORK_VALUE_OPTIONS.has(value)) {
5768
- const operand = argv[++index];
5769
- if (value === "--filter-output")
5770
- filterOutput = true;
5771
- if ((value === "--token-limit" || value === "--token-offset") &&
5772
- operand !== undefined)
5773
- tokenArguments.push(value, operand);
5774
- if (value === "--format")
5775
- rawCollector =
5776
- operand === "json" || operand === "jsonl" || operand === "yaml";
6506
+ const [flag] = value.split("=", 1);
6507
+ if (FRAMEWORK_VALUE_OPTIONS.has(flag)) {
6508
+ if (!value.includes("=") &&
6509
+ (argv[index + 1] === undefined || argv[index + 1].startsWith("-")))
6510
+ break;
6511
+ index += value.includes("=") ? 1 : 2;
6512
+ }
6513
+ else if (INSPECTION_FLAGS.includes(value) ||
6514
+ ["--json", "--full-output", "--token-count"].includes(value)) {
6515
+ index++;
6516
+ }
6517
+ else
6518
+ break;
6519
+ }
6520
+ return index;
6521
+ }
6522
+ /** Translate historical input flags only within their original command. */
6523
+ function normalizeImportArguments(argv, verbIndex, command, subcommand) {
6524
+ const scanImport = command === "scan" && subcommand === "import";
6525
+ const providerAliases = command === "import" && subcommand === "semgrep"
6526
+ ? { "--semgrep-deployment": "--deployment", "--semgrep-ref": "--ref" }
6527
+ : command === "import" && subcommand === "snyk"
6528
+ ? { "--snyk-org": "--org" }
6529
+ : {};
6530
+ if (!scanImport && Object.keys(providerAliases).length === 0)
6531
+ return { args: argv };
6532
+ const args = argv.slice(0, verbIndex + 1);
6533
+ const seen = new Map();
6534
+ for (let index = args.length; index < argv.length; index++) {
6535
+ const token = argv[index];
6536
+ const equals = token.indexOf("=");
6537
+ const name = equals < 0 ? token : token.slice(0, equals);
6538
+ const flag = name.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase());
6539
+ let value = equals < 0 ? argv[index + 1] : token.slice(equals + 1);
6540
+ let canonical = providerAliases[flag] ?? flag;
6541
+ if (scanImport && (flag === "--csv" || flag === "--json")) {
6542
+ if (equals < 0 &&
6543
+ (value === undefined || value.startsWith("--") || value === "-h")) {
6544
+ if (flag === "--csv")
6545
+ return { args: argv, error: "Missing value for flag: --csv" };
6546
+ args.push(token);
6547
+ continue;
6548
+ }
6549
+ if (!value)
6550
+ return { args: argv, error: `${flag} must not be empty.` };
6551
+ args.push(value.startsWith("-") ? "./" + value : value);
6552
+ if (equals < 0)
6553
+ index++;
6554
+ canonical = "--input-format";
6555
+ value = flag.slice(2);
6556
+ args.push(canonical + "=" + value);
6557
+ }
6558
+ else if (Object.hasOwn(providerAliases, flag)) {
6559
+ args.push(canonical + (equals < 0 ? "" : token.slice(equals)));
6560
+ }
6561
+ else {
6562
+ args.push(token);
6563
+ }
6564
+ if (value !== undefined &&
6565
+ (canonical === "--input-format" ||
6566
+ Object.values(providerAliases).includes(canonical))) {
6567
+ if (seen.has(canonical) && seen.get(canonical) !== value)
6568
+ return { args: argv, error: `Conflicting values for ${canonical}.` };
6569
+ seen.set(canonical, value);
5777
6570
  }
5778
6571
  }
6572
+ return { args };
6573
+ }
6574
+ function parseFrameworkArguments(argv) {
6575
+ const args = [];
6576
+ const formats = [];
6577
+ const filters = [];
6578
+ const tokenArguments = [];
6579
+ let tokenView;
6580
+ let tokenError;
6581
+ let fullOutput = false;
6582
+ let argumentError;
6583
+ for (let index = 0; index < argv.length; index++) {
6584
+ const argument = argv[index];
6585
+ const next = argv[index + 1];
6586
+ const equals = argument.indexOf("=");
6587
+ const flag = equals < 0 ? argument : argument.slice(0, equals);
6588
+ if (!FRAMEWORK_VALUE_OPTIONS.has(flag)) {
6589
+ if (argument === "--token-count") {
6590
+ (tokenView ??= {}).count = true;
6591
+ tokenArguments.push(argument);
6592
+ continue;
6593
+ }
6594
+ args.push(argument);
6595
+ if (argument === "--json")
6596
+ formats.push("json");
6597
+ if (argument === "--full-output")
6598
+ fullOutput = true;
6599
+ continue;
6600
+ }
6601
+ // Leave a following flag available when the option is missing its operand.
6602
+ const operand = equals >= 0
6603
+ ? argument.slice(equals + 1)
6604
+ : /^-(?:-|[a-z])/iu.test(next ?? "")
6605
+ ? undefined
6606
+ : next;
6607
+ if (equals < 0 && operand !== undefined)
6608
+ index++;
6609
+ if (operand === undefined ||
6610
+ (!operand && (flag === "--filter-output" || flag === "--format"))) {
6611
+ argumentError ??= `Missing value for flag: ${flag}`;
6612
+ }
6613
+ if (flag === "--filter-output") {
6614
+ filters.push(operand);
6615
+ // Incur cannot advance past an unterminated array slice.
6616
+ if (operand !== undefined &&
6617
+ !/^(?:[^\[\]]|\[[^\[\]]*\])*$/u.test(operand)) {
6618
+ argumentError ??=
6619
+ "--filter-output requires matching brackets for array slices.";
6620
+ continue;
6621
+ }
6622
+ }
6623
+ if (flag === "--token-limit" || flag === "--token-offset") {
6624
+ if (operand === undefined ||
6625
+ !/^\d+$/u.test(operand) ||
6626
+ !Number.isSafeInteger(Number(operand))) {
6627
+ tokenError ??= `${flag} requires a nonnegative integer.`;
6628
+ }
6629
+ else {
6630
+ (tokenView ??= {})[flag === "--token-limit" ? "limit" : "offset"] =
6631
+ Number(operand);
6632
+ tokenArguments.push(flag, operand);
6633
+ }
6634
+ continue;
6635
+ }
6636
+ args.push(flag);
6637
+ if (operand !== undefined)
6638
+ args.push(operand);
6639
+ if (flag === "--format" && operand)
6640
+ formats.push(operand);
6641
+ }
6642
+ // Invalid format operands still go to Incur. Preserve a valid request for
6643
+ // JSON diagnostics if parsing a later operand fails.
6644
+ const format = formats.findLast((value) => ["json", "jsonl", "toon", "yaml", "md"].includes(value));
6645
+ const jsonFormat = isJsonFormat(format) ? format : undefined;
6646
+ if (!jsonFormat)
6647
+ args.push(...tokenArguments);
5779
6648
  return {
5780
- rawCollector: rawCollector && !fullOutput,
5781
- filterOutput,
6649
+ args,
6650
+ formats,
6651
+ jsonFormat,
6652
+ fullOutput,
6653
+ argumentError,
6654
+ filters,
5782
6655
  tokenArguments,
6656
+ tokenView,
6657
+ tokenError,
6658
+ rawStructuredOutput: !fullOutput && (jsonFormat !== undefined || format === "yaml"),
5783
6659
  };
5784
6660
  }
5785
- function cliValueOptions(commands) {
5786
- const options = new Set(FRAMEWORK_VALUE_OPTIONS);
5787
- for (const command of commands.values()) {
5788
- if ("_group" in command) {
5789
- for (const option of cliValueOptions(command.commands))
5790
- options.add(option);
5791
- }
5792
- else if ("options" in command && command.options) {
6661
+ function cliOptionFlag(key) {
6662
+ return `--${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`;
6663
+ }
6664
+ function cliOptionTokens(options) {
6665
+ const tokens = [];
6666
+ for (const [key, value] of Object.entries(options)) {
6667
+ if (value === undefined)
6668
+ continue;
6669
+ const flag = cliOptionFlag(key);
6670
+ for (const item of Array.isArray(value) ? value : [value]) {
6671
+ if (typeof item === "boolean") {
6672
+ tokens.push(item ? flag : `${flag}=false`);
6673
+ }
6674
+ else if (String(item).startsWith("-")) {
6675
+ tokens.push(quoteCliPath(`${flag}=${item}`));
6676
+ }
6677
+ else {
6678
+ tokens.push(flag, quoteCliPath(String(item)));
6679
+ }
6680
+ }
6681
+ }
6682
+ return tokens;
6683
+ }
6684
+ /** Incur prints example keys verbatim and treats every option as a single value.
6685
+ * Give its shared help, manifest and skill renderers the actual shell tokens.
6686
+ */
6687
+ function prepareCliExamples(commands) {
6688
+ for (const entry of commands.values()) {
6689
+ if ("_group" in entry)
6690
+ prepareCliExamples(entry.commands);
6691
+ const command = "_group" in entry ? entry.root : entry;
6692
+ if (!command || !("examples" in command))
6693
+ continue;
6694
+ for (const example of command.examples ?? []) {
6695
+ const tokens = Object.values(example.args ?? {}).map((value) => quoteCliPath(String(value)));
6696
+ example.args = [...tokens, ...cliOptionTokens(example.options ?? {})];
6697
+ delete example.options;
6698
+ }
6699
+ }
6700
+ }
6701
+ function cliValueOptions(commands, options = new Set(FRAMEWORK_VALUE_OPTIONS)) {
6702
+ for (const entry of commands.values()) {
6703
+ if ("_group" in entry)
6704
+ cliValueOptions(entry.commands, options);
6705
+ const command = "_group" in entry ? entry.root : entry;
6706
+ if (command && "options" in command && command.options) {
5793
6707
  for (const [name, schema] of Object.entries(z.toJSONSchema(command.options, { io: "input" }).properties ?? {})) {
5794
6708
  if (typeof schema === "object" && schema.type === "boolean")
5795
6709
  continue;
@@ -5813,8 +6727,9 @@ async function matchAllScans(dependencies, force, options = {}) {
5813
6727
  let relatedPairs = 0;
5814
6728
  let uncertainPairs = 0;
5815
6729
  const newlyMatchedGroups = [];
5816
- for (const { afterScanId, afterFindings, beforeScans, knownFindingGroups = [], } of batches) {
6730
+ for (const batch of batches) {
5817
6731
  options.signal?.throwIfAborted();
6732
+ const { afterScanId, afterFindings, beforeScans, knownFindingGroups = [], } = resolveMatchingBatch(batch, result.findingsByScanId);
5818
6733
  const before = beforeScans.flatMap(({ findings }) => findings);
5819
6734
  const knownGroups = unionFindingGroups([
5820
6735
  ...knownFindingGroups,
@@ -6377,7 +7292,7 @@ async function assessPatchRisk(request, stderr, dependencies) {
6377
7292
  const pathspec = request.files === undefined
6378
7293
  ? []
6379
7294
  : ["--", ...request.files.map((file) => file)];
6380
- const root = await mkdtemp(join(tmpdir(), "codex-security-patch-risk-"));
7295
+ const root = await mkdtemp(join(await realpath(tmpdir()), "codex-security-patch-risk-"));
6381
7296
  const patchPath = join(root, "patch.diff");
6382
7297
  try {
6383
7298
  const head = request.head ??
@@ -6434,7 +7349,7 @@ async function assessPatchRisk(request, stderr, dependencies) {
6434
7349
  }
6435
7350
  }
6436
7351
  async function withPatchIndex(repository, dependencies, operation) {
6437
- const root = await mkdtemp(join(tmpdir(), "codex-security-patch-tree-"));
7352
+ const root = await mkdtemp(join(await realpath(tmpdir()), "codex-security-patch-tree-"));
6438
7353
  try {
6439
7354
  return await operation((args, input) => dependencies.runRepositoryCommand("git", args, repository, {
6440
7355
  environment: {
@@ -6671,7 +7586,20 @@ async function runSkill(skill, inputs, configuration, stdout, stderr, dependenci
6671
7586
  if (input.trim().length === 0) {
6672
7587
  throw new CodexSecurityError("Finding or issue inputs must not be empty.");
6673
7588
  }
7589
+ if (input.startsWith("text:")) {
7590
+ const literal = input.slice("text:".length);
7591
+ if (!literal.trim())
7592
+ throw new CodexSecurityError("Finding or issue inputs must not be empty.");
7593
+ contents.push(literal);
7594
+ continue;
7595
+ }
6674
7596
  let contentsOrLiteral = input;
7597
+ const explicitFile = /^file:\/\//iu.test(input)
7598
+ ? new URL(input)
7599
+ : undefined;
7600
+ if (explicitFile?.hostname) {
7601
+ throw new CodexSecurityError("Finding file URLs must refer to local files.");
7602
+ }
6675
7603
  const windowsNamespace = process.platform === "win32" || input.startsWith("\\");
6676
7604
  const rawDeviceRoot = WINDOWS_LOCAL_DEVICE_ROOT.exec(input)?.[0];
6677
7605
  const localDeviceRoot = rawDeviceRoot?.replaceAll("/", "\\").toLowerCase();
@@ -6686,8 +7614,14 @@ async function runSkill(skill, inputs, configuration, stdout, stderr, dependenci
6686
7614
  !staysWithinWindowsDeviceRoot(input, rawDeviceRoot) ||
6687
7615
  localDeviceRoot !== normalizedDeviceRoot);
6688
7616
  if (!windowsNetworkPath) {
6689
- const path = resolveCliPath(directory, input);
7617
+ const path = resolveCliPath(directory, explicitFile ? fileURLToPath(explicitFile) : input);
6690
7618
  const metadata = await lstat(path, { bigint: true }).catch((error) => {
7619
+ if (explicitFile ||
7620
+ isAbsolute(expandHome(input)) ||
7621
+ input.startsWith("./") ||
7622
+ input.startsWith("../") ||
7623
+ (process.platform === "win32" && /^\.{1,2}\\/u.test(input)))
7624
+ throw error;
6691
7625
  if (typeof error === "object" &&
6692
7626
  error !== null &&
6693
7627
  "code" in error &&
@@ -7209,12 +8143,10 @@ export async function readSkillCommandOutput(stream, appServer) {
7209
8143
  };
7210
8144
  }
7211
8145
  export function skillCommandFailure(command, status, detail, authentication = null) {
7212
- // Paths may contain provider error codes as filenames. Keep the original for display.
8146
+ // Exclude paths and parser locations from advice, but keep the original diagnostic for display.
7213
8147
  const containsParserError = /\b(?:syntax\s*error|pars(?:e|er|ing)|unexpected token|at (?:line|column) \d+)\b/iu.test(detail);
7214
8148
  // Keep a neutral token so a quoted provider/model remains a named model in the message.
7215
- const withoutPaths = detail
7216
- .replace(/\bhttps?:\/\/[^\s"'`<>]+/giu, "")
7217
- .replace(/[^\s"'`()<>,]+/gu, (token) => /[/\\]/u.test(token) && !/^HTTP\/\d+(?:\.\d+)?$/iu.test(token)
8149
+ const withoutPaths = connectionAdviceDetail(detail).replace(/[^\s"'`()<>,]+/gu, (token) => /[/\\]/u.test(token) && !/^HTTP\/\d+(?:\.\d+)?$/iu.test(token)
7218
8150
  ? "[path]"
7219
8151
  : token);
7220
8152
  const diagnosticDetail = containsParserError
@@ -7224,15 +8156,15 @@ export function skillCommandFailure(command, status, detail, authentication = nu
7224
8156
  const classification = classifyConnectionFailure(classificationDetail);
7225
8157
  let advice;
7226
8158
  if (classification === "unauthorized" ||
7227
- /\b(?:authorizationrequired|invalid[._ -]api[._ -]key|token[._ -]expired)\b/iu.test(classificationDetail)) {
8159
+ /\bauthorizationrequired\b/iu.test(classificationDetail)) {
7228
8160
  advice = authenticationFailureMessage(authentication);
7229
8161
  }
7230
8162
  else if (/\bpermissions? to use (?:this |the )?model\b/iu.test(classificationDetail) ||
7231
8163
  (!/\b(?:sqlite3?|database|workbench)\b/iu.test(classificationDetail) &&
7232
- /\bmodel[ \t]+(?:'[^'\r\n]+'|"[^"\r\n]+"|`[^`\r\n]+`)[ \t]+not[ \t]+found\b/iu.test(classificationDetail)) ||
7233
- /\b(?:model[._ -]not[._ -]found|model[._ -]?access[._ -]?denied|access[._ -]?(?:denied[._ -]?to[._ -]?model|to[._ -]?model[._ -]?denied))\b/iu.test(classificationDetail) ||
8164
+ /(?<![\w./\\-])model[ \t]+(?:'[^'\r\n]+'|"[^"\r\n]+"|`[^`\r\n]+`)[ \t]+not[ \t]+found(?!\.?[\w/\\-])/iu.test(classificationDetail)) ||
8165
+ /(?<![\w./\\-])(?:model[._ -]not[._ -]found|model[._ -]?access[._ -]?denied|access[._ -]?(?:denied[._ -]?to[._ -]?model|to[._ -]?model[._ -]?denied))(?!\.?[\w/\\-])/iu.test(classificationDetail) ||
7234
8166
  (classification === "forbidden" &&
7235
- /\b403\b|\bforbidden\b|\bmodel[ _-]?(?:not[ _-]?found|access)\b|\baccess.*model\b/iu.test(classificationDetail))) {
8167
+ /\b403\b|\bforbidden\b|\bmodel[ ._-]?(?:not[ ._-]?found|access)\b|\baccess.*model\b/iu.test(classificationDetail))) {
7236
8168
  advice = "The selected model is unavailable for the current credentials.";
7237
8169
  }
7238
8170
  else if (classification === "rate_limited" ||
@@ -7246,7 +8178,7 @@ export function skillCommandFailure(command, status, detail, authentication = nu
7246
8178
  else if (classification === "network_error" ||
7247
8179
  classification === "timeout" ||
7248
8180
  (!/\b(?:sqlite3?|database|workbench)\b/iu.test(classificationDetail) &&
7249
- /\b(?:ECONNABORTED|timed[._ -]out|network[._ -]?error|(?:(?:network|request)[._ -]?)?timeout(?:[._ -]?error)?)\b/iu.test(classificationDetail))) {
8181
+ /\b(?:ECONNABORTED|network[._ -]?error|(?:(?:network|request)[._ -]?)?timeout(?:[._ -]?error)?)\b/iu.test(classificationDetail))) {
7250
8182
  advice =
7251
8183
  "Codex could not connect to the model service. Check the network and retry.";
7252
8184
  }
@@ -7277,6 +8209,19 @@ async function incurErrorMessage(output) {
7277
8209
  function diagnosticLines(value) {
7278
8210
  return errorMessage(value).split("\n").map(diagnosticValue).join("\n");
7279
8211
  }
8212
+ const PREVIEW_LABEL = process.platform === "win32" ? "Next (PowerShell)" : "Next";
8213
+ function projectPreviewCommand(directory, path) {
8214
+ if (path === undefined)
8215
+ return "codex-security scan . --dry-run";
8216
+ const local = relative(directory, path);
8217
+ let file = local.split(/[\\/]/u)[0] === ".." ? path : local;
8218
+ if (file.startsWith("-") || file.startsWith("~"))
8219
+ file = `./${file}`;
8220
+ // Keep terminal controls out of suggested commands and quote shell syntax.
8221
+ if (escapeTerminalText(file) !== file)
8222
+ return "codex-security scan . -c FILE --dry-run (replace FILE with the selected path)";
8223
+ return `codex-security scan . -c ${quoteCliPath(file)} --dry-run`;
8224
+ }
7280
8225
  function diagnosticValue(value) {
7281
8226
  return errorMessage(value).replaceAll(/[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu, " ");
7282
8227
  }
@@ -7343,6 +8288,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive, r
7343
8288
  let usageFreshness = null;
7344
8289
  let accountLimits = null;
7345
8290
  let maxCostUsd = arguments_.maxCostUsd;
8291
+ if (maxCostUsd !== undefined && arguments_.patch)
8292
+ throw new CodexSecurityError("--patch cannot be combined with a scan cost limit. Run the bounded scan first, then use `codex-security patch --scan SCAN_ID` separately.");
7346
8293
  const showCost = arguments_.showCost === true || maxCostUsd !== undefined;
7347
8294
  let phase = null;
7348
8295
  const targetWarnings = [];
@@ -7430,17 +8377,21 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive, r
7430
8377
  let patchDaybreakFeatures = {};
7431
8378
  let selectedAuthentication = null;
7432
8379
  let repository = "";
8380
+ let runningMockScan = false;
7433
8381
  let failed = false;
7434
8382
  let failure;
7435
8383
  try {
7436
8384
  deepScanOptions(arguments_);
7437
8385
  const directory = dependencies.currentDirectory();
7438
8386
  repository = arguments_.repository ?? directory;
7439
- if (arguments_.validate) {
7440
- repository = await normalizeRepository(resolve(directory, expandHome(repository)), preparationAbortController.signal);
8387
+ const repositoryPath = arguments_.validate
8388
+ ? resolveInputPath(repository, directory)
8389
+ : resolveRepositoryPath(repository, directory);
8390
+ if (arguments_.validate || repositoryPath.split(sep).includes("..")) {
8391
+ repository = await normalizeRepository(repositoryPath, preparationAbortController.signal);
7441
8392
  }
7442
8393
  const target = arguments_.target;
7443
- const prompts = await resolveScanPrompts(arguments_, resolve(directory, repository), directory);
8394
+ const prompts = await resolveScanPrompts(arguments_, resolveRepositoryPath(repository, directory), directory);
7444
8395
  const config = {
7445
8396
  pluginPath: arguments_.pluginPath,
7446
8397
  pythonPath: arguments_.pythonPath,
@@ -7965,7 +8916,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive, r
7965
8916
  if (((arguments_.validate && !arguments_.dryRun) ||
7966
8917
  arguments_.rerunInputIdentity !== undefined) &&
7967
8918
  options.knowledgeBasePaths?.length) {
7968
- options.knowledgeBaseSnapshot = await readKnowledgeBaseSnapshot(options.knowledgeBasePaths, preparationAbortController.signal);
8919
+ options.knowledgeBaseSnapshot = await readKnowledgeBaseSnapshot(options.knowledgeBasePaths, preparationAbortController.signal, resolve(directory, expandHome(repository)));
7969
8920
  }
7970
8921
  if (arguments_.rerunInputIdentity !== undefined) {
7971
8922
  const previousInputs = arguments_.rerunInputIdentity;
@@ -7989,9 +8940,11 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive, r
7989
8940
  preflight = await security.preflight(repository, options);
7990
8941
  }
7991
8942
  else {
8943
+ runningMockScan = arguments_.mock === true;
7992
8944
  result = await security.run(repository, options);
8945
+ runningMockScan = false;
7993
8946
  scanDir = result.scanDir;
7994
- repository = resolve(dependencies.currentDirectory(), repository);
8947
+ repository = resolveRepositoryPath(repository, dependencies.currentDirectory());
7995
8948
  if (arguments_.validate) {
7996
8949
  const scanId = result.manifest.scan.id;
7997
8950
  const checkTarget = async () => {
@@ -8142,7 +9095,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive, r
8142
9095
  if (result !== null && arguments_.validate) {
8143
9096
  const exitCode = requestedSignal === "SIGINT" ? 130 : 143;
8144
9097
  const scanId = quoteCliPath(diagnosticValue(result.manifest.scan.id));
8145
- const message = `Validation interrupted. Original output directory: ${errorMessage(result.scanDir)}. Run codex-security scans show ${scanId} to inspect the completed scan.`;
9098
+ const message = `Validation interrupted. Original output directory: ${errorMessage(result.scanDir)}. Run${cliShellLabel(scanId)} codex-security scans show ${scanId} to inspect the completed scan.`;
8146
9099
  errorOutput.write(`codex-security: ${message}\n`);
8147
9100
  return {
8148
9101
  exitCode,
@@ -8167,7 +9120,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive, r
8167
9120
  }
8168
9121
  if (failed) {
8169
9122
  const costLimitFailure = failure instanceof ScanCostLimitExceededError ? failure : undefined;
8170
- const classification = classifyScanFailure(failure);
9123
+ const classification = runningMockScan
9124
+ ? "local"
9125
+ : classifyScanFailure(failure);
8171
9126
  const message = failure instanceof OutputInsideProtectedRootError
8172
9127
  ? errorMessage(protectedRootErrorMessage(failure))
8173
9128
  : scanFailureMessage(failure, classification, selectedAuthentication, providerOptions.provider);
@@ -8294,6 +9249,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive, r
8294
9249
  let patchSelection = null;
8295
9250
  try {
8296
9251
  if (!arguments_.mock &&
9252
+ maxCostUsd === undefined &&
8297
9253
  actionableFindings.length > 0 &&
8298
9254
  arguments_.patchSeverity === undefined &&
8299
9255
  progress?.interactive === true &&
@@ -8502,7 +9458,7 @@ function scanFailureMessage(error, classification, authentication, provider) {
8502
9458
  return error instanceof IncompleteScanError
8503
9459
  ? diagnosticValue(error)
8504
9460
  : nativeRefreshRecovery;
8505
- const detail = error instanceof IncompleteScanError ? `${diagnosticValue(error)}\n` : "";
9461
+ const detail = `${diagnosticValue(error)}\n`;
8506
9462
  const refreshFailure = message.match(/\byour access token could not be refreshed(?: because your refresh token (has expired|was already used|was revoked))?\. Please log out and sign in again\./iu);
8507
9463
  if (refreshFailure) {
8508
9464
  const recovery = refreshFailure[1]?.toLowerCase() === "was already used"
@@ -8575,7 +9531,7 @@ async function readDeepScanStop(result, maxCostUsd, runWorkbench) {
8575
9531
  const state = response["deepScan"];
8576
9532
  if (state?.terminalReason === "saturated") {
8577
9533
  return {
8578
- reason: `The last ${state.noNewStreak} review rounds found no new issues. More issues may remain.`,
9534
+ reason: `The last ${state.noNewStreak} review round${state.noNewStreak === 1 ? "" : "s"} found no new issues. More issues may remain.`,
8579
9535
  };
8580
9536
  }
8581
9537
  if (state?.terminalReason !== "capped")
@@ -8585,7 +9541,7 @@ async function readDeepScanStop(result, maxCostUsd, runWorkbench) {
8585
9541
  if (state.completionSequence > 0 &&
8586
9542
  state.dispatchedCount >= maxDiscoveryRuns) {
8587
9543
  return {
8588
- reason: `Reached the limit of ${maxDiscoveryRuns} review rounds. ${state.noNewStreak === 0 ? "The latest review still found new issues." : "More issues may remain."}`,
9544
+ reason: `Reached the limit of ${maxDiscoveryRuns} review round${maxDiscoveryRuns === 1 ? "" : "s"}. ${state.noNewStreak === 0 ? "The latest review still found new issues." : "More issues may remain."}`,
8589
9545
  nextStep: `To scan further, rerun with --max-discovery-runs greater than ${maxDiscoveryRuns}.`,
8590
9546
  };
8591
9547
  }
@@ -8628,8 +9584,10 @@ function printScanReference(scan, output, showLogs, selection) {
8628
9584
  const argument = quoteCliPath(diagnosticValue(scanId));
8629
9585
  output.write(`\n${detail.join(" · ")}\n` +
8630
9586
  (selection === undefined ? "" : `Selected ${selection}.\n`) +
8631
- `Inspect: codex-security scans show ${argument}\n` +
8632
- (showLogs ? `Logs: codex-security scans logs ${argument}\n` : ""));
9587
+ `Inspect${cliShellLabel(argument)}: codex-security scans show ${argument}\n` +
9588
+ (showLogs
9589
+ ? `Logs${cliShellLabel(argument)}: codex-security scans logs ${argument}\n`
9590
+ : ""));
8633
9591
  }
8634
9592
  function printFailedScanReference(scan, phase, arguments_, output) {
8635
9593
  if (scan === undefined)
@@ -8681,7 +9639,7 @@ function printScanSummary(result, progress, errorOutput, color, showCost, deepSc
8681
9639
  const confirmedCount = repositoryFindings?.filter((finding) => finding.confirmedInLatestScan)
8682
9640
  .length ?? 0;
8683
9641
  const findingSummary = repositoryFindings?.length
8684
- ? `${confirmedCount} confirmed this scan; ${findingCount - confirmedCount} previously found; ${severitySummary}`
9642
+ ? `${confirmedCount} confirmed in latest repository scan; ${findingCount - confirmedCount} previously found; ${severitySummary}`
8685
9643
  : severitySummary;
8686
9644
  const findingColor = findingCount === 0
8687
9645
  ? 32
@@ -8779,7 +9737,7 @@ function protectedRootErrorMessage(error) {
8779
9737
  const reason = error.pathKind === "output"
8780
9738
  ? "Scan artifacts cannot be written inside the protected scan root."
8781
9739
  : "Temporary and runtime files cannot be created inside the protected scan root.";
8782
- const suggestion = suggestedOutputDirectory(error.protectedRoot);
9740
+ const suggestion = suggestedOutputArgument(error.protectedRoot);
8783
9741
  return [
8784
9742
  `${description} must be outside the scanned directory and any enclosing Git worktree.`,
8785
9743
  ` Resolved path: ${error.outputDirectory}`,
@@ -8788,13 +9746,13 @@ function protectedRootErrorMessage(error) {
8788
9746
  error.pathKind === "output"
8789
9747
  ? suggestion === undefined
8790
9748
  ? "Choose an output directory outside the protected root."
8791
- : `Re-run with --output-dir ${quoteCliPath(suggestion)}.`
9749
+ : `Re-run${cliShellLabel(suggestion)} with --output-dir ${suggestion}.`
8792
9750
  : suggestion === undefined
8793
9751
  ? "Set TMPDIR (or TEMP on Windows) to a writable directory outside the protected root."
8794
- : `Set TMPDIR (or TEMP on Windows) to ${quoteCliPath(suggestion)} after creating that directory.`,
9752
+ : `Set TMPDIR (or TEMP on Windows) to ${suggestion} after creating that directory.`,
8795
9753
  ].join("\n");
8796
9754
  }
8797
- function suggestedOutputDirectory(protectedRoot) {
9755
+ function suggestedOutputArgument(protectedRoot) {
8798
9756
  const parent = dirname(protectedRoot);
8799
9757
  if (parent === protectedRoot)
8800
9758
  return undefined;
@@ -8815,19 +9773,18 @@ function suggestedOutputDirectory(protectedRoot) {
8815
9773
  error !== null &&
8816
9774
  "code" in error &&
8817
9775
  error.code === "ENOENT") {
8818
- return candidate;
9776
+ return quoteCliPath(candidate);
8819
9777
  }
8820
9778
  return undefined;
8821
9779
  }
8822
9780
  }
8823
9781
  return undefined;
8824
9782
  }
8825
- function quoteCliPath(path) {
8826
- if (/^[A-Za-z0-9_./:\\-]+$/u.test(path))
8827
- return path;
8828
- return process.platform === "win32"
8829
- ? `"${path}"`
8830
- : `'${path.replaceAll("'", `'"'"'`)}'`;
9783
+ function importedFindingsCommand(repository) {
9784
+ if (diagnosticValue(repository) !== repository)
9785
+ return "From the repository directory, run codex-security findings imported.";
9786
+ const path = quoteCliPath(repository);
9787
+ return `Stored evidence${cliShellLabel(path)}: codex-security findings imported ${path}`;
8831
9788
  }
8832
9789
  async function selectedProjectConfig(file, dependencies) {
8833
9790
  const selected = file ??
@@ -9123,7 +10080,7 @@ const interruptedExitCode = (signal) => signal.reason === "SIGINT"
9123
10080
  ? 143
9124
10081
  : undefined;
9125
10082
  if (invokedAsMain()) {
9126
- void main().then((exitCode) => {
10083
+ void runCli().then((exitCode) => {
9127
10084
  process.exitCode = exitCode;
9128
10085
  }, (error) => {
9129
10086
  process.stderr.write(`codex-security: ${diagnosticLines(error)}\n`);