@openai/codex-security 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (484) hide show
  1. package/README.md +437 -2692
  2. package/_bundled_plugin/.app.json +5 -1
  3. package/_bundled_plugin/.codex-plugin/plugin.json +4 -0
  4. package/_bundled_plugin/.mcp.json +2 -0
  5. package/_bundled_plugin/examples/completed-scan/coverage.json +0 -1
  6. package/_bundled_plugin/examples/completed-scan/report.md +28 -26
  7. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +1 -1
  8. package/_bundled_plugin/mcp/helpers.mjs +1 -0
  9. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  10. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +6 -213
  11. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  12. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  13. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  14. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  15. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  16. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  17. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  18. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  19. package/_bundled_plugin/mcp/permission-profile-preflight.mjs +556 -0
  20. package/_bundled_plugin/mcp/server.mjs +1 -0
  21. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  22. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  23. package/_bundled_plugin/preflight/capability-profiles.toml +0 -13
  24. package/_bundled_plugin/references/artifact-storage.md +2 -2
  25. package/_bundled_plugin/references/config-preflight.md +0 -4
  26. package/_bundled_plugin/references/core-scan.md +21 -9
  27. package/_bundled_plugin/references/final-report.md +11 -13
  28. package/_bundled_plugin/references/finding-detail-fields.md +90 -80
  29. package/_bundled_plugin/references/sarif-adapter.md +1 -1
  30. package/_bundled_plugin/references/scan-artifacts.md +1 -2
  31. package/_bundled_plugin/references/scan-contract.md +9 -4
  32. package/_bundled_plugin/references/scan-prologue.md +12 -0
  33. package/_bundled_plugin/references/security-guidance.md +2 -2
  34. package/_bundled_plugin/references/standalone-validation.md +11 -0
  35. package/_bundled_plugin/references/threat-model.md +1 -1
  36. package/_bundled_plugin/schemas/coverage.schema.json +43 -170
  37. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +2 -24
  38. package/_bundled_plugin/schemas/definitions/discovery-candidate.schema.json +49 -25
  39. package/_bundled_plugin/schemas/findings.schema.json +159 -567
  40. package/_bundled_plugin/schemas/patch-risk-assessment.schema.json +106 -119
  41. package/_bundled_plugin/schemas/scan-manifest.schema.json +78 -220
  42. package/_bundled_plugin/schemas/tools/candidate-attack-paths.schema.json +91 -83
  43. package/_bundled_plugin/schemas/tools/candidate-validations.schema.json +35 -64
  44. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +5 -2
  45. package/_bundled_plugin/schemas/tools/discovery-candidates.schema.json +6 -55
  46. package/_bundled_plugin/schemas/tools/review-items.schema.json +2 -38
  47. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +169 -294
  48. package/_bundled_plugin/scripts/codex_profile.mjs +239 -0
  49. package/_bundled_plugin/scripts/codex_session.mjs +53 -0
  50. package/_bundled_plugin/scripts/config_preflight.py +26 -62
  51. package/_bundled_plugin/scripts/deep_scan_config.py +9 -11
  52. package/_bundled_plugin/scripts/deep_scan_workbench.py +129 -150
  53. package/_bundled_plugin/scripts/finalize_scan_contract.py +321 -237
  54. package/_bundled_plugin/scripts/finding_preview.py +39 -9
  55. package/_bundled_plugin/scripts/generate_in_scope_files.py +27 -77
  56. package/_bundled_plugin/scripts/generate_rank_input.py +115 -926
  57. package/_bundled_plugin/scripts/launch_codex_security_mcp +35 -10
  58. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +5 -5
  59. package/_bundled_plugin/scripts/rank_preview.py +42 -918
  60. package/_bundled_plugin/scripts/report_projection.py +150 -183
  61. package/_bundled_plugin/scripts/snapshot_sqlite.py +6 -1
  62. package/_bundled_plugin/scripts/threat_model_projection.py +4 -7
  63. package/_bundled_plugin/scripts/validate_scan_contract.py +4 -34
  64. package/_bundled_plugin/scripts/validate_tracking_source.py +3 -13
  65. package/_bundled_plugin/scripts/windows_scan_local_files.py +48 -3
  66. package/_bundled_plugin/scripts/workbench/handoff.py +25 -50
  67. package/_bundled_plugin/scripts/workbench/runtime_toml.py +22 -0
  68. package/_bundled_plugin/scripts/workbench/storage.py +10 -6
  69. package/_bundled_plugin/scripts/workbench_cli.py +102 -184
  70. package/_bundled_plugin/scripts/workbench_db.py +463 -464
  71. package/_bundled_plugin/scripts/workbench_feedback.py +6 -3
  72. package/_bundled_plugin/scripts/workbench_finding_index.py +19 -1
  73. package/_bundled_plugin/scripts/workbench_finding_workflows.py +18 -4
  74. package/_bundled_plugin/scripts/workbench_local_dedupe.py +136 -0
  75. package/_bundled_plugin/scripts/workbench_native_indexes.py +27 -14
  76. package/_bundled_plugin/scripts/workbench_progress.py +14 -58
  77. package/_bundled_plugin/scripts/workbench_publication.py +234 -289
  78. package/_bundled_plugin/scripts/workbench_remediation.py +12 -0
  79. package/_bundled_plugin/scripts/workbench_saved_results.py +172 -49
  80. package/_bundled_plugin/scripts/workbench_scan_history.py +57 -57
  81. package/_bundled_plugin/scripts/workbench_scan_start.py +105 -41
  82. package/_bundled_plugin/scripts/workbench_scan_usage.py +194 -42
  83. package/_bundled_plugin/scripts/workbench_schema.py +37 -1151
  84. package/_bundled_plugin/scripts/workbench_source_excerpt.py +11 -1
  85. package/_bundled_plugin/scripts/workbench_target.py +430 -142
  86. package/_bundled_plugin/scripts/workbench_validation.py +31 -28
  87. package/_bundled_plugin/shared/workbench-history-repairs.json +218 -0
  88. package/_bundled_plugin/shared/workbench-migrations.json +414 -0
  89. package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +15 -4
  90. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +1 -0
  91. package/_bundled_plugin/skills/cloud-findings/SKILL.md +54 -0
  92. package/_bundled_plugin/skills/cloud-findings/agents/openai.yaml +4 -0
  93. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +3 -3
  94. package/_bundled_plugin/skills/finding-discovery/SKILL.md +3 -3
  95. package/_bundled_plugin/skills/propose-security-hardening/references/proposal-format.md +50 -20
  96. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +8 -14
  97. package/_bundled_plugin/skills/security-scan/SKILL.md +22 -7
  98. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +2 -2
  99. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +15 -1
  100. package/_bundled_plugin/skills/threat-model/SKILL.md +1 -1
  101. package/_bundled_plugin/skills/track-findings/SKILL.md +48 -176
  102. package/_bundled_plugin/skills/track-findings/references/github-security-advisories.md +16 -24
  103. package/_bundled_plugin/skills/track-findings/references/jira.md +15 -61
  104. package/_bundled_plugin/skills/triage-finding/SKILL.md +50 -289
  105. package/_bundled_plugin/skills/triage-finding/agents/openai.yaml +2 -2
  106. package/_bundled_plugin/skills/triage-finding/references/ticket-intake.md +23 -43
  107. package/_bundled_plugin/skills/triage-finding/references/triage-result-contract.md +7 -1
  108. package/bin/codex-security.mjs +9 -2
  109. package/dist/api.d.ts +63 -10
  110. package/dist/api.d.ts.map +1 -1
  111. package/dist/api.js +1015 -383
  112. package/dist/api.js.map +1 -1
  113. package/dist/artifact-export.d.ts +1 -1
  114. package/dist/artifact-export.d.ts.map +1 -1
  115. package/dist/artifact-export.js +28 -13
  116. package/dist/artifact-export.js.map +1 -1
  117. package/dist/auth.d.ts +2 -6
  118. package/dist/auth.d.ts.map +1 -1
  119. package/dist/auth.js +19 -9
  120. package/dist/auth.js.map +1 -1
  121. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  122. package/dist/bulk-scan-discovery.js +1 -0
  123. package/dist/bulk-scan-discovery.js.map +1 -1
  124. package/dist/classify-severity.d.ts +26 -9
  125. package/dist/classify-severity.d.ts.map +1 -1
  126. package/dist/classify-severity.js +13 -30
  127. package/dist/classify-severity.js.map +1 -1
  128. package/dist/cli-help.d.ts.map +1 -1
  129. package/dist/cli-help.js +17 -13
  130. package/dist/cli-help.js.map +1 -1
  131. package/dist/cli-signals.d.ts +8 -0
  132. package/dist/cli-signals.d.ts.map +1 -0
  133. package/dist/cli-signals.js +28 -0
  134. package/dist/cli-signals.js.map +1 -0
  135. package/dist/cli.d.ts +4 -3
  136. package/dist/cli.d.ts.map +1 -1
  137. package/dist/cli.js +1102 -905
  138. package/dist/cli.js.map +1 -1
  139. package/dist/cloud-publish.d.ts.map +1 -1
  140. package/dist/cloud-publish.js +10 -9
  141. package/dist/cloud-publish.js.map +1 -1
  142. package/dist/codeowners.d.ts +19 -0
  143. package/dist/codeowners.d.ts.map +1 -0
  144. package/dist/codeowners.js +138 -0
  145. package/dist/codeowners.js.map +1 -0
  146. package/dist/codex-sdk-environment.d.ts +1 -0
  147. package/dist/codex-sdk-environment.d.ts.map +1 -1
  148. package/dist/codex-sdk-environment.js +40 -2
  149. package/dist/codex-sdk-environment.js.map +1 -1
  150. package/dist/component-plan.d.ts +2 -5
  151. package/dist/component-plan.d.ts.map +1 -1
  152. package/dist/component-plan.js +39 -31
  153. package/dist/component-plan.js.map +1 -1
  154. package/dist/component-scan.d.ts +6 -5
  155. package/dist/component-scan.d.ts.map +1 -1
  156. package/dist/component-scan.js +25 -36
  157. package/dist/component-scan.js.map +1 -1
  158. package/dist/config.d.ts.map +1 -1
  159. package/dist/config.js +64 -74
  160. package/dist/config.js.map +1 -1
  161. package/dist/contract.d.ts +16 -3
  162. package/dist/contract.d.ts.map +1 -1
  163. package/dist/contract.js +91 -255
  164. package/dist/contract.js.map +1 -1
  165. package/dist/cost-model.d.ts +13 -6
  166. package/dist/cost-model.d.ts.map +1 -1
  167. package/dist/cost-model.js +14 -4
  168. package/dist/cost-model.js.map +1 -1
  169. package/dist/cost.d.ts +10 -2
  170. package/dist/cost.d.ts.map +1 -1
  171. package/dist/cost.js +102 -104
  172. package/dist/cost.js.map +1 -1
  173. package/dist/custom-validation-prompt.d.ts.map +1 -1
  174. package/dist/custom-validation-prompt.js +6 -5
  175. package/dist/custom-validation-prompt.js.map +1 -1
  176. package/dist/custom-validation.d.ts +1 -2
  177. package/dist/custom-validation.d.ts.map +1 -1
  178. package/dist/custom-validation.js +9 -3
  179. package/dist/custom-validation.js.map +1 -1
  180. package/dist/deduplication/checkpointed-review.d.ts +4 -2
  181. package/dist/deduplication/checkpointed-review.d.ts.map +1 -1
  182. package/dist/deduplication/checkpointed-review.js +23 -9
  183. package/dist/deduplication/checkpointed-review.js.map +1 -1
  184. package/dist/deduplication/codex-review.d.ts +8 -6
  185. package/dist/deduplication/codex-review.d.ts.map +1 -1
  186. package/dist/deduplication/codex-review.js +128 -19
  187. package/dist/deduplication/codex-review.js.map +1 -1
  188. package/dist/deduplication/deduplication-prompts.d.ts +5 -2
  189. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
  190. package/dist/deduplication/deduplication-prompts.js +18 -4
  191. package/dist/deduplication/deduplication-prompts.js.map +1 -1
  192. package/dist/deduplication/deduplication-reviewer.d.ts +27 -5
  193. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
  194. package/dist/deduplication/deduplication-reviewer.js +58 -48
  195. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  196. package/dist/deduplication/deduplication.d.ts.map +1 -1
  197. package/dist/deduplication/deduplication.js +19 -51
  198. package/dist/deduplication/deduplication.js.map +1 -1
  199. package/dist/deduplication/diagnostics.d.ts +17 -0
  200. package/dist/deduplication/diagnostics.d.ts.map +1 -0
  201. package/dist/deduplication/diagnostics.js +5 -0
  202. package/dist/deduplication/diagnostics.js.map +1 -0
  203. package/dist/deduplication/finding-schema.d.ts.map +1 -1
  204. package/dist/deduplication/finding-schema.js +7 -1
  205. package/dist/deduplication/finding-schema.js.map +1 -1
  206. package/dist/deduplication/local.d.ts +31 -0
  207. package/dist/deduplication/local.d.ts.map +1 -0
  208. package/dist/deduplication/local.js +166 -0
  209. package/dist/deduplication/local.js.map +1 -0
  210. package/dist/deduplication/records-protocol.d.ts +3 -8
  211. package/dist/deduplication/records-protocol.d.ts.map +1 -1
  212. package/dist/deduplication/records-protocol.js +11 -184
  213. package/dist/deduplication/records-protocol.js.map +1 -1
  214. package/dist/deduplication/records.d.ts +186 -11
  215. package/dist/deduplication/records.d.ts.map +1 -1
  216. package/dist/deduplication/records.js +10 -18
  217. package/dist/deduplication/records.js.map +1 -1
  218. package/dist/deduplication/scan.d.ts +9 -3
  219. package/dist/deduplication/scan.d.ts.map +1 -1
  220. package/dist/deduplication/scan.js +158 -39
  221. package/dist/deduplication/scan.js.map +1 -1
  222. package/dist/deep-config.d.ts +2 -1
  223. package/dist/deep-config.d.ts.map +1 -1
  224. package/dist/deep-config.js +4 -4
  225. package/dist/deep-config.js.map +1 -1
  226. package/dist/deep-progress.d.ts +17 -1
  227. package/dist/deep-progress.d.ts.map +1 -1
  228. package/dist/deep-progress.js +19 -17
  229. package/dist/deep-progress.js.map +1 -1
  230. package/dist/deep-scan.d.ts +20 -0
  231. package/dist/deep-scan.d.ts.map +1 -0
  232. package/dist/deep-scan.js +113 -0
  233. package/dist/deep-scan.js.map +1 -0
  234. package/dist/errors.d.ts +2 -0
  235. package/dist/errors.d.ts.map +1 -1
  236. package/dist/errors.js +2 -0
  237. package/dist/errors.js.map +1 -1
  238. package/dist/executable-path.d.ts +2 -0
  239. package/dist/executable-path.d.ts.map +1 -0
  240. package/dist/executable-path.js +12 -0
  241. package/dist/executable-path.js.map +1 -0
  242. package/dist/feedback.d.ts +1 -4
  243. package/dist/feedback.d.ts.map +1 -1
  244. package/dist/feedback.js +54 -22
  245. package/dist/feedback.js.map +1 -1
  246. package/dist/finding-catalogue.d.ts.map +1 -1
  247. package/dist/finding-catalogue.js +4 -8
  248. package/dist/finding-catalogue.js.map +1 -1
  249. package/dist/finding-normalization.d.ts +5 -0
  250. package/dist/finding-normalization.d.ts.map +1 -0
  251. package/dist/finding-normalization.js +120 -0
  252. package/dist/finding-normalization.js.map +1 -0
  253. package/dist/finding-retrieval.d.ts +9 -0
  254. package/dist/finding-retrieval.d.ts.map +1 -1
  255. package/dist/finding-retrieval.js.map +1 -1
  256. package/dist/finding-workflow.d.ts +13 -8
  257. package/dist/finding-workflow.d.ts.map +1 -1
  258. package/dist/finding-workflow.js +14 -6
  259. package/dist/finding-workflow.js.map +1 -1
  260. package/dist/findings-client.d.ts +2 -1
  261. package/dist/findings-client.d.ts.map +1 -1
  262. package/dist/findings-client.js +36 -9
  263. package/dist/findings-client.js.map +1 -1
  264. package/dist/findings-errors.d.ts +16 -0
  265. package/dist/findings-errors.d.ts.map +1 -0
  266. package/dist/findings-errors.js +24 -0
  267. package/dist/findings-errors.js.map +1 -0
  268. package/dist/findings-import.d.ts +1 -1
  269. package/dist/findings-import.d.ts.map +1 -1
  270. package/dist/findings-import.js +12 -30
  271. package/dist/findings-import.js.map +1 -1
  272. package/dist/github.d.ts.map +1 -1
  273. package/dist/github.js +7 -1
  274. package/dist/github.js.map +1 -1
  275. package/dist/host-protocol.d.ts +19 -0
  276. package/dist/host-protocol.d.ts.map +1 -0
  277. package/dist/host-protocol.js +270 -0
  278. package/dist/host-protocol.js.map +1 -0
  279. package/dist/hosted-scan-protocol.d.ts +4 -0
  280. package/dist/hosted-scan-protocol.d.ts.map +1 -0
  281. package/dist/hosted-scan-protocol.js +25 -0
  282. package/dist/hosted-scan-protocol.js.map +1 -0
  283. package/dist/hosted-scan.d.ts +117 -0
  284. package/dist/hosted-scan.d.ts.map +1 -0
  285. package/dist/hosted-scan.js +260 -0
  286. package/dist/hosted-scan.js.map +1 -0
  287. package/dist/import-scan.d.ts.map +1 -1
  288. package/dist/import-scan.js +48 -38
  289. package/dist/import-scan.js.map +1 -1
  290. package/dist/index.d.ts +11 -4
  291. package/dist/index.d.ts.map +1 -1
  292. package/dist/index.js +2 -1
  293. package/dist/index.js.map +1 -1
  294. package/dist/knowledge-base.d.ts +7 -1
  295. package/dist/knowledge-base.d.ts.map +1 -1
  296. package/dist/knowledge-base.js +114 -46
  297. package/dist/knowledge-base.js.map +1 -1
  298. package/dist/linear.d.ts.map +1 -1
  299. package/dist/linear.js +2 -7
  300. package/dist/linear.js.map +1 -1
  301. package/dist/mock-scan.d.ts.map +1 -1
  302. package/dist/mock-scan.js +0 -1
  303. package/dist/mock-scan.js.map +1 -1
  304. package/dist/models.d.ts +0 -2
  305. package/dist/models.d.ts.map +1 -1
  306. package/dist/models.js.map +1 -1
  307. package/dist/multiscan.d.ts +9 -3
  308. package/dist/multiscan.d.ts.map +1 -1
  309. package/dist/multiscan.js +240 -135
  310. package/dist/multiscan.js.map +1 -1
  311. package/dist/owner-evidence.d.ts +10 -2
  312. package/dist/owner-evidence.d.ts.map +1 -1
  313. package/dist/owner-evidence.js +67 -8
  314. package/dist/owner-evidence.js.map +1 -1
  315. package/dist/patch-tui.d.ts.map +1 -1
  316. package/dist/patch-tui.js +3 -2
  317. package/dist/patch-tui.js.map +1 -1
  318. package/dist/project-config.js +3 -3
  319. package/dist/project-config.js.map +1 -1
  320. package/dist/provider-profile.d.ts +21 -0
  321. package/dist/provider-profile.d.ts.map +1 -0
  322. package/dist/provider-profile.js +133 -0
  323. package/dist/provider-profile.js.map +1 -0
  324. package/dist/publication-events.d.ts +6 -8
  325. package/dist/publication-events.d.ts.map +1 -1
  326. package/dist/publication-events.js +25 -50
  327. package/dist/publication-events.js.map +1 -1
  328. package/dist/publication-store.d.ts.map +1 -1
  329. package/dist/publication-store.js +95 -109
  330. package/dist/publication-store.js.map +1 -1
  331. package/dist/publication.d.ts +1 -4
  332. package/dist/publication.d.ts.map +1 -1
  333. package/dist/publication.js +2 -13
  334. package/dist/publication.js.map +1 -1
  335. package/dist/publish.d.ts +1 -5
  336. package/dist/publish.d.ts.map +1 -1
  337. package/dist/publish.js +109 -160
  338. package/dist/publish.js.map +1 -1
  339. package/dist/request-metadata.d.ts +9 -0
  340. package/dist/request-metadata.d.ts.map +1 -0
  341. package/dist/request-metadata.js +13 -0
  342. package/dist/request-metadata.js.map +1 -0
  343. package/dist/runtime.d.ts +20 -6
  344. package/dist/runtime.d.ts.map +1 -1
  345. package/dist/runtime.js +407 -148
  346. package/dist/runtime.js.map +1 -1
  347. package/dist/saved-scan-bootstrap.d.ts +14 -0
  348. package/dist/saved-scan-bootstrap.d.ts.map +1 -0
  349. package/dist/saved-scan-bootstrap.js +261 -0
  350. package/dist/saved-scan-bootstrap.js.map +1 -0
  351. package/dist/saved-scan.d.ts +1 -1
  352. package/dist/saved-scan.d.ts.map +1 -1
  353. package/dist/saved-scan.js +6 -12
  354. package/dist/saved-scan.js.map +1 -1
  355. package/dist/scan-activity.js +11 -8
  356. package/dist/scan-activity.js.map +1 -1
  357. package/dist/scan-comparison.d.ts +28 -15
  358. package/dist/scan-comparison.d.ts.map +1 -1
  359. package/dist/scan-comparison.js +276 -281
  360. package/dist/scan-comparison.js.map +1 -1
  361. package/dist/scan-dashboard.d.ts +3 -0
  362. package/dist/scan-dashboard.d.ts.map +1 -1
  363. package/dist/scan-dashboard.js +345 -77
  364. package/dist/scan-dashboard.js.map +1 -1
  365. package/dist/scan-executor.d.ts +104 -0
  366. package/dist/scan-executor.d.ts.map +1 -0
  367. package/dist/scan-executor.js +62 -0
  368. package/dist/scan-executor.js.map +1 -0
  369. package/dist/scan-history-renderer.d.ts.map +1 -1
  370. package/dist/scan-history-renderer.js +54 -13
  371. package/dist/scan-history-renderer.js.map +1 -1
  372. package/dist/scan-inputs.d.ts +6 -0
  373. package/dist/scan-inputs.d.ts.map +1 -0
  374. package/dist/scan-inputs.js +71 -0
  375. package/dist/scan-inputs.js.map +1 -0
  376. package/dist/scan-logs.d.ts +2 -3
  377. package/dist/scan-logs.d.ts.map +1 -1
  378. package/dist/scan-logs.js +12 -6
  379. package/dist/scan-logs.js.map +1 -1
  380. package/dist/scan-sessions.d.ts +4 -0
  381. package/dist/scan-sessions.d.ts.map +1 -1
  382. package/dist/scan-sessions.js +17 -0
  383. package/dist/scan-sessions.js.map +1 -1
  384. package/dist/scan-skill-paths.d.ts +8 -0
  385. package/dist/scan-skill-paths.d.ts.map +1 -0
  386. package/dist/scan-skill-paths.js +47 -0
  387. package/dist/scan-skill-paths.js.map +1 -0
  388. package/dist/security-policy-cli.d.ts.map +1 -1
  389. package/dist/security-policy-cli.js +7 -27
  390. package/dist/security-policy-cli.js.map +1 -1
  391. package/dist/security-policy.d.ts +9 -5
  392. package/dist/security-policy.d.ts.map +1 -1
  393. package/dist/security-policy.js +33 -14
  394. package/dist/security-policy.js.map +1 -1
  395. package/dist/server/api.d.ts +0 -1
  396. package/dist/server/api.d.ts.map +1 -1
  397. package/dist/server/api.js +0 -1
  398. package/dist/server/api.js.map +1 -1
  399. package/dist/server/embeddings.d.ts +3 -1
  400. package/dist/server/embeddings.d.ts.map +1 -1
  401. package/dist/server/embeddings.js +10 -3
  402. package/dist/server/embeddings.js.map +1 -1
  403. package/dist/server/errors.d.ts +5 -2
  404. package/dist/server/errors.d.ts.map +1 -1
  405. package/dist/server/errors.js +7 -0
  406. package/dist/server/errors.js.map +1 -1
  407. package/dist/server/sqlite-store.d.ts +0 -2
  408. package/dist/server/sqlite-store.d.ts.map +1 -1
  409. package/dist/server/sqlite-store.js +54 -44
  410. package/dist/server/sqlite-store.js.map +1 -1
  411. package/dist/server/storage.d.ts +0 -2
  412. package/dist/server/storage.d.ts.map +1 -1
  413. package/dist/server/storage.js.map +1 -1
  414. package/dist/severity-store.js +19 -24
  415. package/dist/severity-store.js.map +1 -1
  416. package/dist/standalone-validation-prompt.d.ts +2 -0
  417. package/dist/standalone-validation-prompt.d.ts.map +1 -0
  418. package/dist/standalone-validation-prompt.js +10 -0
  419. package/dist/standalone-validation-prompt.js.map +1 -0
  420. package/dist/suggest-owners.d.ts +4 -2
  421. package/dist/suggest-owners.d.ts.map +1 -1
  422. package/dist/suggest-owners.js +11 -5
  423. package/dist/suggest-owners.js.map +1 -1
  424. package/dist/targets.d.ts +11 -0
  425. package/dist/targets.d.ts.map +1 -1
  426. package/dist/targets.js +123 -72
  427. package/dist/targets.js.map +1 -1
  428. package/dist/trusted-executable.d.ts +2 -2
  429. package/dist/trusted-executable.d.ts.map +1 -1
  430. package/dist/trusted-executable.js +8 -6
  431. package/dist/trusted-executable.js.map +1 -1
  432. package/dist/value.js +7 -0
  433. package/dist/value.js.map +1 -1
  434. package/dist/version.js.map +1 -1
  435. package/dist/workbench-arguments.d.ts +3 -0
  436. package/dist/workbench-arguments.d.ts.map +1 -0
  437. package/dist/workbench-arguments.js +15 -0
  438. package/dist/workbench-arguments.js.map +1 -0
  439. package/dist/worker-progress.d.ts +44 -11
  440. package/dist/worker-progress.d.ts.map +1 -1
  441. package/dist/worker-progress.js +48 -49
  442. package/dist/worker-progress.js.map +1 -1
  443. package/docs/cli.md +1788 -0
  444. package/docs/findings-service.md +402 -0
  445. package/docs/hosted-scans.md +242 -0
  446. package/package.json +23 -22
  447. package/schemas/hosted-scan-v2.fixture.json +145 -0
  448. package/_bundled_plugin/schemas/tools/worker-threat-model.schema.json +0 -18
  449. package/_bundled_plugin/scripts/workbench_dashboard.py +0 -159
  450. package/_bundled_plugin/scripts/workbench_findings.py +0 -221
  451. package/_bundled_plugin/scripts/workbench_severity.py +0 -122
  452. package/_bundled_plugin/skills/assess-patch-risk/scripts/validate_patch_risk_assessment.py +0 -163
  453. package/dist/server/dashboard/THIRD_PARTY_NOTICES.txt +0 -276
  454. package/dist/server/dashboard/app.css +0 -2
  455. package/dist/server/dashboard/app.js +0 -66
  456. package/dist/server/dashboard/index.html +0 -18
  457. package/dist/server/dashboard-types.d.ts +0 -48
  458. package/dist/server/dashboard-types.d.ts.map +0 -1
  459. package/dist/server/dashboard-types.js +0 -2
  460. package/dist/server/dashboard-types.js.map +0 -1
  461. package/dist/server/dashboard.d.ts +0 -6
  462. package/dist/server/dashboard.d.ts.map +0 -1
  463. package/dist/server/dashboard.js +0 -59
  464. package/dist/server/dashboard.js.map +0 -1
  465. package/dist/server/index.d.ts +0 -2
  466. package/dist/server/index.d.ts.map +0 -1
  467. package/dist/server/index.js +0 -6
  468. package/dist/server/index.js.map +0 -1
  469. package/dist/server/routes.d.ts +0 -7
  470. package/dist/server/routes.d.ts.map +0 -1
  471. package/dist/server/routes.js +0 -98
  472. package/dist/server/routes.js.map +0 -1
  473. package/dist/server/serve.d.ts +0 -2
  474. package/dist/server/serve.d.ts.map +0 -1
  475. package/dist/server/serve.js +0 -28
  476. package/dist/server/serve.js.map +0 -1
  477. package/dist/server/server.d.ts +0 -10
  478. package/dist/server/server.d.ts.map +0 -1
  479. package/dist/server/server.js +0 -16
  480. package/dist/server/server.js.map +0 -1
  481. package/dist/server/validation.d.ts +0 -17
  482. package/dist/server/validation.d.ts.map +0 -1
  483. package/dist/server/validation.js +0 -53
  484. package/dist/server/validation.js.map +0 -1
