@openai/codex-security 0.5.1 → 0.7.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 (313) hide show
  1. package/README.md +151 -36
  2. package/_bundled_plugin/.mcp.json +1 -0
  3. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  4. package/_bundled_plugin/mcp/helpers.mjs.br.part-001 +0 -0
  5. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +1 -1
  6. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  7. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  8. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  9. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  10. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  11. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  12. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  13. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  14. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  15. package/_bundled_plugin/mcp/server.mjs.br.part-002 +0 -0
  16. package/_bundled_plugin/references/access-advisory.md +11 -0
  17. package/_bundled_plugin/references/core-scan.md +30 -77
  18. package/_bundled_plugin/references/final-report.md +45 -189
  19. package/_bundled_plugin/references/scan-contract.md +2 -0
  20. package/_bundled_plugin/references/scan-prologue.md +1 -1
  21. package/_bundled_plugin/references/scan-runtime.md +1 -5
  22. package/_bundled_plugin/references/threat-model.md +33 -41
  23. package/_bundled_plugin/schemas/coverage.schema.json +12 -1
  24. package/_bundled_plugin/schemas/scan-manifest.schema.json +1 -0
  25. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +38 -1
  26. package/_bundled_plugin/scripts/deep_scan_config.py +39 -39
  27. package/_bundled_plugin/scripts/deep_scan_workbench.py +145 -85
  28. package/_bundled_plugin/scripts/finalize_scan_contract.py +189 -57
  29. package/_bundled_plugin/scripts/report_projection.py +44 -15
  30. package/_bundled_plugin/scripts/threat_model_projection.py +4 -2
  31. package/_bundled_plugin/scripts/windows_scan_local_files.py +43 -14
  32. package/_bundled_plugin/scripts/workbench/retained_coverage.py +3218 -0
  33. package/_bundled_plugin/scripts/workbench/retained_records.py +627 -0
  34. package/_bundled_plugin/scripts/workbench/saved_coverage.py +644 -1
  35. package/_bundled_plugin/scripts/workbench/saved_outputs.py +72 -0
  36. package/_bundled_plugin/scripts/workbench/saved_sources.py +712 -0
  37. package/_bundled_plugin/scripts/workbench_cli.py +3 -0
  38. package/_bundled_plugin/scripts/workbench_coverage_receipts.py +479 -0
  39. package/_bundled_plugin/scripts/workbench_db.py +51 -22
  40. package/_bundled_plugin/scripts/workbench_feedback.py +0 -1
  41. package/_bundled_plugin/scripts/workbench_finding_workflows.py +53 -9
  42. package/_bundled_plugin/scripts/workbench_native_indexes.py +56 -44
  43. package/_bundled_plugin/scripts/workbench_saved_results.py +641 -2387
  44. package/_bundled_plugin/scripts/workbench_scan_history.py +72 -7
  45. package/_bundled_plugin/scripts/workbench_schema.py +1 -1
  46. package/_bundled_plugin/scripts/workbench_source_scopes.py +4 -1
  47. package/_bundled_plugin/scripts/workbench_target.py +142 -17
  48. package/_bundled_plugin/scripts/workbench_validation.py +9 -2
  49. package/_bundled_plugin/shared/workbench-history-repairs.json +21 -0
  50. package/_bundled_plugin/shared/workbench-migrations.json +44 -0
  51. package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +3 -14
  52. package/_bundled_plugin/skills/assess-patch-risk/references/windows-validation.md +14 -0
  53. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +38 -103
  54. package/_bundled_plugin/skills/attack-path-analysis/references/attack-path-facts.md +11 -73
  55. package/_bundled_plugin/skills/attack-path-analysis/references/severity-policy.md +57 -116
  56. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +28 -51
  57. package/_bundled_plugin/skills/define-security-policy/SKILL.md +9 -9
  58. package/_bundled_plugin/skills/finding-discovery/SKILL.md +26 -140
  59. package/_bundled_plugin/skills/fix-finding/SKILL.md +19 -30
  60. package/_bundled_plugin/skills/propose-security-hardening/SKILL.md +28 -218
  61. package/_bundled_plugin/skills/propose-security-hardening/references/proposal-format.md +29 -424
  62. package/_bundled_plugin/skills/publish-findings/SKILL.md +134 -0
  63. package/_bundled_plugin/skills/publish-findings/agents/openai.yaml +6 -0
  64. package/_bundled_plugin/skills/publish-findings/references/wiz-import.md +64 -0
  65. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +12 -12
  66. package/_bundled_plugin/skills/security-scan/SKILL.md +28 -16
  67. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +11 -17
  68. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +52 -69
  69. package/_bundled_plugin/skills/threat-model/SKILL.md +16 -9
  70. package/_bundled_plugin/skills/triage-finding/SKILL.md +5 -15
  71. package/_bundled_plugin/skills/triage-finding/references/ticket-intake.md +6 -6
  72. package/_bundled_plugin/skills/validation/SKILL.md +42 -104
  73. package/_bundled_plugin/skills/validation/references/validation-guidance.md +21 -106
  74. package/_bundled_plugin/skills/verify-fix/SKILL.md +8 -4
  75. package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +21 -159
  76. package/_bundled_plugin/skills/vulnerability-writeup/references/report-format.md +18 -60
  77. package/dist/api.d.ts +8 -3
  78. package/dist/api.d.ts.map +1 -1
  79. package/dist/api.js +414 -72
  80. package/dist/api.js.map +1 -1
  81. package/dist/auth.d.ts.map +1 -1
  82. package/dist/auth.js +4 -1
  83. package/dist/auth.js.map +1 -1
  84. package/dist/classify-severity-records.d.ts +5 -2
  85. package/dist/classify-severity-records.d.ts.map +1 -1
  86. package/dist/classify-severity-records.js +40 -34
  87. package/dist/classify-severity-records.js.map +1 -1
  88. package/dist/classify-severity.d.ts +5 -1
  89. package/dist/classify-severity.d.ts.map +1 -1
  90. package/dist/classify-severity.js +20 -30
  91. package/dist/classify-severity.js.map +1 -1
  92. package/dist/cli-help.d.ts.map +1 -1
  93. package/dist/cli-help.js +1 -0
  94. package/dist/cli-help.js.map +1 -1
  95. package/dist/cli.d.ts +9 -2
  96. package/dist/cli.d.ts.map +1 -1
  97. package/dist/cli.js +802 -149
  98. package/dist/cli.js.map +1 -1
  99. package/dist/cloud-endpoint.d.ts +6 -0
  100. package/dist/cloud-endpoint.d.ts.map +1 -0
  101. package/dist/cloud-endpoint.js +51 -0
  102. package/dist/cloud-endpoint.js.map +1 -0
  103. package/dist/cloud-publish.d.ts.map +1 -1
  104. package/dist/cloud-publish.js +7 -5
  105. package/dist/cloud-publish.js.map +1 -1
  106. package/dist/component-scan.d.ts +8 -2
  107. package/dist/component-scan.d.ts.map +1 -1
  108. package/dist/component-scan.js +2 -0
  109. package/dist/component-scan.js.map +1 -1
  110. package/dist/contract.d.ts +2 -0
  111. package/dist/contract.d.ts.map +1 -1
  112. package/dist/contract.js +67 -33
  113. package/dist/contract.js.map +1 -1
  114. package/dist/cost.d.ts +18 -0
  115. package/dist/cost.d.ts.map +1 -1
  116. package/dist/cost.js +107 -12
  117. package/dist/cost.js.map +1 -1
  118. package/dist/coverage-presentation.d.ts +6 -0
  119. package/dist/coverage-presentation.d.ts.map +1 -0
  120. package/dist/coverage-presentation.js +34 -0
  121. package/dist/coverage-presentation.js.map +1 -0
  122. package/dist/custom-validation-prompt.js +3 -3
  123. package/dist/custom-validation-prompt.js.map +1 -1
  124. package/dist/custom-validation.d.ts.map +1 -1
  125. package/dist/custom-validation.js +30 -4
  126. package/dist/custom-validation.js.map +1 -1
  127. package/dist/deduplication/checkpointed-review.d.ts.map +1 -1
  128. package/dist/deduplication/checkpointed-review.js +3 -1
  129. package/dist/deduplication/checkpointed-review.js.map +1 -1
  130. package/dist/deduplication/scan.d.ts.map +1 -1
  131. package/dist/deduplication/scan.js +7 -5
  132. package/dist/deduplication/scan.js.map +1 -1
  133. package/dist/default-severity-rubric.d.ts +3 -0
  134. package/dist/default-severity-rubric.d.ts.map +1 -0
  135. package/dist/default-severity-rubric.js +67 -0
  136. package/dist/default-severity-rubric.js.map +1 -0
  137. package/dist/endor-findings.d.ts +8 -0
  138. package/dist/endor-findings.d.ts.map +1 -0
  139. package/dist/endor-findings.js +238 -0
  140. package/dist/endor-findings.js.map +1 -0
  141. package/dist/external-findings-import.d.ts +5 -0
  142. package/dist/external-findings-import.d.ts.map +1 -0
  143. package/dist/external-findings-import.js +46 -0
  144. package/dist/external-findings-import.js.map +1 -0
  145. package/dist/external-findings-local.d.ts +63 -0
  146. package/dist/external-findings-local.d.ts.map +1 -0
  147. package/dist/external-findings-local.js +344 -0
  148. package/dist/external-findings-local.js.map +1 -0
  149. package/dist/external-findings-publish.d.ts +73 -0
  150. package/dist/external-findings-publish.d.ts.map +1 -0
  151. package/dist/external-findings-publish.js +721 -0
  152. package/dist/external-findings-publish.js.map +1 -0
  153. package/dist/external-findings-read.d.ts +16 -0
  154. package/dist/external-findings-read.d.ts.map +1 -0
  155. package/dist/external-findings-read.js +97 -0
  156. package/dist/external-findings-read.js.map +1 -0
  157. package/dist/external-findings.d.ts +21 -0
  158. package/dist/external-findings.d.ts.map +1 -0
  159. package/dist/external-findings.js +2 -0
  160. package/dist/external-findings.js.map +1 -0
  161. package/dist/external-import-contract.d.ts +15 -0
  162. package/dist/external-import-contract.d.ts.map +1 -0
  163. package/dist/external-import-contract.js +262 -0
  164. package/dist/external-import-contract.js.map +1 -0
  165. package/dist/external-import-models.d.ts +362 -0
  166. package/dist/external-import-models.d.ts.map +1 -0
  167. package/dist/external-import-models.js +3 -0
  168. package/dist/external-import-models.js.map +1 -0
  169. package/dist/external-imports-feature.d.ts +6 -0
  170. package/dist/external-imports-feature.d.ts.map +1 -0
  171. package/dist/external-imports-feature.js +51 -0
  172. package/dist/external-imports-feature.js.map +1 -0
  173. package/dist/finding-workflow.d.ts +23 -6
  174. package/dist/finding-workflow.d.ts.map +1 -1
  175. package/dist/finding-workflow.js +23 -10
  176. package/dist/finding-workflow.js.map +1 -1
  177. package/dist/github-advisories.d.ts +386 -0
  178. package/dist/github-advisories.d.ts.map +1 -0
  179. package/dist/github-advisories.js +133 -0
  180. package/dist/github-advisories.js.map +1 -0
  181. package/dist/github-findings.d.ts +11 -0
  182. package/dist/github-findings.d.ts.map +1 -0
  183. package/dist/github-findings.js +258 -0
  184. package/dist/github-findings.js.map +1 -0
  185. package/dist/hosted-remediation-protocol.d.ts +2 -1
  186. package/dist/hosted-remediation-protocol.d.ts.map +1 -1
  187. package/dist/hosted-remediation-protocol.js +17 -11
  188. package/dist/hosted-remediation-protocol.js.map +1 -1
  189. package/dist/hosted-remediation.d.ts +4 -0
  190. package/dist/hosted-remediation.d.ts.map +1 -1
  191. package/dist/hosted-remediation.js +22 -3
  192. package/dist/hosted-remediation.js.map +1 -1
  193. package/dist/hosted-scan.d.ts +16 -0
  194. package/dist/hosted-scan.d.ts.map +1 -1
  195. package/dist/hosted-scan.js +9 -2
  196. package/dist/hosted-scan.js.map +1 -1
  197. package/dist/import-scan.js +1 -1
  198. package/dist/import-scan.js.map +1 -1
  199. package/dist/index.d.ts +16 -3
  200. package/dist/index.d.ts.map +1 -1
  201. package/dist/index.js +9 -1
  202. package/dist/index.js.map +1 -1
  203. package/dist/knowledge-base.d.ts +1 -0
  204. package/dist/knowledge-base.d.ts.map +1 -1
  205. package/dist/knowledge-base.js +17 -8
  206. package/dist/knowledge-base.js.map +1 -1
  207. package/dist/models.d.ts +1 -0
  208. package/dist/models.d.ts.map +1 -1
  209. package/dist/models.js.map +1 -1
  210. package/dist/owner-evidence.d.ts +2 -0
  211. package/dist/owner-evidence.d.ts.map +1 -1
  212. package/dist/owner-evidence.js +2 -1
  213. package/dist/owner-evidence.js.map +1 -1
  214. package/dist/project-config-schema.d.ts +2 -0
  215. package/dist/project-config-schema.d.ts.map +1 -1
  216. package/dist/project-config-schema.js +1 -0
  217. package/dist/project-config-schema.js.map +1 -1
  218. package/dist/project-config.d.ts +1 -0
  219. package/dist/project-config.d.ts.map +1 -1
  220. package/dist/project-config.js +2 -0
  221. package/dist/project-config.js.map +1 -1
  222. package/dist/publish.d.ts +2 -0
  223. package/dist/publish.d.ts.map +1 -1
  224. package/dist/publish.js +1 -1
  225. package/dist/publish.js.map +1 -1
  226. package/dist/remediation.d.ts +7 -25
  227. package/dist/remediation.d.ts.map +1 -1
  228. package/dist/remediation.js +18 -28
  229. package/dist/remediation.js.map +1 -1
  230. package/dist/result.d.ts +4 -0
  231. package/dist/result.d.ts.map +1 -1
  232. package/dist/result.js +10 -0
  233. package/dist/result.js.map +1 -1
  234. package/dist/runtime.d.ts +1 -0
  235. package/dist/runtime.d.ts.map +1 -1
  236. package/dist/runtime.js +10 -8
  237. package/dist/runtime.js.map +1 -1
  238. package/dist/scan-dashboard.d.ts +5 -3
  239. package/dist/scan-dashboard.d.ts.map +1 -1
  240. package/dist/scan-dashboard.js +79 -26
  241. package/dist/scan-dashboard.js.map +1 -1
  242. package/dist/scan-history-renderer.d.ts.map +1 -1
  243. package/dist/scan-history-renderer.js +8 -2
  244. package/dist/scan-history-renderer.js.map +1 -1
  245. package/dist/scan-owner-suggestions.d.ts +8 -0
  246. package/dist/scan-owner-suggestions.d.ts.map +1 -0
  247. package/dist/scan-owner-suggestions.js +33 -0
  248. package/dist/scan-owner-suggestions.js.map +1 -0
  249. package/dist/scan-settings.d.ts +1 -0
  250. package/dist/scan-settings.d.ts.map +1 -1
  251. package/dist/scan-settings.js +4 -0
  252. package/dist/scan-settings.js.map +1 -1
  253. package/dist/scan-usage-display.d.ts +8 -0
  254. package/dist/scan-usage-display.d.ts.map +1 -0
  255. package/dist/scan-usage-display.js +46 -0
  256. package/dist/scan-usage-display.js.map +1 -0
  257. package/dist/scanner-import.d.ts +20 -0
  258. package/dist/scanner-import.d.ts.map +1 -0
  259. package/dist/scanner-import.js +208 -0
  260. package/dist/scanner-import.js.map +1 -0
  261. package/dist/security-policy-diff.d.ts +2 -0
  262. package/dist/security-policy-diff.d.ts.map +1 -0
  263. package/dist/security-policy-diff.js +197 -0
  264. package/dist/security-policy-diff.js.map +1 -0
  265. package/dist/security-policy.d.ts +7 -3
  266. package/dist/security-policy.d.ts.map +1 -1
  267. package/dist/security-policy.js +11 -76
  268. package/dist/security-policy.js.map +1 -1
  269. package/dist/semgrep-findings.d.ts +10 -0
  270. package/dist/semgrep-findings.d.ts.map +1 -0
  271. package/dist/semgrep-findings.js +293 -0
  272. package/dist/semgrep-findings.js.map +1 -0
  273. package/dist/severity-review.d.ts +3 -0
  274. package/dist/severity-review.d.ts.map +1 -1
  275. package/dist/severity-review.js +19 -0
  276. package/dist/severity-review.js.map +1 -1
  277. package/dist/severity-store.js +7 -2
  278. package/dist/severity-store.js.map +1 -1
  279. package/dist/skill-authentication.d.ts +18 -0
  280. package/dist/skill-authentication.d.ts.map +1 -0
  281. package/dist/skill-authentication.js +82 -0
  282. package/dist/skill-authentication.js.map +1 -0
  283. package/dist/snyk-findings.d.ts +10 -0
  284. package/dist/snyk-findings.d.ts.map +1 -0
  285. package/dist/snyk-findings.js +350 -0
  286. package/dist/snyk-findings.js.map +1 -0
  287. package/dist/suggest-owners.d.ts +4 -1
  288. package/dist/suggest-owners.d.ts.map +1 -1
  289. package/dist/suggest-owners.js +53 -21
  290. package/dist/suggest-owners.js.map +1 -1
  291. package/dist/targets.d.ts +2 -2
  292. package/dist/targets.d.ts.map +1 -1
  293. package/dist/targets.js +16 -3
  294. package/dist/targets.js.map +1 -1
  295. package/dist/wiz-csv.d.ts +9 -0
  296. package/dist/wiz-csv.d.ts.map +1 -0
  297. package/dist/wiz-csv.js +116 -0
  298. package/dist/wiz-csv.js.map +1 -0
  299. package/dist/wiz-findings.d.ts +5 -0
  300. package/dist/wiz-findings.d.ts.map +1 -0
  301. package/dist/wiz-findings.js +464 -0
  302. package/dist/wiz-findings.js.map +1 -0
  303. package/docs/classify-severity-records.md +30 -13
  304. package/docs/cli.md +835 -47
  305. package/docs/findings-service.md +119 -118
  306. package/docs/hosted-remediation.md +43 -24
  307. package/docs/hosted-scans.md +38 -0
  308. package/package.json +11 -9
  309. package/schemas/external-findings.schema.json +1421 -0
  310. package/schemas/project-config.schema.json +4 -0
  311. package/_bundled_plugin/scripts/generate_in_scope_files.py +0 -277
  312. package/_bundled_plugin/scripts/generate_rank_input.py +0 -350
  313. package/_bundled_plugin/scripts/rank_preview.py +0 -129
package/dist/cli.js CHANGED
@@ -7,6 +7,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
7
7
  }
8
8
  return path;
9
9
  };
10
+ import { classificationRunsSchema } from "./severity-review.js";
10
11
  import { workbenchArgs } from "./workbench-arguments.js";
11
12
  import { listenForAbort } from "./cli-signals.js";
12
13
  import { appServerCyberAccessProgram } from "./cli-daybreak.js";
@@ -14,23 +15,25 @@ import { withCodexPreflightLock } from "./provider-profile.js";
14
15
  import { isNonEmptyString, notify, parseJson } from "./value.js";
15
16
  import { compareTimestamps } from "./timestamps.js";
16
17
  import { execFile as execFileCallback, execFileSync, spawn, } from "node:child_process";
17
- import { createHash } from "node:crypto";
18
+ import { createHash, randomUUID } from "node:crypto";
18
19
  import { accessSync, constants, createReadStream, existsSync, lstatSync, realpathSync, writeSync, } from "node:fs";
19
- import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rm, writeFile, } from "node:fs/promises";
20
+ import { chmod, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rm, writeFile, } from "node:fs/promises";
20
21
  import { tmpdir } from "node:os";
21
22
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, win32, } from "node:path";
22
23
  import { cwd } from "node:process";
23
24
  import { createInterface } from "node:readline";
24
25
  import { Readable, Writable as NodeWritable } from "node:stream";
25
26
  import { fileURLToPath, pathToFileURL } from "node:url";
26
- import { isDeepStrictEqual, promisify, stripVTControlCharacters, } from "node:util";
27
+ import { isDeepStrictEqual, parseArgs, promisify, stripVTControlCharacters, } from "node:util";
27
28
  import { Cli, z } from "incur";
28
29
  import Ajv2020 from "ajv/dist/2020.js";
29
30
  import { formatCliHelp } from "./cli-help.js";
31
+ import { formatCoverageScope } from "./coverage-presentation.js";
32
+ import { resolveSkillAuthentication } from "./skill-authentication.js";
30
33
  import { scanLogsJson } from "./cli-scan-logs-json.js";
31
34
  import { ARTIFACT_EXPORT_FILENAMES, exportEnvironment, resolveArtifactFormat, resolveArtifactExportOutput, resolveSavedArtifactDirectory, runArtifactExport, writeArtifactOutput as writeCliOutput, } from "./artifact-export.js";
32
35
  export { exportEnvironment } from "./artifact-export.js";
33
- import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
36
+ import { parse as parseToml } from "smol-toml";
34
37
  import { parse as parseYaml } from "yaml";
35
38
  import { classifyConnectionFailure, CodexSecurity, environmentValue, formatEnvironmentVariableRemovalGuidance, initialCredentialsAvailable, scanCodexHome, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, runtimeScanAuthentication, selectedScanEnvironment, } from "./api.js";
36
39
  import { accountStatus, CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, configuredCodexHome, environmentEntry, readCodexHomeConfig, } from "./auth.js";
@@ -39,6 +42,11 @@ import { isRecord as isJsonObject } from "./record.js";
39
42
  import { suggestOwnersInternal } from "./suggest-owners.js";
40
43
  import { parseImportedFindings } from "./findings-import.js";
41
44
  import { publishScanToCustom } from "./custom-publish.js";
45
+ import { ExternalPublicationError, prepareExternalPublication, } from "./external-findings-publish.js";
46
+ import { prepareLocalExternalImport } from "./external-findings-import.js";
47
+ import { externalImportsDisabledMessage, externalImportsEnabled, } from "./external-imports-feature.js";
48
+ import { listLocalExternalFindings } from "./external-findings-local.js";
49
+ import { EXTERNAL_FINDINGS_READERS } from "./external-findings-read.js";
42
50
  import { publishPatchReview, resolvePatchReviewPublisher, } from "./patch-publication.js";
43
51
  import { DEFAULT_DEDUPE_CONCURRENCY } from "./deduplication/deduplication.js";
44
52
  import { savedScanWorkbench } from "./saved-scan-bootstrap.js";
@@ -47,13 +55,14 @@ import { runRecordsProtocol } from "./deduplication/records-protocol.js";
47
55
  import { runHostRecordsProtocol } from "./host-records-protocol.js";
48
56
  import { classifySeverityRecords, } from "./classify-severity-records.js";
49
57
  import { runHostedScanProtocol } from "./hosted-scan-protocol.js";
58
+ import { runHostedRemediationProtocol } from "./hosted-remediation-protocol.js";
50
59
  import { runValidationRecordsProtocol } from "./validation-records.js";
51
- import { FindingPatchSchema as findingPatchSchema, parseFindingVerifications, remediationPrompt, } from "./remediation.js";
60
+ import { FindingPatchSchema as findingPatchSchema, parseFindingVerifications, remediationPrompt, VerificationModeSchema, } from "./remediation.js";
52
61
  import { classifyScanSeverityInternal, classifyScanDirectorySeverityInternal, } from "./classify-scan-severity.js";
53
62
  import { resolveCompletedScan, resolveWorkflowScan, } from "./saved-scan.js";
54
63
  import { publishFindingsCsvToCloud, publishScanToCloud, } from "./cloud-publish.js";
55
64
  import { createBulkScanDiscoveryDependencies, createTerminalPrompt, runBulkScanWizard, } from "./bulk-scan-discovery.js";