package/README.md CHANGED
@@ -1,2898 +1,643 @@
1
1
  # `@openai/codex-security`
2
2
 
3
- Run Codex Security scans from TypeScript or the command line. This ESM-only
4
- package includes TypeScript declarations and the Codex runtime.
3
+ Run Codex Security from TypeScript or the command line to find, validate, and fix
4
+ security vulnerabilities in your code. The package includes the Codex runtime,
5
+ security plugin, and TypeScript declarations. It uses ES modules.
6
+
7
+ - Scan repositories, selected paths, or Git changes. Deep scans run parallel
8
+ discovery workers on repositories and selected paths.
9
+ - Validate findings, generate patches, and verify existing fixes.
10
+ - Draft security policies and retain threat models.
11
+ - Review saved findings, identify duplicates, classify severity, and suggest owners.
12
+ - Import GitHub code scanning alerts, export SARIF, JSON, or CSV, and publish
13
+ findings to Linear or a findings service.
14
+ - Automate scans across repositories and project components.
15
+
16
+ See the [CLI reference](docs/cli.md),
17
+ [findings guide](docs/findings-service.md), or
18
+ [online documentation](https://learn.chatgpt.com/docs/security) for setup and examples.
5
19
 
6
20
  Before version `1.0.0`, minor releases may change the public API.
7
21
 
8
22
  ## Install
9
23
 
10
- ```bash
11
- npm install @openai/codex-security
12
- npx @openai/codex-security --version
13
- ```
14
-
15
- Use Node.js 22.13.0+ (22.x), 24.x, or 26.x on macOS, Linux, or Windows.
16
- Policy drafting, scans, exports, scan history, and saved findings also need Python 3.10+
17
- (plus `tomli` on Python 3.10).
18
-
19
- ## Run a scan from TypeScript
20
-
21
- Sign in with `npx @openai/codex-security login` or set `OPENAI_API_KEY` or
22
- `CODEX_API_KEY`, then scan a repository you own or have permission to assess:
23
-
24
- ```ts
25
- import { CodexSecurity } from "@openai/codex-security";
26
-
27
- const security = new CodexSecurity();
28
-
29
- try {
30
- const result = await security.run("/path/to/repository", {
31
- outputDir: "/path/outside/repository/results",
32
- });
33
-
34
- console.log(result.reportPath);
35
- console.log(result.findings.findings.length);
36
- } finally {
37
- await security.close();
38
- }
39
- ```
24
+ Supported runtimes:
40
25
 
41
- `result.findings` contains this scan's findings; `repositoryFindings` also
42
- includes earlier open findings when available. Matching earlier findings can
43
- make extra model calls; see [Progress and cost](#progress-and-cost).
26
+ - Node.js 22.13.0+ within 22.x, or Node.js 24.x or 26.x, on macOS, Linux, or Windows.
27
+ - Python 3.10+ for scans, policy generation, exports, scan history, and saved
28
+ findings. Python 3.10 also needs `tomli`.
44
29
 
45
- Keep results outside the repository and restrict access: reports can contain
46
- source code, vulnerability details, and reproduction steps.
30
+ Reading compressed Codex session logs (`.jsonl.zst`) requires Node.js 22.15.0+
31
+ within 22.x, or Node.js 24.x or 26.x. On Node.js 22.13–22.14, compressed sessions
32
+ are unavailable when reading saved activity or attaching scan logs to feedback, and
33
+ scans whose original session is compressed cannot resume. Plain `.jsonl` logs
34
+ work on all supported runtimes.
47
35
 
48
- ### Select a Cyber access program
49
-
50
- For the built-in OpenAI provider, select `standard`, `daybreak_blue`, or
51
- `daybreak_red` per scan:
52
-
53
- ```ts
54
- await security.run("/path/to/repository", {
55
- auth: "api-key",
56
- cyberAccessProgram: "daybreak_blue",
57
- });
58
- ```
59
-
60
- ```sh
61
- codex-security scan . --auth api-key --cyber-access-program daybreak_blue
62
- ```
36
+ `LocalPluginBootstrapError` identifies local plugin setup failures and extends
37
+ `PluginBootstrapError`, so existing catches keep working. Knowledge-base
38
+ preparation errors use `ConfigurationError`; wrapped diagnostics remain in `cause`.
63
39
 
64
- `scan-components` accepts the same flag. Project files use
65
- `scan.cyber_access_program`, including for bulk scans. An explicit CLI or SDK
66
- selection overrides the project setting. Omission preserves Codex defaults;
67
- `standard` explicitly selects the standard program.
40
+ ### Install the CLI
68
41
 
69
- The selection applies to Deep Scan discovery and reducer workers, resumed
70
- workers, custom validation, and post-scan turns. Saved scan recipes retain it
71
- for resume and rerun. Automatic component planning and finding matching also
72
- use the selected program. API-key selection enables Codex's experimental Cyber
73
- support unless the effective native configuration explicitly disables
74
- `features.api_key_cyber_access_programs`.
75
- Explicit disables and API entitlement failures remain errors. Selecting a
76
- program does not grant access; the API verifies the key's entitlement.
42
+ Install the CLI globally:
77
43
 
78
- ### Validate an existing finding
79
-
80
- ```ts
81
- const security = new CodexSecurity();
82
- try {
83
- const result = await security.validate({
84
- repositoryPath: "/path/to/repository",
85
- finding: {
86
- title: "Possible SQL injection",
87
- location: "src/query.ts:42",
88
- },
89
- outputDir: "/path/outside/repository/validation",
90
- });
91
- console.log(result.disposition);
92
- console.log(result.report);
93
- } finally {
94
- await security.close();
95
- }
96
- ```
97
-
98
- Pass literal text or a JSON-serializable object as `finding`, not a file path.
99
- Validation uses the client's settings and credentials without changing
100
- repository files or adding a scan to history.
101
-
102
- To disable Codex usage analytics and built-in metrics, create the client with
103
- `new CodexSecurity({ codexOverrides: { analytics: { enabled: false } } })`.
104
- This setting also applies to scans run by the same client.
105
-
106
- Results include `disposition` (`reportable`, `suppressed`, `not_applicable`,
107
- or `deferred`), a Markdown `report`, `threadId`, and evidence `outputDir`.
108
- `reportable` may rely on static analysis; `deferred` means insufficient evidence.
109
- Failed, incomplete, or malformed responses reject the promise.
110
-
111
- `outputDir` must be empty and outside the Git worktree; it defaults to
112
- `validations/` under the state directory. Pass `auth` to select credentials
113
- or `signal` to cancel.
114
-
115
- ### Import GitHub code scanning alerts
116
-
117
- Import alerts, including third-party SARIF uploads, and validate them against
118
- the matching local checkout:
119
-
120
- ```ts
121
- import {
122
- CodexSecurity,
123
- importGitHubCodeScanningAlerts,
124
- } from "@openai/codex-security";
125
-
126
- const findings = await importGitHubCodeScanningAlerts({
127
- repository: "example/repository",
128
- alertNumbers: [12, 18], // Omit to list all open alerts on the default branch.
129
- githubToken: process.env["GH_TOKEN"],
130
- });
131
-
132
- const security = new CodexSecurity();
133
- try {
134
- for (const finding of findings) {
135
- const result = await security.validate({
136
- repositoryPath: "/path/to/repository",
137
- finding,
138
- });
139
- console.log(finding.url, result.disposition, result.outputDir);
140
- }
141
- } finally {
142
- await security.close();
143
- }
44
+ ```bash
45
+ npm install --global @openai/codex-security
46
+ cs --version
144
47
  ```
145
48
 
146
- Each result contains `source`, `repository`, `number`, `url`, and the full
147
- upstream `alert`. Import is read-only and does not start Codex or check out code.
148
-
149
- Without `alertNumbers`, `state` filters alerts and defaults to `"open"`.
150
- It also accepts `"closed"`, `"dismissed"`, `"fixed"`, and `"all"`. Exact alert
151
- numbers ignore state and reject a nondefault `state`. Use `ref` for another
152
- branch or pull-request reference.
153
-
154
- Supply `githubToken` or use your `gh auth token` credentials, including GitHub
155
- CLI token environment variables. `githubHost` defaults to `GH_HOST` or
156
- `github.com`. The token needs read access to code scanning alerts; access
157
- failures reject the import. Pass `signal` to cancel.
158
-
159
- ### SDK configuration and scan options
160
-
161
- Constructor options:
162
-
163
- | Option | Description |
164
- | ---------------- | ----------------------------------------------------------------------- |
165
- | `pluginPath` | Plugin directory or ZIP; defaults to the bundled plugin. |
166
- | `pythonPath` | Python interpreter; overrides `PYTHON`. |
167
- | `codexOverrides` | Supported settings to deep-merge into the isolated Codex configuration. |
168
-
169
- Options for `security.run(repository, options)` and
170
- `security.preflight(repository, options)`:
171
-
172
- | Option | Description |
173
- | ------------------------------------------- | ----------------------------------------------------------------------------------- |
174
- | `auth` | Credential source: `"auto"`, `"chatgpt"`, or `"api-key"`. |
175
- | `safetyIdentifier` | Stable hashed end-user ID for model requests; requires API-key authentication. |
176
- | `target` | Repository, repository-relative paths, committed diff, or working-tree diff. |
177
- | `mode` | `"standard"` or `"deep"`; deep mode supports repositories and paths. |
178
- | `knowledgeBasePaths` | Architecture documents, security policies, threat models, or directories. |
179
- | `scanPrompt` / `scanPromptFile` | Additional scan instructions as text or a local file. |
180
- | `validationPrompt` / `validationPromptFile` | Custom validation instructions as text or a local file; not Deep. |
181
- | `postScanPrompt` / `postScanPromptFile` | Follow-up instructions as text or a local file. |
182
- | `outputDir` | Artifact directory outside the enclosing Git worktree. |
183
- | `archiveExisting` | Archive existing results in `outputDir` before scanning. |
184
- | `maxCostUsd` | Stop when estimated model cost exceeds this positive USD amount. |
185
- | `stopAfterConsecutiveErrors` | Stop deep discovery after this many consecutive errors (default: 3). |
186
- | `maxTimeHours` | Deep-scan discovery limit in hours: greater than zero, up to 96. |
187
- | `failureSeverity` | Severity threshold recorded in the recipe; the SDK caller decides how to handle it. |
188
- | `parentScanId` | Parent scan ID for a rerun. |
189
- | `expectedPluginVersion` | Required original plugin version when replaying a scan. |
190
- | `signal` | `AbortSignal` to cancel a scan. |
191
-
192
- Follow scans with `onWorkerStatus` and `onReconnect`. `onSessionEvent` receives
193
- saved events with thread IDs and worker numbers. Deep scans can additionally use
194
- `onDeepProgress` for durable independent-review counts: `completed`, `active`,
195
- and `maximum`. The maximum is a configured cap, not a percentage denominator.
196
- `ScanOptions` lists all callbacks.
49
+ `cs` is a short alias for `codex-security`; both commands run the same CLI.
50
+ The installation creates both commands in npm's global executable directory,
51
+ which must be on your `PATH`. If `cs` already resolves to another tool, use
52
+ `codex-security` instead. If npm stops with an `EEXIST` error for `cs`, use
53
+ `npx @openai/codex-security` without a global installation.
197
54
 
198
- `preflight` and CLI `--dry-run` check local inputs without starting Codex or
199
- using the network. They don't authenticate, verify model access, resolve Python,
200
- inspect the plugin, or run scan-lifecycle callbacks. Dry runs print effective settings.
201
- Deep preflight includes all six resolved deep settings and their origins in
202
- `deepScanSources`. Applicable legacy deep configuration is validated during
203
- preflight rather than after runtime startup.
55
+ Continue with the [CLI walkthrough](#cli). To run without a global installation,
56
+ replace `cs` in the CLI examples with `npx @openai/codex-security`.
204
57
 
205
- `ScanSettings` is the shared settings type. `ScanOptions` adds callbacks,
206
- cancellation, workflow, and runtime controls. Load the same project file used by
207
- `scan -c` through the SDK:
58
+ ### Install the TypeScript SDK
208
59
 
209
- ```ts
210
- import { CodexSecurity, loadProjectConfig } from "@openai/codex-security";
60
+ Install the package locally in your TypeScript project:
211
61
 
212
- const { config, options } = await loadProjectConfig("codex-security.yaml");
213
- await using security = new CodexSecurity(config);
214
- const result = await security.run(repository, options);
215
- if (
216
- options.failureSeverity !== undefined &&
217
- result.hasFindingsAtOrAbove(options.failureSeverity)
218
- ) {
219
- process.exitCode = 1;
220
- }
62
+ ```bash
63
+ npm install @openai/codex-security
221
64
  ```
222
65
 
223
- `resolveProjectConfig(input, directory?)` accepts a typed `ProjectConfigInput`
224
- object with the same `snake_case` keys as YAML/JSON and returns the same `{ config,
225
- options }` pair and an immutable `sources` map. Resolved context, prompt, and output
226
- paths have the `AbsolutePath` type. `loadProjectConfig(file, directory?)` resolves the selected file
227
- from `directory`, which defaults to the current directory; paths inside the file
228
- are relative to that file. Object paths are relative to the supplied directory.
229
- Scope paths remain relative to the selected repository. Neither helper starts a
230
- scan, reads prompt contents, or discovers another configuration file. `preflight`
231
- and `run` apply the existing local checks and remaining legacy deep defaults.
232
- Project-file keys follow Codex's configuration convention; SDK options keep their
233
- existing `camelCase` names, and CLI flags keep `kebab-case`.
234
-
235
- Override resolved SDK options with `{ ...options, maxCostUsd: 5 }`, or add
236
- callbacks there. Direct SDK prompt-file paths use the current directory; inline
237
- text takes precedence over its matching file. Files use the same regular-file
238
- protections as the CLI. The SDK records `failureSeverity` without throwing or
239
- changing process status. `hasFindingsAtOrAbove()` uses the CLI's severity ordering
240
- and leaves the findings unchanged.
241
-
242
66
  ## Authentication
243
67
 
244
68
  Sign in with ChatGPT:
245
69
 
246
70
  ```bash
247
- npx @openai/codex-security login
248
- npx @openai/codex-security scan .
71
+ cs login
249
72
  ```
250
73
 
251
- On remote or headless machines, use device auth if your workspace allows it:
74
+ If you installed only the SDK locally, sign in from your project directory:
252
75
 
253
76
  ```bash
254
- npx @openai/codex-security login --device-auth
77
+ npx @openai/codex-security login
255
78
  ```
256
79
 
257
- If device auth is disabled, [sign in over SSH](#remote-login-with-ssh-forwarding).
80
+ In the following CLI examples, replace `cs` with `npx @openai/codex-security`
81
+ when using a local SDK installation, including the API-key login example below.
258
82
 
259
- For CI, set `OPENAI_API_KEY` or `CODEX_API_KEY`. To save a key, pass it on stdin:
83
+ For CI, set `OPENAI_API_KEY` or `CODEX_API_KEY` in the scan process's environment.
84
+ These keys apply to the current command without replacing your saved login.
85
+ To save an API key instead, pass it on stdin:
260
86
 
261
87
  ```bash
262
- printenv OPENAI_API_KEY | npx @openai/codex-security login --with-api-key
88
+ printenv OPENAI_API_KEY | cs login --with-api-key
263
89
  ```
264
90
 
265
- Environment API keys apply to the current command; only `login --with-api-key`
266
- saves them. Pass Codex access tokens on stdin to `login --with-access-token`.
267
- Access-token environment variables are not scan API keys.
91
+ SDK calls accept `auth: "auto" | "chatgpt" | "api-key"`. The default, `"auto"`,
92
+ prefers `OPENAI_API_KEY`, then `CODEX_API_KEY`, then stored credentials.
93
+ Use `"chatgpt"` to ignore environment API keys. The CLI uses the same `--auth`
94
+ values and prompts in an interactive terminal when both credential types are available.
268
95
 
269
- ### Remote login with SSH forwarding
96
+ Some cybersecurity requests and protected findings require
97
+ [Trusted Access for Cyber](https://chatgpt.com/cyber) approval. See the
98
+ [authentication reference](docs/cli.md#authentication) for providers, stored
99
+ credentials, and Cyber access program selection.
270
100
 
271
- Use an SSH tunnel when device auth is disabled.
101
+ ### Remote login with SSH forwarding
272
102
 
273
- On your local machine, replace `user@remote-host` with your SSH address and run:
103
+ On a remote or headless machine, try `login --device-auth` if your workspace
104
+ allows it. Otherwise, open an SSH tunnel from your local machine:
274
105
 
275
106
  ```bash
276
107
  ssh -L 1455:localhost:1455 user@remote-host
277
108
  ```
278
109
 
279
- Run login in that SSH session:
280
-
281
- ```bash
282
- npx @openai/codex-security login
283
- ```
284
-
285
- Open the sign-in URL in your local browser. Keep SSH connected until login finishes.
286
-
287
- See the [authentication guide](https://learn.chatgpt.com/docs/auth?surface=cli#cli-fallback-forward-the-localhost-callback-over-ssh).
288
-
289
- ### Native command authentication and other providers
290
-
291
- SDK callers can select native command authentication through
292
- `codexOverrides.model_providers.<id>.auth` and `model_provider` (including a
293
- selected `profile`). Scans, comparisons, and deduplication reviews preserve
294
- that selection without requiring an API key or replacing it with a stored
295
- login. Codex executes the helper and renews its token. Helper paths and relative
296
- `auth.cwd` values resolve from the supplied `CODEX_HOME` (default `~/.codex`),
297
- not the source checkout; an absolute `auth.cwd` is preserved. Comparisons and
298
- reviews also honor the selected command provider in that home's `config.toml`.
299
- Configuration is passed to Codex for validation, including profile support.
300
-
301
- For other inference providers:
302
-
303
- ```bash
304
- export OPENROUTER_API_KEY="<your-openrouter-api-key>"
305
- npx @openai/codex-security scan . --provider openrouter --model anthropic/claude-sonnet-4.5
306
-
307
- export FIREWORKS_API_KEY="<your-fireworks-api-key>"
308
- npx @openai/codex-security scan . --provider fireworks --model accounts/fireworks/models/qwen3-235b-a22b
309
- ```
110
+ Run `cs login` in that SSH session, then open its sign-in
111
+ URL in your local browser. Keep SSH connected until login finishes.
310
112
 
311
113
  ### Amazon Bedrock
312
114
 
313
- Bedrock uses Codex's native provider; no custom connector or adapter is needed.
314
- Choose an AWS identity and a region with access to the exact Bedrock model ID:
115
+ Bedrock scans use AWS credentials and model access. They do not require
116
+ `codex-security login` or an OpenAI API key. See the
117
+ [Bedrock guide](https://github.com/openai/codex-security/blob/main/docs/bedrock.md)
118
+ for setup, model selection, and verification.
315
119
 
316
- ```bash
317
- export AWS_PROFILE="security-scan"
318
- export AWS_REGION="us-east-2"
319
- npx @openai/codex-security scan . --provider amazon-bedrock --model openai.gpt-5.6-luna
320
- ```
321
-
322
- For an AWS account with approved Daybreak Blue access in `us-east-2`:
323
-
324
- ```bash
325
- npx @openai/codex-security scan . --provider amazon-bedrock \
326
- --model openai.gpt-daybreak-blue-5.6-sol --effort high
327
- ```
120
+ ## Read existing Cloud findings
328
121
 
329
- For separately approved Daybreak Red model access in the same region:
122
+ The Security plugin includes `$cloud-findings` for accounts where Codex Security
123
+ Cloud is available. Install the plugin through your configured Codex marketplace,
124
+ sign in to Codex with ChatGPT, and complete the Cloud connection interactively in
125
+ the intended account and workspace. Installation alone does not authenticate the
126
+ connection. Local scans do not require Cloud, and an API key used for scanning
127
+ does not replace the Cloud connection.
330
128
 
331
- ```bash
332
- npx @openai/codex-security scan . --provider amazon-bedrock \
333
- --model openai.gpt-5.6-cyber --effort high
334
- ```
129
+ In Codex desktop or the interactive Codex CLI, ask:
335
130
 
336
- Both require OpenAI approval/enrollment followed by AWS model-access provisioning.
337
- Red requires separate Red approval and the model-specific approval for
338
- GPT-5.6-Cyber; Blue access does not include it. Contact your AWS account team.
339
- See the AWS model cards for
340
- [Blue](https://docs.aws.amazon.com/en_en/bedrock/latest/userguide/model-card-openai-gpt-daybreak-blue-56-sol.html)
341
- and [Red](https://docs.aws.amazon.com/en_en/bedrock/latest/userguide/model-card-openai-gpt-56-cyber.html),
342
- and [OpenAI's access overview](https://help.openai.com/en/articles/20001258-openai-daybreak-trusted-access-for-cyber-overview).
343
-
344
- Run the exports and CLI command in the same shell, job, or container. Environment
345
- changes in another terminal or a completed subprocess do not reach the scan.
346
- Instead of a profile, you can use `AWS_BEARER_TOKEN_BEDROCK`, AWS access keys, web
347
- identity, container credentials, or the default AWS credential chain. Temporary
348
- access keys require all three of `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`,
349
- and `AWS_SESSION_TOKEN`. Set `AWS_REGION` for the selected model's region and
350
- avoid mixing a profile with unrelated credential environment variables.
351
-
352
- Once model access is provisioned, native Bedrock scans, including Deep Scan
353
- workers, use AWS authentication without a separate `codex-security login` or
354
- OpenAI API key. AWS still controls whether that identity can invoke the model.
355
- Reading local reports, `scans show`, and `export` requires no cloud login.
356
- [Publishing to Cloud](#publish-findings-to-cloud) is a separate operation that
357
- requires ChatGPT credentials; AWS inference credentials do not grant that access.
358
-
359
- `info` and `scan --dry-run` inspect local configuration and inputs. They do not
360
- verify AWS credentials or invoke the model. A model-metadata or OpenAI access
361
- advisory does not establish Bedrock access; use the actual inference result.
362
- An AWS authentication error or model-access denial must be resolved for the
363
- selected AWS identity, model, and region. See the
364
- [Bedrock verification guide](../../docs/bedrock.md) for a live scan recipe.
365
-
366
- OpenAI models such as `openai.gpt-5.6-luna` support `--max-cost`. The exact
367
- `openai.gpt-daybreak-blue-5.6-sol` ID has AWS Standard commercial in-region price
368
- estimates, including short/long-context ranges and the included AWS fee. These
369
- estimates enable `--max-cost`; they are not billing totals or a guaranteed bill
370
- limit. This pricing entry does not change other Bedrock models' estimates.
371
-
372
- Bedrock scans, including Deep Scan workers, default to
373
- `model_reasoning_summary = "none"` because some Bedrock models reject
374
- `reasoning.summary`. This leaves reasoning effort unchanged. Explicit summary
375
- settings in `--codex` overrides or the selected Codex profile take precedence.
376
- For standard scans on older CLI versions, append
377
- `--codex 'model_reasoning_summary="none"'` to your scan command if Bedrock
378
- reports that `reasoning.summary` is unsupported. Deep scans require a CLI
379
- version that forwards this setting to discovery and reducer workers, including
380
- resumed workers. Version `0.1.27` and later includes that fix.
381
-
382
- ### OpenAI credentials
383
-
384
- On Windows, set the API key in PowerShell:
385
-
386
- ```powershell
387
- $env:OPENAI_API_KEY = "<your-api-key>"
388
- npx @openai/codex-security scan C:\code\repository
389
- ```
131
+ > Use $cloud-findings to list findings for example/security-demo in my selected
132
+ > workspace. Inspect the highest-severity finding and its report, and show its
133
+ > recorded assignee, patch links, verification results, and latest scan status.
134
+ > Do not change anything.
390
135
 
391
- Login, logout, scans, validation, patching, and fix verification share a private
392
- credential home for stored OpenAI credentials, including custom providers with
393
- `requires_openai_auth = true`:
394
- `$CODEX_SECURITY_STATE_DIR/codex-home`, or
395
- `$CODEX_HOME/state/plugins/codex-security/codex-home`. Keep this credential
396
- home outside the target directory and every enclosing Git worktree, including
397
- when running a command from a subdirectory. Codex carries
398
- `cli_auth_credentials_store`, `forced_login_method`, and
399
- `forced_chatgpt_workspace_id` from the ambient configuration into this home,
400
- including removing settings that are no longer present in the ambient configuration.
401
- Each command carries its selected provider into this home. Patching and fix
402
- verification also synchronize the ambient home's project-trust decisions and
403
- project-root markers, preserving which project configuration Codex loads.
404
- They hold the credential-home lock until the app-server thread is ready,
405
- then release it before model execution.
406
- Managed-device policies still apply. If this home has no credentials, it imports
407
- an existing file-based Codex sign-in. Logout disables
408
- imports until you log in again.
409
-
410
- Finish operations using older versions before upgrading. Runtime preparation
411
- holds the credential-home lock through pauses; exit or crash releases it.
412
- Compatibility heartbeats protect active locks from older heartbeat-only
413
- clients, but those clients can replace a paused client's lock.
414
-
415
- Keep `.codex-security-scan.sqlite3` between operations; never remove it during
416
- an operation. PID reuse can make old PID-only locks appear active and block
417
- recovery. Stop all operations using this home before removing an old
418
- `.codex-security-scan.lock` directory manually.
419
-
420
- If ChatGPT credentials cannot be refreshed, run `login status`. Retry if the
421
- sign-in recently changed; otherwise run `logout`, then `login`.
422
-
423
- Interactive scans ask whether to use ChatGPT or an environment API key when
424
- both are available. The choice applies to that scan. Noninteractive scans,
425
- including CI, JSON output, and dry runs, prefer the API key. Choose with `--auth`:
136
+ After completing connection setup, the same host connection can be used by
137
+ `codex exec`:
426
138
 
427
139
  ```bash
428
- npx @openai/codex-security scan . --auth chatgpt
429
- npx @openai/codex-security scan . --auth api-key
140
+ codex exec --ephemeral --json -s read-only 'Use $codex-security:cloud-findings to read findings and the latest scan status for example/security-demo in my selected workspace. Inspect one finding and its report. If the workspace or repository is ambiguous, explain the required selection and stop. Do not change anything.'
430
141
  ```
431
142
 
432
- `--auth` also works with `validate`, `patch`, and `verify-fix`. These commands
433
- use the same stored login as `scan`, including a sign-in created with
434
- `codex-security login --device-auth`:
435
-
436
- ```bash
437
- npx @openai/codex-security patch OCCURRENCE_ID --auth chatgpt
438
- npx @openai/codex-security verify-fix OCCURRENCE_ID --auth api-key
439
- ```
143
+ Noninteractive execution needs an existing authenticated connection; it cannot
144
+ complete first-time sign-in. If authentication expires, the app is unavailable,
145
+ or workspace policy denies access, complete the reported setup action before
146
+ retrying. Those failures do not mean the repository has no findings.
440
147
 
441
- `--auth chatgpt` ignores environment API keys. `--auth api-key` requires
442
- `OPENAI_API_KEY` or `CODEX_API_KEY`. The default is `--auth auto`; noninteractive
443
- commands prefer `OPENAI_API_KEY`, then `CODEX_API_KEY`, then stored credentials.
444
- Patch follow-up assessment uses the same selection, and `scan --patch` keeps
445
- the scan's choice. Environment API keys do not replace the saved login.
446
- The SDK uses the same `auth` option on `run`, `validate`, and `preflight`.
447
- Codex may still need ChatGPT credentials to load workspace-managed policies
448
- when using an API key.
449
-
450
- Some cybersecurity requests and protected findings require Trusted Access for
451
- Cyber approval. Apply or check your access at
452
- [chatgpt.com/cyber](https://chatgpt.com/cyber).
453
-
454
- ## Generate a security policy
455
-
456
- `policy` drafts `SECURITY.md` guidance for future scans. It does not run a
457
- vulnerability scan, change application settings, or install the draft in the
458
- checkout. It uses the scan runtime and authentication, requesting read-only
459
- access to the selected repository or component and required tools. Network access,
460
- web search, apps, and MCP servers are disabled. Drafts stay outside the checkout.
461
- The host resolves inherited guidance once and includes each checked descendant
462
- policy separately. Descendant policy links must stay within the selected component.
463
- Inherited and reporting-policy links may also resolve to ancestor `SECURITY.md`
464
- files or the checkout's `.github/SECURITY.md` and `docs/SECURITY.md`.
465
- The model cannot read sibling components or Git metadata. Policy turns deny
466
- access to the resolved Git metadata and markers, including those inside the
467
- selected source tree, nested bare repositories, and associated alternate object
468
- stores.
469
- Policy shell tools inherit only Codex's core environment; custom shell environment
470
- settings, login shells, and shell snapshots are disabled for these turns.
471
- Knowledge-base text stays with the private review artifacts during generation
472
- and is removed afterward.
473
-
474
- Known limitation: policy preflight and generation currently fail on Unix
475
- directories with non-UTF-8 names.
476
-
477
- On macOS, the pinned Codex runtime does not fully enforce write restrictions
478
- under `/tmp` (including `/private/tmp`). Keep the repository and artifacts outside
479
- that tree when read-only enforcement is required. See the
480
- [upstream sandbox limitation](https://github.com/openai/codex/issues/32395).
148
+ Assignment, issue validation, patch checks, periodic fix checks, and finding
149
+ lifecycle status are separate records. Some finding sources do not provide all
150
+ of them. The read workflow reports missing data and incomplete evidence pages,
151
+ and does not describe failed or unfinished scans as clean.
481
152
 
482
- ```bash
483
- npx @openai/codex-security policy .
484
- npx @openai/codex-security policy . --path services/api
485
- npx @openai/codex-security policy . --knowledge-base architecture.md --model gpt-5.6-terra --effort high
486
- npx @openai/codex-security policy . --dry-run --json
487
- ```
488
-
489
- The repository defaults to the current directory. `--path` selects a component,
490
- which inherits policies from its Git root, with the closest policy taking
491
- precedence. Linked worktrees and initialized submodules use their own roots.
492
- Targets and policy links must stay in the selected checkout, outside Git
493
- metadata; ancestor links cannot widen a component policy's scope.
494
-
495
- For an intentional separate Git directory, set `core.worktree` to the checkout's
496
- absolute path. Use `git worktree repair` for moved linked worktrees.
497
-
498
- Generation uses three Codex stages: describe the system, build a threat model,
499
- then draft the policy. The first two documents support review; they are not
500
- additional approval steps or policies to install.
501
- In a terminal, it asks about facts the source cannot establish and shows the
502
- exact diff. If both ChatGPT and API-key credentials are available, it asks which
503
- to use; `--auth chatgpt` or `--auth api-key` selects one explicitly.
504
-
505
- | Invocation | Calls Codex? | Result |
506
- | ---------------------------- | ------------ | ----------------------------------------------------------------------- |
507
- | `policy .` | Yes | Ask owner questions, save documents, and preview the draft. |
508
- | `policy . --headless --json` | Yes | Save documents without prompts and return their paths and review notes. |
509
- | `policy . --format md` | Yes | Generate a draft and write its Markdown to stdout. |
510
- | `policy . --dry-run --json` | No | Check local inputs and show the resolved target and settings. |
511
-
512
- None of these commands installs `SECURITY.md` in the repository. Output formats
513
- change presentation; they do not turn generation into a saved-draft read.
514
-
515
- ### Review the draft
516
-
517
- Review the saved `SECURITY.md` before copying it to the reported target. Check
518
- links from `.github/SECURITY.md` or `docs/SECURITY.md`: copying can change their
519
- guidance too. Preserve reporting instructions and obtain owner approval for
520
- exclusions, accepted risks, and severity decisions. Later scans read this policy.
521
-
522
- Generation and preview check for changes to the selected or inherited policies.
523
- If governing guidance changes during generation, completed documents remain for
524
- inspection, but no completed-draft manifest is written. Other source files are not
525
- frozen; regenerate if relevant source or neighboring policies change.
526
- A failed terminal preview reports a warning and the saved draft paths. Explicit
527
- output formats return the draft directly without running a diff preview.
528
-
529
- Use `--headless` or an explicit output format to skip questions. Unanswered
530
- questions remain in the review notes. Drafts default to the Codex Security state
531
- directory; `--output-dir` selects an empty directory outside every enclosing
532
- Git checkout and its Git metadata.
533
-
534
- ```bash
535
- npx @openai/codex-security policy . --path services/api \
536
- --headless --output-dir /path/outside/repository/api-policy --json
537
- ```
538
-
539
- The artifact directory contains:
540
-
541
- | File | Purpose |
542
- | ---------------------- | --------------------------------------------------------------------------------------- |
543
- | `SECURITY.md` | Editable policy draft. |
544
- | `threatmodel.md` | Detailed threat model with source references. |
545
- | `project-spec.md` | System description and security boundaries. |
546
- | `previous-SECURITY.md` | Original policy used for the diff. |
547
- | `policy-draft.json` | Target, policy hashes, revision, retained threat model, stage status, and review notes. |
548
-
549
- Keep supporting documents private until reviewed for disclosure. A generated
550
- threat scenario is neither owner approval nor a confirmed vulnerability.
551
-
552
- `--format md` writes the draft to stdout. `--json` returns paths, review notes,
553
- status, and estimated cost. Global filters and token options work with these
554
- formats. Progress goes to stderr. `--full-output` reports failures with
555
- `ok: false`. `--max-cost` applies to the whole generation. If a stage cannot
556
- inspect required source evidence, generation stops and preserves completed
557
- documents. Fix the reported problem and use a new output directory to retry.
153
+ ## Run a scan from TypeScript
558
154
 
559
- ### Generate a policy from TypeScript
155
+ Scan a repository you own or have permission to assess:
560
156
 
561
157
  ```ts
562
158
  import { CodexSecurity } from "@openai/codex-security";
563
159
 
564
160
  const security = new CodexSecurity();
161
+
565
162
  try {
566
- const draft = await security.generatePolicy("/path/to/repository", {
567
- path: "services/api",
568
- knowledgeBasePaths: ["/path/to/architecture.md"],
569
- onStage: (stage) => console.error(stage),
570
- });
163
+ const result = await security.run("/path/to/repository");
571
164
 
572
- console.log(await security.previewPolicy(draft));
573
- // Open draft.draftPath in an editor to review the saved policy.
165
+ console.log(result.reportPath);
166
+ console.log(result.findings.findings);
167
+
168
+ if (result.hasFindingsAtOrAbove("high")) {
169
+ process.exitCode = 1;
170
+ }
574
171
  } finally {
575
172
  await security.close();
576
173
  }
577
174
  ```
578
175
 
579
- `preflightPolicy()` checks local inputs without starting Codex.
580
- `previewPolicy()` previews the supplied in-memory draft, uses the client's Python
581
- setting, and makes terminal control characters visible. Editing the saved file
582
- does not change that object. The standalone `securityPolicyDiff()` returns a raw diff
583
- for files or other non-terminal uses; pass an interpreter explicitly if needed.
584
- `generatePolicy()` accepts `auth`, `path`, `knowledgeBasePaths`, `outputDir`,
585
- `maxCostUsd`, `signal`, and progress and cost callbacks. An optional
586
- `answerQuestions` callback receives each group of up to three owner questions
587
- and a cancellation signal. Without it, the questions remain unresolved.
176
+ Omitting `outputDir` saves results in the private Codex Security state directory.
177
+ To choose another location, use a new or empty directory outside the scanned
178
+ repository and its enclosing Git worktree. On macOS and Linux, an existing output
179
+ directory must be private to you (`chmod 700`).
588
180
 
589
- ## CLI
181
+ ### Read results
590
182
 
591
- ```bash
592
- npx @openai/codex-security policy . --path services/api
593
- npx @openai/codex-security scan .
594
- npx @openai/codex-security scan /path/to/repository --path src --path tests
595
- npx @openai/codex-security scan /path/to/repository --diff origin/main --json
596
- npx @openai/codex-security scan /path/to/repository --output-dir /path/outside/repository/results
597
- npx @openai/codex-security scan /path/to/repository --dry-run
598
- ```
183
+ | Result | Contents |
184
+ | --------------------------------- | ---------------------------------------------------------------- |
185
+ | `findings.findings` | Findings from this scan. |
186
+ | `reportPath` | Path to the Markdown report. |
187
+ | `coverage` | What the scan assessed and any coverage gaps. |
188
+ | `repositoryFindings` | This scan's findings plus earlier open findings, when available. |
189
+ | `sarifPath` | SARIF export path, or `null`. |
190
+ | `threatModel` / `threatModelPath` | Saved threat model and document path; either can be `null`. |
191
+ | `cost` | Estimated model usage cost, or `null` when unavailable. |
599
192
 
600
- Use `--help` to browse commands by task, or `<command> --help` (or `-h`) for
601
- options and examples. `scan --help` groups options by scope, Deep Scan, results,
602
- and patching; `publish scan --help` groups destination settings. `scans` and
603
- `findings` run `list` when no subcommand is given.
193
+ Review coverage alongside findings. A report with no findings does not establish
194
+ that the repository is secure. Reports and logs can contain source code,
195
+ vulnerability details, and credentials; review them before sharing.
604
196
 
605
- Use `--version` for the installed version, and
606
- `info --json` for package, plugin, runtime, and model details. `--dry-run`
607
- runs local preflight checks. `info -c FILE --json` inspects resolved configuration
608
- and its sources without a repository or runtime.
197
+ The SDK does not set your process's exit status. Use `hasFindingsAtOrAbove()`
198
+ as in the example to enforce a severity threshold.
609
199
 
610
- ### Project files
200
+ ### Scan options and output
611
201
 
612
- Use `scan -c FILE` / `scan --config FILE` to load reusable scan settings:
202
+ Pass scan settings as the second argument to `run()`. The following SDK snippets
203
+ assume an open `CodexSecurity` client named `security`; close it when finished.
613
204
 
614
- ```bash
615
- codex-security scan . -c codex-security.yaml --dry-run --json
616
- codex-security scan . -c codex-security.json --model gpt-5.6-terra
617
- codex-security init
618
- codex-security info -c codex-security.yaml --json
205
+ ```ts
206
+ const result = await security.run("/path/to/repository", {
207
+ target: ["src", "tests"],
208
+ knowledgeBasePaths: ["/path/to/architecture.md"],
209
+ scanPrompt: "Focus on authentication and authorization.",
210
+ outputDir: "/path/outside/repository/results",
211
+ maxCostUsd: 5,
212
+ });
619
213
  ```
620
214
 
621
- Select one `.yaml`, `.yml`, or `.json` file. `scan`, `bulk-scan`, `scan-components`,
622
- and `info` accept `-c`. They also accept an operator-set
623
- `CODEX_SECURITY_PROJECT_CONFIG`; an explicit `-c` wins. Without either, no file is
624
- loaded or discovered. The repository still comes from the command's target
625
- selection. SDK `run()` and saved reruns do not load project files automatically.
626
-
627
- The selected file is trusted like CLI options and SDK `codexOverrides`. Native
628
- settings can start configured MCP server processes and select model-service destinations. Do not
629
- select configuration controlled by an untrusted repository or pull request; keep
630
- CI scanner configuration outside the checkout being assessed.
631
-
632
- `init [file]` writes `codex-security.yaml` by default and never overwrites an
633
- existing file. YAML starters show defaults as comments; JSON starters contain the
634
- editor schema hint, relative to the chosen file and the invocation directory's
635
- local package installation. `info` reports effective model details and native key sources
636
- without dumping raw native values.
637
-
638
- ```yaml
639
- # yaml-language-server: $schema=./node_modules/@openai/codex-security/schemas/project-config.schema.json
640
- scan:
641
- mode: standard
642
- scope:
643
- paths: [src]
644
- codex:
645
- model: gpt-5.6-sol
646
- model_reasoning_effort: xhigh
647
- policy:
648
- fail_on_severity: high
649
- ```
215
+ | Option | Use |
216
+ | ------------------------------------------- | ------------------------------------------------------------------------------ |
217
+ | `target` | Whole repository (default), repository-relative paths, or a `DiffTarget`. |
218
+ | `mode` | `"standard"` (default) or `"deep"`. Deep scans support repositories and paths. |
219
+ | `knowledgeBasePaths` | Supporting text, PDF, DOCX files, or directories. |
220
+ | `scanPrompt` / `scanPromptFile` | Additional scan instructions. Inline text takes precedence. |
221
+ | `validationPrompt` / `validationPromptFile` | Custom validation instructions for standard scans. |
222
+ | `postScanPrompt` / `postScanPromptFile` | Follow-up instructions after the scan. |
223
+ | `outputDir` | Results directory; omit to use the state directory. |
224
+ | `archiveExisting` | Move previous results aside before reusing `outputDir`. |
225
+ | `maxCostUsd` | Stop at an estimated model cost; see [cost limits](#progress-and-cost). |
226
+ | `signal` | An `AbortSignal` to cancel the scan. |
650
227
 
651
- All settings are optional; `{}` uses the existing defaults. JSON files can use a
652
- root `$schema` string pointing to the same packaged schema. Schema hints are for
653
- editors; the CLI uses its bundled validator without fetching URLs, coercing values,
654
- or dropping unknown keys. Native `codex` settings retain their existing checks and
655
- profile semantics. CLI `scan --schema --json` describes command arguments.
656
-
657
- Settings use built-in defaults, applicable legacy deep defaults, the file, then
658
- explicit CLI values. Lists and scope variants are replaced. `--head` can refine
659
- a file diff and `--base` a file working-tree scope. A selected native profile can
660
- still override root model/effort values. Existing native alias-conflict checks
661
- and the behavior of `--provider openai` are unchanged.
662
-
663
- File context, instruction, validation, and output paths resolve from the file's
664
- directory. CLI file paths resolve from the invocation directory; scope paths
665
- resolve from the repository. The file cannot select a different repository or
666
- enable automatic patching/publication. The loader does not evaluate code,
667
- interpolate environment values, include remote files, or merge multiple files.
668
-
669
- Dry-run output adds `projectConfig.path` and `projectConfig.sources`, selected
670
- prompt paths, and the finding policy without dumping raw native configuration.
671
- Missing or invalid selected files exit `2`. Help, version, and command schema
672
- output do not load project files. Existing scan and finding-policy exit codes
673
- remain unchanged.
228
+ The exported `ScanOptions` type describes all options and callbacks. For full
229
+ CLI behavior, see [scan options and output](docs/cli.md#scan-options-and-output).
674
230
 
675
- ### Scan options and output
231
+ ### Scan a diff
676
232
 
677
- `--path` scopes a scan to one or more paths, `--diff` scans committed changes,
678
- and `--working-tree` scans staged and unstaged changes. Deep scans support
679
- repository and path targets.
680
-
681
- Bulk scans use clean, shallow checkouts and support repository or path scopes.
682
- They reject configured diff or working-tree scopes before starting unless each
683
- affected CSV row supplies its own path scope.
684
-
685
- Working-tree snapshots include files from untracked nested Git repositories.
686
- Initialized submodules must be clean and checked out at the commit recorded by
687
- the parent repository.
688
-
689
- Repeat `--knowledge-base PATH` for UTF-8 text files with any extension (including
690
- JSON and SARIF), PDF, or Word (`.docx`) files. Directories are searched recursively,
691
- skipping other binary files. Explicitly supplied unsupported binary files are rejected.
692
- Bulk scans share these documents with every repository.
693
-
694
- Use an empty output directory outside the scanned directory and enclosing Git
695
- worktree. On macOS/Linux, existing directories must be private to you
696
- (`chmod 700`). `--archive-existing` moves previous results to
697
- `<output-dir>.previous-<timestamp>-<id>`; add `--dry-run` to preview the move.
698
- SARIF output, when produced, is at `<scan-dir>/exports/results.sarif`.
699
-
700
- Scans are report-only by default. Set `--fail-on-severity high` to exit with
701
- `1` if a completed scan finds high or critical issues. Incomplete scans exit
702
- with `2`, writing available results to stdout and a coverage warning to stderr.
703
-
704
- For machine-readable scan output (`--format json` or `--format jsonl`), a scan
705
- execution failure writes one structured object to stdout:
706
-
707
- ```json
708
- {
709
- "status": "failed",
710
- "code": "SCAN_FAILED",
711
- "message": "..."
712
- }
713
- ```
233
+ ```ts
234
+ import { DiffTarget } from "@openai/codex-security";
714
235
 
715
- With `--full-output`, the same code and message are reported under `error` in
716
- an `ok: false` envelope instead.
236
+ const result = await security.run("/path/to/repository", {
237
+ target: DiffTarget.refs({ base: "origin/main" }),
238
+ });
239
+ ```
717
240
 
718
- The command still exits with `2` for runtime, export, invalid-input, or
719
- incomplete-scan failures, and human-readable diagnostics remain on stderr.
720
- Use `scan --schema --format json` to discover this failure variant alongside
721
- the successful scan output. Cancellation and termination retain their `130`
722
- and `143` exit codes.
241
+ `DiffTarget.refs()` compares the base with `HEAD` unless you supply `head`.
242
+ The checkout must be clean, complete, and at that head revision.
243
+ Use `DiffTarget.workingTree()` for staged and unstaged changes relative to `HEAD`.
244
+ Diff targets require standard mode.
723
245
 
724
- ### Import findings as a saved scan
246
+ ### Configure the client
725
247
 
726
- Import an existing findings CSV or JSON file into local scan history and SQLite:
248
+ Set model and native Codex settings on the client:
727
249
 
728
- ```bash
729
- codex-security scan import --csv /path/to/findings.csv
730
- codex-security scan import --json /path/to/findings.json --format json
731
- codex-security scan import --csv /path/to/findings.csv --dry-run
250
+ ```ts
251
+ const security = new CodexSecurity({
252
+ codexOverrides: {
253
+ model_reasoning_effort: "high",
254
+ analytics: { enabled: false },
255
+ },
256
+ });
732
257
  ```
733
258
 
734
- Supply exactly one of `--csv PATH` or `--json PATH`. CSV uses the existing
735
- [findings CSV template](https://github.com/openai/codex-security/blob/main/examples/findings.csv),
736
- including the optional `candidate_id` column. JSON accepts a complete
737
- `codex-security.findings` document or `{ "findings": [...] }`, with each finding
738
- matching the existing findings schema. On `scan import`, `--json` selects the
739
- input file; use `--format json` for JSON output. Other commands retain their
740
- existing `--json` output flag. The selected input must be a regular file, and its
741
- path must not traverse symbolic links or directory junctions. Use the direct
742
- filesystem path when the file or a parent directory is linked.
743
-
744
- Each import creates one completed scan using the configured
745
- `CODEX_SECURITY_STATE_DIR`. The target is a retained copy of the input dataset,
746
- independent of the current repository. Every source occurrence remains a separate
747
- finding, including duplicate reports. Original identifiers are preserved in
748
- `extensions.import`; the original file is sealed under `artifacts/import/`.
749
- JSON writeup paths are retained as source metadata without reading external files.
750
-
751
- Completion means the import finished. Coverage is unknown and the report states
752
- that no security analysis was performed. Importing requires no model calls or
753
- authentication. `--dry-run` validates without saving a scan. `--output-dir` and
754
- `--archive-existing` control saved output, and `scans rerun SCAN_ID` reimports the
755
- retained input.
756
-
757
- ### Generate mock scan results
758
-
759
- Use `--mock` to populate a Standard scan with synthetic test data in seconds,
760
- without Codex authentication or any LLM calls:
259
+ Constructor options are `codexOverrides`, `pythonPath`, and `pluginPath`.
260
+ The bundled runtime and plugin are used by default. `pythonPath` overrides the
261
+ `PYTHON` environment variable. To choose a model, set `codexOverrides.model`.
761
262
 
762
- ```bash
763
- codex-security scan /path/to/repository --mock
764
- codex-security scan /path/to/repository --mock --output-dir /path/outside/repository/mock-results
765
- ```
263
+ New and resumed Deep Scans require a current plugin with
264
+ `directDeepScanEngine: 1`, `workerProviderSnapshot: 4`, and isolated worker
265
+ configuration support. Older custom plugins fail before scan execution; update
266
+ the plugin or omit `pluginPath` to use the bundled version. Discovery, reducer,
267
+ and resumed workers inherit per-scan provider, authentication, environment, and
268
+ executable settings, with their existing read-only permissions. Reading saved
269
+ reports does not require these execution capabilities.
766
270
 
767
- The SDK equivalent is `await security.run(repository, { mock: true })`.
768
- Mock mode is off by default. It uses normal target validation, scan registration,
769
- artifact finalization, reports, and local scan/finding history. Output directories,
770
- archiving, JSON output, exports, and `--fail-on-severity` work as usual.
771
- `--dry-run` only validates inputs; `--mock` saves a completed scan.
271
+ The SDK no longer adapts the older `node ./mcp/server.mjs` MCP entrypoint; use
272
+ the current shell or Windows launcher for runtime-root routing.
772
273
 
773
- Each run contains 12 findings across all severity levels: eight stable findings
774
- recur on subsequent scans of the same repository, and four have new identities
775
- on every run. Two pairs describe the same root causes with different titles and
776
- identities, providing inputs for deduplication testing. Mock scans skip automatic
777
- LLM matching; existing identity-based history indexing still runs. Separate
778
- comparison or deduplication commands retain their usual model behavior.
274
+ Custom plugins must support the current workbench protocol for scan comparison
275
+ and archival. Update an older custom plugin or omit `pluginPath` to use the
276
+ bundled version. The SDK no longer adapts payloads or archives scan directories
277
+ on behalf of older workbench implementations.
779
278
 
780
- Titles, provenance, artifact metadata, and reports identify the results as
781
- synthetic. Paths and code snippets are fictional and are never written into the
782
- repository. Completion means fixture generation finished, not that the repository
783
- was audited. Results enter the selected local state just like other scans; set
784
- `CODEX_SECURITY_STATE_DIR` to a separate directory when creating disposable data.
785
- Token usage is zero. `scans rerun` preserves mock mode.
279
+ Scans use an isolated Codex configuration. See
280
+ [runtime configuration](docs/cli.md#runtime-configuration-and-worker-limits)
281
+ for supported overrides and defaults.
786
282
 
787
- Mock mode supports repository, path, and diff targets in Standard mode. It cannot
788
- be combined with `--dry-run`, `--patch`, Deep mode, custom validation, or post-scan
789
- prompts. Scan prompts and knowledge-base inputs do not change the fixtures, and
790
- mock scans do not offer interactive patching.
283
+ Windows defaults to `windows.sandbox = "elevated"` to enforce credential read
284
+ denials. Explicit `windows.sandbox` settings remain unchanged; Codex reports
285
+ policies unsupported by the selected backend.
791
286
 
792
- ### Attribute scans to end users
287
+ ### Load a project file
793
288
 
794
- When scanning on behalf of users, pass each user's stable hashed ID:
289
+ Load shared CLI and SDK settings explicitly:
795
290
 
796
291
  ```ts
797
- await security.run("/path/to/repository", {
798
- auth: "api-key",
799
- safetyIdentifier: hashedUserId,
800
- });
801
- ```
802
-
803
- ```bash
804
- codex-security scan /path/to/repository --auth api-key --safety-identifier hashed-user-id
805
- ```
806
-
807
- Use a nonblank ID of 1 to 64 characters without NUL or personal data such as
808
- email addresses. It applies to the scan, workers, retries, and follow-up work
809
- without changing shared configuration. Supply it again for reruns.
810
-
811
- The runtime needs native `--safety-identifier` support, and the plugin must
812
- forward it to workers. The bundled runtime doesn't support it yet; choose a
813
- compatible build with `CODEX_CLI_PATH`. The SDK checks the ID's format, not
814
- runtime or plugin compatibility. Older versions may omit the ID.
815
-
816
- ### Scan project components
292
+ import { CodexSecurity, loadProjectConfig } from "@openai/codex-security";
817
293
 
818
- `scan --path` runs one scan across selected paths. To scan each local project
819
- component separately (standard mode by default), use `scan-components`:
294
+ const { config, options } = await loadProjectConfig("codex-security.yaml");
295
+ const security = new CodexSecurity(config);
820
296
 
821
- ```bash
822
- npx @openai/codex-security scan-components /path/to/project \
823
- --component apps/api --component apps/web --component packages/shared \
824
- --workers 4 --output-dir /path/outside/project/results
297
+ try {
298
+ const result = await security.run("/path/to/repository", options);
299
+ if (
300
+ options.failureSeverity !== undefined &&
301
+ result.hasFindingsAtOrAbove(options.failureSeverity)
302
+ ) {
303
+ process.exitCode = 1;
304
+ }
305
+ } finally {
306
+ await security.close();
307
+ }
825
308
  ```
826
309
 
827
- Use `-c FILE` to share settings, including `scan.mode: deep`, context and prompt
828
- files, per-scan deep workers, cost limits, and severity policy. Component plans
829
- override the file's scope. `output.directory` supplies the results directory when
830
- `--output-dir` is omitted. A configured severity threshold returns exit `1` after
831
- completed scans; failures or incomplete results return `2`.
310
+ `run()` does not discover project files. Paths inside a file resolve from that
311
+ file's directory; scope paths resolve from the repository. For a typed object,
312
+ use `resolveProjectConfig(input, directory?)`. Override loaded options with
313
+ `{ ...options, maxCostUsd: 5 }`.
832
314
 
833
- Use `--auto` instead of `--component` for a proposed split. Save a plan to
834
- review or edit, then run it with a new output directory:
315
+ Project files are trusted configuration and can select model endpoints or start
316
+ MCP servers. Keep CI scanner configuration outside the checkout being assessed.
317
+ See the [project configuration guide](https://github.com/openai/codex-security/blob/main/docs/project-configuration.md)
318
+ for the schema and precedence rules.
835
319
 
836
- ```bash
837
- npx @openai/codex-security scan-components /path/to/project \
838
- --auto --plan-only --output-dir /path/outside/project/plan
839
- npx @openai/codex-security scan-components /path/to/project \
840
- --components-file /path/outside/project/plan/components.json \
841
- --output-dir /path/outside/project/results
842
- ```
320
+ ### Check inputs before scanning
843
321
 
844
- For large repositories, automatic planning splits inventories into separate calls
845
- that fit Codex's input character limit. It preserves directory boundaries where
846
- possible and subdivides oversized packages and flat directories as needed. Each
847
- call uses a fresh context and can select only paths within its batch. Omitted
848
- files are retained in `Other files` components within those same boundaries.
849
- Large repositories can therefore require more planning calls and produce more
850
- components. Review or edit the saved plan before scanning with `--components-file`.
851
-
852
- Components use repository-relative paths:
853
-
854
- ```json
855
- {
856
- "components": [
857
- { "name": "API", "paths": ["apps/api", "packages/auth"] },
858
- { "name": "Web", "paths": ["apps/web"] }
859
- ]
860
- }
322
+ ```ts
323
+ const plan = await security.preflight("/path/to/repository", {
324
+ target: ["src"],
325
+ maxCostUsd: 5,
326
+ });
327
+ console.log(plan);
861
328
  ```
862
329
 
863
- Automatic planning respects Git ignore rules and groups omitted files under
864
- `Other files`. Each proposed path must contain an inventoried file. Planning
865
- leaves source files unchanged.
866
-
867
- Each component saves artifacts under `component-N/`. Combined `findings.json`
868
- merges high-confidence root-cause matches, keeping the highest severity and
869
- original IDs. Uncertain matches stay separate. `summary.json` records coverage
870
- and matching status; `report.md` links to component reports. Export and publish
871
- from the individual scan folders, not the combined summary.
872
-
873
- Large comparisons use bounded batches that cover every earlier/later finding
874
- pair. Overlapping confirmed groups are joined in code. Finding text is not
875
- truncated; pairs above Codex's input limit leave matching incomplete.
876
-
877
- Use an empty output directory outside the project. Failed components don't
878
- stop others, but failures, incomplete coverage, or failed matching exit with
879
- `2`. Retry failed or incomplete components with
880
- `--components-file retry-components.json` and a new output directory.
881
- The retry report covers only those components; it does not update the original
882
- combined report.
883
-
884
- `--max-cost` applies per component, excluding planning and matching.
885
- `--model` and `--effort` also apply to matching; `--auth` applies throughout.
886
- Planning and matching reject an ambient command provider that conflicts with
887
- explicit `--auth chatgpt` or `--auth api-key`. A command provider explicitly
888
- selected through SDK `codexOverrides` retains its authentication configuration.
889
- Use `--knowledge-base`, `--scan-prompt-file`, and `--post-scan-prompt-file` as for
890
- bulk scans.
891
-
892
- From TypeScript, use `runComponentScans({ repository, outputDir, components })`.
893
- Use `auto: true` for planning, `planOnly: true` to save the plan without scans,
894
- and `scanOptions.auth` to select credentials.
330
+ `preflight()` checks local inputs without starting Codex or using the network.
331
+ It does not verify credentials, model access, Python, or the plugin. The CLI
332
+ equivalent is `scan --dry-run`.
895
333
 
896
334
  ### Configure deep scans
897
335
 
898
- For `scan --mode deep`, `--workers` sets discovery concurrency and `--subagents`
899
- sets subagents per worker. `--stop-after-no-new` stops after that many runs
900
- without new issues. `--max-discovery-runs` and `--max-time-hours` cap discovery
901
- runs and duration. SDK equivalents:
902
-
903
336
  ```ts
904
- await security.run("/path/to/repository", {
337
+ const result = await security.run("/path/to/repository", {
905
338
  mode: "deep",
906
339
  workers: 2,
907
340
  subagents: 0,
908
341
  stopAfterNoNew: 3,
909
- stopAfterConsecutiveErrors: 2,
342
+ stopAfterConsecutiveErrors: 3,
910
343
  maxDiscoveryRuns: 10,
911
344
  maxTimeHours: 1.5,
912
345
  });
913
346
  ```
914
347
 
915
- Set defaults in `$CODEX_HOME/codex-security/config.toml`:
916
-
917
- ```toml
918
- [deep_scan]
919
- workers = 4
920
- subagents = 3
921
- stop_after_no_new = 4
922
- stop_after_consecutive_errors = 3
923
- max_discovery_runs = 40
924
- max_time_hours = 96
925
- ```
926
-
927
- CLI and SDK options override these defaults. Project files can use
928
- `scan.deep.stop_after_consecutive_errors`, and SDK calls can use
929
- `stopAfterConsecutiveErrors`; there is no new CLI flag for it. `--codex` cannot
930
- configure this section. Worker and run counts must
931
- be positive integers; `subagents` can be zero. Legacy `workers = "auto"` means
932
- four workers. Unknown keys are rejected.
933
-
934
- `max_time_hours` accepts positive values up to 96, including fractional hours.
935
- At the deadline, discovery stops; the scan combines and returns completed findings.
936
-
937
- `scan --workers` controls discovery workers within one deep scan;
938
- `bulk-scan --workers` controls how many repositories are scanned concurrently.
939
-
940
- The project-file deep block uses `subagents_per_worker` for the existing SDK/CLI
941
- `subagents` setting. A valid deep block can remain inactive in standard mode;
942
- explicit deep CLI options require deep mode. All six active values are resolved
943
- before runtime preparation and saved in new recipes. Complete saved values are
944
- independent of later changes to the legacy TOML file.
945
-
946
- ### Runtime configuration and worker limits
947
-
948
- Scans use these isolated Codex defaults instead of your user or repository
949
- configuration:
950
-
951
- ```toml
952
- approval_policy = "on-request"
953
- approvals_reviewer = "auto_review"
954
- cli_auth_credentials_store = "auto"
955
- model = "gpt-5.6-sol"
956
- model_reasoning_effort = "xhigh"
957
- model_reasoning_summary = "detailed" # "none" for amazon-bedrock
958
- show_raw_agent_reasoning = true
959
-
960
- [features]
961
- plugins = true
962
- goals = true
963
-
964
- [features.multi_agent_v2]
965
- enabled = true
966
- max_concurrent_threads_per_session = 9
967
-
968
- [windows]
969
- sandbox = "unelevated"
970
- ```
971
-
972
- Use `--model MODEL` to choose a model and `--effort EFFORT`
973
- for reasoning effort. Both flags work with `scan`, `bulk-scan`, `scan-components`,
974
- `policy`, `validate`, `patch`, `verify-fix`, `suggest-owners`, `classify-severity`,
975
- `scans match`, and `scans compare`.
976
-
977
- Model IDs and reasoning effort values are passed through to Codex unchanged.
978
- The wrapper accepts values such as `minimal`, `none`, and `high`, as
979
- well as future values, without requiring a wrapper update. Supported combinations
980
- depend on the model, inference provider, installed Codex version, and credentials.
981
- Codex and provider errors are reported without substituting another model or effort.
982
- Omitting these flags preserves each command's defaults: scans, policy generation,
983
- validation, patching, verification, and owner suggestions use `gpt-5.6-sol`/`xhigh`;
984
- matching and severity classification use Codex's configured model and `medium` effort.
985
-
986
- Repeat `--codex KEY=VALUE` for other TOML settings on commands that support it:
987
-
988
- ```bash
989
- npx @openai/codex-security scan . \
990
- --model gpt-6.1-sol \
991
- --effort high \
992
- --codex features.multi_agent_v2.max_concurrent_threads_per_session=4
993
-
994
- npx @openai/codex-security patch issues.md --model gpt-6-astra --effort max
995
- npx @openai/codex-security verify-fix issues.md --model gpt-6.1-sol --effort high
996
- ```
997
-
998
- The thread limit of `9` includes the parent and up to eight delegated workers.
999
- It is separate from deep-scan and bulk-scan worker counts.
1000
-
1001
- Quote string values as TOML, for example
1002
- `--codex 'model_reasoning_effort="high"'`. Do not pass both `--model` and
1003
- `--codex 'model="..."'`, or both `--effort` and
1004
- `--codex 'model_reasoning_effort="..."'`: conflicting or repeated keys are
1005
- rejected.
1006
-
1007
- Choose plugins with `--plugin-path`. Overrides of `plugins`, `marketplaces`,
1008
- or `features.plugins` are rejected, including in profiles. Multi-agent v2 must
1009
- stay enabled: `agents.max_threads` and
1010
- `features.multi_agent_v2.enabled=false` are rejected.
1011
-
1012
- `validate`, `patch`, and `verify-fix` accept `--auth`, `--model`, and `--effort`.
1013
- Their `--codex` overrides are limited to `model`, `model_reasoning_effort`,
1014
- `model_provider`, `model_providers`, and `analytics.enabled`.
1015
- Use the same provider settings as `scan` when routing a standalone patch
1016
- through a custom inference gateway:
1017
-
1018
- ```bash
1019
- npx @openai/codex-security patch "Security issue" \
1020
- --model gateway-model \
1021
- --codex 'model_provider="gateway"' \
1022
- --codex 'model_providers.gateway.name="Gateway"' \
1023
- --codex 'model_providers.gateway.base_url="https://gateway.example.test/v1"' \
1024
- --codex 'model_providers.gateway.wire_api="responses"' \
1025
- --codex 'model_providers.gateway.env_key="GATEWAY_API_KEY"'
1026
- ```
1027
-
1028
- Set the selected provider's API-key environment variable before running the
1029
- command; `--auth api-key` uses that configured variable. For `patch` and
1030
- `verify-fix`, provider overrides preserve unspecified fields from the provider's
1031
- existing Codex configuration. With `auto` or `api-key` authentication, a configured
1032
- `env_key` takes precedence over OpenAI account authentication, matching native Codex.
1033
- Explicit `--auth chatgpt` omits the selected custom provider's API-key environment
1034
- variable, clears any configured `experimental_bearer_token`, and selects stored
1035
- account authentication in its runtime configuration, even if the provider normally
1036
- uses only an API key or bearer token. The original environment and
1037
- Codex configuration remain unchanged.
1038
- Model, effort, and provider settings also apply to
1039
- `patch --assess-patch-risk`.
1040
- Sandbox, approval, and plugin settings remain controlled by the command.
1041
-
1042
- `scans resume` and `scans rerun` retain the saved scan's settings. `dedupe` uses
1043
- separate screening and review models, so it does not expose a single model/effort
1044
- override.
1045
-
1046
- Use `--codex 'analytics.enabled=false'` to disable Codex usage analytics and
1047
- built-in metrics for a command:
1048
-
1049
- ```bash
1050
- npx @openai/codex-security validate "Candidate finding" --codex 'analytics.enabled=false'
1051
- npx @openai/codex-security patch "Security issue" --codex 'analytics.enabled=false'
1052
- npx @openai/codex-security verify-fix "Security issue" --codex 'analytics.enabled=false'
1053
- ```
1054
-
1055
- The same setting works for `scan` and `bulk-scan`. An explicit setting is
1056
- preserved when `scan --patch` starts remediation and when
1057
- `patch --assess-patch-risk` starts its follow-up assessment. Boolean `true`
1058
- is also accepted; omitting the setting preserves the command's existing
1059
- configuration and Codex defaults. Validation ignores user configuration.
1060
- For stored OpenAI credentials, patching and verification read configuration
1061
- from the shared credential home. API-key commands and custom providers that use their own credentials retain
1062
- their ambient Codex configuration. Patching and verification preserve project trust from the
1063
- ambient home; explicit `--codex` settings apply to the command and its
1064
- patch-risk assessment.
1065
-
1066
- This setting does not control explicitly configured OpenTelemetry log or trace
1067
- exporters, authentication, integrations, or CLI update checks.
1068
-
1069
- See [Local security model](#local-security-model) for approval and filesystem
1070
- restrictions.
1071
-
1072
- ### Environment variables
1073
-
1074
- | Variable | Effect |
1075
- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
1076
- | `OPENAI_API_KEY`, `CODEX_API_KEY` | Scan credentials; `OPENAI_API_KEY` wins if both are set. |
1077
- | `CODEX_SECURITY_EMBEDDINGS_URL` | Findings service endpoint; see [Embeddings and storage](#embeddings-and-storage). |
1078
- | `CODEX_SECURITY_LINEAR_TEAM`, `CODEX_SECURITY_LINEAR_PROJECT` | Default team and project for completed-scan publication. |
1079
- | `CODEX_SECURITY_LINEAR_API_KEY` | Personal API key for Linear patching and direct publication. |
1080
- | `CODEX_SECURITY_LOG_LEVEL` | CLI-only; `debug` enables verbose diagnostics. |
1081
- | `LOG_LEVEL` | CLI-only fallback when `CODEX_SECURITY_LOG_LEVEL` is unset or blank. |
1082
- | `CODEX_SECURITY_STATE_DIR` | Private scan-history, workbench, and default artifact directory. |
1083
- | `CODEX_SECURITY_PROJECT_CONFIG` | Trusted project file for `scan`, `bulk-scan`, `scan-components`, and `info`; `-c` wins. Unset by default. |
1084
- | `CODEX_HOME` | Ambient Codex home for file-based sign-in and default state; defaults to `~/.codex`. |
1085
- | `CODEX_CLI_PATH` | Codex executable for authentication, plugin setup, scans, and workers. |
1086
- | `PYTHON` | Python interpreter when `--python` or SDK `pythonPath` is unset. |
1087
- | `GH_HOST` | GitHub Enterprise host for interactive `bulk-scan` discovery. |
1088
- | `CODEX_SECURITY_NO_UPDATE_NOTICE`, `NO_UPDATE_NOTIFIER` | Either variable disables interactive update notices. |
1089
- | `CODEX_SECURITY_NPM_REGISTRY`, `npm_config_registry`, `NPM_CONFIG_REGISTRY` | Update-check registry, in precedence order. |
1090
- | `CI` | Disables interactive update notices. |
1091
- | `NO_COLOR`, `TERM` | Disables colored scan history when `NO_COLOR` is defined or `TERM=dumb`. |
1092
-
1093
- Custom Codex executables need thread source attribution for `exec` and
1094
- `app-server` (Codex 0.149.1+). On Windows, use a native `.exe` or `.com`;
1095
- command shims such as `codex.cmd` fall back to the bundled executable.
1096
-
1097
- Python lookup order: `--python` (on `scan`, `bulk-scan`, or `export`) or SDK
1098
- `pythonPath`, then `PYTHON`, the managed Codex runtime, and `python3` or `python`
1099
- on `PATH` (`py` also works on Windows). `CODEX_SECURITY_STATE_DIR` overrides
1100
- `CODEX_HOME` for state storage. Keep state and results outside the repository.
1101
-
1102
- ### Troubleshooting
1103
-
1104
- By default, scans show progress, state transitions, warnings, and summaries.
1105
- Add `--verbose` or set
1106
- `CODEX_SECURITY_LOG_LEVEL=debug` to include lifecycle, configuration, retry,
1107
- and worker diagnostics on stderr. `LOG_LEVEL=debug` is the fallback when
1108
- `CODEX_SECURITY_LOG_LEVEL` is unset or blank.
1109
-
1110
- ```bash
1111
- npx @openai/codex-security scan . --verbose
1112
- ```
1113
-
1114
- Codex Security preserves diagnostic text, including credential-shaped values,
1115
- in CLI output, stored failures, publication receipts, and patch-risk summaries.
1116
- Verbosity controls the amount of diagnostic detail. Native Codex and upstream
1117
- SDK output may already have been redacted before reaching Codex Security.
1118
- Review output and artifacts for sensitive information before sharing them.
348
+ `workers` controls concurrent discovery workers; `subagents` controls delegation
349
+ within each worker. Time and run limits apply to discovery. After discovery
350
+ stops, the scan combines and returns completed findings. See
351
+ [deep scan settings](docs/cli.md#configure-deep-scans) for defaults and saved settings.
1119
352
 
1120
353
  ### Progress and cost
1121
354
 
1122
- Interactive scans show full-screen progress; CI, redirected output, and
1123
- `--headless` use plain status lines. Results go to stdout, progress and
1124
- diagnostics to stderr. Add `--verbose` for diagnostics. Check logs for
1125
- sensitive information before sharing them.
1126
-
1127
- The token summary shows uncached input, cache reads, cache writes, output,
1128
- and total tokens. Total tokens include all input plus output; cache reads and
1129
- writes are subsets of input, not extra tokens. When cache-write usage is missing,
1130
- the summary shows uncached input and cache writes as unavailable.
1131
- The final summary preserves missing-data information from a matching session log.
1132
- If the Codex runtime converts an omitted count to zero before recording it, the
1133
- CLI cannot distinguish that zero from reported usage.
1134
-
1135
- Cost displays show a range using
1136
- [standard API prices](https://developers.openai.com/api/docs/pricing), because
1137
- runtime usage does not identify which requests received long-context pricing.
1138
- The minimum assumes short-context pricing; the maximum assumes long-context
1139
- pricing. These are token-cost estimates for the observed usage, excluding other
1140
- processing tiers, fees, surcharges, and account-specific pricing.
1141
-
1142
- JSON results, scan history, and bulk-scan receipts preserve
1143
- `cost.estimatedUsdRange`: `min`, `max`, and `context: "unknown"`. A `null` maximum
1144
- means an upper estimate is unavailable, including models without verified
1145
- long-context rates. `cost.pricing` records the price source, verification date,
1146
- processing tier, short-context rates, and verified long-context rates when known.
1147
- Models without known short-context prices still have no cost estimate.
1148
- GPT-6 Astra, GPT-6.1 Sol, and GPT-6 Luna have verified standard prices for cost
1149
- estimates and `--max-cost` limits.
1150
-
1151
- For compatibility, `cacheWriteInputTokens` remains the reported token subtotal.
1152
- `cacheWriteInputTokensReported: false` means at least one included usage record
1153
- did not report cache writes. Raw usage uses `cache_write_input_tokens_reported`.
1154
- In that case, the range minimum prices unclassified input as ordinary input,
1155
- and the maximum allows it to be cache writes. Token counts remain unchanged.
1156
- Older saved records remain readable and display a labeled legacy estimate;
1157
- they are not repriced using current rates.
1158
-
1159
- For compatibility, `cost.estimatedUsd` retains the short-context baseline used
1160
- by existing spending limits. `cost.pricing.context: "short"` describes that
1161
- baseline, not observed request contexts. Use `estimatedUsdRange` for cost
1162
- reporting. This change does not change when spending limits stop scans.
1163
-
1164
- `--max-cost USD` stops the scan and its workers when estimated cost exceeds
1165
- the limit, though in-flight requests can finish above it. If deep-scan
1166
- discovery has finished, the scan returns a sealed partial report without more
1167
- model calls and lists unvalidated candidates as follow-up work. Bulk scans
1168
- apply the limit per repository attempt.
1169
-
1170
- With `--max-cost`, automatic finding-history matching makes at most one extra
1171
- model call. If it needs more context, the completed scan is kept and a warning
1172
- directs you to run `scans match --all` explicitly.
1173
-
1174
- For a single scan in the interactive dashboard, reaching 80% of the limit
1175
- offers a higher **total** USD limit. Enter a larger amount to approve it, or
1176
- press Enter with an empty input or Escape to keep the current limit. The scan
1177
- continues running while you decide, and the existing limit remains enforced
1178
- until the increase is saved. Increases keep the same scan and accumulated cost;
1179
- they do not restart work or extend time or discovery limits. CI, JSON/JSONL,
1180
- `--headless`, and `--verbose` scans do not offer budget increases. If usage crosses the limit
1181
- before an increase is approved, the scan still stops.
1182
-
1183
- SDK callers can supply `onBudgetApproaching({ maxCostUsd, cost, signal })` and
1184
- return a higher total limit, or `undefined` to keep the current limit. The
1185
- callback runs once per limit at 80% usage without blocking tracking or
1186
- execution. Its signal aborts when the scan stops or finishes model work; late
1187
- answers are ignored. Invalid increases or failures to save them leave the
1188
- existing limit in place and report a warning. `onCost(cost, maxCostUsd)` reports
1189
- the current limit, including after an approved increase.
1190
-
1191
- These amounts estimate API-equivalent model usage, not ChatGPT subscription
1192
- allowance. Post-scan prompts run after scan cost tracking ends and are outside
1193
- this limit.
1194
-
1195
- ### Bulk scans
1196
-
1197
- Run `gh auth login`, then `npx @openai/codex-security bulk-scan` to select
1198
- GitHub repositories pushed in the last 90 days. Forks and archived repositories
1199
- are excluded; private checkouts use your GitHub CLI sign-in. The command asks
1200
- for an output directory and saves your selection there as `repositories.csv`.
1201
- `--output-dir` requires CSV input.
1202
-
1203
- For CI or an existing repository list, pass a CSV with `id`, `repository`, and
1204
- `revision` (full commit hash). Optional `scope`, `mode`, and `prompt` columns
1205
- customize each scan:
1206
-
1207
- ```csv
1208
- id,repository,revision,scope,mode,prompt
1209
- service,https://github.com/acme/service.git,0123456789abcdef0123456789abcdef01234567,src,standard,Focus on authentication and authorization.
1210
- ```
1211
-
1212
- ```bash
1213
- npx @openai/codex-security bulk-scan repositories.csv \
1214
- --output-dir /path/outside/repositories/security-scans --workers 4
1215
- ```
1216
-
1217
- `--scan-prompt-file PATH` adds instructions to a scan or all bulk scans. Each
1218
- repository's CSV `prompt` follows the shared instructions.
1219
- `-c FILE` shares config with single scans: CSV mode/scope override file defaults,
1220
- and deep settings apply only to deep rows. `output.directory` can supply the
1221
- results directory. `fail_on_severity` returns exit `1` without retrying completed
1222
- scans, including when resuming saved results. A changed project configuration
1223
- requires a new campaign output directory.
1224
- `--post-scan-prompt-file PATH` runs a follow-up in the same authenticated session,
1225
- even after a failed or incomplete scan, but not after cancellation or a
1226
- cost-limit stop.
1227
-
1228
- `--workers` defaults to `4`. `--max-attempts` defaults to `1` attempt per pending
1229
- repository per invocation. Rerunning the command continues the campaign, skips
1230
- completed results, and starts new attempts for pending repositories. If an
1231
- attempt directory is occupied, that repository stops before replacing its
1232
- checkout and the command recommends `--recover`.
1233
-
1234
- #### Recovering failed or interrupted bulk scans
1235
-
1236
- Use the original CSV, output directory, and campaign options with `--recover`:
1237
-
1238
- ```bash
1239
- npx @openai/codex-security bulk-scan repositories.csv \
1240
- --output-dir /path/outside/repositories/security-scans --recover
1241
- ```
1242
-
1243
- Recovery requires an existing campaign with a matching manifest. It skips
1244
- completed results, including partial coverage, and repositories never started.
1245
- For each failed or interrupted repository, it checks the latest attempt:
1246
-
1247
- - A sealed scan is recorded in `results.jsonl` without scanning again.
1248
- - An eligible running Deep Scan resumes its original session, keeping its scan
1249
- ID, completed workers, artifacts, saved settings, and accumulated cost.
1250
- - A failed, canceled, or otherwise unavailable scan starts a new attempt at the
1251
- CSV's pinned revision. Attempt numbers account for both receipts and existing
1252
- directories. Old artifacts and checkouts are preserved; new attempts use
1253
- `recovery-checkouts/<id>/attempt-<n>`.
1254
-
1255
- `--workers` still defaults to `4`; `--max-attempts` defaults to one recovery or
1256
- new attempt per repository. A resume connection failure stops that repository
1257
- for this invocation instead of starting another scan. Other repositories
1258
- continue. Failed and interrupted recovery checkouts remain available for a later
1259
- `--recover`; fresh completed checkouts are removed after recording the result.
1260
- If a reboot interrupted a receipt write, its unfinished tail is saved beside
1261
- `results.jsonl` as `results.jsonl.interrupted-<id>` before appending valid records.
1262
-
1263
- Same-scan resume requires the original checkout, session logs, and Codex Security
1264
- state directory. Recovery does not reconstruct deleted checkpoints or fix the
1265
- underlying cause of execution failures. New attempts incur new scan costs.
1266
- Any remaining failures or partial coverage keep exit code `2`.
1267
- `bulk-scan --help` lists all options.
1268
-
1269
- ### Custom validation
1270
-
1271
- Replace the final validation step of a standard or diff scan with a prompt
1272
- file. Source review still runs; discovery workers do not receive this prompt.
355
+ Use `onProgress` for scan progress and `onCost` for cost updates.
1273
356
 
1274
- ```bash
1275
- npx @openai/codex-security scan . --validation-prompt-file validation.md
1276
- ```
1277
-
1278
- The SDK accepts the same file as `validationPromptFile`, or inline text as
1279
- `validationPrompt`:
357
+ Follow scans with `onWorkerEvent` and `onReconnect`. `onWorkerEvent` reports
358
+ persisted worker sessions discovered by the SDK's existing session tracker,
359
+ independently of model-emitted status markers:
1280
360
 
1281
361
  ```ts
1282
- const result = await security.run(repository, {
1283
- validationPrompt:
1284
- "Run scripts/validate.sh, test each candidate through the local API, and stop the test environment when finished.",
362
+ await security.run(repository, {
363
+ onWorkerEvent(event) {
364
+ console.log(`Worker ${event.worker} observed`);
365
+ },
1285
366
  });
1286
367
  ```
1287
368
 
1288
- Put setup, allowed targets, required evidence, and cleanup in the prompt.
1289
- There are no separate setup or teardown hooks. Use environment variables for
1290
- credentials; keep secrets out of prompts and validation output. Deep scans
1291
- reject this option; scans without candidates skip it.
1292
-
1293
- The SDK supplies the candidate IDs and requires a `CustomValidationResult`:
1294
-
1295
- ```json
1296
- {
1297
- "status": "complete",
1298
- "reason": null,
1299
- "validations": [
1300
- {
1301
- "candidateId": "candidate-1",
1302
- "validation": {
1303
- "disposition": "reportable",
1304
- "method": "integration test",
1305
- "confidence": "high",
1306
- "confidence_rationale": "The test reproduced the reported behavior.",
1307
- "rubric": "Check the protected operation.",
1308
- "evidence": ["The unauthorized request succeeded."],
1309
- "counterevidence_or_proof_gap": "",
1310
- "remaining_uncertainty": "",
1311
- "artifact_paths": []
1312
- },
1313
- "severity": null,
1314
- "impact": null
1315
- }
1316
- ]
1317
- }
1318
- ```
1319
-
1320
- Return one result per candidate with disposition `reportable`, `suppressed`,
1321
- `not_applicable`, or `deferred`. Set `severity` or `impact` to
1322
- `{ "level": "medium", "rationale": "..." }` to revise an assessment, or `null`
1323
- to retain it. Identity and source locations stay unchanged.
1324
-
1325
- The scan saves candidates and results, including suppressed and deferred
1326
- cases, under `artifacts/custom-validation/`. Coverage is incomplete if setup
1327
- fails, output is incomplete or invalid, or any candidate is deferred. An
1328
- incompatible plugin stops the scan; validation never falls back to the default.
1329
- Repeat `--validation-prompt-file` on reruns.
1330
-
1331
- ### Publish findings to Cloud
1332
-
1333
- Choose completed scans from local history:
1334
-
1335
- ```bash
1336
- npx @openai/codex-security publish scan --to cloud --dry-run --json
1337
- ```
1338
-
1339
- Press Space to select scans, then Enter to submit. Nothing is preselected.
1340
-
1341
- For scripts, repeat `--scan` with saved IDs or unique prefixes of at least
1342
- eight characters:
1343
-
1344
- ```bash
1345
- npx @openai/codex-security publish scan \
1346
- --scan SCAN_ID_A --scan SCAN_ID_B \
1347
- --to cloud --dry-run --json
1348
- ```
1349
-
1350
- Find IDs with `scans list --json`, or use `--scan latest` for the current
1351
- repository's latest completed scan. You still need the local sealed artifacts.
1352
-
1353
- `--dry-run` checks inputs and prints findings without logging in or uploading.
1354
- Uploads need ChatGPT credentials saved to a file. Set this in Codex
1355
- `config.toml`, then sign in with ChatGPT again:
1356
-
1357
- ```toml
1358
- cli_auth_credentials_store = "file"
1359
- ```
1360
-
1361
- Cloud publication rejects automatic and keyring storage, even if an
1362
- `auth.json` file exists: the file may be stale or belong to another account.
1363
-
1364
- For CSV input, use an export from `codex-security export --export-format csv`:
1365
-
1366
- ```bash
1367
- npx @openai/codex-security publish scan --to cloud \
1368
- --csv /path/outside/repository/findings.csv
1369
- ```
1370
-
1371
- The [findings CSV template](https://github.com/openai/codex-security/blob/main/examples/findings.csv)
1372
- has the required columns; deep-scan exports may add `candidate_id`. `--csv`
1373
- only supports Cloud and cannot be combined with scan IDs or directories.
1374
-
1375
- For artifacts outside local history, pass a directory or repeat `--scan-dir PATH`.
1376
- Each directory must contain one completed, sealed scan. Bulk-run directories
1377
- and `results.jsonl` files aren't accepted. Don't mix directories with `--scan`.
1378
-
1379
- Multiple scans return:
1380
-
1381
- - `results`: receipts or dry-run previews, each with its `scanId` and `scanDir`.
1382
- - `failed`: errors with `scanDir` and, for saved selections, `scanId`.
1383
- - `notAttempted`: saved scan IDs, or paths for directory inputs, that the command
1384
- did not reach before cancellation.
1385
-
1386
- One scan returns its result directly. Uploads run sequentially. A failed upload
1387
- doesn't stop the rest, but the command exits with `2` if any failed. Cancellation
1388
- stops new requests and returns results so far with `130` (Ctrl-C) or `143`
1389
- (SIGTERM), unless all publications were already confirmed.
1390
-
1391
- Save the output: Cloud receipts aren't stored in scan history. They contain
1392
- Cloud finding IDs in request order, not local IDs. Uploads aren't retried
1393
- automatically. Cloud may have accepted an upload even if its receipt is missing
1394
- or invalid. Check Cloud before retrying; never resend a scan with a confirmed
1395
- receipt.
1396
-
1397
- ### Publish completed scans to Linear
1398
-
1399
- Linear publication accepts one completed scan:
1400
-
1401
- ```bash
1402
- npx @openai/codex-security publish scan --scan SCAN_ID \
1403
- --to linear \
1404
- --linear-team TEAM_ID
1405
- ```
1406
-
1407
- Choose a scan by ID, unique prefix, `latest`, or directory (positional or
1408
- `--scan-dir PATH`). Omit the selector for an interactive picker. Live publication
1409
- and `--skip-existing` require the scan in local history; a directory-based
1410
- `--dry-run` alone does not.
1411
-
1412
- Add `--linear-project PROJECT_ID` (`--project` is an alias) to place issues in
1413
- a project. Destination flags override `CODEX_SECURITY_LINEAR_TEAM` and
1414
- `CODEX_SECURITY_LINEAR_PROJECT`. `--dry-run` previews issue titles without
1415
- contacting Linear; `--json` returns structured results.
1416
-
1417
- Sign in to Codex and connect Linear to publish with your existing Codex
1418
- configuration; publication doesn't use the isolated scan home. To use the
1419
- Linear API directly, set a personal API key:
1420
-
1421
- ```bash
1422
- export CODEX_SECURITY_LINEAR_API_KEY=YOUR_LINEAR_PERSONAL_API_KEY
1423
- npx @openai/codex-security publish scan /path/to/completed-scan \
1424
- --to linear \
1425
- --linear-team TEAM_ID
1426
- ```
1427
-
1428
- Direct API publication leaves issues unassigned unless `--linear-assignee`
1429
- specifies a user ID or email. `--linear-api-key KEY` overrides the environment
1430
- variable, but exposes the key in shell history and process listings. Keys are
1431
- omitted from saved results and artifacts; error messages are returned unchanged.
1432
-
1433
- Check scan integrity and recorded publications before publishing:
1434
-
1435
- ```bash
1436
- npx @openai/codex-security publish check /path/to/completed-scan \
1437
- --to linear --linear-team TEAM_ID --json
1438
- ```
1439
-
1440
- `publish check` is read-only. With an API key it also checks authentication,
1441
- team, project, and assignee access; connected-app access is `not-checked`.
1442
- Issue-creation permission is always `not-tested`.
1443
-
1444
- Each finding becomes an issue titled `[Codex Security][HIGH] Finding title`
1445
- with source locations, code, evidence, and remediation. Choose a destination
1446
- authorized to receive these details. Local history stores successful issue IDs
1447
- separately from sealed scan artifacts.
1448
-
1449
- Republishing creates duplicates by default. `--skip-existing` skips recorded
1450
- successes for the same occurrence, team, and project, without checking remote
1451
- issues. Results distinguish `created` and `skipped` issues. Add `--dry-run`
1452
- to preview the remaining findings.
1453
-
1454
- After an interrupted or indeterminate publication, check the retained handoff,
1455
- evidence, and Linear destination before retrying. Issues may exist without a
1456
- local record. The CLI can't recover those issues, and `--skip-existing` can't
1457
- prevent duplicates from them or concurrent publications.
1458
-
1459
- ```ts
1460
- import { publishScan } from "@openai/codex-security";
1461
-
1462
- const publication = await publishScan("/path/to/completed-scan", {
1463
- destination: "linear",
1464
- teamId: "TEAM_ID",
1465
- });
1466
-
1467
- console.log(publication.scanId);
1468
- console.log(publication.created.length);
1469
- ```
1470
-
1471
- Options include `projectId`, `skipExisting`, `linearApiKey` for direct API
1472
- publication, and `assigneeId` (user ID or email). `checkScanPublication` accepts
1473
- the same destination options for a read-only check.
1474
-
1475
- ### Classify finding severity
1476
-
1477
- Classify findings after a scan or dedupe without repeating discovery or changing
1478
- the original severity, evidence, or sealed scan artifacts:
1479
-
1480
- ```bash
1481
- codex-security classify-severity --scan SCAN_ID --rubric /path/to/policy.md --json
1482
- codex-security classify-severity --scan latest --rubric /path/to/policy.md --json
1483
- codex-security classify-severity --scan-dir /path/to/completed-scan --json
1484
- ```
1485
-
1486
- `--scan` accepts a saved scan ID, unique prefix, or `latest` for the current
1487
- repository, matching `dedupe` and `publish scan`. `--scan-dir` accepts an external
1488
- completed scan without requiring local history. Supply exactly one selector.
1489
- Omitting `--rubric` inherits each finding's existing severity without a model call.
1490
-
1491
- `--rubric PATH` supplies the classification policy. Repeat `--knowledge-base PATH`
1492
- to provide supporting architecture, deployment, or business context. Both accept
1493
- the same UTF-8 text, PDF, DOCX, and directory inputs as scan knowledge bases.
1494
- Rubric classification uses the full supplied report and context in a separate
1495
- read-only Codex turn per finding, without source inspection, tools, or new
1496
- validation. `--model` and `--effort` select the classification model and reasoning
1497
- effort; otherwise Codex's configured model and the helper's medium effort apply.
1498
-
1499
- The result contains one assessment per selected finding:
1500
-
1501
- - `decision`: `assessed` or `excluded`; policy exclusions do not become Low.
1502
- - `level`: `critical`, `high`, `medium`, `low`, or `informational`; null for exclusions.
1503
- - `rubricLabel`: the policy's original label, such as `URGENT`, normalized to
1504
- `critical`; null for inherited severity or exclusions.
1505
- - `rationale`, separate `confidence`, and `reviewTrigger` describing a missing
1506
- fact that would change the classification. Inherited severity has no new
1507
- classification-confidence judgment.
1508
- - `findingId`, `occurrenceId`, and `inputSha256` binding the assessment to the
1509
- report. Top-level metadata includes `assessedAt`, `rubricSha256`, and
1510
- `knowledgeBaseSha256` for the supplied policy and context snapshots.
1511
-
1512
- Scan classification saves each successful finding immediately in the local
1513
- workbench SQLite database. Rerunning skips assessments with matching finding
1514
- evidence, rubric, and knowledge-base hashes, including exclusions, and returns
1515
- both reused and newly generated assessments. Changed inputs are classified again.
1516
- Use `--reprocess` to rerun every selected finding regardless of its saved
1517
- assessment; each row is replaced only after its new assessment succeeds. A failed
1518
- or canceled run keeps completed checkpoints, so a normal retry resumes missing
1519
- work. Changing only the model or effort requires `--reprocess`.
1520
-
1521
- SQLite is authoritative. A successful run also exports the complete selected
1522
- result to `severity-classification.json` alongside the sealed artifacts. The file
1523
- is replaced atomically and is not read for reuse or publication. The scan's
1524
- original findings and severity are unchanged. The database stores the requested
1525
- selection and policy/context hashes; publication rejects an incomplete selection
1526
- or assessments whose inputs no longer match. Rubric documents are read at
1527
- classification time, not again at publication time.
1528
-
1529
- ```bash
1530
- codex-security classify-severity --scan latest --rubric /path/to/policy.md --reprocess
1531
- ```
1532
-
1533
- Use repeatable `--finding-id ID` to classify a selected set, such as the
1534
- `uniqueFindingIds` returned by dedupe. With a saved classification, Linear
1535
- publication defaults to that selection, omits excluded records, and uses assessed
1536
- severity for issue priority and title. The description retains original scan
1537
- severity and adds classification reasoning. Without a saved classification,
1538
- publication retains its existing severity mapping and selection behavior.
1539
- Publication rejects assessments whose IDs or evidence hashes no longer match.
1540
-
1541
- ```bash
1542
- codex-security classify-severity --scan SCAN_ID --rubric /path/to/policy.md \
1543
- --finding-id FINDING_ID --json
1544
- codex-security publish scan --scan SCAN_ID --to linear --linear-team TEAM_ID \
1545
- --dry-run --json
1546
- codex-security publish scan --scan SCAN_ID --to linear --linear-team TEAM_ID \
1547
- --skip-existing --json
1548
- ```
1549
-
1550
- `publish scan --to linear` also accepts repeatable `--finding-id ID` to select a
1551
- subset directly. If a classification exists, every explicitly selected finding
1552
- must have an assessment. Classification does not change existing Linear tickets;
1553
- `--skip-existing` preserves recorded tickets and any human priority edits. It
1554
- retains the existing limitations around unrecorded or concurrent publications.
1555
-
1556
- The SDK exposes the same operations:
1557
-
1558
- ```ts
1559
- import {
1560
- classifySeverity,
1561
- classifyScanSeverity,
1562
- classifyScanDirectorySeverity,
1563
- publishScan,
1564
- } from "@openai/codex-security";
1565
-
1566
- // Supplied reports from any source: returns an assessment without writing files.
1567
- const classification = await classifySeverity(findings, {
1568
- rubricPath: "/path/to/policy.md",
1569
- knowledgeBasePaths: ["/path/to/context.md"],
1570
- });
1571
-
1572
- // Saved IDs (including prefixes/latest), or sealed directories; saves an assessment.
1573
- await classifyScanSeverity("SCAN_ID", { rubricPath: "/path/to/policy.md" });
1574
- await classifyScanDirectorySeverity(scanDirectory, {
1575
- rubricPath: "/path/to/policy.md",
1576
- findingIds: dedupeResult.uniqueFindingIds,
1577
- });
1578
-
1579
- await publishScan(scanDirectory, {
1580
- destination: "linear",
1581
- teamId: "TEAM_ID",
1582
- skipExisting: true,
1583
- });
1584
-
1585
- // Alternatively supply a classification directly, without a saved assessment.
1586
- await publishScan(scanDirectory, {
1587
- destination: "linear",
1588
- teamId: "TEAM_ID",
1589
- classification,
1590
- findingIds: classification.assessments.map(({ findingId }) => findingId),
1591
- dryRun: true,
1592
- });
1593
- ```
1594
-
1595
- `classifySeverity` accepts reports with `findingId`, `title`, and `summary`, plus
1596
- their available evidence and metadata. Original `severity` and `occurrenceId`
1597
- may be absent for imported reports; reports without severity require a rubric.
1598
- `classifySeverity` remains an in-memory operation without database persistence.
1599
- The scan wrappers use the local state database (also for external scan
1600
- directories), accept `reprocess: true`, and accept `findingIds: []` as an
1601
- intentionally empty selection. Rows outside the selected set are retained.
1602
- Use the same `CODEX_SECURITY_STATE_DIR` for classification and publication.
1603
- JSON exports from versions without database checkpoints must be reclassified
1604
- once before they can be reused.
1605
- Pass `signal` to cancel any classification operation. Keep human overrides in the
1606
- calling workflow or issue tracker; assessments remain separate recommendations.
1607
-
1608
- ### Suggest finding owners
1609
-
1610
- Suggest contributors who can fix findings in a local Git repository:
369
+ The callback contains only `{ kind: "observed", worker: number }`. The scan-local
370
+ worker number matches `onActivity` and `onSessionEvent`; no prompts, raw thread
371
+ IDs, or session contents are exposed. Each session is reported once per run,
372
+ including nested workers and scan-associated validation or Deep Scan sessions.
373
+ On resume, already persisted workers can be reported again. Observation ends
374
+ with scan cost tracking, before `postScanPrompt`.
375
+
376
+ This works with the bundled Codex version. Persistence and polling can delay
377
+ notification, and missing notifications do not prove that delegation was skipped.
378
+ An observed session does not establish that a worker just started or that file
379
+ review has begun. The callback does not report failed spawn attempts, phase names,
380
+ or planned counts, and cannot act as a pre-dispatch gate. Use `maxCostUsd` or
381
+ `signal` for cancellation. Observer failures go to `onObserverError` without
382
+ stopping the scan.
383
+
384
+ `onWorkerStatus` remains available for tool-derived preflight status and
385
+ **best-effort** phase dispatch counts from model-emitted text markers. A missing
386
+ dispatch status does not mean delegation was skipped. `onSessionEvent` receives
387
+ saved events with thread IDs and worker numbers and can contain source code or
388
+ credentials. Deep scans additionally expose durable independent-review counts
389
+ through `onDeepProgress`: `completed`, `active`, and `maximum`. The maximum is a
390
+ configured cap, not a percentage denominator. The optional `consolidating` flag
391
+ reports when results are being combined or the coordinator has finished.
392
+ `ScanOptions` lists all callbacks.
1611
393
 
1612
- ```bash
1613
- npx @openai/codex-security suggest-owners findings.json --source-root /path/to/repo --json > owners.json
1614
- ```
394
+ Costs estimate API-equivalent model usage, not your bill or ChatGPT subscription
395
+ allowance. Use `cost.estimatedUsdRange` for reporting. `maxCostUsd` uses the
396
+ short-context estimate; in-flight requests can exceed it. Post-scan prompts run
397
+ outside that limit. Matching earlier findings can also make model calls.
398
+ See [progress and cost](docs/cli.md#progress-and-cost) for accounting and budget callbacks.
1615
399
 
1616
- The input is a Codex Security findings document or a JSON object containing a
1617
- `findings` array, such as the output of `export --export-format json`. The source
1618
- root defaults to the current directory. The command reads committed `HEAD`,
1619
- source around each finding location, blame for the affected lines, and file
1620
- history reachable from that commit. It does not read uncommitted source or change
1621
- findings, files, or ticket assignments.
1622
-
1623
- The checkout must own its Git references and objects. Linked worktrees and bound
1624
- separate Git directories are supported. Checkouts that borrow external object
1625
- stores, including `git clone --shared`, are rejected; use an independent clone.
1626
-
1627
- Each result preserves the finding and occurrence IDs and has status `identified`,
1628
- `abstained`, or `error`. Identified results include an observed Git author name
1629
- and email, a reason, and checked Git citations. Missing source or unclear
1630
- ownership produces an abstention. Git identities do not establish active
1631
- employment or an issue tracker account. Match accounts before assigning tickets.
1632
- Use a checkout that matches the findings; otherwise their line ranges may be stale.
1633
-
1634
- The command uses existing Codex credentials and the Codex Security default model and effort.
1635
- Use `--model` and `--effort` to override them. Model selection runs with tools and
1636
- network access disabled. Exit code `0` includes successful recommendations and
1637
- abstentions; `2` means invalid input or at least one failed recommendation. A
1638
- per-finding failure retains the other results in the report. Cancellation uses
1639
- exit code `130` for SIGINT or `143` for SIGTERM.
1640
-
1641
- The SDK accepts finding IDs, titles, summaries, and source locations directly:
400
+ ### Validate an existing finding
1642
401
 
1643
402
  ```ts
1644
- import { suggestOwners } from "@openai/codex-security";
1645
-
1646
- const owners = await suggestOwners("/path/to/repo", result.findings, {
1647
- reasoningEffort: "high",
403
+ import { writeFile } from "node:fs/promises";
404
+
405
+ const result = await security.validate({
406
+ repositoryPath: "/path/to/repository",
407
+ finding: {
408
+ title: "Possible SQL injection",
409
+ location: "src/query.ts:42",
410
+ },
1648
411
  });
412
+ console.log(result.disposition, result.report);
413
+ await writeFile("/path/to/reports/assessment.md", result.report, "utf8");
1649
414
  ```
1650
415
 
1651
- SDK inputs may include `sourceRevision`. If it differs from `HEAD`, the collector
1652
- ignores the old line ranges and reports the mismatch. Reports record the analyzed
1653
- revision, model, effort, and limitations; they remain separate from scan artifacts.
1654
-
1655
- ### Feedback
1656
-
1657
- Send a problem report to OpenAI and share the returned feedback ID with support:
1658
-
1659
- ```sh
1660
- codex-security feedback --reason "The scan stopped before it finished"
1661
- codex-security feedback SCAN_ID --reason "The scan stopped before it finished" --include-logs
1662
- ```
1663
-
1664
- Without an ID, `feedback` selects the most recently started scan in the current
1665
- repository, including active or failed scans. If there are no saved scans, it sends
1666
- a general report. The report includes your description, version details, and the selected
1667
- scan and session IDs. Add `--json` for structured output.
1668
-
1669
- Logs are off by default. `--include-logs` uploads Codex diagnostics and saved scan
1670
- and worker activity. These can contain source code, prompts, findings, tool
1671
- output, and other sensitive data. Only include logs you can share with OpenAI.
1672
- The command uses Codex's feedback service and respects `feedback.enabled = false`.
1673
-
1674
- For scans started through the Desktop plugin, run the command on the machine
1675
- where the scan ran, using the same Codex home and Codex Security state directory.
1676
- It searches active and archived sessions in both that Codex home and the CLI's
1677
- managed home, and attaches available worker logs even if the parent log is missing.
1678
- Earlier retries that started separate sessions may be missing when their session
1679
- IDs are no longer recorded.
1680
-
1681
- Standard scans run inside an existing Codex conversation attach only the owner's
1682
- saved session; they do not record which subagents belong to the scan. Deep Scans
1683
- and scans launched by `codex-security` also attach their recorded execution
1684
- threads and descendants, without following unrelated children of the owner.
1685
-
1686
- ### Scan history and reruns
1687
-
1688
- Commands default to the current repository. Select scans by full ID or a
1689
- unique prefix of at least eight characters.
1690
-
1691
- New recipes retain resolved settings and the authentication choice, not
1692
- credentials. Reruns do not reload project files; complete saved deep settings do
1693
- not use current legacy defaults. Older partial recipes retain their previous
1694
- fallback behavior. Context paths and the current checkout are not immutable input
1695
- snapshots.
1696
-
1697
- Reruns require replacement scan instructions when the original scan used them.
1698
- New recipes mark this requirement, and `scans rerun` refuses to omit them silently; use
1699
- `scans rerun [SCAN_ID] --scan-prompt-file FILE` to supply a nonempty replacement.
1700
- Replacement files resolve from the invocation directory. Custom validation keeps its existing
1701
- `scans rerun --validation-prompt-file` requirement.
1702
-
1703
- | Command | Purpose |
1704
- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
1705
- | `scans list [REPOSITORY]` | List scans. Filter by artifact root with `--scan-root DIR`. |
1706
- | `scans show [SCAN_ID]` | Show a scan; defaults to the latest completed one. `--show-linked-findings` includes earlier finding links. |
1707
- | `scans logs [SCAN_ID]` | Show session events; defaults to the latest scan, including active scans. |
1708
- | `scans resume SCAN_ID` | Resume an interrupted Deep Scan in its original session and output directory. |
1709
- | `scans rerun [SCAN_ID]` | Repeat a scan on the current checkout; defaults to the latest completed scan. |
1710
- | `scans match BEFORE AFTER` | Link findings with the same root cause. |
1711
- | `scans match --all` | Match completed scans across the repository's worktrees and clones. |
1712
- | `scans compare [BEFORE] [AFTER]` | Compare scans; defaults to the latest two completed scans. |
1713
- | `findings list [REPOSITORY]` | List open findings. `findings` is an alias. |
1714
- | `findings false-positive OCCURRENCE_ID --reason TEXT` | Mark a false positive. Later scans dismiss matches only while the reason applies. |
1715
-
1716
- #### Resuming an interrupted Deep Scan
1717
-
1718
- After the CLI process or host stops unexpectedly, find the scan and rejoin it:
1719
-
1720
- ```bash
1721
- npx @openai/codex-security scans list --scan-root /path/to/security-scans
1722
- npx @openai/codex-security scans resume SCAN_ID
1723
- ```
1724
-
1725
- The scan must still be `running`, with its original checkout, output directory,
1726
- and owning Codex session available in the same Codex Security state directory.
1727
- The checkout's identity, revision, and contents must match the saved target.
1728
- Completed, failed, and canceled scans cannot resume; `scans rerun` starts a new scan.
1729
-
1730
- Resume uses the saved configuration and instructions with the installed plugin.
1731
- New scans save the selected authentication mode, explicit safety identifier, and
1732
- post-scan prompt contents. Resume restores the authentication choice without
1733
- saving credentials. Single-scan resume restores the prompt even if its original
1734
- file changes or disappears.
1735
- Older records that did not save these values cannot reconstruct them. Bulk
1736
- recovery still requires matching campaign inputs and options; it uses the supplied
1737
- post-scan prompt when the scan has no saved prompt.
1738
- It keeps the scan ID, completed workers, artifacts, and accumulated session cost.
1739
- The existing coordinator recovers interrupted workers after its lease expires.
1740
- If discovery finished before the interruption, resume completes and seals the
1741
- same scan. No archiving or new attempt directory is needed. A failed connection
1742
- leaves the existing scan available for another resume attempt.
1743
-
1744
- Compatible saved scans can resume after a plugin update. Already-sealed results
1745
- keep their original producer version and contents when completion is recorded.
1746
- Unsupported or invalid sealed artifacts are rejected before resuming, preserving
1747
- the saved scan state and files.
1748
-
1749
- For bulk campaigns, use [`bulk-scan --recover`](#recovering-failed-or-interrupted-bulk-scans)
1750
- to recover eligible attempts and update `results.jsonl`. Individual `scans resume`
1751
- does not update campaign receipts.
1752
-
1753
- #### Matching saved scans
1754
-
1755
- Matching requires sealed artifacts and reuses saved matches unless you pass
1756
- `--force`. Comparisons classify findings as new, persisting, reopened, resolved,
1757
- or unknown. Missing findings aren't resolved if the later scan is incomplete
1758
- or excludes their original scope. With one ID, `scans compare` compares it
1759
- to the latest completed scan.
1760
-
1761
- Use `scans match --all --force` to rebuild comparisons chronologically while
1762
- retaining stable finding identities. Ctrl-C keeps comparisons already saved.
1763
- Only high-confidence duplicates are grouped; uncertain and independently
1764
- related findings stay separate. Matching preserves triage and sealed artifacts.
1765
-
1766
- Codex runs only for new matching decisions, using existing authentication.
1767
- `scans match` and `scans compare` accept `--model` and `--effort`; the defaults
1768
- are Codex's configured model and `medium` effort. Cached matches are reused
1769
- even when these flags change. To recompute all matches:
1770
-
1771
- ```bash
1772
- npx @openai/codex-security scans match --all --force \
1773
- --model gpt-6.1-sol --effort high
1774
- ```
1775
-
1776
- Scans without sealed artifacts are skipped, but their confirmed links can still
1777
- be reused. Older custom plugins save confirmed and uncertain matches; use the
1778
- bundled plugin for related links and large comparisons.
1779
-
1780
- SDK callers can compare findings without saving a workbench comparison:
1781
-
1782
- ```ts
1783
- import { readFile } from "node:fs/promises";
1784
- import {
1785
- matchScanFindings,
1786
- type FindingsDocument,
1787
- } from "@openai/codex-security";
1788
-
1789
- const before = JSON.parse(
1790
- await readFile("/path/to/earlier-scan/findings.json", "utf8"),
1791
- ) as FindingsDocument;
1792
- const after = JSON.parse(
1793
- await readFile("/path/to/later-scan/findings.json", "utf8"),
1794
- ) as FindingsDocument;
1795
-
1796
- const comparison = await matchScanFindings(
1797
- { before: before.findings, after: after.findings },
1798
- { workingDirectory: "/path/to/repository" },
1799
- );
1800
- console.log(comparison.matches, comparison.uncertain, comparison.related ?? []);
1801
- ```
1802
-
1803
- Pass `knownFindingGroups` to reuse confirmed groups of stable `findingId` values
1804
- from your store. Results identify the original `occurrenceId` values. Options
1805
- include model, reasoning effort, `AbortSignal`, and an optional `onProgress`
1806
- callback whose errors do not interrupt matching.
416
+ Pass finding text or a JSON-serializable object, not a file path. Standalone
417
+ validation uses source evidence in a read-only, offline session. It does not build
418
+ the target, execute application code, run tests or PoCs, or add a scan to history.
419
+ The validator returns the assessment without writing report files. The example
420
+ saves `result.report` in an existing directory. `outputDir` selects the session
421
+ directory, not a report destination. Callers that previously read reports from it
422
+ must save `result.report` instead.
423
+ Callers needing runtime proof must arrange a separate reproduction step. Standard,
424
+ Deep, and diff scan validation keep their existing workflows.
1807
425
 
1808
- History lives in `$CODEX_SECURITY_STATE_DIR/workbench.sqlite3`, or
1809
- `$CODEX_HOME/state/plugins/codex-security/workbench.sqlite3`. The CLI and
1810
- workbench maintain the database and its journal files as the current user.
1811
- Keep state private, writable, and outside the scanned repository.
426
+ The disposition is `reportable`, `suppressed`, `not_applicable`, or `deferred`.
427
+ `reportable` can rely on static analysis; `deferred` means there is insufficient
428
+ evidence. Failed or malformed responses reject the promise. `outputDir`, `auth`,
429
+ and `signal` are also supported.
1812
430
 
1813
- On Windows, an older sandboxed run can leave an invalid credential-home ancestor
1814
- ACL. Preserve that state and its reports, and select a **new**, private
1815
- `CODEX_SECURITY_STATE_DIR` outside both the old state and the repository.
1816
- Sign in again if needed and keep using the new setting; it starts separate scan
1817
- history. Existing ancestor ACLs are not rewritten.
1818
-
1819
- Scan configurations don't store credentials; session logs and live details can
1820
- contain them. Press `d` during a scan for details, then `a` for all sources,
1821
- `m` for the main scan, or `1` through `9` for a worker.
1822
-
1823
- ### Exports and CI
1824
-
1825
- `export` reads saved results without starting Codex or loading credentials.
1826
- It defaults to the current repository's latest completed scan. Select a result
1827
- directory positionally, or use `--scan ID` with a scan ID or unique prefix;
1828
- these source selectors cannot be combined. `--artifact findings` is the default
1829
- and requires sealed results. Findings support `--export-format csv|json|sarif`,
1830
- with `sarif` as the default. Use `--source-root PATH` to add SARIF source-line
1831
- fingerprints.
1832
-
1833
- Standard, Deep, Diff, and policy workflows save threat models with
1834
- their results. They also write `threatmodel.md`; if that file cannot be written,
1835
- the saved model remains available for export. Component and bulk scans keep a
1836
- separate model for each child run. New documents record the model and scan
1837
- scopes and identify provisional or recovered content. Some results have no
1838
- saved model.
1839
-
1840
- Use `--artifact threat-model` to export the retained model as Markdown. The
1841
- format is `md` and the default destination is `./threatmodel.md`. Explicitly
1842
- selected results can expose a saved model before scan completion or after a
1843
- later failure. Policy result directories and historical saved Markdown models
1844
- are also supported. A historical document in a sealed scan must be listed in
1845
- the manifest with a matching digest. A missing model returns an error; export
1846
- does not substitute an older run or generate a new model.
1847
-
1848
- ```bash
1849
- codex-security export --artifact threat-model
1850
- codex-security export --scan SCAN_ID --artifact threat-model --output docs/threatmodel.md
1851
- codex-security export /path/to/policy-results --artifact threat-model --output -
1852
- codex-security scan . --knowledge-base docs/threatmodel.md
1853
- ```
431
+ To validate GitHub code scanning alerts, first import them with
432
+ `importGitHubCodeScanningAlerts()`. See the
433
+ [import guide](docs/cli.md#import-alerts-from-the-cli) for CLI and SDK examples.
1854
434
 
1855
- `--output -` emits only artifact content, with diagnostics on stderr. Markdown
1856
- and CSV stdout cannot be combined with JSON command output. Exporting into a
1857
- repository does not make the document automatic scan input; use the existing
1858
- `--knowledge-base` option when you want to provide it as context.
435
+ ### Generate and verify a patch
1859
436
 
1860
- `ScanResult.threatModel` contains the saved structured model or Markdown.
1861
- `threatModelPath` points to its current document, including supported historical
1862
- filenames. Either can be null. The model remains exportable when the document
1863
- could not be written. Scan JSON and policy results expose these fields. History
1864
- reports model availability, provenance, and the document path without including
1865
- the model body. Policy generation saves its model before drafting `SECURITY.md`,
1866
- so a later drafting failure does not discard it.
1867
-
1868
- SDK scan methods verify model paths before returning them. A manually
1869
- constructed `ScanResult` uses the `threatModelPath` supplied in its options, or
1870
- `null` if omitted.
1871
-
1872
- The SDK offers the same offline export without an authenticated session:
437
+ `patch()` runs the bundled remediation workflow non-interactively against a
438
+ workspace that the caller has intentionally made writable:
1873
439
 
1874
440
  ```ts
1875
- import { exportArtifact } from "@openai/codex-security";
1876
-
1877
- const exported = await exportArtifact({
1878
- source: { directory: "/path/to/scan-results" }, // Or { scanId: "SCAN_ID" }.
1879
- artifact: "threat-model",
1880
- output: "/path/to/threatmodel.md",
1881
- });
1882
- console.log(exported.path, exported.provenance);
1883
- ```
1884
-
1885
- `exportArtifact` also supports findings with `format: "csv" | "json" | "sarif"`.
1886
- For threat-model file exports, returned provenance belongs to the same saved
1887
- snapshot as the exported document. `output: "-"` streams to stdout and returns
1888
- null path/provenance. `pythonPath` selects the helper interpreter and `signal`
1889
- cancels the export. `export --help` lists the CLI options.
1890
-
1891
- JSON preserves the sealed findings document. CSV marks findings as open,
1892
- omits local triage state, and cannot go to stdout when JSON output is requested.
1893
- CSV escapes spreadsheet formula prefixes and literal leading apostrophes with
1894
- an extra apostrophe; import removes that escape. Older CSV exports cannot
1895
- distinguish some literal apostrophes from escapes. Use the JSON export when
1896
- recovering those values from an older scan. Distinct CSV occurrence IDs are
1897
- retained even when their finding IDs match, including when publishing CSV.
1898
-
1899
- For CI, save output outside the checkout and set a severity threshold:
1900
-
1901
- ```bash
1902
- SCAN_ROOT="$(mktemp -d)"
1903
- npx @openai/codex-security scan . \
1904
- --diff origin/main \
1905
- --output-dir "$SCAN_ROOT/results" \
1906
- --json \
1907
- --fail-on-severity high > "$SCAN_ROOT/findings.json"
1908
- ```
1909
-
1910
- Scan exit codes are `0` for a completed report-only scan or passing policy,
1911
- `1` for a policy violation, `2` for invalid input, incomplete coverage, or a
1912
- runtime/export error, `130` for interruption, and `143` for termination.
1913
- JSON scans do not use interactive controls. `validate`, `login`, and `logout`
1914
- reject `--json`.
1915
-
1916
- `install-hook` adds an optional local Git pre-commit check for staged and
1917
- unstaged changes. It's advisory; use a required CI check to enforce a passing
1918
- scan. When Git runs the hook, it blocks commits if the scan can't finish or
1919
- finds an issue at or above the threshold (`high` by default). Set it when
1920
- installing with `--fail-on-severity`. The installer respects `core.hooksPath`
1921
- and leaves custom hooks alone.
1922
-
1923
- We recommend installing the CLI outside the repository and running that copy
1924
- directly. For a global installation:
1925
-
1926
- ```bash
1927
- npm install --global @openai/codex-security
1928
- ```
1929
-
1930
- If the repository also has a local copy, `npx` may run it instead.
1931
-
1932
- Before installing or replacing a hook, run
1933
- `git -C /path/to/repository rev-parse --git-path hooks/pre-commit`. Git may
1934
- return a path relative to `/path/to/repository`. Check the hook, if it exists,
1935
- and the path to its directory for symlinks or shared locations. Leave custom,
1936
- linked, shared, or unverified hooks alone. If they need to change, contact the
1937
- owner or use a required CI check. Check older generated hooks too; the installer
1938
- can update them automatically.
1939
-
1940
- If the hooks directory belongs only to this repository and there is no hook,
1941
- run the global CLI from outside the repository:
1942
-
1943
- ```bash
1944
- codex-security install-hook /path/to/repository
1945
- ```
1946
-
1947
- To migrate a hook, confirm it's a regular file used only by this repository
1948
- and contains only the generated Codex Security command. Keep its severity.
1949
- The installer can update older hooks that invoke `npx` if you use the same
1950
- severity. Newer hooks store absolute paths to Node and the CLI. If either path
1951
- changes, the installer won't replace the hook: back it up, remove it, and rerun
1952
- `codex-security install-hook /path/to/repository` with the same
1953
- `--fail-on-severity` value (default: `high`). If reinstallation fails, restore
1954
- the backup and verify the hook before relying on it.
1955
-
1956
- ### Import alerts from the CLI
1957
-
1958
- `import github OWNER/REPO` reads open code scanning alerts from the default
1959
- branch. Repeat `--github-alert NUMBER` for exact alerts. Filter with
1960
- `--github-state open|closed|dismissed|fixed|all` or select a reference with
1961
- `--github-ref REF`. Authentication follows the
1962
- [SDK import options](#import-github-code-scanning-alerts).
1963
-
1964
- ```bash
1965
- # Import all open alerts, or a selected subset, as complete JSON.
1966
- npx @openai/codex-security import github example/repository --format json \
1967
- > /path/outside/repository/github-alerts.json
1968
- npx @openai/codex-security import github example/repository \
1969
- --github-alert 12 --github-alert 18 --format json
1970
- # Run from the corresponding local repository; imported contents are data.
1971
- npx @openai/codex-security validate /path/outside/repository/github-alerts.json
1972
- ```
1973
-
1974
- Import is read-only and returns an array (`[]` when empty). `--json` aliases
1975
- `--format json`. Save validation inputs without output filters or token limits.
1976
- Use the SDK loop for a disposition per alert.
1977
-
1978
- ### Validate and patch findings
1979
-
1980
- `validate` assesses candidates; `patch` fixes and verifies them. Both accept
1981
- files or literal text and work in the current directory. Pass a saved finding
1982
- or occurrence ID to `patch` to use its original repository.
1983
-
1984
- Add `--validation-prompt-file PATH` to supply custom dynamic validation
1985
- instructions, using the same UTF-8 prompt file format as `scan`. The patch task
1986
- uses these instructions to set up the environment, build or start the application,
1987
- exercise the fix, check legitimate behavior, and clean up. Include the commands,
1988
- authorized targets, expected results, and cleanup steps for your environment.
1989
- The task must report validation evidence or explain which checks failed or could
1990
- not run before claiming the patch is fixed or verified.
1991
-
1992
- ```bash
1993
- npx @openai/codex-security patch OCCURRENCE_ID --validation-prompt-file validation.md
1994
- npx @openai/codex-security patch issues.md --validation-prompt-file validation.md
1995
- ```
1996
-
1997
- The flag works with saved findings, issue text/files, and Linear inputs. Relative
1998
- prompt paths resolve from the directory where you invoke the CLI, including when
1999
- the saved finding belongs to another repository. The file is read once before
2000
- patching; missing, empty, or non-regular files fail before the patch task starts.
2001
- Without the flag, the usual fix-finding verification applies. The flag does not
2002
- change sandbox permissions and cannot be combined with `--resume-pr`.
2003
-
2004
- Add `--assess-patch-risk` to a `patch` command to run the bundled patch-risk
2005
- assessment skill once on the completed patch. The assessment is advisory and
2006
- does not change the patch or its merge state. Human-readable commands print the
2007
- report after the patch results; saved-finding JSON output returns it as
2008
- `patchRisk.report` in the same result object. When combined with `--create-pr`,
2009
- the draft pull request or merge request body includes only the concise Markdown
2010
- summary from the assessment; the validated JSON remains in the command result.
2011
-
2012
- ```bash
2013
- npx @openai/codex-security validate "Possible SQL injection" --effort high
2014
- npx @openai/codex-security patch OCCURRENCE_ID
2015
- npx @openai/codex-security patch --scan SCAN_ID --severity high --json
2016
- npx @openai/codex-security patch --scan SCAN_ID --severity high --create-pr
2017
- npx @openai/codex-security patch --scan SCAN_ID --assess-patch-risk --create-pr
2018
- npx @openai/codex-security patch --linear-issue SEC-123 --assess-patch-risk --create-pr
2019
- ```
2020
-
2021
- `--scan latest` selects the current repository's latest completed scan. Patch
2022
- commands support `--json`, including literal-text and file inputs. Change
2023
- the model with `--model gpt-6.1-sol` or effort with `--effort high`.
2024
- The existing `--codex 'model="..."'` syntax is also supported.
2025
- Each finding gets its own saved Codex desktop task.
2026
-
2027
- Before patching, the CLI runs a command with the task's sandbox policy. If the
2028
- sandbox cannot start, the command exits with a nonzero status and reports
2029
- `SANDBOX_UNAVAILABLE`. JSON errors include `ok: false`. A completed model response
2030
- with no repository changes fails with `NO_PATCH_APPLIED`. Results report `applied`,
2031
- `filesChanged`, and `files`; existing local changes do not count as patch changes.
2032
- These fields report file changes, not proof that the security issue is fixed.
2033
- Saved findings still require a verified result from the patch task.
2034
-
2035
- For a controlled container that provides its own isolation, explicitly opt in:
2036
-
2037
- ```bash
2038
- npx @openai/codex-security patch "Security issue" --external-sandbox --json
2039
- ```
2040
-
2041
- `--external-sandbox` defaults to false. It uses Codex's external-sandbox policy
2042
- and prints a warning: Codex does not enforce filesystem or network isolation for
2043
- the patch task. The container must enforce those boundaries. The CLI never
2044
- falls back to this mode automatically. Optional patch-risk assessment still uses
2045
- its read-only Codex sandbox.
2046
-
2047
- `scan --patch` patches after a complete scan. `--patch-severity` defaults to
2048
- `low`; `high` selects high and critical findings. Use the interactive browser
2049
- to select findings and add patch instructions. Results include a `patches`
2050
- entry per finding with status `verified`, `no_change`, `blocked`, or `failed`.
2051
- Verified and already-fixed findings no longer fail `--fail-on-severity`.
2052
- Patching shows each finding's position, elapsed time, and live Codex activity.
2053
- Progress goes to stderr; completed results stay in the terminal history.
2054
-
2055
- `--create-pr` commits generated patch files and opens a draft GitHub pull request
2056
- with `gh` or a draft GitLab merge request with `glab`. Install and authenticate
2057
- the appropriate CLI first (`gh auth login` or `glab auth login`). GitLab.com is
2058
- selected from the `origin` push URL, including SSH URLs and subgroup projects.
2059
- For self-hosted GitLab, set `GITLAB_HOST` to the host in that URL and authenticate
2060
- with `glab auth login --hostname HOST`. The existing `GITLAB_URI` and `GL_HOST`
2061
- aliases are also accepted, in that order after `GITLAB_HOST`. Other hosts retain
2062
- the GitHub workflow.
441
+ const security = new CodexSecurity();
442
+ try {
443
+ const result = await security.patch({
444
+ repositoryPath: "/path/to/disposable/workspace",
445
+ finding: {
446
+ title: "Possible SQL injection",
447
+ summary: "User input reaches a raw SQL query.",
448
+ locations: [{ path: "src/query.ts", startLine: 42 }],
449
+ },
450
+ signal,
451
+ onActivity(activity) {
452
+ console.log(activity.description);
453
+ },
454
+ onCost(cost) {
455
+ console.log(cost.estimatedUsd);
456
+ },
457
+ });
2063
458
 
2064
- ```bash
2065
- GITLAB_HOST=gitlab.example.com npx @openai/codex-security patch --scan SCAN_ID --create-pr
459
+ switch (result.status) {
460
+ case "verified":
461
+ case "no_change":
462
+ console.log(result.verificationReport);
463
+ break;
464
+ case "blocked":
465
+ case "failed":
466
+ console.error(result.reason);
467
+ break;
468
+ }
469
+ } finally {
470
+ await security.close();
471
+ }
2066
472
  ```
2067
473
 
2068
- Both providers use the existing `pullRequest: { branch, url }` JSON result.
2069
- Supplied-issue requests require a clean working tree before patching so
2070
- existing work is never included. If publication fails, run the printed
2071
- `patch --resume-pr BRANCH` command in the same repository. It reuses the saved
2072
- commit without rerunning Codex, but refuses to publish if the branch changed.
2073
- Use the same GitLab host setting when resuming a self-hosted merge request.
2074
-
2075
- To patch Linear issues, repeat `--linear-issue ISSUE` (ID or URL), or use
2076
- `--linear-project "PROJECT"` with an optional native JSON `--linear-filter`.
2077
- Completed and canceled issues are excluded unless the filter sets `state`.
2078
- Use `CODEX_SECURITY_LINEAR_API_KEY` or `LINEAR_API_KEY` for an API key, or
2079
- `LINEAR_ACCESS_TOKEN` for OAuth. `--linear-api-key KEY` overrides these; prefer
2080
- environment variables to keep keys out of shell history. Intake is read-only,
2081
- includes comments, and keeps Linear credentials out of the patch subprocess.
2082
- Issue URLs must match the selected workspace.
2083
-
2084
- ### Verify fixes
2085
-
2086
- `verify-fix` checks fixes in a read-only sandbox. Pass a description, saved
2087
- finding ID, `--scan SCAN_ID`, `--linear-issue ISSUE`, or `--linear-project "PROJECT"`.
2088
- Linear credentials and filters work as for `patch`. To check a finished backlog,
2089
- explicitly filter for completed issues.
2090
-
2091
- Results include evidence and a status: `fixed`, `still_vulnerable`, or
2092
- `inconclusive`. Use `--json` for structured output. Exit codes are `0` if all
2093
- findings are fixed, `1` if any remain vulnerable, and `2` if verification is
2094
- inconclusive or couldn't finish.
2095
-
2096
- ### Command discovery and integrations
2097
-
2098
- The CLI uses [Incur](https://github.com/wevm/incur). Use `--llms` for the
2099
- command manifest, `scan --schema --format json` for a command schema, and
2100
- `completions bash|zsh|fish` for shell completions. Scan output supports
2101
- `--format toon|json|yaml|jsonl` and `--full-output`.
474
+ Pass literal finding text or a JSON-serializable object; strings are never read
475
+ as file paths. Sandboxed patch commands may edit only `repositoryPath` and run
476
+ without network access or web search. Patch workspaces are always treated as
477
+ untrusted Codex projects, so repository-local Codex configuration and MCP
478
+ servers are not loaded. Host-configured tools retain their host permissions.
479
+ The method does not create a commit, push, open a pull request, publish findings,
480
+ change remote finding state, or add a scan to history.
481
+ Callers remain responsible for reviewing and deriving the authoritative diff,
482
+ approval, commit creation, and delivery.
483
+
484
+ The discriminated result reports `verified`, `no_change`, `blocked`, or
485
+ `failed`, plus repository-relative `changedFiles`, `threadId`, and estimated
486
+ `cost` when model pricing and usage are available. Verified and no-change
487
+ results include `verificationReport`; blocked and failed results include
488
+ `reason`. Transport, authentication, cancellation, incomplete turns, and
489
+ malformed results reject the promise. Failed, blocked, or interrupted operations
490
+ can leave partial workspace changes for the caller to inspect or discard.
491
+
492
+ `changedFiles` is model-reported metadata, not the authoritative diff.
493
+ Patch-risk assessment is not included in this API.
494
+
495
+ Patch operations reuse constructor configuration and credentials. Pass `auth`,
496
+ `safetyIdentifier`, `model`, or `reasoningEffort` for per-call selection.
497
+ `onActivity`, `onSessionEvent`, `onCost`, `onReconnect`, `onAuthentication`,
498
+ `onWarning`, and `onObserverError` use the same observer contracts as scans.
2102
499
 
2103
- `skills add` syncs agent skills; `mcp add` registers the CLI as an MCP server.
2104
- MCP exposes only the read-only `info` command because the transport cannot
2105
- cancel active scans.
2106
-
2107
- ## Findings service (preview)
2108
-
2109
- The findings API uses the same `ghcr.io/openai/codex-security` image as the
2110
- scanner, for Linux `amd64` and `arm64`. `compose.findings.yaml` starts the API
2111
- in a separate container with its own state volume and server configuration.
2112
- Once a release is published, it can be pulled without a GitHub login. See
2113
- [container release setup](../../docker/README.md) for the required maintainer
2114
- setup and publication process.
500
+ ## CLI
2115
501
 
2116
- From the repository root, copy the example if you do not already have a `.env`:
502
+ After [installing the CLI](#install-the-cli), sign in if needed:
2117
503
 
2118
504
  ```bash
2119
- cp .env.example .env
505
+ cs login
2120
506
  ```
2121
507
 
2122
- Set `OPENAI_API_KEY` in `.env`, then pull and start the findings API:
508
+ From your repository, optionally [draft a `SECURITY.md`](#generate-a-security-policy)
509
+ that explains what counts as a security issue in your project:
2123
510
 
2124
511
  ```bash
2125
- docker compose -f compose.findings.yaml pull
2126
- docker compose -f compose.findings.yaml up --no-build -d
2127
- curl -i http://127.0.0.1:3000/v1/findings
512
+ cs policy .
2128
513
  ```
2129
514
 
2130
- You can deploy with just `compose.findings.yaml` and a private `.env`; no source
2131
- checkout or Node.js installation is required. `CODEX_SECURITY_FINDINGS_IMAGE`
2132
- defaults to `ghcr.io/openai/codex-security:latest`. Set it to a published
2133
- version, `sha-<commit>` tag, or digest for repeatable deployments.
515
+ The draft is saved outside your repository. Review the diff and notes, edit the
516
+ draft, then copy only `SECURITY.md` to the **Policy target** shown. Skip this step
517
+ to keep your current policy or scan without one.
2134
518
 
2135
- To build from a source checkout, first prepare the
2136
- [universal native payload](../../plugins/codex-security/native/README.md#package-inputs)
2137
- for that checkout. Then run from the repository root:
519
+ Then scan the repository:
2138
520
 
2139
521
  ```bash
2140
- docker build --target scanner -t codex-security:local .
2141
- export CODEX_SECURITY_FINDINGS_IMAGE=codex-security:local
2142
- docker compose -f compose.findings.yaml up --no-build -d
522
+ cs scan .
2143
523
  ```
2144
524
 
2145
- For an existing deployment using the separate findings image or
2146
- `--target findings-service`, follow the [single-image migration guide](../../docker/README.md#migrating-the-findings-service).
2147
-
2148
- ### Read-only dashboard
2149
-
2150
- Open `http://localhost:3000/dashboard` on the running findings service. The UI
2151
- uses the public OpenAI Apps SDK UI design system, follows the browser's light
2152
- or dark preference, and polls the service every five seconds. It never starts,
2153
- cancels, resumes, publishes, edits, or deduplicates anything.
2154
-
2155
- The dashboard opens on Findings, followed by Duplicate groups. Both views
2156
- support search, repository filtering, sorting, pagination, and record details.
2157
- Click any column header to sort all matching records; click it again to reverse
2158
- the order. The arrow marks the active column and direction. Changing the sort
2159
- returns to the first page, and automatic refreshes keep the selected order.
2160
- By default, findings sort by last update descending, then severity descending,
2161
- then ID ascending to break ties. Groups sort by last update descending and ID
2162
- ascending.
2163
- Findings show stored content and links to their duplicate groups. Groups link
2164
- back to their member findings, preserving separate overlapping groups and the
2165
- original finding records.
2166
-
2167
- The dashboard reads only findings, repository associations, and duplicate groups
2168
- stored in the service's configured database. It does not display scans or
2169
- workflows: publication sends findings, not remote scan or workflow history. It
2170
- does not read report or source paths from stored records. The UI retains the last
2171
- successful data on a refresh failure and shows a connection warning until polling
2172
- succeeds.
2173
-
2174
- `GET /v1/dashboard` returns a consistent read snapshot with overview counts,
2175
- repository choices, a page of records, and optional selected-record details:
2176
-
2177
- - `view`: `findings` (default) or `groups`.
2178
- - `query`, `repository`: optional search text and exact repository ID.
2179
- - `sort`: `activity` (default; last update), `newest` (created), `title`,
2180
- `repository`, `severity` (findings only), or `members` (groups only).
2181
- - `direction`: `asc` or `desc` (default). Text sorts alphabetically without
2182
- case sensitivity, severity by level, and member counts numerically.
2183
- - `limit`, `offset`: existing pagination conventions, defaulting to 50 and 0.
2184
- - `id`: optional exact record ID to include in `detail`; unknown IDs return
2185
- `detail: null` without hiding the list.
2186
-
2187
- Overview counts are service-wide, not filtered page totals. Responses and UI
2188
- assets are served by the same Node process; no separate frontend server, CDN,
2189
- model credentials, or new CLI flags are needed to view the dashboard. Compiled
2190
- HTML, JavaScript, and CSS are included in the npm package and container. Frontend
2191
- source, build tools, and tests are not shipped as runtime dependencies.
2192
-
2193
- The existing preview access boundary is unchanged. The dashboard contains
2194
- sensitive finding content: keep the service on a trusted local endpoint or behind
2195
- an authenticated proxy. It does not add authentication or broaden the default
2196
- network binding.
2197
-
2198
- ### API
2199
-
2200
- Mutation requests to `POST /v1/bulk/findings` and `POST /v1/dedupe-groups` require
2201
- `Content-Type: application/json`; charset parameters are accepted. Other media
2202
- types, including a missing content type, return HTTP 400 `invalid_request`
2203
- before embedding or storage. The API remains unauthenticated and requires an
2204
- authenticated TLS proxy before sharing access.
2205
-
2206
- `POST /v1/bulk/findings` accepts `{"findings": [...]}`, using the existing SDK
2207
- `Finding` model, including `findingId`, `occurrenceId`, and `fingerprints`.
2208
- A complete exported `findings.json` document is also accepted; only its
2209
- `findings` array is imported. No files or source paths referenced by the
2210
- findings are opened. Only the supplied JSON is processed.
2211
-
2212
- Include `repositoryId` alongside `findings` to associate every imported finding
2213
- with a repository. For SDK/CLI scans, use `scan.target.targetId` from the sealed
2214
- `scan-manifest.json`. IDs are matched exactly; the service does not infer a
2215
- repository from titles, paths, or URLs. Reimports add associations without
2216
- removing earlier ones, so a finding can belong to more than one repository.
2217
- Imports without this metadata remain accepted, but unassociated findings are
2218
- only available to explicit all-repository retrieval until imported with an ID.
2219
-
2220
- | Method | Path | Response |
2221
- | ------ | --------------------------------------- | ----------------------------------------------------------------------------------- |
2222
- | `POST` | `/v1/bulk/findings` | HTTP 201 with an array of stored finding IDs, in request order |
2223
- | `GET` | `/v1/findings?limit=50&offset=0` | HTTP 200 with a page of complete findings |
2224
- | `GET` | `/v1/finding/{id}/potential-duplicates` | HTTP 200 with the stored finding and up to 50 potential duplicates, without vectors |
2225
- | `POST` | `/v1/dedupe-groups` | HTTP 201 with the persisted duplicate groups |
2226
- | `GET` | `/v1/finding/{id}/dedupe-groups` | HTTP 200 with every stored group containing this finding |
2227
-
2228
- Bulk insertion generates embeddings and then writes the findings and vectors
2229
- in one SQLite transaction. If embedding generation fails or a finding identity
2230
- conflicts with another stored identity, no part of the batch is written.
2231
- Reusing a `findingId` updates that finding and replaces its embedding; retries
2232
- do not create extra rows. An existing ID's fingerprint, rule, and identity
2233
- anchor/instance cannot be replaced. Repeated IDs in one request are applied in order,
2234
- with the last supplied record retained. Stored scan occurrences are unchanged.
2235
-
2236
- For example, add `repositoryId` to a copy of an exported findings document
2237
- saved as `findings-import.json` (leave the sealed scan artifacts unchanged),
2238
- then import it with the API key configured before starting Compose:
525
+ To narrow the scan scope or check the configuration before scanning:
2239
526
 
2240
527
  ```bash
2241
- curl http://127.0.0.1:3000/v1/bulk/findings \
2242
- -H 'Content-Type: application/json' \
2243
- --data-binary @findings-import.json
2244
- ```
2245
-
2246
- ```json
2247
- ["csf_852f90d6e1177502ff113d4a"]
2248
- ```
2249
-
2250
- The potential-duplicates response contains `finding` (the complete stored
2251
- anchor) and `potentialDuplicates` (an array of complete `Finding` records).
2252
- Neither includes embedding vectors. The anchor is not repeated in the array.
2253
- Specify one scope explicitly on the request:
2254
-
2255
- ```text
2256
- GET /v1/finding/{id}/potential-duplicates?repositoryId=target_sha256_example
2257
- GET /v1/finding/{id}/potential-duplicates?allRepositories=true
528
+ cs scan . --path src --path tests
529
+ cs scan . --diff origin/main --json
530
+ cs scan . --dry-run
2258
531
  ```
2259
532
 
2260
- Repository scope requires the anchor and each candidate to be associated with
2261
- that repository. All-repository scope includes tagged and untagged findings.
2262
- Omitting scope or combining a repository with `allRepositories=true` returns
2263
- HTTP 400. Scope selects candidates; it is not an authorization boundary.
533
+ Use `--help` to find commands and `<command> --help` for options. Scans are
534
+ report-only by default. Add `--fail-on-severity high` to return exit code `1`
535
+ for high or critical findings; execution and required-output failures return `2`.
536
+ Scope exclusions and follow-up notes do not change a completed scan's exit code.
2264
537
 
2265
- Candidates have cosine similarity at least 0.55 and the same embedding model
2266
- and dimensions as the anchor. They are ordered by descending similarity, with
2267
- ties resolved by insertion time and finding ID, and limited to 50. Each request
2268
- reads a current snapshot; separate requests do not share a database snapshot.
2269
- SQLite first filters repository associations, reads only IDs and embedding
2270
- vectors (plus the anchor's model), and performs exact cosine ranking. It then
2271
- loads complete documents only for the anchor and the selected top 50 candidates,
2272
- all within the same read transaction.
2273
- The API does not run Codex or decide whether candidates are duplicates.
538
+ The [CLI reference](docs/cli.md) covers scan history, reruns, bulk and component
539
+ scans, custom validation, imports, patching, and integrations.
2274
540
 
2275
- ### Publishing to a custom findings service
541
+ ### Generate a security policy
2276
542
 
2277
- Publish a completed scan directly from the local CLI to the Docker service:
543
+ Use `policy` to draft a new `SECURITY.md` or update an existing one. To select a
544
+ component:
2278
545
 
2279
546
  ```bash
2280
- codex-security publish scan --scan SCAN_ID --to custom \
2281
- --findings-url http://localhost:3000 --json
2282
- ```
2283
-
2284
- `--findings-url` is required for `--to custom`, with no default. It is the
2285
- service base URL, including `http://` or `https://`; the client appends
2286
- `/v1/bulk/findings`, preserving any base path. A different endpoint must
2287
- implement that API and return the stored finding IDs. The command sends the
2288
- complete sealed findings and their manifest's `scan.target.targetId` as
2289
- `repositoryId`, without changing scan artifacts or forwarding model credentials.
2290
- The service creates embeddings and commits the batch before acknowledging it.
2291
-
2292
- The existing saved-scan selector, external `--scan-dir`, and interactive picker
2293
- work with custom publication. Custom publication accepts one scan, not CSV
2294
- input or Linear options. Add `--dry-run` to validate and preview the payload
2295
- without making an HTTP request. Existing Linear and Cloud destinations are
2296
- unchanged. Upload failures and incomplete receipts fail the command; uploads
2297
- are not automatically retried because a lost response may have been committed.
2298
-
2299
- ```typescript
2300
- import { publishScanToCustom } from "@openai/codex-security";
2301
-
2302
- const receipt = await publishScanToCustom("/path/to/completed-scan", {
2303
- findingsUrl: "http://localhost:3000",
2304
- // dryRun: true,
2305
- // signal: controller.signal,
2306
- });
2307
- console.log(receipt.repositoryId, receipt.findingIds);
2308
- ```
2309
-
2310
- ### Deduplication from the SDK and CLI
2311
-
2312
- Publish the scan with `--to custom` (or import it through the bulk API with its
2313
- `repositoryId`) before deduplicating. The
2314
- workflow reads a completed saved scan, queries candidates by finding ID, and
2315
- runs Luna and Sol in the calling SDK/CLI process. Once all reviews finish,
2316
- it posts accepted groups to the service. It does not re-upload findings or
2317
- change scan artifacts.
2318
-
2319
- ```bash
2320
- codex-security dedupe --scan SCAN_ID --findings-url http://127.0.0.1:3000 --json
2321
- ```
2322
-
2323
- Deduplication runs up to 8 jobs concurrently by default. Set `--concurrency N`
2324
- to choose a positive integer, or `--concurrency 1` for serial execution. The SDK
2325
- equivalent is `concurrency: N`. Candidate neighborhoods are fetched first, with
2326
- the same concurrency limit. Luna screenings and ready Sol pair reviews then use
2327
- two queues sharing one worker pool, with at most 8 jobs running in total by
2328
- default. Each available worker takes a ready job as soon as its current job
2329
- finishes; it does not wait for a batch to finish.
2330
-
2331
- A Sol pair review becomes ready once every Luna screening covering that pair
2332
- has finished and none voted `DISTINCT`. It can run while unrelated Luna
2333
- screenings continue. Results are combined in input order so completion timing
2334
- does not change the groups.
2335
-
2336
- An explicit model refusal keeps the affected pairs separate and allows unrelated
2337
- reviews to continue. It is recorded as `NO_DECISION`, not a reviewed `DISTINCT`
2338
- verdict. A screening refusal applies to every anchor/candidate pair in that
2339
- screening; a pair-review refusal applies only to its assigned pair. Neither pair
2340
- can be merged indirectly through other findings. Recognized policy errors and
2341
- explicit refusal responses are not retried or sent to another model.
2342
-
2343
- If another kind of job fails after its retries, queued jobs stop and already running jobs
2344
- finish before the command reports the failure. No groups are posted from an
2345
- incomplete review. To retain completed reviews across runs, use a
2346
- `--workflow-id` as described below.
2347
-
2348
- The default scope is the saved scan's repository, identified by
2349
- `scan.target.targetId` in its manifest. Add `--all-repositories` to search the
2350
- entire stored corpus explicitly; the flag defaults to false. The SDK has the
2351
- equivalent optional `allRepositories: true` setting. This narrows the previous
2352
- preview's implicit all-repository behavior.
2353
-
2354
- Provide `--findings-url` and either `--scan` or `--workflow-id`, with no implicit
2355
- scan or service URL. As with `publish scan --scan`, the scan selector accepts a full ID, unique
2356
- prefix, or `latest` for the current repository. The saved scan must be complete
2357
- and its sealed artifacts must be available.
2358
-
2359
- ```typescript
2360
- import { deduplicateScan } from "@openai/codex-security";
2361
-
2362
- const result = await deduplicateScan("scan_example_001", {
2363
- findingsUrl: "http://127.0.0.1:3000",
2364
- // concurrency: 8, // Shared worker limit for Luna and Sol; use 1 for serial.
2365
- // allRepositories: true, // Omit to search only this scan's repository.
2366
- // signal: controller.signal,
2367
- });
2368
- console.log(result.duplicateGroups);
2369
- ```
2370
-
2371
- For a complete, sealed scan directory that is not registered in local scan
2372
- history, provide the repository checkout separately:
2373
-
2374
- ```typescript
2375
- import { deduplicateScanDirectory } from "@openai/codex-security";
2376
-
2377
- const result = await deduplicateScanDirectory("/path/to/completed-scan", {
2378
- repository: "/path/to/repository",
2379
- findingsUrl: "http://127.0.0.1:3000",
2380
- // concurrency: 8,
2381
- // expectedScanId: "scan_example_001",
2382
- // allRepositories: true,
2383
- // signal: controller.signal,
2384
- });
2385
- console.log(result.duplicateGroups);
2386
- ```
2387
-
2388
- The CLI and SDK return the same result:
2389
-
2390
- ```json
2391
- {
2392
- "scanId": "scan_example_001",
2393
- "uniqueFindingIds": ["csf_852f90d6e1177502ff113d4a"],
2394
- "duplicateGroups": [],
2395
- "deduplicationStatus": "completed"
2396
- }
547
+ cs policy . --path services/api
2397
548
  ```
2398
549
 
2399
- `uniqueFindingIds` contains one representative for each selected finding after
2400
- accepted duplicate groups are collapsed. A representative can be an existing
2401
- stored finding outside the scan. Each `duplicateGroups` entry contains all
2402
- members of an accepted group, with its canonical finding first. The canonical
2403
- has the highest reported severity; ties use finding ID. Results do not delete,
2404
- merge, or change stored finding documents. Accepted groups are saved as durable
2405
- associations in the service before `deduplicationStatus` becomes `completed`.
2406
-
2407
- When any review is refused, the result instead has
2408
- `deduplicationStatus: "completed_with_refusals"` and a `refusals` array. Each
2409
- entry contains `decision: "NO_DECISION"`, `stage`, `model`, `findingIds`, and
2410
- `reason`. For screening, the first finding ID is the anchor and the remaining
2411
- IDs are its candidates. The CLI logs each refusal to stderr and exits
2412
- successfully after saving the accepted groups. SDK callers can inspect and log
2413
- the same structured entries. Findings retained because of a refusal are not
2414
- confirmed unique. Successful runs without refusals keep their existing output
2415
- shape. No command, flag, or default changes are required.
2416
-
2417
- This behavior applies to post-scan Luna/Sol deduplication. Deep Scan's internal
2418
- reducer uses a separate workflow.
2419
-
2420
- ### Host-provided records deduplication
2421
-
2422
- `codex-security dedupe --records` accepts a versioned JSON-RPC run over stdin
2423
- and emits serial `review.run` requests on stdout for a host-provided model
2424
- backend. It requires no saved scan or Findings API and performs no local model
2425
- execution or persistence. The SDK exposes `deduplicateRecords(input,
2426
- { reviewRunner, signal })`. The input contains original observations and explicit candidate links. Results
2427
- contain groups of observation IDs and unresolved observations.
2428
-
2429
- See the [records protocol and Python fake-host example](docs/dedupe-records.md)
2430
- for the complete input, review contract, cancellation, and persistence rules.
2431
-
2432
- ### Stored duplicate groups
2433
-
2434
- `POST /v1/dedupe-groups` accepts a batch of explicitly reviewed member sets:
2435
-
2436
- ```json
2437
- {
2438
- "groups": [
2439
- ["csf_000000000000000000000001", "csf_000000000000000000000002"],
2440
- ["csf_000000000000000000000002", "csf_000000000000000000000003"]
2441
- ]
2442
- }
2443
- ```
550
+ Existing files stay unchanged until you review and copy the draft to the
551
+ **Policy target** shown. Scans already use root and component policies; you can
552
+ keep them without generating new ones.
2444
553
 
2445
- Each group must contain at least two distinct, existing finding IDs. The entire
2446
- batch is committed in one transaction; a missing finding returns HTTP 409 and
2447
- writes none of the batch. A response contains `groupId`, `findingIds`, and
2448
- `createdAt` for each group. Group identity depends on membership, not member
2449
- order, so submitting the same set again returns its original ID and timestamp.
2450
-
2451
- SQLite stores groups in `finding_dedupe_groups` and memberships in
2452
- `finding_dedupe_group_members`. A finding may belong to multiple groups:
2453
- `[A, B]`, `[B, C]`, and `[C, A]` are three separate reviewed sets. Overlapping
2454
- groups are not automatically united or promoted into an unreviewed larger
2455
- group. Stored members are sorted by ID; their order does not designate a
2456
- canonical. The CLI result retains its existing canonical-first ordering.
2457
-
2458
- `GET /v1/finding/{id}/dedupe-groups` returns every group containing that finding,
2459
- including each group's full membership, or `[]` if it has no groups. These
2460
- associations do not rewrite original findings, fingerprints, scan artifacts,
2461
- embeddings, or external tickets. They do not require an embedding API key or
2462
- trigger model calls. Review-generated merged findings remain review outputs;
2463
- they do not replace stored documents.
2464
-
2465
- ### Resuming a local findings workflow
2466
-
2467
- Add `--workflow-id` to opt into durable state shared by `scan`, `publish scan
2468
- --to custom`, and `dedupe`. The SDK equivalents are the optional `workflowId`
2469
- fields on `ScanOptions`, `PublishScanToCustomOptions`, and `DeduplicateScanOptions`.
2470
- Without a workflow ID, existing command behavior and output shapes are unchanged.
554
+ The SDK provides `generatePolicy()`, `preflightPolicy()`, and `previewPolicy()`. See
555
+ [policy generation](docs/cli.md#generate-a-security-policy) for SDK examples,
556
+ policy locations and reporting instructions, headless use, and saved artifacts.
2471
557
 
2472
- ```bash
2473
- codex-security scan /path/to/repository --workflow-id run-001
2474
- codex-security publish scan --workflow-id run-001 --to custom --findings-url http://localhost:3000
2475
- codex-security dedupe --workflow-id run-001 --findings-url http://localhost:3000 --json
2476
- ```
2477
-
2478
- Repeat this sequence with the same ID after a process stops. Completed scans and
2479
- acknowledged publications are reused; unfinished stages run again. If the scan
2480
- completed before the workflow recorded its receipt, recovery verifies the saved
2481
- scan and its sealed artifacts instead of scanning again. Scan IDs and artifact
2482
- locations are recorded in the scan-registration transaction. This resumes between
2483
- completed steps; it does not resume individual model turns inside an unfinished
2484
- scan. Existing output-directory and archive safeguards still apply to scan retries.
2485
-
2486
- Publication and dedupe can use the workflow ID in place of `--scan`; an explicit
2487
- scan selector must identify that same scan. A workflow can also begin at custom
2488
- publication of a completed scan. The CLI and `deduplicateScan` require local scan
2489
- history to locate the approved source checkout; `deduplicateScanDirectory` uses
2490
- the supplied repository. For a workflow, dedupe first completes publication
2491
- if its receipt is missing. `--all-repositories` retains its existing default of
2492
- false. Changing a workflow's scan, destination, or bound scope is an error: choose
2493
- a different workflow ID. Use one coordinating process per workflow.
2494
-
2495
- Workflow metadata, stage statuses, errors, publication receipts, and results live
2496
- in the local workbench SQLite database under `CODEX_SECURITY_STATE_DIR`, outside
2497
- the sealed scan artifacts. Identity, scan/artifact references, destination, scope,
2498
- hashes, stage statuses, and errors use explicit columns; only receipts and result
2499
- payloads use JSON. Review source, scope, model settings, and contract/hash bindings
2500
- also use columns; review results remain JSON. Existing workflows and checkpoints
2501
- are migrated atomically in place without changing their review keys.
2502
- Successful empty results are stored as completed
2503
- results, not treated as missing work. An empty scan can complete workflow
2504
- publication with an empty receipt. Dry-run never advances a workflow stage.
2505
-
2506
- A completed `dedupe --workflow-id` returns its saved result without repeating
2507
- reviews or group writes. A publication whose acknowledgement was lost is retried
2508
- using the service's existing idempotent upsert.
2509
-
2510
- Concurrent jobs save their validated reviews independently. Resuming with the
2511
- same workflow ID reuses completed reviews and retries unfinished jobs. The
2512
- concurrency setting is not part of a review's checkpoint identity, so it is safe
2513
- to change `--concurrency` when resuming. Cancellation stops active reviews and
2514
- leaves their completed checkpoints available for the next run.
2515
-
2516
- Each validated screening and pair review is checkpointed locally,
2517
- including DISTINCT decisions. Screening checkpoints retain pair recommendations
2518
- and rationales under host-assigned pair slots bound to the original records.
2519
- Every SAME pair-review checkpoint retains its
2520
- required `canonicalFindingId` and generated `mergedFinding`; the merged record
2521
- must satisfy the Finding schema and preserve the canonical finding ID. Validation
2522
- still happens through `review_validator.submit_decisions`; invalid submissions
2523
- are corrected in the same review conversation. A completed turn without an
2524
- accepted submission receives one corrective turn in that same conversation.
2525
- If formatting remains invalid, the job retries in a fresh review session.
2526
- Explicit transient Codex failures and unexpected process exits also retry, with
2527
- at most three fresh sessions per review. Transient findings-service failures, including
2528
- rate limits and network errors, receive up to three request attempts. Retries use
2529
- exponential backoff with jitter; HTTP retries honor `Retry-After`. Waiting to retry
2530
- occupies the job's concurrency slot.
2531
-
2532
- Cancellation, authentication or configuration errors, permanent HTTP errors, and
2533
- required-source-access blockers are not retried. Model refusals continue with
2534
- `NO_DECISION` as described above. Other exhausted retries fail deduplication;
2535
- invalid or unfinished reviews are not cached. Completed checkpoints remain
2536
- available when the workflow resumes.
2537
-
2538
- Refusals are not saved as validated review checkpoints. A completed workflow
2539
- retains its final `completed_with_refusals` result, including all refusal entries,
2540
- and returns it on subsequent calls. To attempt those reviews again after
2541
- resolving the refusal, run dedupe without that workflow ID or with a new one.
2542
-
2543
- Checkpoints bind to the exact original records and ordering, approved source path,
2544
- Git revision and current file contents (including ignored files), repository scope,
2545
- model and reasoning settings, Codex configuration and version, and prompt/contract version. Changed
2546
- inputs cause a new review rather than reusing a decision. Source changes during
2547
- review stop that attempt before group writes; restart with the same ID to review
2548
- the changed source. Original findings, never prior rationales or merged findings,
2549
- are supplied to later independent reviews. Source snapshots do not follow directory
2550
- links outside the approved checkout.
2551
-
2552
- Before posting groups, the workflow saves the exact final result and write payload.
2553
- If posting fails or its acknowledgement is lost, rerunning dedupe replays that
2554
- payload without looking up candidates or running models. Group persistence reuses
2555
- the existing membership identity, so replay does not create another group. The
2556
- dedupe stage completes only after acknowledgement. Empty results are also retained.
2557
- A completed workflow or pending write represents its already reviewed snapshot;
2558
- use another workflow ID for a fresh review rather than changing that saved result.
2559
-
2560
- ### Deduplication workflow
2561
-
2562
- 1. For each distinct finding ID in the scan, request
2563
- `/v1/finding/{id}/potential-duplicates` with the selected repository or
2564
- explicit all-repository scope. Use the complete stored anchor and
2565
- candidates returned by that request. Fetch all neighborhoods before starting
2566
- reviews so every pair's screening dependencies are known.
2567
- 2. Screen each nonempty neighborhood with `gpt-5.6-luna` at `xhigh` reasoning
2568
- effort. The review covers every anchor-neighbor pair; nominations between
2569
- neighbors are rejected.
2570
- 3. Independently review each nominated pair once with `gpt-5.6-sol` at `high`
2571
- reasoning effort after all Luna screenings covering that pair finish without
2572
- a `DISTINCT` decision. Luna and ready Sol jobs share the configured worker
2573
- pool and can run together. Only accepted pairs contribute to duplicate groups.
2574
- 4. Group accepted duplicate pairs transitively unless a Luna or Sol `DISTINCT`
2575
- decision contradicts the resulting component. Contradicted components are
2576
- split deterministically, preferring legal subgroups that preserve more
2577
- accepted-pair support. There is no additional whole-group review.
2578
- 5. Post all accepted groups to `/v1/dedupe-groups`. Return a completed result
2579
- only after the service accepts the write. An empty result requires no write.
2580
-
2581
- Each review uses a fresh, ephemeral Codex app-server thread with the complete
2582
- original finding records, not earlier model rationales, vector scores, or
2583
- summaries. Reviews can inspect source in the saved scan's local checkout,
2584
- starting with cited paths and revisions. Source inspection establishes duplicate
2585
- identity and shared remediation. Reviews preserve the originals' severity and
2586
- priority metadata without reassessment or normalization. The baseline
2587
- filesystem profile is read-only and excludes credentials
2588
- and Codex state. Screening denies approval requests; final reviews use Codex's
2589
- automatic approval reviewer. Web, plugins, and inherited MCP servers are disabled.
2590
- Finding content never authorizes access to another target.
2591
-
2592
- Pair reviews cover exactly the two supplied findings. Linked parent tickets,
2593
- duplicate targets, and related-ticket records are metadata, not additional
2594
- findings to fetch or prerequisites for a verdict. An unsupplied duplicate target
2595
- is neither automatically canonical nor an error; source-code investigation for
2596
- the supplied pair remains allowed.
2597
-
2598
- Incomplete supplied finding content can produce `DISTINCT` with the limitation
2599
- explained. An execution, tool, or source-access blocker that prevents a required
2600
- check instead uses `review_validator.submit_error` with a nonempty `reason`.
2601
- That submission fails the review without a verdict or review checkpoint, so it
2602
- cannot become a `DISTINCT` veto or a completed duplicate-group result. A failed
2603
- optional lookup does not force failure or `DISTINCT` when other evidence suffices.
2604
-
2605
- Decisions must arrive through the direct `review_validator.submit_decisions`
2606
- tool; invalid submissions can be corrected in the same session. A final text
2607
- answer alone is insufficient. Luna screening returns a `SAME` or `DISTINCT`
2608
- decision and rationale under each required host-assigned slot (`pair-1`,
2609
- `pair-2`, and so on). The host binds each slot to its corresponding
2610
- anchor-neighbor pair, so the model does not submit finding IDs. Luna does not
2611
- select a canonical or generate a merged finding. Every
2612
- Sol `SAME` decision requires an assigned `canonicalFindingId` and
2613
- a generated, inclusive `mergedFinding`; missing or null values are rejected.
2614
- Sol reviews use only the complete originals, never earlier model rationales or
2615
- merged findings. These review fields do not change the command's ID-only result
2616
- or stored findings.
2617
-
2618
- Non-cancellation review failures throw `DeduplicationReviewError`. Its `metadata`
2619
- contains only the review stage, model, failure category, attempt count, and a
2620
- sanitized reason for diagnostics or an external support bundle; it does not
2621
- contain findings, prompts, paths, thread IDs, or credentials.
2622
-
2623
- If a completed turn has no accepted submission, whether it ended with text only
2624
- or after rejected submissions, the runner sends one corrective instruction in
2625
- the same conversation. This preserves the original assignment, source work, and
2626
- tool feedback. Reviews are limited to two turns; `metadata.attempts` counts
2627
- those turns (or the initial attempt if setup fails). Accepted results are not
2628
- replayed. Cancellation, accepted `submit_error` reports, and model or transport
2629
- failures remain terminal.
2630
-
2631
- The SDK does not retain private review transcripts, subprocess stderr, or full
2632
- provider/RPC error payloads, and ephemeral review state is removed after the
2633
- session. The public metadata is a limited diagnostic summary, not a complete
2634
- troubleshooting trace; it intentionally omits the original error cause. Private
2635
- diagnostic retention is not currently implemented.
2636
-
2637
- Model calls run sequentially on the SDK/CLI host using its Codex sign-in or
2638
- `OPENAI_API_KEY`/`CODEX_API_KEY`, with access to the configured models. Model
2639
- credentials are not sent to the findings API. Larger scans can take time and
2640
- incur multiple model calls per finding. Empty scans and findings without
2641
- eligible neighbors do not invoke review models. `completed` means this
2642
- retrieval, review, and group persistence completed, not that every possible pair in the
2643
- database was compared or that model decisions are infallible. An API, review, or write-back
2644
- failure fails the command without claiming a completed result. Retry after
2645
- fixing the failure; stored findings remain unchanged. A lost write-back response
2646
- may have committed groups; retrying the same memberships does not duplicate
2647
- them. Failed or interrupted reviews write no groups. The CLI supports Ctrl-C
2648
- and SIGTERM, and the SDK accepts an `AbortSignal`.
2649
-
2650
- ### Listing and errors
2651
-
2652
- Listing defaults to `limit=50` and `offset=0`; `limit` must be a positive
2653
- integer and `offset` a non-negative integer. Records are ordered by their first
2654
- insertion time, then finding ID. Follow `nextOffset` until it is `null`:
2655
-
2656
- ```json
2657
- {
2658
- "findings": [],
2659
- "limit": 50,
2660
- "offset": 0,
2661
- "total": 0,
2662
- "nextOffset": null
2663
- }
2664
- ```
558
+ ### Exports and CI
2665
559
 
2666
- The list includes API imports and complete finding documents from existing CLI
2667
- scan history. It returns the latest stored document for each finding ID,
2668
- without embedding vectors. Legacy identities without a complete document are
2669
- not included. Pagination reflects current database contents, not a snapshot
2670
- held between HTTP requests.
2671
-
2672
- Malformed JSON, invalid finding objects, repository metadata, groups, scopes, and pagination return HTTP
2673
- 400 (`invalid_request`). Identity conflicts or missing dedupe group members return 409 (`finding_conflict`),
2674
- embedding provider failures or unusable vectors return 502 (`embedding_failed`),
2675
- and missing embedding credentials return 503 (`embedding_unavailable`). A
2676
- potential-duplicates query without a current embedding returns 404
2677
- (`finding_not_indexed`), including findings outside the requested repository or
2678
- whose embedding was invalidated by an update; import the finding with the
2679
- matching `repositoryId` before retrying. This is an error, not an
2680
- empty candidate list. Unknown routes return 404 (`not_found`); unexpected
2681
- server failures return 500 (`internal_error`). Errors have an `error` code and,
2682
- for expected failures, a `message`. Request bodies and provider error bodies
2683
- are not logged.
2684
-
2685
- ### Embeddings and storage
2686
-
2687
- Set `OPENAI_API_KEY` in the repository-root `.env`, using `.env.example` as a
2688
- template, or export `OPENAI_API_KEY` or `CODEX_API_KEY` in the host environment.
2689
- Compose passes the key to the service; exported values override `.env` values.
2690
- The `.env` file is excluded from Git and Docker builds. `OPENAI_API_KEY` takes
2691
- precedence over `CODEX_API_KEY`; remove the `OPENAI_API_KEY` entry if using
2692
- `CODEX_API_KEY` instead. Listing and empty imports do not require a key.
2693
- A Codex ChatGPT login is not an embedding API credential.
2694
-
2695
- Set `CODEX_SECURITY_EMBEDDINGS_URL` to override the full embeddings endpoint URL,
2696
- including its path and any query parameters. Unset or empty values use
2697
- `https://api.openai.com/v1/embeddings`. Export it before `codex-security serve`,
2698
- or set it in `.env` for Docker Compose, which passes it to the service. For example:
560
+ Export saved findings or a threat model without starting another analysis:
2699
561
 
2700
562
  ```bash
2701
- CODEX_SECURITY_EMBEDDINGS_URL=https://embeddings.example.com/v1/embeddings codex-security serve
563
+ cs export --scan SCAN_ID --export-format sarif --output results.sarif
564
+ cs export --scan SCAN_ID --artifact threat-model --output threatmodel.md
2702
565
  ```
2703
566
 
2704
- The configured endpoint receives the finding inputs and the API key as a bearer
2705
- token and must support the same OpenAI embeddings request and response format.
2706
-
2707
- The service calls the OpenAI embeddings API with `text-embedding-3-large` and
2708
- 1,536 dimensions. The complete finding JSON is tokenized using `js-tiktoken`'s
2709
- bundled `cl100k_base` encoding. Long inputs are split without truncation;
2710
- their vectors are combined by token weight and normalized. Requests respect
2711
- the provider's 8,192-token input, 300,000-token request, and 2,048-input limits.
2712
- See the [embedding API contract](https://developers.openai.com/api/reference/resources/embeddings/methods/create).
2713
-
2714
- Storage initializes before the server listens. The SQLite adapter reuses the
2715
- bundled workbench's schema and migrations at
2716
- `$CODEX_SECURITY_STATE_DIR/workbench.sqlite3`. An append-only migration adds
2717
- complete finding documents and an embedding table, while retaining the existing
2718
- finding identity table and scan history. Both the API and current CLI indexing
2719
- use the same finding upsert operation. Changing a stored document invalidates
2720
- its old embedding so later matching cannot use a stale vector. Historical
2721
- findings are not automatically embedded; submit them to a bulk endpoint first.
2722
-
2723
- The `findings-state` named volume persists `/state`, including the database,
2724
- across container replacements. Keep the same Compose project name to reuse it.
2725
- The image runs as UID/GID `10001:10001`; a bind mount must be writable by that
2726
- UID/GID if used instead of the named volume.
2727
-
2728
- Stop the service with
2729
- `docker compose -f compose.findings.yaml down`; add `--volumes` only when you
2730
- intend to delete the stored data.
2731
-
2732
- The findings Compose configuration sets `HOST=0.0.0.0`, `PORT=3000`, and
2733
- `CODEX_SECURITY_STATE_DIR=/state`. Keep port and volume mappings aligned if
2734
- changing these settings. Compose binds only to host loopback; the API has no
2735
- authentication. Use an authenticated TLS proxy before sharing access. Finding
2736
- JSON is sent to the configured embeddings endpoint (`api.openai.com` over HTTPS
2737
- by default); the database and generated embeddings stay in the local volume.
2738
-
2739
- ### Upgrades and backups
2740
-
2741
- Read the release notes and stop the service before backing up the entire
2742
- `/state` directory. For the published-image Compose configuration:
567
+ The SDK provides `exportArtifact()` for the same offline operations. See
568
+ [exports and CI](docs/cli.md#exports-and-ci) for details. For repository or pull
569
+ request scans in GitHub Actions, use the
570
+ [GitHub Action guide](https://github.com/openai/codex-security/blob/main/github-action/README.md).
571
+ Separate examples cover
572
+ [GitHub Actions with Bedrock](https://github.com/openai/codex-security/blob/main/examples/github-actions/README.md)
573
+ and [Azure Pipelines](https://github.com/openai/codex-security/blob/main/examples/azure-pipelines/README.md).
2743
574
 
2744
- ```bash
2745
- docker compose -f compose.findings.yaml stop findings
2746
- mkdir -p backups
2747
- chmod 700 backups
2748
- docker compose -f compose.findings.yaml run --rm --no-deps --user 0:0 \
2749
- --entrypoint tar -T findings -C /state -czf - . > backups/findings-state.tgz
2750
- chmod 600 backups/findings-state.tgz
2751
- ```
575
+ ### Classify finding severity
2752
576
 
2753
- Keep backups separately; this command overwrites an existing backup of the same
2754
- name. Set `CODEX_SECURITY_FINDINGS_IMAGE` to the new version or digest and repeat
2755
- the pull/start commands above, retaining the volume. Startup applies SQLite
2756
- migrations automatically. To roll back, stop the service, restore the pre-upgrade
2757
- backup, and select the previous image digest; an older image may not support the
2758
- migrated database.
577
+ Use `classify-severity` with your own rubric to assess saved findings without
578
+ changing their original severity or evidence. The SDK exposes `classifySeverity()`,
579
+ `classifyScanSeverity()`, and `classifyScanDirectorySeverity()`. See
580
+ [severity classification](docs/cli.md#classify-finding-severity) for selection,
581
+ checkpointing, and publication behavior.
2759
582
 
2760
- ### Running without Docker
583
+ ### Suggest finding owners
2761
584
 
2762
- With Node.js and Python 3 installed:
585
+ Use `suggest-owners` or the SDK's `suggestOwners()` to suggest contributors based
586
+ on CODEOWNERS, source, and Git history. Declared owners take priority over Git
587
+ contributors. Suggestions do not assign tickets. See
588
+ [owner suggestions](docs/cli.md#suggest-finding-owners) for input and output examples.
2763
589
 
2764
- ```bash
2765
- npm install -g @openai/codex-security
2766
- CODEX_SECURITY_STATE_DIR="$HOME/.codex-security-findings" codex-security serve --port 3000
2767
- ```
590
+ ### Publish findings to Cloud
2768
591
 
2769
- `--port` overrides `PORT` (default: `3000`). Open
2770
- `http://127.0.0.1:3000/dashboard`. Stop with Ctrl+C or SIGTERM.
592
+ `publish scan --to cloud` uploads selected findings to Codex Security Cloud.
593
+ It requires ChatGPT credentials; inference API keys and AWS credentials do not
594
+ grant Cloud access. See [Cloud publication](docs/cli.md#publish-findings-to-cloud)
595
+ for setup and review steps, or [Linear publication](docs/cli.md#publish-completed-scans-to-linear)
596
+ for issue creation.
2771
597
 
2772
- Export `OPENAI_API_KEY` or `CODEX_API_KEY` to import findings with embeddings.
2773
- Startup and listing need no key. The service does not load `.env` or authenticate
2774
- requests; keep it on loopback or behind an authenticated TLS proxy.
598
+ ## Findings storage and deduplication
2775
599
 
2776
- For a source build, first prepare the
2777
- [universal native payload](../../plugins/codex-security/native/README.md#package-inputs)
2778
- for that checkout. Then run from its `sdk/typescript` directory:
600
+ Saved-scan deduplication uses local SQLite directly:
2779
601
 
2780
602
  ```bash
2781
- pnpm install --frozen-lockfile
2782
- pnpm --dir ../../plugins/codex-security/mcp-app install --frozen-lockfile
2783
- pnpm run build:plugin
2784
- pnpm run build
2785
- node bin/codex-security.mjs serve --port 3000
603
+ cs dedupe --scan SCAN_ID --json
2786
604
  ```
2787
605
 
2788
- `pnpm run start:server` and `node dist/server/index.js` still work.
2789
-
2790
- Local defaults are `HOST=127.0.0.1` and `PORT=3000`. The existing
2791
- `CODEX_SECURITY_STATE_DIR` and `PYTHON` settings select storage and Python;
2792
- without a state override, the service uses the same default state directory as
2793
- the CLI. These settings also work on Windows.
2794
-
2795
- HTTP routing, embedding generation, and the SQLite adapter live
2796
- separately under `src/server/`. `startFindingsServer` receives a `FindingEmbedder`
2797
- whose `embed(findings)` method returns one `{ model, vector }` per finding in
2798
- input order. `OpenAiFindingEmbedder` handles tokenization, batching, API calls,
2799
- and vector normalization; it does not access storage. The `FindingsStore`
2800
- interface stores findings and vectors and exposes
2801
- `findPotentialDuplicates(findingId, scope)`. Repository filtering, vector ranking,
2802
- and fetching selected documents stay inside the store implementation; replacing
2803
- SQLite with an indexed store does not change the service or SDK/CLI. Repository
2804
- associations are stored separately from finding documents, with an append-only
2805
- migration that also imports known associations from stored scan occurrences.
2806
- New scan findings retain their target associations when indexed locally.
2807
- The server entrypoint selects the concrete
2808
- embedder and store, so either can be replaced independently.
2809
-
2810
- For renewable embeddings credentials, import `OpenAiFindingEmbedder`,
2811
- `SqliteFindingsStore`, and `startFindingsServer` from
2812
- `@openai/codex-security/server`. The embedder's first argument accepts a static
2813
- key or `() => string | Promise<string>`. It calls the callback before every
2814
- HTTP batch, including subsequent calls to `embed`; callers own token acquisition.
2815
- Pass `fetch` as the second argument and
2816
- `process.env.CODEX_SECURITY_EMBEDDINGS_URL || undefined` as the third to use
2817
- the same full endpoint URL and default as `codex-security serve`. Importing the
2818
- server API does not start a listener.
2819
-
2820
- The local workflow lives under `src/deduplication/`. `FindingDeduplicator`
2821
- receives a candidate API client and a `DeduplicationReviewer`, keeping grouping
2822
- separate from HTTP and model transport. `CodexDeduplicationReviewer` owns prompts
2823
- and result validation; `CodexReviewRunner` owns app-server sessions and cleanup.
2824
- `deduplicateScan` validates saved scan artifacts before running the workflow;
2825
- `deduplicateScanDirectory` performs the same validation for an explicit sealed
2826
- scan directory without consulting local scan history.
2827
- The SDK reuses the existing Codex runtime and credentials without additional
2828
- runtime dependencies.
606
+ The [findings guide](docs/findings-service.md) covers local storage, embedding
607
+ credentials, deduplication, backups, and independently operated HTTP endpoints.
608
+ The local `serve` command and browser dashboard have been removed. Existing
609
+ scans, findings, and duplicate groups remain in the workbench database.
610
+ For records stored in your own system, see
611
+ [SDK records deduplication](docs/dedupe-records.md).
2829
612
 
2830
613
  ## Containerized bulk scans
2831
614
 
2832
- Create `repositories.csv` as described under [Bulk scans](#bulk-scans).
2833
- Use device login only if your workspace allows it.
2834
- With a published image, run from the Codex Security repository root:
2835
-
2836
- ```bash
2837
- mkdir -p results state
2838
- chmod 700 results state
2839
- export CODEX_SECURITY_USER="$(id -u):$(id -g)"
2840
- export CODEX_SECURITY_IMAGE=ghcr.io/openai/codex-security:latest
2841
- docker compose pull codex-security
2842
- docker compose run --rm codex-security login --device-auth
2843
- docker compose run --rm codex-security
2844
- ```
2845
-
2846
- Results go to `results/`; device login stays in `state/`. For unattended scans,
2847
- set `OPENAI_API_KEY` or `CODEX_API_KEY`. Private GitHub checkouts use `GH_TOKEN`
2848
- or `GITHUB_TOKEN`; GitHub Enterprise uses `CODEX_SECURITY_GIT_HOST`. The container
2849
- requires CSV input, without interactive discovery.
2850
-
2851
- Compose accepts `CODEX_SECURITY_IMAGE`, `CODEX_SECURITY_USER`,
2852
- `CODEX_SECURITY_SECCOMP`, `CODEX_SECURITY_CSV`, `CODEX_SECURITY_RESULTS`, and
2853
- `CODEX_SECURITY_STATE` for the image, user, seccomp profile, and mounts.
2854
-
2855
- Codex 0.156.1 requires Bubblewrap for filesystem-restricted execution on Linux.
2856
- On Ubuntu hosts that restrict unprivileged user namespaces, an administrator
2857
- must install the AppArmor profile and use the Compose override:
2858
-
2859
- ```bash
2860
- sudo install -m 0644 docker/codex-security.apparmor /etc/apparmor.d/codex-security-container
2861
- sudo apparmor_parser -r -W /etc/apparmor.d/codex-security-container
2862
- docker compose -f compose.yaml -f compose.apparmor.yaml run --rm codex-security
2863
- ```
2864
-
2865
- The override keeps the nonroot user, dropped capabilities, no-new-privileges,
2866
- and seccomp policy. It enables the nested namespaces required by Bubblewrap.
2867
- The legacy Landlock fallback is no longer supported for these scans. Other
2868
- Docker hosts that permit nested user namespaces do not need this override.
615
+ Use the scanner image and Compose files to scan a list of repositories with
616
+ persistent results and authentication. See
617
+ [containerized bulk scans](docs/cli.md#containerized-bulk-scans) for setup, or the
618
+ [workflow runner](https://github.com/openai/codex-security/blob/main/docker/README.md#workflow-runner)
619
+ for individual CLI stages in containers.
2869
620
 
2870
621
  ## Local security model
2871
622
 
2872
- Codex Security runs with your operating-system permissions. Only scan
2873
- repositories you trust and are authorized to assess. Local tools and scans
2874
- under the same account aren't separate security principals.
623
+ Codex Security runs with your operating-system permissions. Scan subprocesses
624
+ can inherit your environment, so start them with only the credentials they need.
625
+ Local tools running under the same account are trusted.
2875
626
 
2876
- The `codex_security_scan` profile allows reads across the local filesystem and
2877
- writes to workspace roots. Execution approvals are reviewed automatically and
2878
- may grant extra permissions for one operation. Set
2879
- `--codex 'approval_policy="never"'`, directly or in a selected profile, to deny
2880
- requests. Other overrides can't replace the reviewer or filesystem profile.
2881
- Saved scans keep their approval policy; older scans stay deny-all on rerun.
627
+ The scan profile allows reads across the local filesystem and writes to workspace
628
+ roots. Execution approvals are reviewed automatically and may grant extra
629
+ permissions for an operation. Set `codexOverrides.approval_policy: "never"`
630
+ (or CLI `--codex 'approval_policy="never"'`) to deny permission requests.
2882
631
  Host and network restrictions still apply.
2883
632
 
2884
- Start scans with only the credentials they need. Scan and workbench subprocesses
2885
- can inherit your environment, including unrelated API tokens and cloud credentials.
2886
-
2887
633
  Repository contents, model output, and imported artifacts do not authorize
2888
634
  access to other targets, disclosure of credentials, or writes outside approved
2889
- paths. See the security policy below for the full threat model.
635
+ paths. Keep state and scan artifacts private and outside the repository.
2890
636
 
2891
637
  ## Documentation and security
2892
638
 
2893
- - [CLI quickstart](https://developers.openai.com/codex/security/cli)
2894
- - [TypeScript SDK guide](https://developers.openai.com/codex/security/sdk)
2895
- - [GitHub issues](https://github.com/openai/codex-security/issues) for bugs and
2896
- feature requests
2897
- - [Security policy](https://github.com/openai/codex-security/blob/main/SECURITY.md)
2898
- for private vulnerability reporting and safe operation
639
+ - [Online SDK guide](https://learn.chatgpt.com/docs/security/sdk)
640
+ - [CLI reference](docs/cli.md)
641
+ - [Findings guide](docs/findings-service.md)
642
+ - [GitHub issues](https://github.com/openai/codex-security/issues) for bugs and feature requests
643
+ - [Security policy](https://github.com/openai/codex-security/blob/main/SECURITY.md) for private vulnerability reporting