56
- import { DEFAULT_CODEX_CONFIG, deepMerge, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergeCodexOverrides, hasCommandAuth, inlineToml, quoteTomlString, modelProviderConfigOverride, resolveCommandAuthConfig, resolveCodexProfile, mergedCodexConfig, scanModel, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
65
+ import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergeCodexOverrides, hasCommandAuth, inlineToml, quoteTomlString, modelProviderConfigOverride, resolveCommandAuthConfig, resolveCodexProfile, mergedCodexConfig, scanModel, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
57
66
  import { formatUsd } from "./cost.js";
58
67
  import { formatScanCost, formatScanCostTokens, formatTokenUsage, } from "./cost-model.js";
59
68
  import { readRegularInputFile, resolveScanPrompts } from "./prompt-files.js";
@@ -62,6 +71,7 @@ import { prepareKnowledgeBase, readKnowledgeBaseSnapshot, } from "./knowledge-ba
62
71
  import { restoreScanKnowledge, scanInputIdentity } from "./scan-inputs.js";
63
72
  import { workflowDigest } from "./finding-workflow.js";
64
73
  import { CodexSecurityError, AuthenticationRequiredError, ConfigurationError, InvalidTargetError, IncompleteScanError, LocalPluginBootstrapError, OutputDirectoryError, OutputInsideProtectedRootError, PluginPythonUnavailableError, errorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
74
+ import { GITHUB_ADVISORY_STATES, importGitHubAdvisories, } from "./github-advisories.js";
65
75
  import { GITHUB_ALERT_STATES, importGitHubCodeScanningAlerts, } from "./github.js";
66
76
  import { importLinearIssues, isLinearIssueIdentifier, resolveLinearApiKey, } from "./linear.js";
67
77
  import { runMultiscan } from "./multiscan.js";
@@ -69,7 +79,7 @@ import { componentPlanSchema } from "./component-plan.js";
69
79
  import { runComponentScans, } from "./component-scan.js";
70
80
  import { checkScanPublication, forceTerminatePublicationProcesses as terminatePublishers, publishScanInternal, } from "./publish.js";
71
81
  import { importScan } from "./import-scan.js";
72
- import { bundledPluginRoot, acquireCodexSecurityCredentialHomeLock, withCredentialHomeLock, requireOutputOutsideRepositories, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, executablePathForSpawn, expandHome, prepareCodexSecurityCredentialHome, resolveCodexCommand, resolvePluginPython, pluginMetadata, runWorkbench, sameFile, setCodexSecurityCredentialLogout, } from "./runtime.js";
82
+ import { bundledPluginRoot, cleanupSdkDirectory, createIsolatedHome, resolvePluginPath, acquireCodexSecurityCredentialHomeLock, withCredentialHomeLock, requireOutputOutsideRepositories, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, executablePathForSpawn, environmentWithGit, expandHome, prepareCodexSecurityCredentialHome, resolveCodexCommand, resolvePluginPython, pluginMetadata, runWorkbench, workbenchEnvironment, sameFile, setCodexSecurityCredentialLogout, } from "./runtime.js";
73
83
  import { comparisonFindingGroups, comparisonForScan, matchScanFindingsInternal, unionFindingGroups, } from "./scan-comparison.js";
74
84
  import { scanActivitiesFromEvent } from "./scan-activity.js";
75
85
  import { codexSecurityRequestContext } from "./request-metadata.js";
@@ -78,10 +88,11 @@ import { findScanSession, readSavedScanLogs, } from "./scan-logs.js";
78
88
  import { sendFeedback } from "./feedback.js";
79
89
  import { renderScanHistory, } from "./scan-history-renderer.js";
80
90
  import { ScanDashboard } from "./scan-dashboard.js";
91
+ import { ACCOUNT_LIMITS_UNAVAILABLE, formatAccountLimits, formatUsageFreshness, isChatGptAuthentication, USAGE_TIME_UNAVAILABLE, } from "./scan-usage-display.js";
81
92
  import { policyDisplayData, runPolicyCommand, } from "./security-policy-cli.js";
82
93
  import { scanPhaseLabel as scanPhase, scanProgressCount, } from "./worker-progress.js";
83
- import { abortable, DiffTarget, enclosingGitWorktreeRoots, UNSUPPORTED_GIT_ENVIRONMENT, relativePathIsOutside as isOutsidePath, } from "./targets.js";
84
- import { resolveTrustedExecutable } from "./trusted-executable.js";
94
+ import { abortable, DiffTarget, enclosingGitWorktreeRoots, gitMarkerRoot, normalizeRepository, UNSUPPORTED_GIT_ENVIRONMENT, relativePathIsOutside as isOutsidePath, } from "./targets.js";
95
+ import { inspectTrustedExecutable, resolveTrustedExecutable, } from "./trusted-executable.js";
85
96
  import { BUNDLED_PLUGIN_VERSION, checkForUpdate, CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION, formatUpdateNotice, updateNoticeEnabled, VERSION, } from "./version.js";
86
97
  import { readProjectConfig, resolveScanSettings, projectScopeTarget, configurationSources, projectConfigStarter, } from "./project-config.js";
87
98
  import { resolveConfigPath } from "./config-path.js";
@@ -92,6 +103,19 @@ const PROGRESS_REFRESH_MILLISECONDS = 1_000;
92
103
  const execFile = promisify(execFileCallback);
93
104
  const WINDOWS_NETWORK_PATH = /^[\\/]{2}/u;
94
105
  const WINDOWS_LOCAL_DEVICE_ROOT = /^[\\/]{2}[?.][\\/](?:[A-Za-z]:|Volume\{[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\}|GLOBALROOT[\\/]Device[\\/]HarddiskVolume[0-9]+)(?=[\\/]|$)/iu;
106
+ const FRAMEWORK_ACTIONS = new Set([
107
+ "--llms",
108
+ "--llms-full",
109
+ "--mcp",
110
+ "--update",
111
+ "--incur-update-check",
112
+ ]);
113
+ const FRAMEWORK_VALUE_OPTIONS = new Set([
114
+ "--format",
115
+ "--filter-output",
116
+ "--token-limit",
117
+ "--token-offset",
118
+ ]);
95
119
  const OUTPUT_OPTION = /^--(?:format|filter-output|full-output|token-count|token-limit|token-offset)(?:=|$)/u;
96
120
  const HIDE_CURSOR = "\u001B[?25l";
97
121
  const SHOW_CURSOR = "\u001B[?25h";
@@ -127,6 +151,7 @@ const SKILL_AUTH_OPTION = z
127
151
  .enum(SCAN_AUTH_MODES)
128
152
  .default("auto")
129
153
  .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication.");
154
+ const VERIFICATION_MODE_OPTION = VerificationModeSchema.optional().describe("Use static source review or standard verification (default: standard).");
130
155
  const PROJECT_CONFIG_OPTION = optionValue("--config")
131
156
  .optional()
132
157
  .describe("Load a trusted YAML/JSON file (default: CODEX_SECURITY_PROJECT_CONFIG, otherwise no file).");
@@ -279,6 +304,27 @@ function publicationIssueUrl(value) {
279
304
  }
280
305
  return value;
281
306
  }
307
+ function renderExternalPublicationSummary(result) {
308
+ return [
309
+ `Import ${result.status}.`,
310
+ `Submission totals — Created: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Failed: ${result.counts.error}`,
311
+ `Excluded: ${result.excluded.length} Awaiting acknowledgement: ${result.unacknowledged} Verified: ${result.verified}`,
312
+ ...result.failures.map((item) => `Failed ${diagnosticValue(item.source_finding_id)} (${item.code}): ${diagnosticValue(item.message)}`),
313
+ ...result.excluded.map((item) => `Excluded item ${item.position}${item.source_finding_id ? ` (${diagnosticValue(item.source_finding_id)})` : ""}: ${diagnosticValue(item.reason)}`),
314
+ ...(result.savedSubmission
315
+ ? [`Saved submission: ${diagnosticValue(result.savedSubmission)}`]
316
+ : []),
317
+ ...(result.status === "interrupted"
318
+ ? []
319
+ : [
320
+ "Imported evidence remains not assessed by Codex.",
321
+ result.cloudUrl
322
+ ? `View Cloud repository: ${diagnosticValue(result.cloudUrl)}`
323
+ : "Open the repository in Codex Security Cloud.",
324
+ ]),
325
+ "",
326
+ ].join("\n");
327
+ }
282
328
  function renderPublicationSummary(result, color) {
283
329
  const created = result.created.length;
284
330
  const failed = result.failed.length;
@@ -673,23 +719,50 @@ const DEFAULT_DEPENDENCIES = {
673
719
  runCodex: (args, output, environment, input) => runCodexSkillCommand(args, output, resolveCodexCommand(environment), environment, input),
674
720
  runRepositoryCommand,
675
721
  exportFindings: runArtifactExport,
676
- runWorkbench: async (args, input, signal, pythonPath, protectedRoot) => {
677
- const environment = {
678
- ...exportEnvironment(),
679
- CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
680
- };
681
- return await runWorkbench({
682
- python: await resolvePluginPython({
683
- configuredPath: pythonPath,
684
- environment,
685
- protectedRoot,
686
- signal,
687
- }),
688
- pluginRoot: await bundledPluginRoot(),
722
+ runWorkbench: async (args, input, signal, pythonPath, protectedRoot, gitProtectedRoots = [], pluginPath) => {
723
+ const checkingTarget = args[0] === "get-scan" && args.includes("--check-target");
724
+ let environment = !checkingTarget || protectedRoot === undefined
725
+ ? {
726
+ ...exportEnvironment(),
727
+ CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
728
+ }
729
+ : workbenchEnvironment(process.env);
730
+ const protectedRoots = await Promise.all((protectedRoot === undefined
731
+ ? []
732
+ : typeof protectedRoot === "string"
733
+ ? [protectedRoot]
734
+ : protectedRoot).map(async (root) => (await gitMarkerRoot(root, signal, "outermost")) ?? root));
735
+ const python = await resolvePluginPython({
736
+ configuredPath: pythonPath,
689
737
  environment,
690
738
  signal,
691
- failureMessage: "Could not read Codex Security scan history",
692
- }, args, input);
739
+ protectedRoot: protectedRoot === undefined ? undefined : protectedRoots,
740
+ });
741
+ if (checkingTarget && protectedRoot !== undefined) {
742
+ const git = await inspectTrustedExecutable("git", environment, [
743
+ ...protectedRoots,
744
+ ...gitProtectedRoots,
745
+ ]);
746
+ environment = environmentWithGit(git.environment, git);
747
+ }
748
+ const workspace = pluginPath === undefined
749
+ ? undefined
750
+ : await createIsolatedHome(undefined, (path) => requireOutputOutsideRepositories([...protectedRoots, ...gitProtectedRoots], path, "runtime"));
751
+ try {
752
+ return await runWorkbench({
753
+ python,
754
+ pluginRoot: workspace === undefined
755
+ ? await bundledPluginRoot()
756
+ : await resolvePluginPath(pluginPath, workspace, signal),
757
+ environment,
758
+ signal,
759
+ failureMessage: "Could not read Codex Security scan history",
760
+ }, args, input);
761
+ }
762
+ finally {
763
+ if (workspace !== undefined)
764
+ await cleanupSdkDirectory(workspace).catch(() => undefined);
765
+ }
693
766
  },
694
767
  matchFindings: (input, options) => matchScanFindingsInternal(input, options, { surface: "cli" }),
695
768
  };
@@ -708,80 +781,16 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
708
781
  const ambientConfig = output.appServer === undefined
709
782
  ? {}
710
783
  : resolveCodexProfile(await readCodexHomeConfig(processEnvironment));
711
- const overrides = parseToml(stringifyToml(output.codexOverrides ?? {}));
712
- const config = deepMerge(structuredClone(ambientConfig), overrides);
713
- const provider = output.modelProvider ?? scanModelProvider(config);
714
- // Native Codex ignores configured tables for these built-in providers.
715
- const providerConfiguration = typeof provider === "string" &&
716
- !["openai", "ollama", "lmstudio"].includes(provider)
717
- ? config["model_providers"]?.[provider]
718
- : undefined;
719
- const providerEnvKey = typeof providerConfiguration?.["env_key"] === "string"
720
- ? providerConfiguration["env_key"]
721
- : undefined;
722
- const commandAuth = providerConfiguration?.["auth"] != null;
723
- const explicitChatgpt = output.auth === "chatgpt" && !isExternalModelProvider(provider);
724
- const providerBearer = typeof providerConfiguration?.["experimental_bearer_token"] ===
725
- "string";
726
- const providerKeyConfigured = providerEnvKey !== undefined || providerBearer;
727
- const requiresOpenAiAuth = !commandAuth &&
728
- (explicitChatgpt || !providerKeyConfigured) &&
729
- (provider === undefined ||
730
- provider === "openai" ||
731
- providerConfiguration?.["requires_openai_auth"] === true ||
732
- (explicitChatgpt && providerKeyConfigured));
784
+ const resolved = resolveSkillAuthentication({ ...output, auth: output.auth }, processEnvironment, ambientConfig);
785
+ const { provider, providerConfiguration, providerEnvKey, requiresOpenAiAuth, } = resolved;
786
+ authentication = resolved.authentication;
733
787
  modelProvider = output.modelProvider;
734
788
  let credentialConfig;
735
- if (providerEnvKey !== undefined && !commandAuth && !explicitChatgpt) {
736
- const key = environmentEntry(processEnvironment, providerEnvKey)?.trim();
737
- if (!key && output.auth === "api-key") {
738
- throw new AuthenticationRequiredError(`API-key authentication requires ${providerEnvKey}. Set a valid API key for the selected provider.`);
739
- }
740
- authentication = key
741
- ? { method: "api_key", source: providerEnvKey, verified: false }
742
- : { method: "stored_credentials", verified: false };
743
- }
744
- else {
745
- authentication = scanAuthentication(processEnvironment, output.auth, provider, commandAuth);
746
- }
747
- if (authentication.method === "stored_credentials" &&
748
- isExternalModelProvider(provider)) {
749
- const externalProvider = EXTERNAL_CODEX_PROVIDERS[provider];
750
- throw new AuthenticationRequiredError(`Set ${providerEnvKey ?? externalProvider.env_key} to run ${output.command} through ${externalProvider.name}.`);
751
- }
752
- let selected = selectedScanEnvironment(processEnvironment, authentication.method === "command" ? "chatgpt" : output.auth, provider);
753
- if (explicitChatgpt &&
754
- !commandAuth &&
755
- providerConfiguration !== undefined &&
756
- providerKeyConfigured) {
757
- if (providerEnvKey !== undefined) {
758
- selected = Object.fromEntries(Object.entries(selected).filter(([name]) => process.platform === "win32"
759
- ? name.toUpperCase() !== providerEnvKey.toUpperCase()
760
- : name !== providerEnvKey));
761
- }
762
- // Native provider keys take precedence over stored authentication.
763
- // Apply explicit ChatGPT selection to the home and CLI configuration.
764
- const providerOverrides = typeof provider === "string"
765
- ? overrides["model_providers"]?.[provider]
766
- : undefined;
767
- for (const selectedConfig of [
768
- providerConfiguration,
769
- providerOverrides,
770
- ]) {
771
- if (selectedConfig === undefined)
772
- continue;
773
- delete selectedConfig["env_key"];
774
- delete selectedConfig["experimental_bearer_token"];
775
- selectedConfig["requires_openai_auth"] = true;
776
- }
777
- args = [
778
- ...args,
779
- ...modelProviderConfigOverride(overrides).flatMap((value) => [
780
- "--config",
781
- value,
782
- ]),
783
- ];
784
- }
789
+ let selected = resolved.environment;
790
+ args = [
791
+ ...args,
792
+ ...resolved.configOverrides.flatMap((value) => ["--config", value]),
793
+ ];
785
794
  if (authentication.method === "stored_credentials" &&
786
795
  requiresOpenAiAuth) {
787
796
  const directory = await realpath(output.directory ?? output.appServer?.directory ?? process.cwd());
@@ -1095,18 +1104,42 @@ async function skillDaybreakConfigOverrides(args, command, environment, director
1095
1104
  return overrides;
1096
1105
  }
1097
1106
  export async function main(argv = process.argv.slice(2), output = process.stdout, errorOutput = process.stderr, dependencies = DEFAULT_DEPENDENCIES) {
1107
+ const importsEnabled = externalImportsEnabled(dependencies.environment);
1108
+ const remediationOperation = argv[0] === "patch"
1109
+ ? "patch"
1110
+ : argv[0] === "verify-fix"
1111
+ ? "verify"
1112
+ : undefined;
1113
+ const hostedCommand = argv[0] === "scan" || remediationOperation !== undefined;
1098
1114
  if ((((argv[0] === "dedupe" ||
1099
1115
  argv[0] === "validate" ||
1100
1116
  argv[0] === "classify-severity") &&
1101
1117
  argv.includes("--records")) ||
1102
- (argv[0] === "scan" &&
1118
+ (hostedCommand &&
1103
1119
  argv.some((arg) => arg === "--host" || arg.startsWith("--host=")))) &&
1104
1120
  !argv.includes("--help") &&
1105
1121
  !argv.includes("-h") &&
1106
1122
  !argv.includes("--schema")) {
1107
- if (argv.length !== 2 || (argv[0] === "scan" && argv[1] !== "--host")) {
1108
- errorOutput.write(argv[0] === "scan"
1109
- ? "codex-security: --host must be used alone with scan.\n"
1123
+ let classificationRuns;
1124
+ if (argv[0] === "classify-severity") {
1125
+ try {
1126
+ const { values } = parseArgs({
1127
+ args: argv.slice(1),
1128
+ options: {
1129
+ records: { type: "boolean" },
1130
+ runs: { type: "string" },
1131
+ },
1132
+ });
1133
+ classificationRuns = classificationRunsSchema.parse(values.runs === undefined ? 3 : Number(values.runs));
1134
+ }
1135
+ catch {
1136
+ errorOutput.write("codex-security: Use --records with only --runs (an integer from 1 to 10; default: 3).\n");
1137
+ return 2;
1138
+ }
1139
+ }
1140
+ else if (argv.length !== 2 || (hostedCommand && argv[1] !== "--host")) {
1141
+ errorOutput.write(hostedCommand
1142
+ ? `codex-security: --host must be used alone with ${argv[0]}.\n`
1110
1143
  : `codex-security: --records must be used alone with ${argv[0]}.\n`);
1111
1144
  return 2;
1112
1145
  }
@@ -1120,8 +1153,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1120
1153
  ? runValidationRecordsProtocol
1121
1154
  : runRecordsProtocol;
1122
1155
  const code = argv[0] === "classify-severity"
1123
- ? await runHostRecordsProtocol(dependencies.recordsInput ?? process.stdin, output, (value, options) => classifySeverityRecords(value, options), controller.signal)
1124
- : await runProtocol(dependencies.recordsInput ?? process.stdin, output, controller.signal);
1156
+ ? await runHostRecordsProtocol(dependencies.recordsInput ?? process.stdin, output, (value, options) => classifySeverityRecords(value, {
1157
+ ...options,
1158
+ classificationRuns,
1159
+ }), controller.signal)
1160
+ : remediationOperation !== undefined
1161
+ ? await runHostedRemediationProtocol(dependencies.recordsInput ?? process.stdin, output, controller.signal, remediationOperation)
1162
+ : await runProtocol(dependencies.recordsInput ?? process.stdin, output, controller.signal);
1125
1163
  exitCode =
1126
1164
  controller.signal.reason === "SIGINT"
1127
1165
  ? 130
@@ -1338,7 +1376,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1338
1376
  async run({ args, format }) {
1339
1377
  const requestedRepository = resolveCliPath(dependencies.currentDirectory(), args.repository ?? ".");
1340
1378
  const repository = await realpath(requestedRepository).catch(() => requestedRepository);
1341
- return presentHistory(await history(["list-repositories"], async (value) => {
1379
+ return presentHistory(await history(["list-repositories", "--status", "scanned"], async (value) => {
1342
1380
  const repositories = value["repositories"];
1343
1381
  let target = repositories.find((entry) => entry["targetPath"] === requestedRepository);
1344
1382
  const canonicalTarget = repositories.find((entry) => entry["targetPath"] === repository);
@@ -1366,6 +1404,50 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1366
1404
  }), "findings", format, { repository: requestedRepository });
1367
1405
  },
1368
1406
  });
1407
+ if (importsEnabled) {
1408
+ findingFeedback.command("imported", {
1409
+ description: "List imported vendor evidence for a local repository.",
1410
+ mcp: false,
1411
+ args: z.object({
1412
+ repository: z
1413
+ .string()
1414
+ .optional()
1415
+ .describe("Local repository to inspect (default: current directory)."),
1416
+ }),
1417
+ output: z.record(z.string(), z.unknown()).optional(),
1418
+ async run({ args, format, error: incurError }) {
1419
+ const controller = new AbortController();
1420
+ const removeSignals = listenForAbort(dependencies, controller);
1421
+ try {
1422
+ const repository = resolveCliPath(dependencies.currentDirectory(), args.repository ?? ".");
1423
+ const findings = await (dependencies.listLocalExternalFindings ?? listLocalExternalFindings)({ repository }, {
1424
+ environment: dependencies.environment,
1425
+ signal: controller.signal,
1426
+ });
1427
+ return { repository, findings };
1428
+ }
1429
+ catch (error) {
1430
+ if (controller.signal.aborted) {
1431
+ exitCode = controller.signal.reason === "SIGINT" ? 130 : 143;
1432
+ if (argv.includes("--full-output") &&
1433
+ (format === "json" || format === "jsonl")) {
1434
+ structuredError = true;
1435
+ return incurError({
1436
+ code: "FINDINGS_READ_FAILED",
1437
+ message: diagnosticValue(error),
1438
+ exitCode,
1439
+ });
1440
+ }
1441
+ return;
1442
+ }
1443
+ throw error;
1444
+ }
1445
+ finally {
1446
+ removeSignals();
1447
+ }
1448
+ },
1449
+ });
1450
+ }
1369
1451
  const scanHistory = Cli.create("scans", {
1370
1452
  description: "Review saved scans (default: list).",
1371
1453
  })
@@ -2212,6 +2294,212 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2212
2294
  });
2213
2295
  },
2214
2296
  });
2297
+ let disabledImportInvocation = false;
2298
+ function registerFindingPublication() {
2299
+ publication.command("findings", {
2300
+ description: "Preview and import selected Wiz, Snyk, Semgrep Code, Endor, or GitHub findings locally or to Cloud.",
2301
+ hint: "For Snyk Open Source SCA vulnerabilities only, prefer native snyk test JSON or an official plugin snyk-findings-export/v1 bundle; Open Source SARIF 2.1.0 is also supported. Snyk licenses, Code, Container, IaC and platform backlogs are unsupported. For Semgrep Code, supply native JSON or SARIF and --source-repository-url. For Endor, supply native Finding JSON or endorctl SARIF 2.1.0. For GitHub, supply complete JSON/JSONL saved by import github or import github-advisories. GHSA advisories do not establish an installed dependency or applicability. For Wiz, prefer a native package vulnerability JSON report or named SAST/repository-secret/IaC JSON collections with repository metadata. Normalized JSONL and repository package-vulnerability CSV (SCA only, GitHub repositories) are also supported. Gzip is supported for each format; Wiz CSV does not cover SAST or cloud posture. Other Wiz CSV profiles, scan events, workload secrets, and cloud configuration exports are not supported. --to local stores unassessed evidence for a local repository path without Cloud login. --full-output requires --format json or --format jsonl.\nExample: codex-security publish findings selected-wiz.json --to local --repository ./project --provider wiz --source-key TENANT_ID/vulnerability-finding --dry-run --format json",
2302
+ destructive: true,
2303
+ mcp: false,
2304
+ args: z.object({
2305
+ file: z
2306
+ .string()
2307
+ .describe("Snyk native test JSON, plugin SCA bundle or Open Source SARIF; Semgrep Code JSON/SARIF; Endor Finding JSON/endorctl SARIF; saved GitHub import output; native Wiz JSON, normalized JSONL, or repository package-vulnerability CSV."),
2308
+ }),
2309
+ options: z.object({
2310
+ to: z
2311
+ .enum(["cloud", "local"])
2312
+ .describe("Import destination (required)."),
2313
+ repository: optionValue("--repository").describe("Local repository path for --to local; authorized repository ID or URL for --to cloud."),
2314
+ provider: z
2315
+ .enum(EXTERNAL_FINDINGS_READERS)
2316
+ .describe("Provider that produced these findings."),
2317
+ sourceRepositoryUrl: optionValue("--source-repository-url")
2318
+ .optional()
2319
+ .describe("Required for Semgrep: source repository URL, checked against the Cloud destination or configured local Git remotes."),
2320
+ sourceKey: optionValue("--source-key").describe("Stable vendor tenant and finding namespace; not a project selection filter."),
2321
+ dryRun: z
2322
+ .boolean()
2323
+ .default(false)
2324
+ .describe("Read and preview the destination and findings without storing them."),
2325
+ yes: z
2326
+ .boolean()
2327
+ .default(false)
2328
+ .describe("Confirm publication of the previewed input without a terminal prompt."),
2329
+ }),
2330
+ output: z.record(z.string(), z.unknown()).optional(),
2331
+ async run({ args, options, format, formatExplicit, error: incurError }) {
2332
+ return await withTerminalErrorsHandled(errorOutput, async () => {
2333
+ const writeDiagnostic = (message) => notify(() => errorOutput.write(message));
2334
+ const machineFormat = format === "json" || format === "jsonl";
2335
+ if (argv.includes("--full-output") && !machineFormat) {
2336
+ structuredError = true;
2337
+ exitCode = 2;
2338
+ return incurError({
2339
+ code: "INVALID_ARGUMENTS",
2340
+ message: "Finding imports support --full-output with --format json or --format jsonl. Choose one of those formats or omit --full-output.",
2341
+ exitCode,
2342
+ });
2343
+ }
2344
+ const controller = new AbortController();
2345
+ const removeSignals = listenForAbort(dependencies, controller);
2346
+ const structured = formatExplicit && format !== "toon";
2347
+ const humanSummary = format === "toon" &&
2348
+ !formatExplicit &&
2349
+ !argv.some((argument) => OUTPUT_OPTION.test(argument));
2350
+ const confirmImport = async (preview, showPreview) => {
2351
+ if (options.yes)
2352
+ return true;
2353
+ const prompt = dependencies.externalPublicationPrompt ??
2354
+ createTerminalPrompt(errorOutput);
2355
+ const local = options.to === "local";
2356
+ if (!prompt.isInteractive())
2357
+ throw new CodexSecurityError(`${local ? "Local import" : "Publication"} needs confirmation. Run --dry-run, review the results, then use --yes to approve this input.`);
2358
+ if (structured)
2359
+ showPreview();
2360
+ const action = local
2361
+ ? `Store these ${preview.findings.length} findings locally`
2362
+ : `Publish these ${preview.findings.length} findings`;
2363
+ return prompt.confirm(`${action}${preview.excluded.length ? ` and skip ${preview.excluded.length} excluded records` : ""}?`, false, controller.signal);
2364
+ };
2365
+ let lastProgress = "";
2366
+ const onProgress = (event) => {
2367
+ if (errorOutput.isTTY !== true)
2368
+ return;
2369
+ const step = event.total
2370
+ ? Math.floor((event.completed * 10) / event.total)
2371
+ : 0;
2372
+ const key = `${event.phase}:${step}`;
2373
+ if (key === lastProgress)
2374
+ return;
2375
+ lastProgress = key;
2376
+ const labels = {
2377
+ reading: "Reading selected findings",
2378
+ discovering: "Checking Cloud account and repository",
2379
+ preparing: "Preparing findings",
2380
+ waiting: "Waiting for publication access",
2381
+ uploading: "Acknowledged findings",
2382
+ verifying: "Verifying source records",
2383
+ };
2384
+ writeDiagnostic(`${labels[event.phase]}${event.total === undefined ? "..." : `: ${event.completed}/${event.total}`}\n`);
2385
+ };
2386
+ try {
2387
+ if (!importsEnabled)
2388
+ throw new CodexSecurityError(externalImportsDisabledMessage);
2389
+ if (options.to === "local") {
2390
+ const prepared = await (dependencies.prepareLocalExternalImport ??
2391
+ prepareLocalExternalImport)(resolveCliPath(dependencies.currentDirectory(), args.file), {
2392
+ ...options,
2393
+ repository: resolveCliPath(dependencies.currentDirectory(), options.repository),
2394
+ }, {
2395
+ environment: dependencies.environment,
2396
+ signal: controller.signal,
2397
+ });
2398
+ const { preview } = prepared;
2399
+ const showPreview = () => {
2400
+ writeDiagnostic(`Local repository: ${diagnosticValue(preview.repository)}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}\n`);
2401
+ for (const excluded of preview.excluded)
2402
+ writeDiagnostic(`Excluded item ${excluded.position}: ${diagnosticValue(excluded.reason)}\n`);
2403
+ for (const finding of preview.findings.slice(0, 5))
2404
+ writeDiagnostic(` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`);
2405
+ writeDiagnostic(`Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\nUse --dry-run --format json to inspect all normalized findings and complete evidence before storing them.\n`);
2406
+ };
2407
+ if (!structured)
2408
+ showPreview();
2409
+ if (options.dryRun) {
2410
+ if (humanSummary)
2411
+ renderedOutput = "Dry run complete. No findings stored.\n";
2412
+ return { ...preview, dryRun: true };
2413
+ }
2414
+ if (!(await confirmImport(preview, showPreview))) {
2415
+ if (humanSummary)
2416
+ renderedOutput = "No findings stored.\n";
2417
+ return { imported: false, preview };
2418
+ }
2419
+ const result = await prepared.import();
2420
+ if (result.excluded.length > 0)
2421
+ exitCode = 1;
2422
+ const summary = `Local import complete.\nCreated: ${result.counts.created} Updated: ${result.counts.updated} Unchanged: ${result.counts.unchanged} Excluded: ${result.excluded.length}\nImported evidence remains not assessed by Codex.\nRead stored evidence with codex-security findings imported REPOSITORY.\n`;
2423
+ if (humanSummary)
2424
+ renderedOutput = summary;
2425
+ else if (!structured)
2426
+ writeDiagnostic(summary);
2427
+ return { ...result };
2428
+ }
2429
+ const prepared = await prepareExternalPublication(resolveCliPath(dependencies.currentDirectory(), args.file), options, {
2430
+ environment: dependencies.environment,
2431
+ fetch: dependencies.cloudFetch,
2432
+ signal: controller.signal,
2433
+ onProgress,
2434
+ });
2435
+ const { preview } = prepared;
2436
+ const showPreview = () => {
2437
+ writeDiagnostic(`Cloud API: ${diagnosticValue(preview.cloudApiUrl)}\nAccount: ${diagnosticValue(preview.accountId)}\nDestination: ${diagnosticValue(preview.destination.url)} (${diagnosticValue(preview.destination.id)})\nEnvironment: ${[...new Set(preview.requests.map((request) => request.repository.environment_id))].map(diagnosticValue).join(", ")}\nSource: ${preview.source.provider} / ${diagnosticValue(preview.source.source_key)}\nRead: ${preview.read} Ready: ${preview.findings.length} Excluded: ${preview.excluded.length}${preview.resumed ? "\nResuming the saved submission." : ""}\n`);
2438
+ if (preview.cloudUrl)
2439
+ writeDiagnostic(`Cloud app: ${diagnosticValue(preview.cloudUrl)}\n`);
2440
+ for (const excluded of preview.excluded)
2441
+ writeDiagnostic(`Excluded item ${excluded.position}: ${diagnosticValue(excluded.reason)}\n`);
2442
+ writeDiagnostic(`Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\n`);
2443
+ const severities = new Map();
2444
+ for (const finding of preview.findings)
2445
+ severities.set(finding.evidence.severity, (severities.get(finding.evidence.severity) ?? 0) + 1);
2446
+ writeDiagnostic(`Severities: ${[...severities].map(([severity, count]) => `${severity}: ${count}`).join(" ")}\n`);
2447
+ for (const finding of preview.findings.slice(0, 5))
2448
+ writeDiagnostic(` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`);
2449
+ if (preview.findings.length > 5)
2450
+ writeDiagnostic(`Showing 5 of ${preview.findings.length} findings.\n`);
2451
+ writeDiagnostic("Use --dry-run --format json to inspect all normalized findings and the complete evidence before uploading.\n");
2452
+ };
2453
+ if (!structured)
2454
+ showPreview();
2455
+ if (options.dryRun) {
2456
+ if (humanSummary)
2457
+ renderedOutput = "Dry run complete. No findings uploaded.\n";
2458
+ return { ...preview, dryRun: true };
2459
+ }
2460
+ if (!(await confirmImport(preview, showPreview))) {
2461
+ if (humanSummary)
2462
+ renderedOutput = "No findings published.\n";
2463
+ return { published: false, preview };
2464
+ }
2465
+ const result = await prepared.publish();
2466
+ if (result.status === "partial")
2467
+ exitCode = 1;
2468
+ if (humanSummary)
2469
+ renderedOutput = renderExternalPublicationSummary(result);
2470
+ else if (!structured)
2471
+ writeDiagnostic(renderExternalPublicationSummary(result));
2472
+ return { ...result };
2473
+ }
2474
+ catch (error) {
2475
+ if (argv.includes("--full-output") && machineFormat)
2476
+ failedResultOutput = {
2477
+ format,
2478
+ code: "IMPORT_FAILED",
2479
+ message: diagnosticValue(error),
2480
+ };
2481
+ reportPublicationError(diagnosticValue(error), controller.signal.aborted ? controller.signal.reason : undefined);
2482
+ if (error instanceof ExternalPublicationError) {
2483
+ if (humanSummary)
2484
+ renderedOutput = renderExternalPublicationSummary(error.result);
2485
+ return { ...error.result };
2486
+ }
2487
+ const failure = { status: "failed", error: diagnosticValue(error) };
2488
+ if (machineFormat &&
2489
+ !argv.includes("--full-output") &&
2490
+ argv.some((argument) => /^--filter-output(?:=|$)/u.test(argument)))
2491
+ filteredScanFailure = { format, data: failure };
2492
+ return structured ? failure : undefined;
2493
+ }
2494
+ finally {
2495
+ removeSignals();
2496
+ }
2497
+ });
2498
+ },
2499
+ });
2500
+ }
2501
+ if (importsEnabled)
2502
+ registerFindingPublication();
2215
2503
  publication.command("check", {
2216
2504
  description: "Check saved scan history and Linear access without creating issues.",
2217
2505
  mcp: false,
@@ -2243,10 +2531,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2243
2531
  },
2244
2532
  });
2245
2533
  const imports = Cli.create("import", {
2246
- description: "Read GitHub code scanning alerts.",
2534
+ description: importsEnabled
2535
+ ? "Read GitHub code scanning alerts and security advisories."
2536
+ : "Read GitHub code scanning alerts.",
2247
2537
  }).command("github", {
2248
2538
  description: "Read GitHub code scanning alerts without changing GitHub.",
2249
- hint: "To save CSV or JSON findings as a local scan, use codex-security scan import --help.",
2539
+ hint: `${importsEnabled ? "Save complete --format json output for publish findings --provider github. " : ""}This command reads code-scanning alerts; Dependabot and secret-scanning alerts are not supported. To save CSV or JSON findings as a local scan, use codex-security scan import --help.`,
2250
2540
  destructive: false,
2251
2541
  mcp: false,
2252
2542
  args: z.object({
@@ -2309,6 +2599,88 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2309
2599
  }
2310
2600
  },
2311
2601
  });
2602
+ function registerGitHubAdvisories() {
2603
+ imports.command("github-advisories", {
2604
+ description: "Read GitHub security advisories without changing GitHub.",
2605
+ hint: "Defaults to published repository advisories. Use --github-advisory-source global with explicit --github-advisory IDs to select public database entries. Advisories do not establish an installed dependency or applicability to the selected repository.",
2606
+ destructive: false,
2607
+ mcp: false,
2608
+ args: z.object({
2609
+ repository: z
2610
+ .string()
2611
+ .min(1)
2612
+ .describe("Source repository, or target context for global IDs, in OWNER/REPO form."),
2613
+ }),
2614
+ options: z.object({
2615
+ githubAdvisory: z
2616
+ .array(optionValue("--github-advisory").regex(/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/iu, "GitHub advisory IDs must use GHSA-xxxx-xxxx-xxxx form."))
2617
+ .default([])
2618
+ .describe("Exact GHSA ID; repeat to select a subset. Required for global advisories."),
2619
+ githubAdvisorySource: z
2620
+ .enum(["repository", "global"])
2621
+ .default("repository")
2622
+ .describe("Advisory API to read; global requires exact IDs and never lists the database."),
2623
+ githubState: z
2624
+ .enum(GITHUB_ADVISORY_STATES)
2625
+ .default("published")
2626
+ .describe("Repository advisory list state; omit when selecting exact GHSA IDs."),
2627
+ }),
2628
+ output: z
2629
+ .array(z.object({
2630
+ source: z.literal("github-security-advisory"),
2631
+ selection: z.enum(["repository", "global"]),
2632
+ repository: z.string(),
2633
+ githubHost: z.string(),
2634
+ ghsaId: z.string(),
2635
+ url: z.string(),
2636
+ advisory: z.record(z.string(), z.unknown()),
2637
+ }))
2638
+ .optional(),
2639
+ async run({ args, options, error: incurError }) {
2640
+ const controller = new AbortController();
2641
+ const removeSignals = listenForAbort(dependencies, controller);
2642
+ try {
2643
+ if (!importsEnabled)
2644
+ throw new CodexSecurityError(externalImportsDisabledMessage);
2645
+ return await (dependencies.importGitHubAdvisories ?? importGitHubAdvisories)({
2646
+ repository: args.repository,
2647
+ advisoryIds: options.githubAdvisory,
2648
+ source: options.githubAdvisorySource,
2649
+ state: options.githubState,
2650
+ signal: controller.signal,
2651
+ }, {
2652
+ environment: dependencies.environment,
2653
+ currentDirectory: dependencies.currentDirectory(),
2654
+ });
2655
+ }
2656
+ catch (error) {
2657
+ const signal = controller.signal.reason;
2658
+ if (signal === "SIGINT" || signal === "SIGTERM") {
2659
+ exitCode = signal === "SIGINT" ? 130 : 143;
2660
+ errorOutput.write(`codex-security: GitHub advisory import ${signal === "SIGINT" ? "canceled" : "terminated"}.\n`);
2661
+ }
2662
+ else {
2663
+ exitCode = 2;
2664
+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);
2665
+ }
2666
+ if (argv.includes("--full-output")) {
2667
+ structuredError = true;
2668
+ return incurError({
2669
+ code: "GITHUB_IMPORT_FAILED",
2670
+ message: diagnosticValue(error),
2671
+ exitCode,
2672
+ });
2673
+ }
2674
+ return undefined;
2675
+ }
2676
+ finally {
2677
+ removeSignals();
2678
+ }
2679
+ },
2680
+ });
2681
+ }
2682
+ if (importsEnabled)
2683
+ registerGitHubAdvisories();
2312
2684
  const infoOutput = z.object({
2313
2685
  sdkVersion: z.string(),
2314
2686
  bundledPluginVersion: z.string(),
@@ -2322,7 +2694,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2322
2694
  nextStep: z.string(),
2323
2695
  configuration: z.record(z.string(), z.unknown()),
2324
2696
  });
2325
- const cli = Cli.create("codex-security", {
2697
+ const cliOptions = {
2326
2698
  aliases: ["cs"],
2327
2699
  description: "Find, review, and fix security issues in your code.",
2328
2700
  version: VERSION,
@@ -2331,7 +2703,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2331
2703
  tools: { discovery: "direct" },
2332
2704
  instructions: "Use info for read-only SDK metadata. Scans and other state-changing commands are CLI-only because the MCP transport cannot cancel active commands.",
2333
2705
  },
2334
- })
2706
+ };
2707
+ const cli = Cli.create("codex-security", cliOptions)
2335
2708
  .command("policy", {
2336
2709
  description: "Draft SECURITY.md for review.",
2337
2710
  destructive: true,
@@ -2555,12 +2928,17 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2555
2928
  .boolean()
2556
2929
  .default(false)
2557
2930
  .describe("Patch and verify confirmed findings after the scan."),
2931
+ validate: z
2932
+ .boolean()
2933
+ .default(false)
2934
+ .describe("Run standalone finding validation after the scan."),
2558
2935
  patchSeverity: z
2559
2936
  .enum(REPORTABLE_SEVERITIES)
2560
2937
  .optional()
2561
2938
  .describe("Patch findings at or above LEVEL; requires --patch."),
2562
2939
  createPr: CREATE_PR_OPTION.describe("Create a draft pull request or merge request after verified patches; requires --patch."),
2563
2940
  maxCost: ScanSettingsSchema.shape.maxCostUsd.describe("Stop above AMOUNT in estimated USD; the dashboard offers increases near the limit."),
2941
+ ownerSuggestions: ScanSettingsSchema.shape.ownerSuggestions,
2564
2942
  showCost: SHOW_COST_OPTION,
2565
2943
  headless: z
2566
2944
  .boolean()
@@ -2584,8 +2962,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2584
2962
  .refine((options) => !options.patch || !options.dryRun, {
2585
2963
  message: "--patch cannot be combined with --dry-run.",
2586
2964
  })
2587
- .refine((options) => !options.mock || (!options.dryRun && !options.patch), {
2588
- message: "--mock cannot be combined with --dry-run or --patch.",
2965
+ .refine((options) => !options.validate || !options.dryRun, {
2966
+ message: "--validate cannot be combined with --dry-run.",
2967
+ })
2968
+ .refine((options) => !options.mock ||
2969
+ (!options.dryRun && !options.patch && !options.validate), {
2970
+ message: "--mock cannot be combined with --dry-run, --patch, or --validate.",
2589
2971
  }),
2590
2972
  output: scanOutputSchema("SCAN_FAILED"),
2591
2973
  async run({ args, error: incurError, format, options }) {
@@ -2620,6 +3002,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2620
3002
  if (options.archiveExisting && settings.outputDir === undefined) {
2621
3003
  throw new CodexSecurityError("--archive-existing requires --output-dir.");
2622
3004
  }
3005
+ if (options.validate && settings.maxCostUsd !== undefined) {
3006
+ throw new CodexSecurityError("--validate cannot be combined with a scan cost limit because standalone validation is not cost-tracked.");
3007
+ }
2623
3008
  outcome = await runScan({
2624
3009
  ...settings,
2625
3010
  codexOverrides: config.codexOverrides,
@@ -2632,6 +3017,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2632
3017
  pluginPath: options.pluginPath,
2633
3018
  pythonPath: options.python,
2634
3019
  patch: options.patch,
3020
+ validate: options.validate,
2635
3021
  patchSeverity: options.patchSeverity,
2636
3022
  createPr: options.createPr,
2637
3023
  showCost: options.showCost,
@@ -2778,14 +3164,17 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2778
3164
  })
2779
3165
  .command("classify-severity", {
2780
3166
  description: "Assess severity for saved findings or canonical records.",
2781
- hint: "Use --rubric for saved findings or --records alone for host-provided classification.",
3167
+ hint: "Use --rubric to override the built-in policy or --records for host-provided classification.",
2782
3168
  destructive: true,
2783
3169
  mcp: false,
2784
3170
  options: z.object({
3171
+ runs: classificationRunsSchema
3172
+ .default(3)
3173
+ .describe("Number of independent classification runs (1–10; default: 3)."),
2785
3174
  records: z
2786
3175
  .boolean()
2787
3176
  .default(false)
2788
- .describe("Classify canonical records through host-provided reviews over version 1 JSON-RPC; use alone."),
3177
+ .describe("Classify canonical records through host-provided reviews over version 1 JSON-RPC; accepts --runs."),
2789
3178
  reprocess: z
2790
3179
  .boolean()
2791
3180
  .default(false)
@@ -2798,7 +3187,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2798
3187
  .describe("External completed scan directory."),
2799
3188
  rubric: optionValue("--rubric")
2800
3189
  .optional()
2801
- .describe("Classification policy document; omit to inherit existing severity without a model call."),
3190
+ .describe("Classification policy document; omit to classify with the built-in severity rubric."),
2802
3191
  knowledgeBase: z
2803
3192
  .array(optionValue("--knowledge-base"))
2804
3193
  .default([])
@@ -2831,6 +3220,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2831
3220
  knowledgeBasePaths: options.knowledgeBase.map((path) => resolveCliPath(currentDirectory, path)),
2832
3221
  findingIds: options.findingId.length === 0 ? undefined : options.findingId,
2833
3222
  reprocess: options.reprocess,
3223
+ classificationRuns: options.runs,
2834
3224
  model: options.model,
2835
3225
  reasoningEffort: options.effort,
2836
3226
  };
@@ -3155,11 +3545,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3155
3545
  ? (event) => {
3156
3546
  const componentName = componentNames.get(event.componentId) ??
3157
3547
  event.componentId;
3158
- const line = componentScanEventLine(componentName, event, options.showCost || settings.maxCostUsd !== undefined);
3548
+ const line = componentScanEventLine(componentName, event, options.showCost || settings.maxCostUsd !== undefined, settings.auth);
3159
3549
  if (line !== null)
3160
3550
  errorOutput.write(line);
3161
3551
  }
3162
- : (event) => dashboard?.recordComponentEvent(event),
3552
+ : (event) => dashboard?.recordComponentEvent(event, settings.auth),
3163
3553
  onDeduplicationStarted: () => {
3164
3554
  if (dashboard !== null)
3165
3555
  dashboard.showComponents("Combining duplicate findings");
@@ -3602,6 +3992,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3602
3992
  .describe("Finding text, a file, or a saved finding identifier."),
3603
3993
  }),
3604
3994
  options: z.object({
3995
+ host: z
3996
+ .boolean()
3997
+ .default(false)
3998
+ .describe("Run one hosted fix verification over JSON-RPC stdin/stdout; use alone."),
3999
+ verificationMode: VERIFICATION_MODE_OPTION,
3605
4000
  auth: SKILL_AUTH_OPTION,
3606
4001
  ...MODEL_OPTIONS.shape,
3607
4002
  scan: optionValue("--scan")
@@ -3635,8 +4030,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3635
4030
  },
3636
4031
  ],
3637
4032
  output: z.record(z.string(), z.unknown()).optional(),
3638
- async run({ format, options }) {
4033
+ async run({ format, options, error: incurError }) {
4034
+ const diagnostics = captureOutput();
4035
+ let failureReported = false;
3639
4036
  try {
4037
+ if (options.host)
4038
+ throw new CodexSecurityError("Use verify-fix --host alone.");
3640
4039
  const linear = options.linearIssue.length > 0 || !!options.linearProject;
3641
4040
  if (options.linearIssue.length > 0 && options.linearProject) {
3642
4041
  throw new CodexSecurityError("Use either --linear-issue or --linear-project, not both.");
@@ -3689,22 +4088,33 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3689
4088
  const response = captureOutput();
3690
4089
  const progress = new FindingProgressPresenter(errorOutput, dependencies, repository, identifiers.length);
3691
4090
  progress.startVerification();
4091
+ const verificationErrors = new NodeWritable({
4092
+ write(chunk, _encoding, callback) {
4093
+ diagnostics.stream.write(chunk);
4094
+ progress.stop();
4095
+ void writeCliOutput(errorOutput, chunk).then(() => callback(), callback);
4096
+ },
4097
+ });
3692
4098
  try {
3693
- exitCode = await runSkill("verify-fix", selected === undefined ? [...positionals, ...imports] : [], options, response.stream, errorOutput, dependencies, {
4099
+ exitCode = await runSkill("verify-fix", selected === undefined ? [...positionals, ...imports] : [], options, response.stream, verificationErrors, dependencies, {
3694
4100
  directory: repository,
3695
4101
  ...(selected === undefined
3696
4102
  ? {}
3697
4103
  : { findings: selected.findings }),
3698
4104
  auth: options.auth,
3699
4105
  verificationIds: identifiers,
4106
+ verificationMode: options.verificationMode,
3700
4107
  environment,
3701
4108
  onEvent: progress.observe.bind(progress),
3702
4109
  });
3703
4110
  if (exitCode !== 0) {
3704
- if (exitCode !== 130 && exitCode !== 143)
3705
- exitCode = 2;
3706
- frameworkExit = exitCode;
3707
- return undefined;
4111
+ if (exitCode === 130 || exitCode === 143) {
4112
+ frameworkExit = exitCode;
4113
+ return undefined;
4114
+ }
4115
+ failureReported = diagnostics.text().trim().length > 0;
4116
+ throw new CodexSecurityError(diagnostics.text().trim() ||
4117
+ `Codex verification failed with exit code ${exitCode}.`);
3708
4118
  }
3709
4119
  results = parseFindingVerifications(response.text(), identifiers);
3710
4120
  progress.complete(results);
@@ -3732,8 +4142,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3732
4142
  }
3733
4143
  catch (error) {
3734
4144
  exitCode = 2;
3735
- errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);
3736
- throw error;
4145
+ const message = errorMessage(error);
4146
+ if (!failureReported)
4147
+ errorOutput.write(`codex-security: ${diagnosticValue(message)}\n`);
4148
+ return finishScan({ exitCode, error: message }, format, incurError, "VERIFICATION_FAILED");
3737
4149
  }
3738
4150
  },
3739
4151
  })
@@ -3749,6 +4161,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3749
4161
  .describe("Issue text, a file, or a saved finding identifier."),
3750
4162
  }),
3751
4163
  options: z.object({
4164
+ host: z
4165
+ .boolean()
4166
+ .default(false)
4167
+ .describe("Run one hosted patch over JSON-RPC stdin/stdout; use alone."),
4168
+ verificationMode: VERIFICATION_MODE_OPTION,
3752
4169
  auth: SKILL_AUTH_OPTION,
3753
4170
  ...MODEL_OPTIONS.shape,
3754
4171
  externalSandbox: z
@@ -3804,6 +4221,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3804
4221
  files: [],
3805
4222
  };
3806
4223
  try {
4224
+ if (options.host)
4225
+ throw new CodexSecurityError("Use patch --host alone.");
3807
4226
  const linear = options.linearIssue.length > 0 || !!options.linearProject;
3808
4227
  if (options.resumePr !== undefined) {
3809
4228
  if (positionals.length > 0 ||
@@ -3813,6 +4232,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3813
4232
  options.assessPatchRisk ||
3814
4233
  options.validationPromptFile !== undefined ||
3815
4234
  options.externalSandbox ||
4235
+ options.verificationMode !== undefined ||
3816
4236
  linear ||
3817
4237
  options.linearFilter !== undefined ||
3818
4238
  options.linearApiKey !== undefined ||
@@ -3857,6 +4277,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3857
4277
  auth: options.auth,
3858
4278
  externalSandbox: options.externalSandbox,
3859
4279
  validationPrompt,
4280
+ verificationMode: options.verificationMode,
3860
4281
  });
3861
4282
  exitCode = patchExitCode(patches);
3862
4283
  const files = await changedPatchFiles(selected.repository, patchBase, dependencies);
@@ -3934,6 +4355,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3934
4355
  auth: options.auth,
3935
4356
  externalSandbox: options.externalSandbox,
3936
4357
  validationPrompt,
4358
+ verificationMode: options.verificationMode,
3937
4359
  });
3938
4360
  if (!jsonOutput)
3939
4361
  await writeCliOutput(output, report.text());
@@ -4240,7 +4662,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4240
4662
  },
4241
4663
  });
4242
4664
  const commands = Cli.toCommands.get(cli);
4243
- const valueOptions = cliValueOptions(commands);
4665
+ let valueOptions = cliValueOptions(commands);
4244
4666
  function isScanImportCommand(argv) {
4245
4667
  const commandIndex = cliCommandIndex(argv);
4246
4668
  return argv[commandIndex] === "scan" && argv[commandIndex + 1] === "import";
@@ -4348,6 +4770,36 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4348
4770
  command === "publish" ||
4349
4771
  command === "import";
4350
4772
  const subcommand = nestedCommand ? argv[commandIndex + 1] : undefined;
4773
+ if (command === "import" &&
4774
+ (subcommand === "github" || subcommand === "github-advisories") &&
4775
+ frameworkFlags.rawCollector) {
4776
+ // Incur's skill-sync notice turns a saved collector array into an object.
4777
+ cliOptions.sync = false;
4778
+ }
4779
+ if (!importsEnabled &&
4780
+ ((command === "publish" && subcommand === "findings") ||
4781
+ (command === "findings" && subcommand === "imported") ||
4782
+ (command === "import" && subcommand === "github-advisories"))) {
4783
+ if (process.env["COMPLETE"] ||
4784
+ argv.some((value) => FRAMEWORK_ACTIONS.has(value))) {
4785
+ return externalImportsDisabledMessage;
4786
+ }
4787
+ if (!argv.includes("--version")) {
4788
+ if (argv.includes("--schema") ||
4789
+ (command !== "publish" &&
4790
+ (command !== "import" || !argv.includes("--full-output")))) {
4791
+ return externalImportsDisabledMessage;
4792
+ }
4793
+ disabledImportInvocation = true;
4794
+ // This route only formats a disabled command; it is not an installed skill.
4795
+ cliOptions.sync = false;
4796
+ if (command === "publish")
4797
+ registerFindingPublication();
4798
+ else
4799
+ registerGitHubAdvisories();
4800
+ valueOptions = cliValueOptions(commands);
4801
+ }
4802
+ }
4351
4803
  if (command === "info") {
4352
4804
  for (let index = 0; index < argv.length; index += 1) {
4353
4805
  const argument = argv[index];
@@ -4405,8 +4857,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4405
4857
  : 1)) {
4406
4858
  return `Unexpected positional argument for ${command}${subcommand === undefined ? "" : ` ${subcommand}`}.`;
4407
4859
  }
4860
+ if (disabledImportInvocation && frameworkFlags.hideDisabledRoute)
4861
+ return externalImportsDisabledMessage;
4408
4862
  }
4409
4863
  argv = normalizeScanImportArguments(defaultListCommand(argv));
4864
+ const frameworkArgv = argv.flatMap((argument) => {
4865
+ const separator = argument.indexOf("=");
4866
+ if (separator < 0 ||
4867
+ !FRAMEWORK_VALUE_OPTIONS.has(argument.slice(0, separator)))
4868
+ return [argument];
4869
+ return [argument.slice(0, separator), argument.slice(separator + 1)];
4870
+ });
4871
+ const frameworkFlags = frameworkOutputFlags(frameworkArgv);
4410
4872
  const policyFullOutput = argv[cliCommandIndex(argv)] === "policy" && argv.includes("--full-output");
4411
4873
  const argumentError = validateCliArguments(argv, positionals);
4412
4874
  if (argumentError !== undefined && !policyFullOutput) {
@@ -4500,12 +4962,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4500
4962
  }
4501
4963
  let notice;
4502
4964
  try {
4503
- await cli.serve(argv.flatMap((argument) => {
4504
- if (!/^--(?:format|filter-output|token-limit|token-offset)=/u.test(argument))
4505
- return [argument];
4506
- const separator = argument.indexOf("=");
4507
- return [argument.slice(0, separator), argument.slice(separator + 1)];
4508
- }), {
4965
+ await cli.serve(frameworkArgv, {
4509
4966
  stdout: frameworkCapture.stream.write,
4510
4967
  exit: (code) => {
4511
4968
  frameworkExit = code;
@@ -4553,6 +5010,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4553
5010
  catch { }
4554
5011
  }
4555
5012
  if (frameworkExit !== undefined) {
5013
+ if (disabledImportInvocation && exitCode === 0) {
5014
+ reportPublicationError(externalImportsDisabledMessage, undefined);
5015
+ return exitCode;
5016
+ }
4556
5017
  if (policyFullOutput || structuredError) {
4557
5018
  if (exitCode === 0)
4558
5019
  exitCode = 2;
@@ -4583,7 +5044,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4583
5044
  ...envelope,
4584
5045
  ok: false,
4585
5046
  error: {
4586
- code: "SCAN_FAILED",
5047
+ code: failedResultOutput.code ?? "SCAN_FAILED",
4587
5048
  message: failedResultOutput.message,
4588
5049
  },
4589
5050
  }, null, failedResultOutput.format === "json" ? 2 : undefined)}\n`;
@@ -4710,6 +5171,9 @@ async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt
4710
5171
  DEEP_SCAN_SETTINGS.some(([name]) => deepScan.data?.[name] === undefined)) {
4711
5172
  throw new CodexSecurityError("The saved scan recipe is missing resolved deep scan settings.");
4712
5173
  }
5174
+ const ownerSuggestions = ScanSettingsSchema.shape.ownerSuggestions.safeParse(recipe["ownerSuggestions"]);
5175
+ if (!ownerSuggestions.success)
5176
+ throw new CodexSecurityError("The saved scan recipe contains an invalid owner suggestions setting.");
4713
5177
  const auth = z.enum(SCAN_AUTH_MODES).optional().safeParse(recipe["auth"]);
4714
5178
  const cyberAccessProgram = ScanSettingsSchema.shape.cyberAccessProgram.safeParse(recipe["cyberAccessProgram"]);
4715
5179
  if (!cyberAccessProgram.success) {
@@ -4736,6 +5200,7 @@ async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt
4736
5200
  repository,
4737
5201
  auth: auth.data ?? DEFAULT_SCAN_AUTH,
4738
5202
  cyberAccessProgram: cyberAccessProgram.data,
5203
+ ownerSuggestions: ownerSuggestions.data,
4739
5204
  // Saved scopes contain literal repository names, not home-relative inputs.
4740
5205
  target: paths.length > 0
4741
5206
  ? paths.map((path) => path === "~" || path.startsWith("~/") || path.startsWith("~\\")
@@ -4767,13 +5232,32 @@ async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt
4767
5232
  : undefined,
4768
5233
  };
4769
5234
  }
5235
+ function frameworkOutputFlags(argv) {
5236
+ let hideDisabledRoute = false;
5237
+ let fullOutput = false;
5238
+ let rawCollector = false;
5239
+ for (let index = 0; index < argv.length; index++) {
5240
+ const value = argv[index];
5241
+ if (FRAMEWORK_ACTIONS.has(value) ||
5242
+ value === "--schema" ||
5243
+ value === "--help" ||
5244
+ value === "-h")
5245
+ hideDisabledRoute = true;
5246
+ if (value === "--full-output")
5247
+ fullOutput = true;
5248
+ if (value === "--json")
5249
+ rawCollector = true;
5250
+ if (FRAMEWORK_VALUE_OPTIONS.has(value)) {
5251
+ const operand = argv[++index];
5252
+ if (value === "--format")
5253
+ rawCollector =
5254
+ operand === "json" || operand === "jsonl" || operand === "yaml";
5255
+ }
5256
+ }
5257
+ return { hideDisabledRoute, rawCollector: rawCollector && !fullOutput };
5258
+ }
4770
5259
  function cliValueOptions(commands) {
4771
- const options = new Set([
4772
- "--format",
4773
- "--filter-output",
4774
- "--token-limit",
4775
- "--token-offset",
4776
- ]);
5260
+ const options = new Set(FRAMEWORK_VALUE_OPTIONS);
4777
5261
  for (const command of commands.values()) {
4778
5262
  if ("_group" in command) {
4779
5263
  for (const option of cliValueOptions(command.commands))
@@ -5546,6 +6030,7 @@ async function runSkill(skill, inputs, configuration, stdout, stderr, dependenci
5546
6030
  verificationIds: options.verificationIds,
5547
6031
  findingInstructions: options.findingInstructions,
5548
6032
  validationInstructions: options.validationPrompt,
6033
+ verificationMode: options.verificationMode,
5549
6034
  })
5550
6035
  : validate
5551
6036
  ? await standaloneValidationPrompt(plugin)
@@ -6102,6 +6587,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6102
6587
  let deepConsolidating = false;
6103
6588
  let runningCost = null;
6104
6589
  let runningUsage = null;
6590
+ let usageFreshness = null;
6591
+ let accountLimits = null;
6105
6592
  let maxCostUsd = arguments_.maxCostUsd;
6106
6593
  const showCost = arguments_.showCost === true || maxCostUsd !== undefined;
6107
6594
  let phase = null;
@@ -6181,6 +6668,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6181
6668
  let providerOptions = { provider: "openai" };
6182
6669
  let auth = arguments_.auth;
6183
6670
  let patchAnalyticsOverride;
6671
+ let validation;
6672
+ let validationError;
6184
6673
  let patchServiceTier;
6185
6674
  let patchRequestMetadata;
6186
6675
  let patchOtel;
@@ -6194,6 +6683,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6194
6683
  deepScanOptions(arguments_);
6195
6684
  const directory = dependencies.currentDirectory();
6196
6685
  repository = arguments_.repository ?? directory;
6686
+ if (arguments_.validate) {
6687
+ repository = await normalizeRepository(resolve(directory, expandHome(repository)), preparationAbortController.signal);
6688
+ }
6197
6689
  const target = arguments_.target;
6198
6690
  const prompts = await resolveScanPrompts(arguments_, resolve(directory, repository), directory);
6199
6691
  const config = {
@@ -6297,6 +6789,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6297
6789
  input: scanInput,
6298
6790
  onInterrupt,
6299
6791
  });
6792
+ dashboard.setChatGptAuth(isChatGptAuthentication(selectedAuthentication, auth));
6300
6793
  }
6301
6794
  const scope = scanScope(arguments_);
6302
6795
  const runningMessage = () => {
@@ -6313,9 +6806,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6313
6806
  details.push(`Reviews: ${deepProgress.completed} completed, ${deepProgress.active} active, cap ${deepProgress.maximum}`);
6314
6807
  }
6315
6808
  else if (fileProgress !== null) {
6316
- const count = scanProgressCount(fileProgress);
6317
- if (count.total > 0)
6318
- details.push(`${count.label === "reviews" ? "Reviews" : "Files"}: ${count.completed.toLocaleString("en-US")}/${count.total.toLocaleString("en-US")}`);
6809
+ details.push(formatScanProgressCount(fileProgress, "status"));
6319
6810
  }
6320
6811
  const tokens = runningCost !== null
6321
6812
  ? formatScanCostTokens(runningCost)
@@ -6325,6 +6816,12 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6325
6816
  if (showCost && runningCost !== null) {
6326
6817
  details.push(`Cost: ${formatScanCost(runningCost)}`);
6327
6818
  }
6819
+ if (tokens !== null)
6820
+ details.push(usageFreshness ?? USAGE_TIME_UNAVAILABLE);
6821
+ if (accountLimits !== null)
6822
+ details.push(diagnosticValue(accountLimits));
6823
+ else if (isChatGptAuthentication(selectedAuthentication, auth))
6824
+ details.push(ACCOUNT_LIMITS_UNAVAILABLE);
6328
6825
  return details.length === 0 ? stage : `${stage} | ${details.join(" | ")}`;
6329
6826
  };
6330
6827
  if (dashboard === null) {
@@ -6360,6 +6857,22 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6360
6857
  archiveExisting: arguments_.archiveExisting,
6361
6858
  parentScanId: arguments_.parentScanId,
6362
6859
  expectedPluginVersion: arguments_.expectedPluginVersion,
6860
+ onUsageObservation: async (observation) => {
6861
+ if (dashboard !== null) {
6862
+ dashboard.setUsageObservation(observation);
6863
+ return;
6864
+ }
6865
+ usageFreshness = formatUsageFreshness(observation);
6866
+ accountLimits = formatAccountLimits(observation);
6867
+ const priorUsage = runningUsage;
6868
+ const priorCost = runningCost;
6869
+ // Usage and cost callbacks render the same poll. Refresh here for a receipt alone.
6870
+ await Promise.resolve();
6871
+ if (runningUsage === priorUsage && runningCost === priorCost) {
6872
+ progress?.stopTimer();
6873
+ progress?.startTimer(runningMessage());
6874
+ }
6875
+ },
6363
6876
  onUsage: async (usage) => {
6364
6877
  runningUsage = usage;
6365
6878
  if (dashboard !== null) {
@@ -6429,6 +6942,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6429
6942
  },
6430
6943
  onAuthentication: (authentication) => {
6431
6944
  selectedAuthentication = authentication;
6945
+ dashboard?.setChatGptAuth(isChatGptAuthentication(authentication, auth));
6432
6946
  const bedrock = providerOptions.provider === "amazon-bedrock" ||
6433
6947
  authentication.method === "aws_credentials";
6434
6948
  diagnostic("authentication.selected", {
@@ -6538,8 +7052,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6538
7052
  if (progress === null)
6539
7053
  return;
6540
7054
  progress.stopTimer();
6541
- const count = scanProgressCount(update);
6542
- progress.stage(`Scan phase: ${phase}${count.total === 0 ? "" : ` (${count.completed.toLocaleString("en-US")}/${count.total.toLocaleString("en-US")} ${count.label})`}.`);
7055
+ const count = formatScanProgressCount(update, "phase");
7056
+ progress.stage(`Scan phase: ${phase} (${count}).`);
6543
7057
  progress.startTimer(runningMessage());
6544
7058
  },
6545
7059
  onDeepProgress: (update) => {
@@ -6615,10 +7129,12 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6615
7129
  }
6616
7130
  },
6617
7131
  };
7132
+ if (((arguments_.validate && !arguments_.dryRun) ||
7133
+ arguments_.rerunInputIdentity !== undefined) &&
7134
+ options.knowledgeBasePaths?.length) {
7135
+ options.knowledgeBaseSnapshot = await readKnowledgeBaseSnapshot(options.knowledgeBasePaths, preparationAbortController.signal);
7136
+ }
6618
7137
  if (arguments_.rerunInputIdentity !== undefined) {
6619
- if (options.knowledgeBasePaths?.length) {
6620
- options.knowledgeBaseSnapshot = await readKnowledgeBaseSnapshot(options.knowledgeBasePaths, preparationAbortController.signal);
6621
- }
6622
7138
  const previousInputs = arguments_.rerunInputIdentity;
6623
7139
  const currentInputs = scanInputIdentity(options.scanPrompt, options.knowledgeBaseSnapshot);
6624
7140
  const changes = isJsonObject(previousInputs)
@@ -6643,6 +7159,96 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6643
7159
  result = await security.run(repository, options);
6644
7160
  scanDir = result.scanDir;
6645
7161
  repository = resolve(dependencies.currentDirectory(), repository);
7162
+ if (arguments_.validate) {
7163
+ const scanId = result.manifest.scan.id;
7164
+ const checkTarget = async () => {
7165
+ const context = await dependencies.runWorkbench(["get-scan", "--scan-id", scanId, "--check-target"], undefined, preparationAbortController.signal, config.pythonPath, repository, options.knowledgeBaseSnapshot?.protectedRoots, config.pluginPath);
7166
+ const scan = context["scan"];
7167
+ if (!isJsonObject(scan) ||
7168
+ scan["targetPath"] !== (await realpath(repository))) {
7169
+ throw new CodexSecurityError("The recorded scan target does not match the validation repository.");
7170
+ }
7171
+ };
7172
+ const findings = result.findings.findings;
7173
+ if (targetWarnings.length > 0) {
7174
+ validation = {
7175
+ status: "skipped",
7176
+ reason: "The scan target changed during execution.",
7177
+ };
7178
+ }
7179
+ else if (findings.length === 0) {
7180
+ try {
7181
+ await checkTarget();
7182
+ validation = { status: "complete", findings: 0 };
7183
+ }
7184
+ catch (error) {
7185
+ const message = errorMessage(error);
7186
+ validationError = message;
7187
+ validation = { status: "failed", findings: 0, message };
7188
+ errorOutput.write(`codex-security: Validation failed: ${diagnosticValue(message)}\n`);
7189
+ }
7190
+ }
7191
+ else {
7192
+ stopPresentation();
7193
+ try {
7194
+ progress?.stage(`Validating ${findings.length} scan findings`);
7195
+ }
7196
+ catch { }
7197
+ try {
7198
+ const scanDirectory = result.scanDir;
7199
+ let reportPath = join(scanDirectory, "validation.md");
7200
+ const report = await open(reportPath, "wx", 0o600).catch(async (error) => {
7201
+ if (error.code !== "EEXIST")
7202
+ throw error;
7203
+ reportPath = join(scanDirectory, `validation-${randomUUID()}.md`);
7204
+ return await open(reportPath, "wx", 0o600);
7205
+ });
7206
+ validation = { status: "failed", findings: 0, reportPath };
7207
+ let completed = 0;
7208
+ try {
7209
+ for (const finding of findings) {
7210
+ const assessment = await security.validate({
7211
+ repositoryPath: repository,
7212
+ scanId: result.manifest.scan.id,
7213
+ workflowId: arguments_.workflowId,
7214
+ knowledgeBasePaths: options.knowledgeBasePaths,
7215
+ knowledgeBaseSnapshot: options.knowledgeBaseSnapshot,
7216
+ finding,
7217
+ auth,
7218
+ cyberAccessProgram: arguments_.cyberAccessProgram,
7219
+ safetyIdentifier: arguments_.safetyIdentifier,
7220
+ signal: preparationAbortController.signal,
7221
+ });
7222
+ await report.writeFile(`${completed === 0 ? "" : "\n---\n\n"}## ${finding.occurrenceId}\n\nDisposition: ${assessment.disposition}\n\nEvidence: ${assessment.outputDir}\n\n${assessment.report}\n`);
7223
+ completed += 1;
7224
+ validation = { ...validation, findings: completed };
7225
+ }
7226
+ }
7227
+ finally {
7228
+ await report.close();
7229
+ }
7230
+ await checkTarget();
7231
+ validation = {
7232
+ status: "complete",
7233
+ findings: findings.length,
7234
+ reportPath,
7235
+ };
7236
+ try {
7237
+ progress?.stage(`Finding validation saved to ${reportPath}`);
7238
+ }
7239
+ catch { }
7240
+ }
7241
+ catch (error) {
7242
+ const message = errorMessage(error);
7243
+ validationError = message;
7244
+ validation = { ...validation, status: "failed", message };
7245
+ errorOutput.write(`codex-security: Validation failed: ${diagnosticValue(message)}\n`);
7246
+ if (validation["reportPath"] !== undefined) {
7247
+ errorOutput.write(`Partial validation report: ${diagnosticValue(validation["reportPath"])}\n`);
7248
+ }
7249
+ }
7250
+ }
7251
+ }
6646
7252
  }
6647
7253
  }
6648
7254
  catch (error) {
@@ -6657,7 +7263,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6657
7263
  diagnostic("runtime.cleanup.failed", {
6658
7264
  classification: classifyConnectionFailure(error),
6659
7265
  });
6660
- if (!failed) {
7266
+ if (!failed && validationError === undefined) {
6661
7267
  failed = true;
6662
7268
  failure = error;
6663
7269
  }
@@ -6668,8 +7274,11 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6668
7274
  let failureData;
6669
7275
  if (arguments_.includeFailureResults &&
6670
7276
  (failed || requestedSignal !== null)) {
6671
- if (result !== null)
7277
+ if (result !== null) {
6672
7278
  failureData = result.toJSON();
7279
+ if (validation !== undefined)
7280
+ failureData = { ...failureData, validation };
7281
+ }
6673
7282
  else if (registeredScan !== undefined) {
6674
7283
  try {
6675
7284
  const contract = await loadContract(registeredScan.scanDir, {
@@ -6692,6 +7301,19 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6692
7301
  signal: requestedSignal,
6693
7302
  partial_output: scanDir !== null,
6694
7303
  });
7304
+ if (result !== null && arguments_.validate) {
7305
+ const exitCode = requestedSignal === "SIGINT" ? 130 : 143;
7306
+ const message = `Validation interrupted. Completed scan output was kept at ${errorMessage(result.scanDir)}.`;
7307
+ errorOutput.write(`codex-security: ${message}\n`);
7308
+ return {
7309
+ exitCode,
7310
+ error: message,
7311
+ data: {
7312
+ ...result.toJSON(),
7313
+ validation: { ...validation, status: "failed", exitCode },
7314
+ },
7315
+ };
7316
+ }
6695
7317
  const exitCode = interruptedExit(requestedSignal, scanDir, errorOutput);
6696
7318
  printFailedScanReference(registeredScan, phase, arguments_, errorOutput);
6697
7319
  return {
@@ -6778,6 +7400,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6778
7400
  let scanData = targetWarnings.length === 0
6779
7401
  ? result.toJSON()
6780
7402
  : { ...result.toJSON(), warnings: targetWarnings };
7403
+ if (validation !== undefined)
7404
+ scanData = { ...scanData, validation };
6781
7405
  let deepScanStop;
6782
7406
  if (arguments_.mode === "deep") {
6783
7407
  deepScanStop = (await readDeepScanStop(result, maxCostUsd, dependencies.runWorkbench).catch(() => undefined)) ?? {
@@ -6807,6 +7431,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6807
7431
  ...(error === undefined ? {} : { error }),
6808
7432
  };
6809
7433
  };
7434
+ if (validationError !== undefined) {
7435
+ return finishResult(2, validationError);
7436
+ }
6810
7437
  if (targetWarnings.length > 0) {
6811
7438
  const message = "Scan target changed during execution; results do not represent the current checkout.";
6812
7439
  errorOutput.write(`codex-security: ${message}\n`);
@@ -7192,6 +7819,7 @@ function printScanSummary(result, progress, errorOutput, color, showCost, deepSc
7192
7819
  ? ""
7193
7820
  : ` ${paint("THREAT MODEL", "1;36")} ${paint(errorMessage(threatModelPath), 4)}\n`) +
7194
7821
  `\n ${paint("FINDINGS", 1)} ${paint(`${findingCount}${findingSummary === "" ? "" : ` (${findingSummary})`}`, findingColor)}\n` +
7822
+ ` ${paint("SCOPE", 1)} ${formatCoverageScope(result.coverage)}\n` +
7195
7823
  (deepScanStop === undefined
7196
7824
  ? ""
7197
7825
  : ` ${paint("STOPPED", 1)} ${deepScanStop.reason}\n`) +
@@ -7216,11 +7844,29 @@ function printScanSummary(result, progress, errorOutput, color, showCost, deepSc
7216
7844
  errorOutput.write(`\n ${deepScanStop.nextStep}\n`);
7217
7845
  }
7218
7846
  }
7219
- function componentScanEventLine(componentName, event, showCost) {
7847
+ function formatScanProgressCount(progress, style) {
7848
+ const { label, completed, total } = scanProgressCount(progress);
7849
+ const totalText = total.toLocaleString("en-US");
7850
+ if (label === "files" && completed === 0) {
7851
+ return style === "phase"
7852
+ ? `${totalText} ${total === 1 ? "file" : "files"} inventoried`
7853
+ : `File inventory: ${totalText}`;
7854
+ }
7855
+ const ratio = `${completed.toLocaleString("en-US")}/${totalText}`;
7856
+ return style === "phase"
7857
+ ? `${ratio} ${label}`
7858
+ : `${label === "reviews" ? "Reviews" : "Files"}: ${ratio}`;
7859
+ }
7860
+ function componentScanEventLine(componentName, event, showCost, requestedAuth) {
7861
+ if (event.type === "authentication") {
7862
+ return isChatGptAuthentication(event.value, requestedAuth)
7863
+ ? `codex-security: ${componentName} | ${ACCOUNT_LIMITS_UNAVAILABLE}\n`
7864
+ : null;
7865
+ }
7220
7866
  if (event.type === "progress") {
7221
7867
  const progress = event.value;
7222
- const count = scanProgressCount(progress);
7223
- return `codex-security: ${componentName} ${scanPhase(progress.phase)} | ${count.label === "reviews" ? "Reviews" : "Files"}: ${count.completed.toLocaleString("en-US")}/${count.total.toLocaleString("en-US")}\n`;
7868
+ const count = formatScanProgressCount(progress, "status");
7869
+ return `codex-security: ${componentName} ${scanPhase(progress.phase)} | ${count}\n`;
7224
7870
  }
7225
7871
  if (event.type === "usage") {
7226
7872
  const tokens = formatTokenUsage(event.value);
@@ -7228,6 +7874,13 @@ function componentScanEventLine(componentName, event, showCost) {
7228
7874
  ? null
7229
7875
  : `codex-security: ${componentName} | Tokens: ${tokens}\n`;
7230
7876
  }
7877
+ if (event.type === "usage-observation") {
7878
+ const details = [
7879
+ formatUsageFreshness(event.value) ?? USAGE_TIME_UNAVAILABLE,
7880
+ formatAccountLimits(event.value),
7881
+ ].filter((detail) => detail !== null);
7882
+ return `codex-security: ${componentName} | ${diagnosticValue(details.join(" | "))}\n`;
7883
+ }
7231
7884
  if (event.type !== "cost" || !showCost)
7232
7885
  return null;
7233
7886
  return `codex-security: ${componentName} | Cost: ${formatScanCost(event.value)}\n`;