@openai/codex-security 0.1.27 → 0.1.28

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 (187) hide show
  1. package/README.md +250 -55
  2. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  3. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  4. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  5. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  6. package/_bundled_plugin/references/artifact-storage.md +56 -0
  7. package/_bundled_plugin/references/config-preflight.md +7 -1
  8. package/_bundled_plugin/references/final-report.md +2 -0
  9. package/_bundled_plugin/references/scan-artifacts.md +6 -14
  10. package/_bundled_plugin/references/scan-prologue.md +2 -0
  11. package/_bundled_plugin/references/security-guidance.md +2 -0
  12. package/_bundled_plugin/scripts/deep_scan_config.py +10 -8
  13. package/_bundled_plugin/scripts/deep_scan_defaults.json +8 -0
  14. package/_bundled_plugin/scripts/reserved_artifact_paths.json +6 -0
  15. package/_bundled_plugin/scripts/windows_scan_local_files.py +1 -3
  16. package/_bundled_plugin/scripts/workbench/storage.py +18 -0
  17. package/_bundled_plugin/scripts/workbench_cli.py +13 -0
  18. package/_bundled_plugin/scripts/workbench_db.py +13 -13
  19. package/_bundled_plugin/scripts/workbench_saved_results.py +72 -1
  20. package/_bundled_plugin/scripts/workbench_scan_usage.py +23 -10
  21. package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +2 -0
  22. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +2 -0
  23. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +5 -1
  24. package/_bundled_plugin/skills/finding-discovery/SKILL.md +2 -0
  25. package/_bundled_plugin/skills/fix-finding/SKILL.md +3 -1
  26. package/_bundled_plugin/skills/fix-finding/agents/openai.yaml +1 -1
  27. package/_bundled_plugin/skills/propose-security-hardening/SKILL.md +2 -0
  28. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +5 -1
  29. package/_bundled_plugin/skills/threat-model/SKILL.md +2 -0
  30. package/_bundled_plugin/skills/validation/SKILL.md +2 -0
  31. package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +2 -0
  32. package/dist/api.d.ts +7 -23
  33. package/dist/api.d.ts.map +1 -1
  34. package/dist/api.js +109 -113
  35. package/dist/api.js.map +1 -1
  36. package/dist/auth.d.ts.map +1 -1
  37. package/dist/auth.js.map +1 -1
  38. package/dist/bulk-scan-discovery.d.ts +1 -1
  39. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  40. package/dist/bulk-scan-discovery.js +2 -2
  41. package/dist/bulk-scan-discovery.js.map +1 -1
  42. package/dist/classify-scan-severity.js.map +1 -1
  43. package/dist/classify-severity.d.ts.map +1 -1
  44. package/dist/classify-severity.js.map +1 -1
  45. package/dist/cli.d.ts +6 -2
  46. package/dist/cli.d.ts.map +1 -1
  47. package/dist/cli.js +646 -365
  48. package/dist/cli.js.map +1 -1
  49. package/dist/cloud-publish.js.map +1 -1
  50. package/dist/component-plan.js.map +1 -1
  51. package/dist/component-scan.d.ts +4 -2
  52. package/dist/component-scan.d.ts.map +1 -1
  53. package/dist/component-scan.js +7 -1
  54. package/dist/component-scan.js.map +1 -1
  55. package/dist/config-path.d.ts +6 -0
  56. package/dist/config-path.d.ts.map +1 -0
  57. package/dist/config-path.js +6 -0
  58. package/dist/config-path.js.map +1 -0
  59. package/dist/config.d.ts +2 -0
  60. package/dist/config.d.ts.map +1 -1
  61. package/dist/config.js +13 -3
  62. package/dist/config.js.map +1 -1
  63. package/dist/contract.js.map +1 -1
  64. package/dist/cost-model.d.ts +20 -6
  65. package/dist/cost-model.d.ts.map +1 -1
  66. package/dist/cost-model.js +73 -8
  67. package/dist/cost-model.js.map +1 -1
  68. package/dist/cost.d.ts.map +1 -1
  69. package/dist/custom-publish.js.map +1 -1
  70. package/dist/deduplication/checkpointed-review.d.ts.map +1 -1
  71. package/dist/deduplication/checkpointed-review.js.map +1 -1
  72. package/dist/deduplication/codex-review.d.ts.map +1 -1
  73. package/dist/deduplication/codex-review.js.map +1 -1
  74. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
  75. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  76. package/dist/deduplication/deduplication.js.map +1 -1
  77. package/dist/deduplication/scan.d.ts.map +1 -1
  78. package/dist/deduplication/scan.js.map +1 -1
  79. package/dist/deep-config.d.ts +17 -0
  80. package/dist/deep-config.d.ts.map +1 -0
  81. package/dist/deep-config.js +145 -0
  82. package/dist/deep-config.js.map +1 -0
  83. package/dist/deep-progress.d.ts.map +1 -1
  84. package/dist/deep-scan-defaults.d.ts +9 -0
  85. package/dist/deep-scan-defaults.d.ts.map +1 -0
  86. package/dist/deep-scan-defaults.js +10 -0
  87. package/dist/deep-scan-defaults.js.map +1 -0
  88. package/dist/errors.d.ts.map +1 -1
  89. package/dist/errors.js +2 -2
  90. package/dist/errors.js.map +1 -1
  91. package/dist/feedback.d.ts.map +1 -1
  92. package/dist/feedback.js +21 -7
  93. package/dist/feedback.js.map +1 -1
  94. package/dist/finding-catalogue.js.map +1 -1
  95. package/dist/finding-workflow.d.ts.map +1 -1
  96. package/dist/finding-workflow.js.map +1 -1
  97. package/dist/findings-client.d.ts.map +1 -1
  98. package/dist/findings-client.js.map +1 -1
  99. package/dist/findings-import.d.ts +6 -6
  100. package/dist/github.d.ts +625 -7
  101. package/dist/github.d.ts.map +1 -1
  102. package/dist/github.js.map +1 -1
  103. package/dist/import-scan.js.map +1 -1
  104. package/dist/index.d.ts +5 -0
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +1 -0
  107. package/dist/index.js.map +1 -1
  108. package/dist/knowledge-base.d.ts.map +1 -1
  109. package/dist/knowledge-base.js +17 -6
  110. package/dist/knowledge-base.js.map +1 -1
  111. package/dist/models.d.ts.map +1 -1
  112. package/dist/models.js.map +1 -1
  113. package/dist/multiscan.d.ts +6 -6
  114. package/dist/multiscan.d.ts.map +1 -1
  115. package/dist/multiscan.js +69 -4
  116. package/dist/multiscan.js.map +1 -1
  117. package/dist/patch-tui.d.ts.map +1 -1
  118. package/dist/patch-tui.js.map +1 -1
  119. package/dist/project-config-schema.d.ts +191 -0
  120. package/dist/project-config-schema.d.ts.map +1 -0
  121. package/dist/project-config-schema.js +85 -0
  122. package/dist/project-config-schema.js.map +1 -0
  123. package/dist/project-config.d.ts +50 -0
  124. package/dist/project-config.d.ts.map +1 -0
  125. package/dist/project-config.js +220 -0
  126. package/dist/project-config.js.map +1 -0
  127. package/dist/prompt-files.d.ts +13 -0
  128. package/dist/prompt-files.d.ts.map +1 -0
  129. package/dist/prompt-files.js +74 -0
  130. package/dist/prompt-files.js.map +1 -0
  131. package/dist/publication-events.d.ts.map +1 -1
  132. package/dist/publication-events.js.map +1 -1
  133. package/dist/publish.d.ts.map +1 -1
  134. package/dist/publish.js +1 -1
  135. package/dist/publish.js.map +1 -1
  136. package/dist/result.d.ts +2 -1
  137. package/dist/result.d.ts.map +1 -1
  138. package/dist/result.js +5 -0
  139. package/dist/result.js.map +1 -1
  140. package/dist/runtime.js +4 -4
  141. package/dist/runtime.js.map +1 -1
  142. package/dist/scan-comparison.d.ts.map +1 -1
  143. package/dist/scan-comparison.js.map +1 -1
  144. package/dist/scan-dashboard.d.ts +1 -0
  145. package/dist/scan-dashboard.d.ts.map +1 -1
  146. package/dist/scan-dashboard.js +34 -22
  147. package/dist/scan-dashboard.js.map +1 -1
  148. package/dist/scan-history-renderer.d.ts.map +1 -1
  149. package/dist/scan-history-renderer.js.map +1 -1
  150. package/dist/scan-logs.d.ts +12 -5
  151. package/dist/scan-logs.d.ts.map +1 -1
  152. package/dist/scan-logs.js +49 -18
  153. package/dist/scan-logs.js.map +1 -1
  154. package/dist/scan-modes.d.ts +3 -0
  155. package/dist/scan-modes.d.ts.map +1 -0
  156. package/dist/scan-modes.js +2 -0
  157. package/dist/scan-modes.js.map +1 -0
  158. package/dist/scan-settings.d.ts +81 -0
  159. package/dist/scan-settings.d.ts.map +1 -0
  160. package/dist/scan-settings.js +123 -0
  161. package/dist/scan-settings.js.map +1 -0
  162. package/dist/security-policy-cli.js +2 -2
  163. package/dist/security-policy-cli.js.map +1 -1
  164. package/dist/security-policy.d.ts.map +1 -1
  165. package/dist/security-policy.js.map +1 -1
  166. package/dist/server/dashboard/THIRD_PARTY_NOTICES.txt +2 -2
  167. package/dist/server/dashboard/app.js +2 -2
  168. package/dist/server/dashboard.js.map +1 -1
  169. package/dist/server/embeddings.d.ts.map +1 -1
  170. package/dist/server/embeddings.js.map +1 -1
  171. package/dist/server/errors.d.ts.map +1 -1
  172. package/dist/server/errors.js.map +1 -1
  173. package/dist/server/findings-service.d.ts.map +1 -1
  174. package/dist/server/findings-service.js.map +1 -1
  175. package/dist/server/serve.js.map +1 -1
  176. package/dist/server/sqlite-store.d.ts.map +1 -1
  177. package/dist/server/sqlite-store.js.map +1 -1
  178. package/dist/severity-store.js.map +1 -1
  179. package/dist/targets.d.ts +2 -1
  180. package/dist/targets.d.ts.map +1 -1
  181. package/dist/targets.js.map +1 -1
  182. package/dist/thread-source.d.ts.map +1 -1
  183. package/dist/version.js.map +1 -1
  184. package/dist/worker-progress.d.ts.map +1 -1
  185. package/dist/worker-progress.js.map +1 -1
  186. package/package.json +31 -28
  187. package/schemas/project-config.schema.json +211 -0
package/dist/cli.js CHANGED
@@ -2,9 +2,9 @@
2
2
  import { execFile as execFileCallback, execFileSync, spawn, } from "node:child_process";
3
3
  import { createHash } from "node:crypto";
4
4
  import { accessSync, constants, createReadStream, existsSync, lstatSync, realpathSync, writeSync, } from "node:fs";
5
- import { chmod, lstat, mkdir, mkdtemp, open, readFile, realpath, rm, writeFile, } from "node:fs/promises";
5
+ import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rm, writeFile, } from "node:fs/promises";
6
6
  import { homedir, tmpdir } from "node:os";
7
- import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep, win32, } from "node:path";
7
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve, win32, } from "node:path";
8
8
  import { cwd } from "node:process";
9
9
  import { createInterface } from "node:readline";
10
10
  import { Readable, Writable as NodeWritable } from "node:stream";
@@ -23,9 +23,10 @@ import { classifyScanSeverityInternal, classifyScanDirectorySeverityInternal, }
23
23
  import { resolveCompletedScan, resolveWorkflowScan, } from "./saved-scan.js";
24
24
  import { publishFindingsCsvToCloud, publishScanToCloud, } from "./cloud-publish.js";
25
25
  import { createBulkScanDiscoveryDependencies, runBulkScanWizard, } from "./bulk-scan-discovery.js";
26
- import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, hasCommandAuth, inlineToml, modelProviderConfigOverride, resolveCommandAuthConfig, mergedCodexConfig, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
26
+ import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergeCodexOverrides, hasCommandAuth, inlineToml, modelProviderConfigOverride, resolveCommandAuthConfig, mergedCodexConfig, scanModel, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
27
27
  import { formatUsd } from "./cost.js";
28
- import { formatScanCostTokens, formatTokenUsage } from "./cost-model.js";
28
+ import { formatScanCost, formatScanCostTokens, formatTokenUsage, } from "./cost-model.js";
29
+ import { isOutsidePath, readRegularInputFile, resolveScanPrompts, } from "./prompt-files.js";
29
30
  import { CodexSecurityError, AuthenticationRequiredError, ConfigurationError, InvalidTargetError, OutputDirectoryError, OutputInsideProtectedRootError, PluginPythonUnavailableError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
30
31
  import { GITHUB_ALERT_STATES, importGitHubCodeScanningAlerts, } from "./github.js";
31
32
  import { importLinearIssues, isLinearIssueIdentifier, resolveLinearApiKey, } from "./linear.js";
@@ -47,6 +48,11 @@ import { scanPhaseLabel as scanPhase, } from "./worker-progress.js";
47
48
  import { abortable, DiffTarget, enclosingGitWorktreeRoots, } from "./targets.js";
48
49
  import { resolveTrustedExecutable } from "./trusted-executable.js";
49
50
  import { BUNDLED_PLUGIN_VERSION, checkForUpdate, CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION, formatUpdateNotice, updateNoticeEnabled, VERSION, } from "./version.js";
51
+ import { readProjectConfig, resolveScanSettings, projectScopeTarget, configurationSources, projectConfigStarter, } from "./project-config.js";
52
+ import { resolveConfigPath } from "./config-path.js";
53
+ import { resolveDeepScanConfig } from "./deep-config.js";
54
+ import { SCAN_MODES } from "./scan-modes.js";
55
+ import { DEEP_SCAN_SETTINGS, DeepScanSettingsSchema, DEFAULT_SCAN_AUTH, FailureSeveritySchema, REPORTABLE_SEVERITIES, SCAN_SEVERITIES, ScanSettingsSchema, pickScanSettings, meetsSeverity, } from "./scan-settings.js";
50
56
  const PROGRESS_REFRESH_MILLISECONDS = 1_000;
51
57
  const execFile = promisify(execFileCallback);
52
58
  const WINDOWS_NETWORK_PATH = /^[\\/]{2}/u;
@@ -59,16 +65,7 @@ const DUPLICATE_SIGNAL_WINDOW_MS = 500;
59
65
  const PUBLICATION_GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, {
60
66
  granularity: "grapheme",
61
67
  });
62
- const REPORTABLE_SEVERITIES = [
63
- "critical",
64
- "high",
65
- "medium",
66
- "low",
67
- ];
68
- const DISPLAY_SEVERITIES = [
69
- ...REPORTABLE_SEVERITIES,
70
- "informational",
71
- ];
68
+ const DISPLAY_SEVERITIES = SCAN_SEVERITIES;
72
69
  const MODEL_REASONING_EFFORTS = [
73
70
  "minimal",
74
71
  "low",
@@ -81,12 +78,17 @@ const DEFAULT_SCAN_MODEL_CONFIGURATION = scanModelConfiguration(DEFAULT_CODEX_CO
81
78
  const CODEX_OVERRIDE_DESCRIPTION = 'Repeat TOML KEY=VALUE; e.g. model_reasoning_effort="high" or features.multi_agent_v2.max_concurrent_threads_per_session=4.';
82
79
  const PLUGIN_PATH_DESCRIPTION = "Codex Security plugin directory or ZIP (default: bundled plugin).";
83
80
  const PYTHON_PATH_DESCRIPTION = "Python interpreter (default: PYTHON or automatic discovery).";
81
+ const PROJECT_CONFIG_OPTION = optionValue("--config")
82
+ .optional()
83
+ .describe("Load a trusted YAML/JSON file (default: CODEX_SECURITY_PROJECT_CONFIG, otherwise no file).");
84
84
  const EXPORT_DEFAULT_OUTPUTS = {
85
85
  csv: "findings.csv",
86
86
  json: "findings.json",
87
87
  sarif: "results.sarif",
88
88
  };
89
89
  const VALUE_OPTIONS = new Set([
90
+ "--config",
91
+ "-c",
90
92
  "--port",
91
93
  "--workflow-id",
92
94
  "--concurrency",
@@ -152,6 +154,10 @@ const PROVIDER_OPTION = z
152
154
  .enum(["openai", "openrouter", "fireworks", "amazon-bedrock"])
153
155
  .default("openai")
154
156
  .describe("Inference provider for scans.");
157
+ const SHOW_COST_OPTION = z
158
+ .boolean()
159
+ .default(false)
160
+ .describe("Show estimated USD cost; always shown when a cost limit is set.");
155
161
  const CREATE_PR_OPTION = z
156
162
  .boolean()
157
163
  .default(false)
@@ -604,95 +610,21 @@ function effortOption() {
604
610
  .optional()
605
611
  .describe(`Model reasoning effort (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.reasoningEffort}).`);
606
612
  }
607
- const DEEP_SCAN_OPTION_SCHEMAS = {
608
- workers: z
609
- .number()
610
- .int()
611
- .positive()
612
- .optional()
613
- .describe("Maximum concurrent deep-scan discovery workers."),
614
- subagents: z
615
- .number()
616
- .int()
617
- .nonnegative()
618
- .optional()
619
- .describe("Subagents available to each deep-scan worker."),
620
- stopAfterNoNew: z
621
- .number()
622
- .int()
623
- .positive()
624
- .optional()
625
- .describe("Stop after this many runs find no new issues."),
626
- maxDiscoveryRuns: z
627
- .number()
628
- .int()
629
- .positive()
630
- .optional()
631
- .describe("Maximum deep-scan discovery runs."),
632
- maxTimeHours: z
633
- .number()
634
- .positive()
635
- .max(96)
636
- .optional()
637
- .describe("Maximum deep-scan discovery hours (default: 96; maximum: 96)."),
638
- };
639
- async function readPromptFiles(directory, scanPromptFile, postScanPromptFile, repository = directory, validationPromptFile) {
640
- const [scanPrompt, postScanPrompt, validationPrompt] = await Promise.all([
641
- scanPromptFile === undefined
642
- ? undefined
643
- : readRegularInputFile(resolveCliPath(directory, scanPromptFile), repository),
644
- postScanPromptFile === undefined
645
- ? undefined
646
- : readRegularInputFile(resolveCliPath(directory, postScanPromptFile), repository),
647
- validationPromptFile === undefined
648
- ? undefined
649
- : readRegularInputFile(resolveCliPath(directory, validationPromptFile), repository),
650
- ]);
651
- if (validationPrompt !== undefined && !validationPrompt.trim()) {
652
- throw new CodexSecurityError("The validation prompt must not be empty.");
653
- }
654
- return {
655
- ...(scanPrompt?.trim() ? { scanPrompt } : {}),
656
- ...(validationPrompt === undefined ? {} : { validationPrompt }),
657
- ...(postScanPrompt?.trim() ? { postScanPrompt } : {}),
658
- };
613
+ const DEEP_SCAN_OPTION_SCHEMAS = Object.fromEntries(DEEP_SCAN_SETTINGS.filter(([, , , flag]) => flag !== null).map(([name]) => [
614
+ name,
615
+ DeepScanSettingsSchema.shape[name],
616
+ ]));
617
+ export function resolveCliPath(directory, value) {
618
+ return resolveConfigPath(directory, value);
659
619
  }
660
- async function readRegularInputFile(path, repository, metadata) {
661
- const selected = metadata ?? (await lstat(path, { bigint: true }));
662
- if (!selected.isFile()) {
663
- throw new CodexSecurityError("Input files must be regular files.");
664
- }
665
- const canonicalRepository = await realpath(repository);
666
- const canonicalParent = await realpath(dirname(path));
667
- if (isOutsidePath(relative(canonicalRepository, canonicalParent))) {
668
- for (let ancestor = dirname(path);; ancestor = dirname(ancestor)) {
669
- if (!isOutsidePath(relative(canonicalRepository, await realpath(ancestor)))) {
670
- throw new CodexSecurityError("Input files must not follow repository directory links outside the selected repository.");
671
- }
672
- if (dirname(ancestor) === ancestor) {
673
- break;
674
- }
675
- }
676
- }
677
- const file = await open(join(canonicalParent, basename(path)), constants.O_RDONLY |
678
- (constants.O_NOFOLLOW ?? 0) |
679
- (constants.O_NONBLOCK ?? 0));
680
- try {
681
- const opened = await file.stat({ bigint: true });
682
- if (!opened.isFile() ||
683
- opened.dev !== selected.dev ||
684
- opened.ino !== selected.ino) {
685
- throw new CodexSecurityError("Input files must remain regular files.");
686
- }
687
- return await file.readFile({ encoding: "utf8" });
688
- }
689
- finally {
690
- await file.close();
620
+ class PatchCommandError extends CodexSecurityError {
621
+ code;
622
+ constructor(code, message) {
623
+ super(message);
624
+ this.code = code;
691
625
  }
692
626
  }
693
- export function resolveCliPath(directory, value) {
694
- return resolve(directory, expandHome(value));
695
- }
627
+ const SANDBOX_UNAVAILABLE_MESSAGE = "The patch sandbox could not start. Check the runner's sandbox permissions and retry. No patch was applied; 0 files changed.";
696
628
  const findingPatchSchema = z.object({
697
629
  occurrenceId: z.string(),
698
630
  status: z.enum(["verified", "no_change", "blocked", "failed"]),
@@ -793,7 +725,7 @@ const DEFAULT_DEPENDENCIES = {
793
725
  [status] = await Promise.all([
794
726
  new Promise((resolve, reject) => {
795
727
  invocation.once("error", reject);
796
- invocation.once("close", (code, signal) => resolve(signal === null ? code ?? 1 : 1));
728
+ invocation.once("close", (code, signal) => resolve(signal === null ? (code ?? 1) : 1));
797
729
  }),
798
730
  forwarded,
799
731
  ]);
@@ -1023,6 +955,7 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
1023
955
  threadSource: output.appServer.threadSource,
1024
956
  input: invocation.stdin,
1025
957
  sandbox: output.appServer.sandbox,
958
+ externalSandbox: output.appServer.externalSandbox,
1026
959
  onEvent: output.appServer.onEvent,
1027
960
  }),
1028
961
  new Promise((resolve) => {
@@ -1040,7 +973,7 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
1040
973
  ? 130
1041
974
  : requestedSignal === "SIGTERM" || signal === "SIGTERM"
1042
975
  ? 143
1043
- : code ?? 1);
976
+ : (code ?? 1));
1044
977
  };
1045
978
  forceStatusCompletion = () => complete(null, null);
1046
979
  invocation.once("error", (error) => {
@@ -1053,6 +986,9 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
1053
986
  invocation.once(output === undefined ? "exit" : "close", complete);
1054
987
  });
1055
988
  let [status, events] = await Promise.all([invocationStatus, captured]);
989
+ if (events?.sandboxUnavailable && requestedSignal === null) {
990
+ throw new PatchCommandError("SANDBOX_UNAVAILABLE", SANDBOX_UNAVAILABLE_MESSAGE);
991
+ }
1056
992
  if (status === 0 && output?.appServer !== undefined && events?.error) {
1057
993
  status = 1;
1058
994
  }
@@ -1178,6 +1114,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1178
1114
  let renderedHistory;
1179
1115
  let renderedPublication;
1180
1116
  let renderedPolicy;
1117
+ let renderedPatch;
1118
+ let patchStructuredError = false;
1181
1119
  const runImport = (options) => runScanImport(options, errorOutput, dependencies);
1182
1120
  const history = async (args, select = (value) => value) => {
1183
1121
  try {
@@ -1464,6 +1402,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1464
1402
  scanId: z.string().min(1).describe("Interrupted Deep Scan identifier."),
1465
1403
  }),
1466
1404
  options: z.object({
1405
+ showCost: SHOW_COST_OPTION,
1467
1406
  verbose: z
1468
1407
  .boolean()
1469
1408
  .default(false)
@@ -1482,13 +1421,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1482
1421
  typeof saved["scanDir"] !== "string") {
1483
1422
  throw new CodexSecurityError("The workbench returned invalid scan resume context.");
1484
1423
  }
1485
- scanArguments = scanArgumentsFromRecipe(saved["recipe"], saved["scanId"]);
1424
+ scanArguments = await prepareScanArgumentsFromRecipe(saved["recipe"], saved["scanId"], {
1425
+ scanPrompt: typeof saved["userContext"] === "string"
1426
+ ? saved["userContext"]
1427
+ : undefined,
1428
+ }, dependencies.currentDirectory());
1486
1429
  scanArguments.resumeScanId = saved["scanId"];
1487
- scanArguments.outputDir = saved["scanDir"];
1430
+ scanArguments.outputDir = resolveCliPath(dependencies.currentDirectory(), saved["scanDir"]);
1488
1431
  scanArguments.parentScanId = undefined;
1489
1432
  // Resume uses the installed engine with the saved recipe and checkpoints.
1490
1433
  scanArguments.expectedPluginVersion = undefined;
1491
1434
  scanArguments.verbose = options.verbose;
1435
+ scanArguments.showCost = options.showCost;
1492
1436
  }
1493
1437
  catch (error) {
1494
1438
  const message = errorMessage(error);
@@ -1524,6 +1468,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1524
1468
  .describe("Saved scan identifier (default: latest completed scan)."),
1525
1469
  }),
1526
1470
  options: z.object({
1471
+ showCost: SHOW_COST_OPTION,
1472
+ scanPromptFile: optionValue("--scan-prompt-file")
1473
+ .optional()
1474
+ .describe("Supply additional scan instructions; required when the saved scan used them."),
1527
1475
  validationPromptFile: optionValue("--validation-prompt-file")
1528
1476
  .optional()
1529
1477
  .describe("Use FILE for custom validation; required when rerunning a custom-validation scan."),
@@ -1548,8 +1496,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1548
1496
  isJsonObject(recipe) &&
1549
1497
  recipe["import"] !== undefined &&
1550
1498
  isJsonObject(recipe["import"])) {
1551
- if (options.validationPromptFile !== undefined) {
1552
- throw new CodexSecurityError("--validation-prompt-file is not supported when rerunning an imported scan; imports do not perform security analysis.");
1499
+ if (options.validationPromptFile !== undefined ||
1500
+ options.scanPromptFile !== undefined) {
1501
+ const option = options.validationPromptFile !== undefined
1502
+ ? "--validation-prompt-file"
1503
+ : "--scan-prompt-file";
1504
+ throw new CodexSecurityError(`${option} is not supported when rerunning an imported scan; imports do not perform security analysis.`);
1553
1505
  }
1554
1506
  const imported = recipe["import"];
1555
1507
  const sourcePath = imported["sourcePath"];
@@ -1574,8 +1526,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1574
1526
  }
1575
1527
  return outcome.data;
1576
1528
  }
1577
- scanArguments = scanArgumentsFromRecipe(recipe, scanId, options.validationPromptFile);
1529
+ scanArguments = await prepareScanArgumentsFromRecipe(recipe, scanId, {
1530
+ scanPromptFile: options.scanPromptFile === undefined
1531
+ ? undefined
1532
+ : resolveCliPath(dependencies.currentDirectory(), options.scanPromptFile),
1533
+ validationPromptFile: options.validationPromptFile === undefined
1534
+ ? undefined
1535
+ : resolveCliPath(dependencies.currentDirectory(), options.validationPromptFile),
1536
+ }, dependencies.currentDirectory());
1578
1537
  scanArguments.verbose = options.verbose;
1538
+ scanArguments.showCost = options.showCost;
1579
1539
  }
1580
1540
  catch (error) {
1581
1541
  const message = errorMessage(error);
@@ -2255,6 +2215,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2255
2215
  version: VERSION,
2256
2216
  mcp: {
2257
2217
  command: "npx --yes @openai/codex-security --mcp",
2218
+ tools: { discovery: "direct" },
2258
2219
  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.",
2259
2220
  },
2260
2221
  })
@@ -2418,6 +2379,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2418
2379
  "Use ./import to scan a repository named import.",
2419
2380
  destructive: true,
2420
2381
  mcp: false,
2382
+ alias: { config: "c" },
2421
2383
  args: z.object({
2422
2384
  repository: z
2423
2385
  .string()
@@ -2426,13 +2388,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2426
2388
  }),
2427
2389
  options: z
2428
2390
  .object({
2391
+ config: PROJECT_CONFIG_OPTION,
2429
2392
  workflowId: optionValue("--workflow-id")
2430
2393
  .optional()
2431
2394
  .describe("Reuse completed work in the named local findings workflow."),
2432
- auth: z
2433
- .enum(SCAN_AUTH_MODES)
2434
- .default("auto")
2435
- .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
2395
+ auth: ScanSettingsSchema.shape.auth.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication (default: auto)."),
2436
2396
  verbose: z
2437
2397
  .boolean()
2438
2398
  .default(false)
@@ -2442,11 +2402,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2442
2402
  .describe("Stable hashed end-user ID for this scan's model requests (1–64 characters)."),
2443
2403
  path: z
2444
2404
  .array(optionValue("--path"))
2445
- .default([])
2405
+ .optional()
2406
+ .meta({ default: [] })
2446
2407
  .describe("Scan only PATH; repeat for multiple repository-relative paths."),
2447
2408
  knowledgeBase: z
2448
2409
  .array(optionValue("--knowledge-base"))
2449
- .default([])
2410
+ .optional()
2411
+ .meta({ default: [] })
2450
2412
  .describe("Add security-context files or directories; repeat for multiple paths."),
2451
2413
  scanPromptFile: optionValue("--scan-prompt-file")
2452
2414
  .optional()
@@ -2462,7 +2424,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2462
2424
  .describe("Scan committed Git changes from BASE to --head."),
2463
2425
  workingTree: z
2464
2426
  .boolean()
2465
- .default(false)
2427
+ .optional()
2428
+ .meta({ default: false })
2466
2429
  .describe("Scan staged and unstaged changes against --base."),
2467
2430
  head: optionValue("--head")
2468
2431
  .optional()
@@ -2470,10 +2433,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2470
2433
  base: optionValue("--base")
2471
2434
  .optional()
2472
2435
  .describe("Git base ref for --working-tree (default: HEAD)."),
2473
- mode: z
2474
- .enum(["standard", "deep"])
2475
- .default("standard")
2476
- .describe("Scan mode; deep supports repository and path targets."),
2436
+ mode: ScanSettingsSchema.shape.mode.describe("Scan mode (default: standard); deep supports repository and path targets."),
2477
2437
  ...DEEP_SCAN_OPTION_SCHEMAS,
2478
2438
  model: optionValue("--model")
2479
2439
  .optional()
@@ -2497,10 +2457,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2497
2457
  .array(optionValue("--codex"))
2498
2458
  .default([])
2499
2459
  .describe(CODEX_OVERRIDE_DESCRIPTION),
2500
- failOnSeverity: z
2501
- .enum(REPORTABLE_SEVERITIES)
2502
- .optional()
2503
- .describe("Exit 1 for findings at or above LEVEL."),
2460
+ failOnSeverity: FailureSeveritySchema.optional().describe("Exit 1 for findings at or above LEVEL."),
2504
2461
  patch: z
2505
2462
  .boolean()
2506
2463
  .default(false)
@@ -2510,11 +2467,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2510
2467
  .optional()
2511
2468
  .describe("Patch findings at or above LEVEL; requires --patch."),
2512
2469
  createPr: CREATE_PR_OPTION,
2513
- maxCost: z
2514
- .number()
2515
- .positive()
2516
- .optional()
2517
- .describe("Stop above AMOUNT in estimated USD; the dashboard offers increases near the limit."),
2470
+ maxCost: ScanSettingsSchema.shape.maxCostUsd.describe("Stop above AMOUNT in estimated USD; the dashboard offers increases near the limit."),
2471
+ showCost: SHOW_COST_OPTION,
2518
2472
  headless: z
2519
2473
  .boolean()
2520
2474
  .default(false)
@@ -2528,17 +2482,6 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2528
2482
  .default(false)
2529
2483
  .describe("Save synthetic Standard scan findings without calling an LLM."),
2530
2484
  })
2531
- .refine((options) => Number(options.path.length > 0) +
2532
- Number(options.diff !== undefined) +
2533
- Number(options.workingTree) <=
2534
- 1, {
2535
- message: "--path, --diff, and --working-tree are mutually exclusive.",
2536
- })
2537
- .refine((options) => options.head === undefined || options.diff !== undefined, { message: "--head requires --diff." })
2538
- .refine((options) => options.base === undefined || options.workingTree, {
2539
- message: "--base requires --working-tree.",
2540
- })
2541
- .refine((options) => !options.archiveExisting || options.outputDir !== undefined, { message: "--archive-existing requires --output-dir." })
2542
2485
  .refine((options) => options.patchSeverity === undefined || options.patch, {
2543
2486
  message: "--patch-severity requires --patch.",
2544
2487
  })
@@ -2550,15 +2493,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2550
2493
  })
2551
2494
  .refine((options) => !options.mock || (!options.dryRun && !options.patch), {
2552
2495
  message: "--mock cannot be combined with --dry-run or --patch.",
2553
- })
2554
- .refine((options) => options.mode === "deep" ||
2555
- (options.workers === undefined &&
2556
- options.subagents === undefined &&
2557
- options.stopAfterNoNew === undefined &&
2558
- options.maxDiscoveryRuns === undefined &&
2559
- options.maxTimeHours === undefined), { message: "Deep scan settings require --mode deep." }),
2496
+ }),
2560
2497
  examples: [
2561
2498
  { args: { repository: "." } },
2499
+ {
2500
+ args: { repository: "." },
2501
+ options: { config: "codex-security.yaml" },
2502
+ },
2562
2503
  { args: { repository: "." }, options: { model: "gpt-5.6-terra" } },
2563
2504
  {
2564
2505
  args: { repository: "." },
@@ -2582,44 +2523,63 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2582
2523
  exitCode = 2;
2583
2524
  return;
2584
2525
  }
2585
- const outcome = await runScan({
2586
- auth: options.auth,
2587
- workflowId: options.workflowId,
2588
- safetyIdentifier: options.safetyIdentifier,
2589
- verbose: options.verbose,
2590
- repository: args.repository,
2591
- paths: options.path,
2592
- knowledgeBasePaths: options.knowledgeBase,
2593
- scanPromptFile: options.scanPromptFile,
2594
- validationPromptFile: options.validationPromptFile,
2595
- postScanPromptFile: options.postScanPromptFile,
2596
- diff: options.diff,
2597
- workingTree: options.workingTree,
2598
- head: options.head,
2599
- base: options.base,
2600
- mode: options.mode,
2601
- workers: options.workers,
2602
- subagents: options.subagents,
2603
- stopAfterNoNew: options.stopAfterNoNew,
2604
- maxDiscoveryRuns: options.maxDiscoveryRuns,
2605
- maxTimeHours: options.maxTimeHours,
2606
- model: options.model,
2607
- effort: options.effort,
2608
- provider: options.provider,
2609
- outputDir: options.outputDir,
2610
- archiveExisting: options.archiveExisting,
2611
- pluginPath: options.pluginPath,
2612
- pythonPath: options.python,
2613
- codex: options.codex,
2614
- failOnSeverity: options.failOnSeverity,
2615
- patch: options.patch,
2616
- patchSeverity: options.patchSeverity,
2617
- createPr: options.createPr,
2618
- maxCostUsd: options.maxCost,
2619
- headless: options.headless,
2620
- dryRun: options.dryRun,
2621
- mock: options.mock,
2622
- }, errorOutput, dependencies, format !== "json" && format !== "jsonl");
2526
+ let outcome;
2527
+ try {
2528
+ const directory = dependencies.currentDirectory();
2529
+ const project = await selectedProjectConfig(options.config, dependencies);
2530
+ const scope = resolveCliScope(project?.input.scan?.scope, {
2531
+ paths: options.path,
2532
+ diff: options.diff,
2533
+ workingTree: options.workingTree,
2534
+ head: options.head,
2535
+ base: options.base,
2536
+ });
2537
+ const { config, options: settings, projectConfig: provenance, } = resolveScanSettings(project, {
2538
+ auth: options.auth,
2539
+ target: scope.target,
2540
+ knowledgeBasePaths: options.knowledgeBase,
2541
+ scanPromptFile: options.scanPromptFile,
2542
+ validationPromptFile: options.validationPromptFile,
2543
+ postScanPromptFile: options.postScanPromptFile,
2544
+ mode: options.mode,
2545
+ workers: options.workers,
2546
+ subagents: options.subagents,
2547
+ stopAfterNoNew: options.stopAfterNoNew,
2548
+ maxDiscoveryRuns: options.maxDiscoveryRuns,
2549
+ maxTimeHours: options.maxTimeHours,
2550
+ outputDir: options.outputDir,
2551
+ failureSeverity: options.failOnSeverity,
2552
+ maxCostUsd: options.maxCost,
2553
+ codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider, project?.input.codex),
2554
+ }, directory, scope.sources);
2555
+ if (options.archiveExisting && settings.outputDir === undefined) {
2556
+ throw new CodexSecurityError("--archive-existing requires --output-dir.");
2557
+ }
2558
+ outcome = await runScan({
2559
+ ...settings,
2560
+ codexOverrides: config.codexOverrides,
2561
+ projectConfig: provenance,
2562
+ workflowId: options.workflowId,
2563
+ safetyIdentifier: options.safetyIdentifier,
2564
+ verbose: options.verbose,
2565
+ repository: args.repository,
2566
+ archiveExisting: options.archiveExisting,
2567
+ pluginPath: options.pluginPath,
2568
+ pythonPath: options.python,
2569
+ patch: options.patch,
2570
+ patchSeverity: options.patchSeverity,
2571
+ createPr: options.createPr,
2572
+ showCost: options.showCost,
2573
+ headless: options.headless,
2574
+ dryRun: options.dryRun,
2575
+ mock: options.mock,
2576
+ }, errorOutput, dependencies, format !== "json" && format !== "jsonl");
2577
+ }
2578
+ catch (error) {
2579
+ const message = errorMessage(error);
2580
+ errorOutput.write(`${message}\n`);
2581
+ outcome = { exitCode: 2, error: message };
2582
+ }
2623
2583
  exitCode = outcome.exitCode;
2624
2584
  if (outcome.error !== undefined) {
2625
2585
  return incurError({
@@ -2861,6 +2821,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2861
2821
  description: "Run standard scans for project components and combine the results.",
2862
2822
  destructive: true,
2863
2823
  mcp: false,
2824
+ alias: { config: "c" },
2864
2825
  args: z.object({
2865
2826
  repository: z
2866
2827
  .string()
@@ -2870,10 +2831,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2870
2831
  }),
2871
2832
  options: z
2872
2833
  .object({
2873
- auth: z
2874
- .enum(SCAN_AUTH_MODES)
2875
- .default("auto")
2876
- .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
2834
+ config: PROJECT_CONFIG_OPTION,
2835
+ auth: ScanSettingsSchema.shape.auth.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
2877
2836
  component: z
2878
2837
  .array(optionValue("--component"))
2879
2838
  .default([])
@@ -2893,16 +2852,19 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2893
2852
  .boolean()
2894
2853
  .default(false)
2895
2854
  .describe("Print status lines instead of the interactive dashboard."),
2896
- outputDir: optionValue("--output-dir").describe("Empty results directory outside the repository."),
2855
+ outputDir: optionValue("--output-dir")
2856
+ .optional()
2857
+ .describe("Empty results directory outside the repository."),
2897
2858
  workers: z
2898
2859
  .number()
2899
2860
  .int()
2900
2861
  .positive()
2901
2862
  .default(4)
2902
- .describe("Concurrent standard component scans."),
2863
+ .describe("Concurrent component scans; deep workers are configured per scan."),
2903
2864
  knowledgeBase: z
2904
2865
  .array(optionValue("--knowledge-base"))
2905
- .default([])
2866
+ .optional()
2867
+ .meta({ default: [] })
2906
2868
  .describe("Read shared security docs for every component."),
2907
2869
  scanPromptFile: optionValue("--scan-prompt-file")
2908
2870
  .optional()
@@ -2920,6 +2882,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2920
2882
  .positive()
2921
2883
  .optional()
2922
2884
  .describe("Stop each component scan if estimated USD cost exceeds AMOUNT."),
2885
+ showCost: SHOW_COST_OPTION,
2923
2886
  pluginPath: optionValue("--plugin-path")
2924
2887
  .optional()
2925
2888
  .describe(PLUGIN_PATH_DESCRIPTION),
@@ -2960,10 +2923,23 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2960
2923
  try {
2961
2924
  const directory = dependencies.currentDirectory();
2962
2925
  const repository = resolveCliPath(directory, args.repository ?? ".");
2926
+ const project = await selectedProjectConfig(options.config, dependencies);
2927
+ const resolved = resolveScanSettings(project, {
2928
+ auth: options.auth,
2929
+ outputDir: options.outputDir,
2930
+ knowledgeBasePaths: options.knowledgeBase,
2931
+ scanPromptFile: options.scanPromptFile,
2932
+ postScanPromptFile: options.postScanPromptFile,
2933
+ maxCostUsd: options.maxCost,
2934
+ codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider, project?.input.codex),
2935
+ }, directory);
2936
+ const settings = resolved.options;
2937
+ if (settings.outputDir === undefined)
2938
+ throw new ConfigurationError("--output-dir or output.directory is required for component scans.");
2963
2939
  const config = {
2940
+ ...resolved.config,
2964
2941
  pluginPath: options.pluginPath,
2965
2942
  pythonPath: options.python,
2966
- codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider),
2967
2943
  };
2968
2944
  const components = options.componentsFile === undefined
2969
2945
  ? options.component.map((path) => ({ name: path, paths: [path] }))
@@ -2977,7 +2953,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2977
2953
  repository,
2978
2954
  presentation: "components",
2979
2955
  model: scanModelConfiguration(await mergedCodexConfig(config)),
2980
- maxCostUsd: options.maxCost,
2956
+ mode: settings.mode,
2957
+ maxCostUsd: settings.maxCostUsd,
2958
+ showCost: options.showCost,
2981
2959
  clock: dependencies,
2982
2960
  color: dependencies.environment["NO_COLOR"] === undefined,
2983
2961
  sanitize: safeErrorMessage,
@@ -2998,18 +2976,14 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2998
2976
  }
2999
2977
  const result = await runComponentScans({
3000
2978
  repository,
3001
- outputDir: resolveCliPath(directory, options.outputDir),
2979
+ outputDir: settings.outputDir,
3002
2980
  ...(options.auto ? { auto: true } : { components }),
3003
2981
  planOnly: options.planOnly,
3004
2982
  workers: options.workers,
3005
2983
  config,
3006
2984
  scanOptions: {
3007
- auth: options.auth,
3008
- knowledgeBasePaths: options.knowledgeBase.map((path) => resolveCliPath(directory, path)),
3009
- ...(await readPromptFiles(directory, options.scanPromptFile, options.postScanPromptFile, repository)),
3010
- ...(options.maxCost === undefined
3011
- ? {}
3012
- : { maxCostUsd: options.maxCost }),
2985
+ ...settings,
2986
+ ...(await resolveScanPrompts(settings, repository, directory)),
3013
2987
  },
3014
2988
  createSecurity: dependencies.createSecurity,
3015
2989
  planComponents: dependencies.planComponents,
@@ -3023,7 +2997,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3023
2997
  ? (event) => {
3024
2998
  const componentName = componentNames.get(event.componentId) ??
3025
2999
  event.componentId;
3026
- const line = componentScanEventLine(componentName, event);
3000
+ const line = componentScanEventLine(componentName, event, options.showCost || settings.maxCostUsd !== undefined);
3027
3001
  if (line !== null)
3028
3002
  errorOutput.write(line);
3029
3003
  }
@@ -3056,7 +3030,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3056
3030
  result.incomplete ||
3057
3031
  result.deduplication?.status === "incomplete"
3058
3032
  ? 2
3059
- : 0);
3033
+ : result.policyFailed
3034
+ ? 1
3035
+ : 0);
3060
3036
  return { ...result };
3061
3037
  }
3062
3038
  catch (error) {
@@ -3075,6 +3051,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3075
3051
  description: "Discover repositories and run resumable bulk security scans.",
3076
3052
  destructive: true,
3077
3053
  mcp: false,
3054
+ alias: { config: "c" },
3078
3055
  args: z.object({
3079
3056
  input: z
3080
3057
  .string()
@@ -3083,6 +3060,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3083
3060
  .describe("CSV repository list; omit to discover repositories interactively."),
3084
3061
  }),
3085
3062
  options: z.object({
3063
+ config: PROJECT_CONFIG_OPTION,
3086
3064
  recover: z
3087
3065
  .boolean()
3088
3066
  .default(false)
@@ -3094,7 +3072,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3094
3072
  .describe("Resumable results directory; required with a repository CSV."),
3095
3073
  knowledgeBase: z
3096
3074
  .array(optionValue("--knowledge-base"))
3097
- .default([])
3075
+ .optional()
3076
+ .meta({ default: [] })
3098
3077
  .describe("Read shared security docs for every repository."),
3099
3078
  workers: z
3100
3079
  .number()
@@ -3102,10 +3081,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3102
3081
  .positive()
3103
3082
  .default(4)
3104
3083
  .describe("Concurrent repository scans. Per-scan Codex workers are separate."),
3105
- mode: z
3106
- .enum(["standard", "deep"])
3107
- .default("standard")
3108
- .describe("Default scan mode for repositories without a CSV mode."),
3084
+ mode: ScanSettingsSchema.shape.mode.describe("Default scan mode for repositories without a CSV mode."),
3109
3085
  scanPromptFile: optionValue("--scan-prompt-file")
3110
3086
  .optional()
3111
3087
  .describe("Append instructions from FILE to every scan."),
@@ -3169,7 +3145,26 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3169
3145
  if (options.recover && args.input === undefined) {
3170
3146
  throw new Error("Bulk recovery requires the original repository CSV and --output-dir.");
3171
3147
  }
3172
- const prompts = await readPromptFiles(currentDirectory, options.scanPromptFile, options.postScanPromptFile, currentDirectory, options.validationPromptFile);
3148
+ const project = await selectedProjectConfig(options.config, dependencies);
3149
+ const overrides = {
3150
+ mode: options.mode,
3151
+ outputDir: options.outputDir,
3152
+ knowledgeBasePaths: options.knowledgeBase,
3153
+ scanPromptFile: options.scanPromptFile,
3154
+ validationPromptFile: options.validationPromptFile,
3155
+ postScanPromptFile: options.postScanPromptFile,
3156
+ maxCostUsd: options.maxCost,
3157
+ };
3158
+ const resolved = resolveScanSettings(project, overrides, currentDirectory);
3159
+ const settings = resolved.options;
3160
+ // A CSV row may choose a different mode; resolve the same file for both
3161
+ // modes so inactive deep defaults remain available to deep rows.
3162
+ const scanOptionsByMode = project === undefined
3163
+ ? undefined
3164
+ : Object.fromEntries(SCAN_MODES.map((mode) => [
3165
+ mode,
3166
+ resolveScanSettings(project, { ...overrides, mode }, currentDirectory).options,
3167
+ ]));
3173
3168
  let inputPath;
3174
3169
  let outputDir;
3175
3170
  let githubHost;
@@ -3182,7 +3177,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3182
3177
  output: errorOutput,
3183
3178
  now: dependencies.now,
3184
3179
  currentDirectory: dependencies.currentDirectory,
3185
- }), controller.signal);
3180
+ }), controller.signal, settings.outputDir);
3186
3181
  if (wizard === null)
3187
3182
  return;
3188
3183
  inputPath = wizard.inputPath;
@@ -3190,33 +3185,36 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3190
3185
  githubHost = wizard.githubHost;
3191
3186
  }
3192
3187
  else {
3193
- if (options.outputDir === undefined) {
3188
+ if (settings.outputDir === undefined) {
3194
3189
  throw new Error("--output-dir is required with a repository CSV.");
3195
3190
  }
3196
3191
  inputPath = resolveCliPath(currentDirectory, args.input);
3197
- outputDir = resolveCliPath(currentDirectory, options.outputDir);
3192
+ outputDir = settings.outputDir;
3198
3193
  }
3199
3194
  const result = await runMultiscan({
3200
3195
  inputPath,
3201
3196
  outputDir,
3202
3197
  ...(githubHost === undefined ? {} : { githubHost }),
3203
3198
  workers: options.workers,
3204
- mode: options.mode,
3199
+ mode: settings.mode,
3205
3200
  maxAttempts: options.maxAttempts,
3206
- ...(options.maxCost === undefined
3201
+ ...(settings.maxCostUsd === undefined
3207
3202
  ? {}
3208
- : { maxCostUsd: options.maxCost }),
3209
- knowledgeBasePaths: options.knowledgeBase,
3210
- ...prompts,
3203
+ : { maxCostUsd: settings.maxCostUsd }),
3204
+ knowledgeBasePaths: settings.knowledgeBasePaths,
3205
+ scanOptionsByMode,
3206
+ scanPromptFile: settings.scanPromptFile,
3207
+ validationPromptFile: settings.validationPromptFile,
3208
+ postScanPromptFile: settings.postScanPromptFile,
3211
3209
  config: {
3210
+ codexOverrides: mergeCodexOverrides(resolved.config.codexOverrides, parseCodexOverrides(options.codex, options.model, options.effort, options.provider, project?.input.codex)),
3212
3211
  pluginPath: options.pluginPath,
3213
3212
  pythonPath: options.python,
3214
- codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider),
3215
3213
  },
3216
3214
  createSecurity: dependencies.createSecurity,
3217
3215
  ...(options.recover
3218
3216
  ? {
3219
- recoverScan: async (scanDir) => {
3217
+ recoverScan: async (scanDir, prompts) => {
3220
3218
  const history = await dependencies.runWorkbench(["list-scans", "--scan-root", scanDir], undefined, controller.signal);
3221
3219
  const scan = history["scans"].find((scan) => resolve(scan.scanDir) === scanDir);
3222
3220
  if (scan === undefined)
@@ -3230,6 +3228,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3230
3228
  });
3231
3229
  return {
3232
3230
  coverage: contract.coverage,
3231
+ findings: contract.findings,
3233
3232
  cost: scan["cost"] ??
3234
3233
  null,
3235
3234
  };
@@ -3253,7 +3252,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3253
3252
  errorOutput.write(`codex-security: ${scan.scanId}: Original session logs are unavailable. Preserving this attempt and starting a new one.\n`);
3254
3253
  return undefined;
3255
3254
  }
3256
- const recipe = scanArgumentsFromRecipe(saved["recipe"], scan.scanId);
3255
+ const recipe = await prepareScanArgumentsFromRecipe(saved["recipe"], scan.scanId, {
3256
+ scanPrompt: typeof saved["userContext"] === "string"
3257
+ ? saved["userContext"]
3258
+ : undefined,
3259
+ }, currentDirectory);
3257
3260
  const security = dependencies.createSecurity({
3258
3261
  pluginPath: options.pluginPath,
3259
3262
  pythonPath: options.python,
@@ -3261,18 +3264,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3261
3264
  });
3262
3265
  try {
3263
3266
  return await security.run(recipe.repository, {
3267
+ ...pickScanSettings(recipe),
3264
3268
  resumeScanId: scan.scanId,
3265
3269
  outputDir: scanDir,
3266
- mode: recipe.mode,
3267
- target: targetFromArguments(recipe),
3268
- knowledgeBasePaths: recipe.knowledgeBasePaths,
3269
- workers: recipe.workers,
3270
- subagents: recipe.subagents,
3271
- stopAfterNoNew: recipe.stopAfterNoNew,
3272
- maxDiscoveryRuns: recipe.maxDiscoveryRuns,
3273
- maxTimeHours: recipe.maxTimeHours,
3274
- maxCostUsd: recipe.maxCostUsd,
3275
- failureSeverity: recipe.failOnSeverity,
3276
3270
  safetyIdentifier: recipe.safetyIdentifier,
3277
3271
  postScanPrompt: recipe.postScanPrompt ?? prompts.postScanPrompt,
3278
3272
  signal: controller.signal,
@@ -3292,7 +3286,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3292
3286
  });
3293
3287
  exitCode =
3294
3288
  interruptedExitCode() ??
3295
- (result.failed > 0 || result.incomplete > 0 ? 2 : 0);
3289
+ (result.failed > 0 || result.incomplete > 0
3290
+ ? 2
3291
+ : result.policyFailed
3292
+ ? 1
3293
+ : 0);
3296
3294
  return { ...result };
3297
3295
  }
3298
3296
  catch (error) {
@@ -3569,6 +3567,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3569
3567
  .default("auto")
3570
3568
  .describe("Credential source: auto, chatgpt, or api-key."),
3571
3569
  effort: effortOption(),
3570
+ externalSandbox: z
3571
+ .boolean()
3572
+ .default(false)
3573
+ .describe("Use the container's isolation instead of the Codex sandbox (default: false)."),
3572
3574
  scan: optionValue("--scan")
3573
3575
  .optional()
3574
3576
  .describe("Patch open findings from a saved scan."),
@@ -3598,7 +3600,15 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3598
3600
  .describe('Repeat TOML model="gpt-5.6-terra", model_reasoning_effort="high", or analytics.enabled=false.'),
3599
3601
  }),
3600
3602
  output: z.record(z.string(), z.unknown()).optional(),
3601
- async run({ format, options }) {
3603
+ async run({ format, options, error: commandError }) {
3604
+ const jsonOutput = format === "json" || format === "jsonl";
3605
+ const fullOutput = argv.includes("--full-output");
3606
+ const structuredOutput = jsonOutput || fullOutput;
3607
+ let patchResult = {
3608
+ applied: false,
3609
+ filesChanged: 0,
3610
+ files: [],
3611
+ };
3602
3612
  try {
3603
3613
  const linear = options.linearIssue.length > 0 || !!options.linearProject;
3604
3614
  if (options.resumePr !== undefined) {
@@ -3607,6 +3617,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3607
3617
  options.severity !== undefined ||
3608
3618
  options.createPr ||
3609
3619
  options.assessPatchRisk ||
3620
+ options.externalSandbox ||
3610
3621
  linear ||
3611
3622
  options.linearFilter !== undefined ||
3612
3623
  options.linearApiKey !== undefined ||
@@ -3635,15 +3646,33 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3635
3646
  if (savedFindings && linear) {
3636
3647
  throw new CodexSecurityError("Saved findings cannot be combined with Linear issues or projects.");
3637
3648
  }
3649
+ if (options.externalSandbox) {
3650
+ errorOutput.write("WARNING: --external-sandbox disables Codex sandbox enforcement for patching. The container must provide isolation.\n");
3651
+ }
3638
3652
  if (savedFindings) {
3639
3653
  const selected = await selectSavedFindings(positionals, options.scan, options.severity, dependencies);
3640
3654
  const patchRiskBase = options.assessPatchRisk
3641
3655
  ? await snapshotPatchTree(selected.repository, dependencies)
3642
3656
  : undefined;
3643
- const patches = await runFindingPatches(selected, options.codex, options.effort, errorOutput, dependencies, { auth: options.auth });
3657
+ const patchBase = patchRiskBase ??
3658
+ (await snapshotPatchState(selected.repository, dependencies));
3659
+ const patches = await runFindingPatches(selected, options.codex, options.effort, errorOutput, dependencies, { auth: options.auth, externalSandbox: options.externalSandbox });
3644
3660
  exitCode = patchExitCode(patches);
3661
+ const files = await changedPatchFiles(selected.repository, patchBase, dependencies);
3662
+ patchResult = {
3663
+ scanId: selected.scanId,
3664
+ repository: selected.repository,
3665
+ patches,
3666
+ applied: files.length > 0,
3667
+ filesChanged: files.length,
3668
+ files,
3669
+ };
3670
+ if (exitCode !== 0 || files.length === 0) {
3671
+ throw new PatchCommandError(exitCode === 0 ? "NO_PATCH_APPLIED" : "PATCH_FAILED", `Patch did not complete successfully; ${files.length} files changed. Review the patch results before retrying.`);
3672
+ }
3673
+ errorOutput.write(`Patch applied. Files changed: ${files.length}.\n`);
3645
3674
  let patchRisk;
3646
- if (options.assessPatchRisk && exitCode === 0) {
3675
+ if (patchRiskBase !== undefined) {
3647
3676
  const files = verifiedPatchFiles(selected, patches);
3648
3677
  if (files.length > 0) {
3649
3678
  patchRisk = await runPatchRiskAssessment({
@@ -3656,14 +3685,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3656
3685
  }, errorOutput, dependencies);
3657
3686
  }
3658
3687
  }
3659
- const pullRequest = options.createPr && exitCode === 0
3688
+ const pullRequest = options.createPr
3660
3689
  ? await createPatchPullRequest(selected.repository, selected.scanId, verifiedPatchFiles(selected, patches), errorOutput, dependencies, patchRisk?.summary)
3661
3690
  : undefined;
3662
- if (format === "json" || format === "jsonl") {
3691
+ if (structuredOutput) {
3663
3692
  return {
3664
- scanId: selected.scanId,
3665
- repository: selected.repository,
3666
- patches,
3693
+ ...patchResult,
3667
3694
  ...(patchRisk === undefined
3668
3695
  ? {}
3669
3696
  : { patchRisk: { report: patchRisk.report } }),
@@ -3678,9 +3705,6 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3678
3705
  if (options.severity !== undefined) {
3679
3706
  throw new CodexSecurityError("--severity requires a saved finding identifier or --scan.");
3680
3707
  }
3681
- if (format === "json" || format === "jsonl") {
3682
- throw new CodexSecurityError("JSON patch output requires a saved finding identifier or --scan.");
3683
- }
3684
3708
  const imports = linear
3685
3709
  ? await importLinearIssues({
3686
3710
  issues: options.linearIssue,
@@ -3695,37 +3719,85 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3695
3719
  ? undefined
3696
3720
  : Object.fromEntries(Object.entries(dependencies.environment).filter(([name]) => !/^(?:CODEX_SECURITY_)?LINEAR_(?:API_KEY|ACCESS_TOKEN)$/iu.test(name)));
3697
3721
  const repository = dependencies.currentDirectory();
3698
- const patchBase = options.assessPatchRisk || options.createPr
3722
+ const patchGitBase = options.assessPatchRisk || options.createPr
3699
3723
  ? await snapshotPatchTree(repository, dependencies)
3700
3724
  : undefined;
3725
+ const patchBase = patchGitBase ??
3726
+ (await snapshotPatchState(repository, dependencies));
3701
3727
  if (options.createPr) {
3702
- await requireCleanPatchPullRequestBase(repository, patchBase, dependencies);
3703
- }
3704
- exitCode = await runSkill("fix-finding", [...positionals, ...imports], options.codex, options.effort, output, errorOutput, dependencies, { environment, auth: options.auth });
3705
- if (patchBase !== undefined && exitCode === 0) {
3706
- const files = await changedPatchFiles(repository, patchBase, dependencies);
3707
- const patchRisk = options.assessPatchRisk
3708
- ? await runPatchRiskAssessment({
3709
- repository,
3710
- environment,
3711
- base: patchBase,
3712
- files,
3713
- codexOverrides: options.codex,
3714
- effort: options.effort,
3715
- auth: options.auth,
3716
- }, errorOutput, dependencies)
3717
- : undefined;
3718
- if (options.createPr) {
3719
- const identifier = directPatchIdentifier(positionals, imports);
3720
- await createPatchPullRequest(repository, identifier ?? directPatchDigest(positionals, imports), files, errorOutput, dependencies, patchRisk?.summary, identifier === undefined
3721
- ? "Applies a security fix generated from supplied issue data."
3722
- : `Applies a security fix generated for ${identifier}.`);
3723
- }
3728
+ await requireCleanPatchPullRequestBase(repository, patchGitBase, dependencies);
3729
+ }
3730
+ let report = "";
3731
+ exitCode = await runSkill("fix-finding", [...positionals, ...imports], options.codex, options.effort, {
3732
+ write: (value) => {
3733
+ report += value.toString();
3734
+ return true;
3735
+ },
3736
+ }, errorOutput, dependencies, {
3737
+ environment,
3738
+ auth: options.auth,
3739
+ externalSandbox: options.externalSandbox,
3740
+ });
3741
+ if (!jsonOutput)
3742
+ output.write(report);
3743
+ const files = await changedPatchFiles(repository, patchBase, dependencies);
3744
+ patchResult = {
3745
+ repository,
3746
+ applied: files.length > 0,
3747
+ filesChanged: files.length,
3748
+ files,
3749
+ };
3750
+ if (exitCode !== 0) {
3751
+ throw new PatchCommandError("PATCH_FAILED", `Patch command exited with status ${exitCode}.`);
3752
+ }
3753
+ if (files.length === 0) {
3754
+ throw new PatchCommandError("NO_PATCH_APPLIED", "No patch was applied; 0 files changed.");
3755
+ }
3756
+ errorOutput.write(`Patch applied. Files changed: ${files.length}.\n`);
3757
+ const patchRisk = options.assessPatchRisk
3758
+ ? await runPatchRiskAssessment({
3759
+ repository,
3760
+ environment,
3761
+ base: patchGitBase,
3762
+ files,
3763
+ codexOverrides: options.codex,
3764
+ effort: options.effort,
3765
+ auth: options.auth,
3766
+ }, errorOutput, dependencies)
3767
+ : undefined;
3768
+ if (options.createPr) {
3769
+ const identifier = directPatchIdentifier(positionals, imports);
3770
+ await createPatchPullRequest(repository, identifier ?? directPatchDigest(positionals, imports), files, errorOutput, dependencies, patchRisk?.summary, identifier === undefined
3771
+ ? "Applies a security fix generated from supplied issue data."
3772
+ : `Applies a security fix generated for ${identifier}.`);
3724
3773
  }
3774
+ if (structuredOutput)
3775
+ return {
3776
+ ...patchResult,
3777
+ ...(jsonOutput ? { report } : {}),
3778
+ };
3725
3779
  }
3726
3780
  catch (error) {
3727
- exitCode = 2;
3728
- errorOutput.write(`codex-security: ${safeErrorMessage(error)}\n`);
3781
+ if (exitCode === 0)
3782
+ exitCode = 2;
3783
+ const message = safeErrorMessage(error);
3784
+ errorOutput.write(`codex-security: ${message}\n`);
3785
+ if (!structuredOutput)
3786
+ return;
3787
+ patchStructuredError = true;
3788
+ const failure = {
3789
+ code: error instanceof PatchCommandError ? error.code : "PATCH_FAILED",
3790
+ message,
3791
+ };
3792
+ if (!fullOutput) {
3793
+ renderedPatch =
3794
+ JSON.stringify({
3795
+ ok: false,
3796
+ ...patchResult,
3797
+ error: failure,
3798
+ }) + "\n";
3799
+ }
3800
+ return commandError({ ...failure, exitCode });
3729
3801
  }
3730
3802
  },
3731
3803
  })
@@ -3850,6 +3922,34 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3850
3922
  exitCode = 1;
3851
3923
  }
3852
3924
  },
3925
+ })
3926
+ .command("init", {
3927
+ description: "Write a starter project configuration without overwriting an existing file.",
3928
+ destructive: true,
3929
+ mcp: false,
3930
+ args: z.object({
3931
+ file: z
3932
+ .string()
3933
+ .min(1)
3934
+ .optional()
3935
+ .describe("YAML or JSON destination (default: codex-security.yaml)."),
3936
+ }),
3937
+ output: z.object({ path: z.string() }).optional(),
3938
+ async run({ args }) {
3939
+ try {
3940
+ const directory = dependencies.currentDirectory();
3941
+ const path = resolveCliPath(directory, args.file ?? "codex-security.yaml");
3942
+ await writeFile(path, projectConfigStarter(path, directory), {
3943
+ flag: "wx",
3944
+ mode: 0o600,
3945
+ });
3946
+ return { path };
3947
+ }
3948
+ catch (error) {
3949
+ exitCode = 2;
3950
+ errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
3951
+ }
3952
+ },
3853
3953
  })
3854
3954
  .command("feedback", {
3855
3955
  description: "Send feedback to OpenAI and return a feedback ID.",
@@ -3916,7 +4016,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3916
4016
  },
3917
4017
  })
3918
4018
  .command("info", {
3919
- description: "Show read-only SDK and bundled-plugin metadata.",
4019
+ description: "Show SDK metadata and resolved configuration without preparing a scan.",
4020
+ alias: { config: "c" },
4021
+ options: z.object({ config: PROJECT_CONFIG_OPTION }),
3920
4022
  mcp: {
3921
4023
  annotations: {
3922
4024
  readOnlyHint: true,
@@ -3936,8 +4038,17 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3936
4038
  model: z.string(),
3937
4039
  reasoningEffort: z.string(),
3938
4040
  nextStep: z.string(),
4041
+ configuration: z.record(z.string(), z.unknown()),
3939
4042
  }),
3940
- run() {
4043
+ async run({ options }) {
4044
+ const directory = dependencies.currentDirectory();
4045
+ const project = await selectedProjectConfig(options.config, dependencies);
4046
+ const resolved = resolveScanSettings(project, {}, directory);
4047
+ const codex = await mergedCodexConfig(resolved.config);
4048
+ const deep = resolved.options.mode === "deep"
4049
+ ? await resolveDeepScanConfig(resolved.options, join(expandHome(environmentValue(dependencies.environment, "CODEX_HOME") ??
4050
+ join(homedir(), ".codex"), dependencies.environment), "codex-security", "config.toml"))
4051
+ : undefined;
3941
4052
  return {
3942
4053
  sdkVersion: VERSION,
3943
4054
  bundledPluginVersion: BUNDLED_PLUGIN_VERSION,
@@ -3946,8 +4057,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3946
4057
  cliVersion: VERSION,
3947
4058
  codexVersion: CODEX_EXECUTABLE_VERSION,
3948
4059
  codexSdkVersion: CODEX_SDK_VERSION,
3949
- ...scanModelConfiguration(DEFAULT_CODEX_CONFIG),
4060
+ ...scanModelConfiguration(codex),
3950
4061
  nextStep: "codex-security scan . --dry-run",
4062
+ configuration: {
4063
+ ...(project?.path === undefined ? {} : { path: project.path }),
4064
+ settings: { ...resolved.options, ...deep?.settings },
4065
+ sources: configurationSources(resolved.sources, deep?.sources),
4066
+ },
3951
4067
  };
3952
4068
  },
3953
4069
  });
@@ -4040,7 +4156,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4040
4156
  if (notice !== undefined)
4041
4157
  errorOutput.write(formatUpdateNotice(notice));
4042
4158
  if (frameworkExit !== undefined) {
4043
- if (policyFullOutput) {
4159
+ if (policyFullOutput || patchStructuredError) {
4044
4160
  if (exitCode === 0)
4045
4161
  exitCode = 2;
4046
4162
  }
@@ -4055,6 +4171,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4055
4171
  return exitCode;
4056
4172
  try {
4057
4173
  await writeCliOutput(output, renderedPolicy ??
4174
+ renderedPatch ??
4058
4175
  renderedPublication ??
4059
4176
  renderedHistory ??
4060
4177
  frameworkOutput);
@@ -4149,10 +4266,15 @@ function defaultListCommand(argv) {
4149
4266
  ...argv.slice(commandIndex + 1),
4150
4267
  ];
4151
4268
  }
4152
- function scanArgumentsFromRecipe(recipe, parentScanId, validationPromptFile) {
4269
+ async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt, scanPromptFile, validationPromptFile, }, directory) {
4153
4270
  if (recipe === undefined || !isJsonObject(recipe)) {
4154
4271
  throw new CodexSecurityError("This scan does not have a saved launch recipe.");
4155
4272
  }
4273
+ if (recipe["requiresScanPrompt"] === true &&
4274
+ scanPrompt === undefined &&
4275
+ scanPromptFile === undefined) {
4276
+ throw new CodexSecurityError("This scan used additional instructions. Supply --scan-prompt-file to rerun it.");
4277
+ }
4156
4278
  if (recipe["validationMode"] === "custom" &&
4157
4279
  validationPromptFile === undefined) {
4158
4280
  throw new CodexSecurityError("This scan used custom validation. Supply --validation-prompt-file to rerun it.");
@@ -4212,13 +4334,17 @@ function scanArgumentsFromRecipe(recipe, parentScanId, validationPromptFile) {
4212
4334
  maxCostUsd <= 0)) {
4213
4335
  throw new CodexSecurityError("The saved scan recipe contains an invalid cost limit.");
4214
4336
  }
4215
- const deepScan = z
4216
- .object(DEEP_SCAN_OPTION_SCHEMAS)
4217
- .optional()
4218
- .safeParse(recipe["deepScan"]);
4337
+ const deepScan = DeepScanSettingsSchema.optional().safeParse(recipe["deepScan"]);
4219
4338
  if (!deepScan.success) {
4220
4339
  throw new CodexSecurityError("The saved scan recipe contains invalid deep scan settings.");
4221
4340
  }
4341
+ if (recipe["deepScanResolved"] === true &&
4342
+ DEEP_SCAN_SETTINGS.some(([name]) => deepScan.data?.[name] === undefined)) {
4343
+ throw new CodexSecurityError("The saved scan recipe is missing resolved deep scan settings.");
4344
+ }
4345
+ const auth = z.enum(SCAN_AUTH_MODES).optional().safeParse(recipe["auth"]);
4346
+ if (!auth.success)
4347
+ throw new CodexSecurityError("The saved scan recipe contains an invalid authentication choice.");
4222
4348
  if (mode !== "deep" &&
4223
4349
  deepScan.data !== undefined &&
4224
4350
  Object.keys(deepScan.data).length > 0) {
@@ -4230,25 +4356,31 @@ function scanArgumentsFromRecipe(recipe, parentScanId, validationPromptFile) {
4230
4356
  (postScanPrompt !== undefined && typeof postScanPrompt !== "string")) {
4231
4357
  throw new CodexSecurityError("The saved scan recipe contains invalid launch settings.");
4232
4358
  }
4359
+ const prompts = await resolveScanPrompts({ scanPrompt, scanPromptFile, validationPromptFile }, repository, directory);
4360
+ if (recipe["requiresScanPrompt"] === true && !prompts.scanPrompt?.trim()) {
4361
+ throw new CodexSecurityError("This scan used additional instructions. The --scan-prompt-file must not be empty.");
4362
+ }
4233
4363
  return {
4234
4364
  repository,
4235
- paths,
4236
- knowledgeBasePaths,
4237
- validationPromptFile,
4365
+ auth: auth.data ?? DEFAULT_SCAN_AUTH,
4366
+ target: paths.length > 0
4367
+ ? paths
4368
+ : kind === "refs"
4369
+ ? DiffTarget.refs({ base: reference, head: head ?? "HEAD" })
4370
+ : kind === "working_tree"
4371
+ ? DiffTarget.workingTree({ base: reference ?? "HEAD" })
4372
+ : "repository",
4373
+ knowledgeBasePaths: knowledgeBasePaths.map((path) => resolveCliPath(directory, path)),
4374
+ ...prompts,
4238
4375
  safetyIdentifier,
4239
4376
  postScanPrompt,
4240
- diff: kind === "refs" ? reference : undefined,
4241
- workingTree: kind === "working_tree",
4242
- head: kind === "refs" ? head ?? "HEAD" : undefined,
4243
- base: kind === "working_tree" ? reference : undefined,
4244
4377
  mode,
4245
4378
  ...deepScan.data,
4246
4379
  archiveExisting: false,
4247
- codex: [],
4248
4380
  codexOverrides: Object.hasOwn(config, "approval_policy")
4249
4381
  ? config
4250
4382
  : { ...config, approval_policy: "never" },
4251
- failOnSeverity: threshold,
4383
+ failureSeverity: threshold,
4252
4384
  maxCostUsd,
4253
4385
  dryRun: false,
4254
4386
  parentScanId,
@@ -4283,6 +4415,7 @@ function validateCliArguments(argv, positionals) {
4283
4415
  "serve",
4284
4416
  "feedback",
4285
4417
  "info",
4418
+ "init",
4286
4419
  ].includes(command)) {
4287
4420
  return undefined;
4288
4421
  }
@@ -4335,6 +4468,7 @@ function validateCliArguments(argv, positionals) {
4335
4468
  "model",
4336
4469
  "reasoningEffort",
4337
4470
  "nextStep",
4471
+ "configuration",
4338
4472
  ]);
4339
4473
  for (let index = 0; index < argv.length; index += 1) {
4340
4474
  const argument = argv[index];
@@ -4473,10 +4607,6 @@ function staysWithinWindowsDeviceRoot(input, root) {
4473
4607
  function isFindingIdentifier(value) {
4474
4608
  return /^(?:occ|csf)_[A-Za-z0-9_-]+$/u.test(value);
4475
4609
  }
4476
- function meetsSeverity(finding, threshold) {
4477
- const severity = DISPLAY_SEVERITIES.indexOf(finding.severity.level);
4478
- return severity >= 0 && severity <= REPORTABLE_SEVERITIES.indexOf(threshold);
4479
- }
4480
4610
  async function* workbenchFindings(arguments_, dependencies) {
4481
4611
  let offset;
4482
4612
  do {
@@ -4763,10 +4893,57 @@ async function requireCleanPatchPullRequestBase(repository, base, dependencies)
4763
4893
  }
4764
4894
  }
4765
4895
  async function changedPatchFiles(repository, base, dependencies) {
4896
+ if (base instanceof Map) {
4897
+ const head = await snapshotPatchDirectory(repository);
4898
+ return [...new Set([...base.keys(), ...head.keys()])]
4899
+ .filter((path) => base.get(path) !== head.get(path))
4900
+ .sort();
4901
+ }
4766
4902
  const head = await snapshotPatchTree(repository, dependencies);
4767
4903
  const output = await dependencies.runRepositoryCommand("git", ["--literal-pathspecs", "diff", "--name-only", "-z", base, head], repository, { trim: false });
4768
4904
  return output.split("\0").filter(Boolean);
4769
4905
  }
4906
+ async function snapshotPatchState(repository, dependencies) {
4907
+ try {
4908
+ await dependencies.runRepositoryCommand("git", ["rev-parse", "--show-toplevel"], repository, { environment: { LC_ALL: "C" } });
4909
+ }
4910
+ catch (error) {
4911
+ const message = errorMessage(error);
4912
+ if (!message.includes("not a git repository") &&
4913
+ message !== "git is not available on a trusted PATH.")
4914
+ throw error;
4915
+ return snapshotPatchDirectory(repository);
4916
+ }
4917
+ return snapshotPatchTree(repository, dependencies);
4918
+ }
4919
+ // Literal patch inputs also work in directories without Git metadata.
4920
+ async function snapshotPatchDirectory(repository) {
4921
+ const files = new Map();
4922
+ const visit = async (directory) => {
4923
+ for (const entry of await readdir(join(repository, directory), {
4924
+ withFileTypes: true,
4925
+ })) {
4926
+ if (entry.name === ".git")
4927
+ continue;
4928
+ const path = directory ? `${directory}/${entry.name}` : entry.name;
4929
+ const absolute = join(repository, path);
4930
+ if (entry.isDirectory()) {
4931
+ await visit(path);
4932
+ }
4933
+ else if (entry.isSymbolicLink()) {
4934
+ files.set(path, `link:${await readlink(absolute)}`);
4935
+ }
4936
+ else if (entry.isFile()) {
4937
+ const hash = createHash("sha256");
4938
+ for await (const chunk of createReadStream(absolute))
4939
+ hash.update(chunk);
4940
+ files.set(path, `${(await lstat(absolute)).mode & 0o111}:${hash.digest("hex")}`);
4941
+ }
4942
+ }
4943
+ };
4944
+ await visit("");
4945
+ return files;
4946
+ }
4770
4947
  function safePatchText(value) {
4771
4948
  return stripVTControlCharacters(safeErrorMessage(value)).replaceAll(/[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu, " ");
4772
4949
  }
@@ -4896,6 +5073,7 @@ async function runFindingPatches(selected, codexOverrides, effort, stderr, depen
4896
5073
  stderr.write(`\nPatching ${selected.findings.length} confirmed finding${selected.findings.length === 1 ? "" : "s"}...\n`);
4897
5074
  const patches = [];
4898
5075
  for (const finding of selected.findings) {
5076
+ const base = await snapshotPatchState(selected.repository, dependencies);
4899
5077
  let response = "";
4900
5078
  const stdout = {
4901
5079
  write(value) {
@@ -4915,6 +5093,7 @@ async function runFindingPatches(selected, codexOverrides, effort, stderr, depen
4915
5093
  if (status === 130 || status === 143) {
4916
5094
  throw new CodexSecurityError("Patch operation was interrupted.");
4917
5095
  }
5096
+ const changedFiles = await changedPatchFiles(selected.repository, base, dependencies);
4918
5097
  const failed = (reason, files = []) => ({
4919
5098
  occurrenceId: finding.occurrenceId,
4920
5099
  status: "failed",
@@ -4943,6 +5122,10 @@ async function runFindingPatches(selected, codexOverrides, effort, stderr, depen
4943
5122
  !parsed.data.verification?.trim()) {
4944
5123
  patch = failed("Patch verification was not reported.", parsed.data.files);
4945
5124
  }
5125
+ else if (parsed.data.status === "verified" &&
5126
+ changedFiles.length === 0) {
5127
+ patch = failed("No patch was applied; 0 files changed.");
5128
+ }
4946
5129
  else {
4947
5130
  patch = parsed.data;
4948
5131
  }
@@ -5138,6 +5321,7 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
5138
5321
  directory,
5139
5322
  prompt,
5140
5323
  threadSource,
5324
+ ...(options.externalSandbox ? { externalSandbox: true } : {}),
5141
5325
  ...(verify || assess ? { sandbox: "read-only" } : {}),
5142
5326
  ...(options.onEvent === undefined
5143
5327
  ? {}
@@ -5154,9 +5338,24 @@ export async function readSkillCommandOutput(stream, appServer) {
5154
5338
  let threadId;
5155
5339
  let turnId;
5156
5340
  let completed = false;
5341
+ let sandboxUnavailable = false;
5342
+ const externalSandbox = appServer?.externalSandbox
5343
+ ? { type: "externalSandbox", networkAccess: "enabled" }
5344
+ : undefined;
5157
5345
  const send = (request) => {
5158
5346
  appServer?.input.write(`${JSON.stringify(request)}\n`);
5159
5347
  };
5348
+ const startTurn = () => {
5349
+ send({
5350
+ id: 3,
5351
+ method: "turn/start",
5352
+ params: {
5353
+ threadId: threadId,
5354
+ ...(externalSandbox ? { sandboxPolicy: externalSandbox } : {}),
5355
+ input: [{ type: "text", text: appServer.prompt, text_elements: [] }],
5356
+ },
5357
+ });
5358
+ };
5160
5359
  const startThread = (config) => {
5161
5360
  if (appServer === undefined)
5162
5361
  return;
@@ -5221,6 +5420,7 @@ export async function readSkillCommandOutput(stream, appServer) {
5221
5420
  }
5222
5421
  else if (value["error"] !== undefined) {
5223
5422
  error = value["error"].message;
5423
+ sandboxUnavailable = value["id"] === 5;
5224
5424
  appServer.input.end();
5225
5425
  }
5226
5426
  else if (value["id"] === 1 || value["id"] === "login") {
@@ -5312,17 +5512,31 @@ export async function readSkillCommandOutput(stream, appServer) {
5312
5512
  }
5313
5513
  else if (value["id"] === 2) {
5314
5514
  await appServer.onThreadStarted?.();
5315
- threadId = value["result"].thread.id;
5316
- send({
5317
- id: 3,
5318
- method: "turn/start",
5319
- params: {
5320
- threadId,
5321
- input: [
5322
- { type: "text", text: appServer.prompt, text_elements: [] },
5323
- ],
5324
- },
5325
- });
5515
+ const result = value["result"];
5516
+ threadId = result.thread.id;
5517
+ if (appServer.threadSource === CODEX_SECURITY_THREAD_SOURCES.remediation) {
5518
+ send({
5519
+ id: 5,
5520
+ method: "command/exec",
5521
+ params: {
5522
+ command: [process.execPath, "-e", ""],
5523
+ cwd: appServer.directory,
5524
+ sandboxPolicy: externalSandbox ?? result.sandbox,
5525
+ },
5526
+ });
5527
+ continue;
5528
+ }
5529
+ startTurn();
5530
+ }
5531
+ else if (value["id"] === 5) {
5532
+ const result = value["result"];
5533
+ if (result.exitCode !== 0) {
5534
+ sandboxUnavailable = true;
5535
+ error = SANDBOX_UNAVAILABLE_MESSAGE;
5536
+ appServer.input.end();
5537
+ continue;
5538
+ }
5539
+ startTurn();
5326
5540
  }
5327
5541
  else if (value["id"] === 3) {
5328
5542
  turnId = value["result"].turn.id;
@@ -5386,6 +5600,7 @@ export async function readSkillCommandOutput(stream, appServer) {
5386
5600
  ...(error === undefined ? {} : { error }),
5387
5601
  malformed,
5388
5602
  ...(appServer === undefined ? {} : { completed }),
5603
+ ...(sandboxUnavailable ? { sandboxUnavailable } : {}),
5389
5604
  };
5390
5605
  }
5391
5606
  export function skillCommandFailure(command, status, detail, authentication = null) {
@@ -5421,9 +5636,6 @@ function incurErrorMessage(output) {
5421
5636
  return message;
5422
5637
  }
5423
5638
  }
5424
- function isOutsidePath(path) {
5425
- return path === ".." || path.startsWith(`..${sep}`) || isAbsolute(path);
5426
- }
5427
5639
  async function runExport(arguments_, output, errorOutput, dependencies) {
5428
5640
  try {
5429
5641
  const canonicalScan = await realpath(arguments_.scanDir).catch(() => arguments_.scanDir);
@@ -5545,6 +5757,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5545
5757
  let fileProgress = null;
5546
5758
  let runningCost = null;
5547
5759
  let maxCostUsd = arguments_.maxCostUsd;
5760
+ const showCost = arguments_.showCost === true || maxCostUsd !== undefined;
5548
5761
  let phase = null;
5549
5762
  const targetWarnings = [];
5550
5763
  const configuredLogLevel = dependencies.environment["CODEX_SECURITY_LOG_LEVEL"]?.trim() ||
@@ -5630,13 +5843,12 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5630
5843
  try {
5631
5844
  const directory = dependencies.currentDirectory();
5632
5845
  repository = arguments_.repository ?? directory;
5633
- const target = targetFromArguments(arguments_);
5634
- const prompts = await readPromptFiles(directory, arguments_.scanPromptFile, arguments_.postScanPromptFile, resolve(directory, repository), arguments_.validationPromptFile);
5846
+ const target = arguments_.target;
5847
+ const prompts = await resolveScanPrompts(arguments_, resolve(directory, repository), directory);
5635
5848
  const config = {
5636
5849
  pluginPath: arguments_.pluginPath,
5637
5850
  pythonPath: arguments_.pythonPath,
5638
- codexOverrides: arguments_.codexOverrides ??
5639
- parseCodexOverrides(arguments_.codex, arguments_.model, arguments_.effort, arguments_.provider),
5851
+ codexOverrides: arguments_.codexOverrides,
5640
5852
  };
5641
5853
  const selectedProfileName = config.codexOverrides?.["profile"];
5642
5854
  const effectiveConfiguration = {
@@ -5680,14 +5892,14 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5680
5892
  codex_sdk_version: CODEX_SDK_VERSION,
5681
5893
  mode: arguments_.mode,
5682
5894
  max_cost_usd: arguments_.maxCostUsd,
5683
- target: arguments_.paths.length > 0
5895
+ target: Array.isArray(target) && target.length > 0
5684
5896
  ? "paths"
5685
- : arguments_.diff !== undefined
5897
+ : target instanceof DiffTarget && target.kind === "refs"
5686
5898
  ? "diff"
5687
- : arguments_.workingTree
5899
+ : target instanceof DiffTarget
5688
5900
  ? "working_tree"
5689
5901
  : "repository",
5690
- requested_auth: auth ?? "auto",
5902
+ requested_auth: auth ?? DEFAULT_SCAN_AUTH,
5691
5903
  dry_run: arguments_.dryRun,
5692
5904
  mock: arguments_.mock,
5693
5905
  profile: typeof selectedProfileName === "string"
@@ -5704,6 +5916,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5704
5916
  dashboard = new ScanDashboard(errorOutput, {
5705
5917
  repository,
5706
5918
  mode: arguments_.mode,
5919
+ showCost,
5707
5920
  model: scanModelConfiguration(await mergedCodexConfig(config)),
5708
5921
  ...(arguments_.maxCostUsd === undefined
5709
5922
  ? {}
@@ -5731,7 +5944,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5731
5944
  }
5732
5945
  if (runningCost !== null) {
5733
5946
  details.push(`Tokens: ${formatScanCostTokens(runningCost)}`);
5734
- details.push(`Cost: ${formatUsd(runningCost.estimatedUsd)}`);
5947
+ if (showCost)
5948
+ details.push(`Cost: ${formatScanCost(runningCost)}`);
5735
5949
  }
5736
5950
  return details.length === 0 ? stage : `${stage} | ${details.join(" | ")}`;
5737
5951
  };
@@ -5753,6 +5967,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5753
5967
  errorOutput.write("codex-security: Mock scan: generating synthetic findings; no security analysis or LLM calls.\n");
5754
5968
  }
5755
5969
  const options = {
5970
+ ...pickScanSettings(arguments_),
5756
5971
  ...(arguments_.resumeScanId === undefined
5757
5972
  ? {}
5758
5973
  : { resumeScanId: arguments_.resumeScanId }),
@@ -5762,22 +5977,10 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5762
5977
  : { workflowId: arguments_.workflowId }),
5763
5978
  auth,
5764
5979
  safetyIdentifier: arguments_.safetyIdentifier,
5765
- target,
5766
- knowledgeBasePaths: arguments_.knowledgeBasePaths,
5767
5980
  ...prompts,
5768
- postScanPrompt: arguments_.postScanPrompt ?? prompts.postScanPrompt,
5769
- mode: arguments_.mode,
5770
- workers: arguments_.workers,
5771
- subagents: arguments_.subagents,
5772
- stopAfterNoNew: arguments_.stopAfterNoNew,
5773
- maxDiscoveryRuns: arguments_.maxDiscoveryRuns,
5774
- maxTimeHours: arguments_.maxTimeHours,
5775
- outputDir: arguments_.outputDir,
5776
5981
  archiveExisting: arguments_.archiveExisting,
5777
5982
  parentScanId: arguments_.parentScanId,
5778
5983
  expectedPluginVersion: arguments_.expectedPluginVersion,
5779
- failureSeverity: arguments_.failOnSeverity,
5780
- maxCostUsd: arguments_.maxCostUsd,
5781
5984
  onCost: (cost, limit = maxCostUsd) => {
5782
5985
  if (limit !== maxCostUsd && limit !== undefined) {
5783
5986
  dashboard?.note(`Total cost limit increased to ${formatUsd(limit)}.`);
@@ -5785,7 +5988,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5785
5988
  maxCostUsd = limit;
5786
5989
  diagnostic("cost.updated", {
5787
5990
  model: cost.model,
5788
- estimated_usd: cost.estimatedUsd,
5991
+ estimated_usd: showCost ? cost.estimatedUsd : undefined,
5992
+ cost_estimate: showCost ? formatScanCost(cost) : undefined,
5789
5993
  input_tokens: cost.inputTokens,
5790
5994
  cached_input_tokens: cost.cachedInputTokens,
5791
5995
  cache_write_input_tokens: cost.cacheWriteInputTokens,
@@ -5799,10 +6003,10 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5799
6003
  }
5800
6004
  progress?.stopTimer();
5801
6005
  if (maxCostUsd === undefined) {
5802
- progress?.stage(`Tokens: ${formatScanCostTokens(cost)}. Estimated cost: ${formatUsd(cost.estimatedUsd)} USD.`);
6006
+ progress?.stage(`Tokens: ${formatScanCostTokens(cost)}.${showCost ? ` Estimated cost: ${formatScanCost(cost)}.` : ""}`);
5803
6007
  }
5804
6008
  else {
5805
- progress?.stage(`Estimated cost: ${formatUsd(cost.estimatedUsd)} of ${formatUsd(maxCostUsd)} limit`);
6009
+ progress?.stage(`Estimated cost: ${formatScanCost(cost)}; short-context budget baseline: ${formatUsd(cost.estimatedUsd)} of ${formatUsd(maxCostUsd)} limit`);
5806
6010
  }
5807
6011
  if (maxCostUsd === undefined || cost.estimatedUsd <= maxCostUsd) {
5808
6012
  progress?.startTimer(runningMessage());
@@ -5828,7 +6032,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5828
6032
  onAuthentication: (authentication) => {
5829
6033
  selectedAuthentication = authentication;
5830
6034
  diagnostic("authentication.selected", {
5831
- requested: auth ?? "auto",
6035
+ requested: auth ?? DEFAULT_SCAN_AUTH,
5832
6036
  method: authentication.method,
5833
6037
  source: "source" in authentication ? authentication.source : undefined,
5834
6038
  verified: authentication.verified,
@@ -5958,11 +6162,10 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5958
6162
  if (status.kind === "dispatch") {
5959
6163
  dashboard.setStage(scanPhase(status.phase));
5960
6164
  }
5961
- if (message !== null)
5962
- dashboard.note(message);
6165
+ dashboard.note(message);
5963
6166
  return;
5964
6167
  }
5965
- if (message === null || progress === null)
6168
+ if (progress === null)
5966
6169
  return;
5967
6170
  progress.stopTimer();
5968
6171
  progress.stage(message);
@@ -6049,6 +6252,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6049
6252
  partial_output: scanDir !== null,
6050
6253
  max_cost_usd: costLimitFailure?.maxCostUsd,
6051
6254
  estimated_usd: costLimitFailure?.cost.estimatedUsd,
6255
+ cost_estimate: costLimitFailure === undefined
6256
+ ? undefined
6257
+ : formatScanCost(costLimitFailure.cost),
6052
6258
  });
6053
6259
  errorOutput.write(`${message}\n`);
6054
6260
  if (failure instanceof ScanInterruptedError) {
@@ -6076,7 +6282,24 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6076
6282
  verified: effectivePreflight.authentication.verified,
6077
6283
  });
6078
6284
  progress?.stopTimer();
6079
- return { exitCode: 0, data: { dryRun: true, ...effectivePreflight } };
6285
+ return {
6286
+ exitCode: 0,
6287
+ data: {
6288
+ dryRun: true,
6289
+ ...effectivePreflight,
6290
+ ...(arguments_.projectConfig === undefined
6291
+ ? {}
6292
+ : {
6293
+ projectConfig: {
6294
+ ...arguments_.projectConfig,
6295
+ sources: configurationSources(arguments_.projectConfig.sources, preflight.deepScanSources),
6296
+ },
6297
+ scanPromptFile: arguments_.scanPromptFile,
6298
+ validationPromptFile: arguments_.validationPromptFile,
6299
+ failOnSeverity: arguments_.failureSeverity,
6300
+ }),
6301
+ },
6302
+ };
6080
6303
  }
6081
6304
  if (result === null) {
6082
6305
  diagnostic("scan.failed", {
@@ -6086,7 +6309,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6086
6309
  errorOutput.write("scan completed without a result\n");
6087
6310
  return { exitCode: 2, error: "Scan completed without a result." };
6088
6311
  }
6089
- const threshold = arguments_.failOnSeverity;
6312
+ const threshold = arguments_.failureSeverity;
6090
6313
  const findings = result.findings.findings;
6091
6314
  const actionableFindings = findings.filter((finding) => meetsSeverity(finding, "low"));
6092
6315
  let scanData = targetWarnings.length === 0
@@ -6102,13 +6325,16 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6102
6325
  progress?.stage(`Scan complete · ${result.manifest.scan.id.slice(0, 8)}`);
6103
6326
  printScanSummary(result, progress, errorOutput, progress?.interactive === true &&
6104
6327
  dependencies.environment["NO_COLOR"] === undefined &&
6105
- dependencies.environment["TERM"] !== "dumb", deepScanStop);
6328
+ dependencies.environment["TERM"] !== "dumb", showCost, deepScanStop);
6106
6329
  const completedScan = (exitCode) => {
6107
6330
  diagnostic("scan.completed", {
6108
6331
  coverage: result.coverage.completeness,
6109
6332
  findings: findings.length,
6110
6333
  scan_id: result.manifest.scan.id,
6111
- estimated_usd: result.cost?.estimatedUsd,
6334
+ estimated_usd: showCost ? result.cost?.estimatedUsd : undefined,
6335
+ cost_estimate: showCost && result.cost !== null
6336
+ ? formatScanCost(result.cost)
6337
+ : undefined,
6112
6338
  exit_code: exitCode,
6113
6339
  });
6114
6340
  progress?.stopTimer();
@@ -6125,7 +6351,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6125
6351
  return completedScan(2);
6126
6352
  }
6127
6353
  let patchThreshold = arguments_.patch
6128
- ? arguments_.patchSeverity ?? "low"
6354
+ ? (arguments_.patchSeverity ?? "low")
6129
6355
  : undefined;
6130
6356
  let patchSelection = null;
6131
6357
  if (!arguments_.mock &&
@@ -6312,8 +6538,11 @@ function scanFailureMessage(error, authentication) {
6312
6538
  }
6313
6539
  }
6314
6540
  function scanScope(arguments_) {
6315
- if (arguments_.paths.length > 0) {
6316
- const displayed = arguments_.paths.slice(0, 3).map((path) => {
6541
+ const paths = Array.isArray(arguments_.target)
6542
+ ? arguments_.target
6543
+ : [];
6544
+ if (paths.length > 0) {
6545
+ const displayed = paths.slice(0, 3).map((path) => {
6317
6546
  const portable = path.replaceAll("\\", "/");
6318
6547
  const scoped = isAbsolute(path) ||
6319
6548
  /^[A-Za-z]:\//u.test(portable) ||
@@ -6322,12 +6551,12 @@ function scanScope(arguments_) {
6322
6551
  : portable;
6323
6552
  return errorMessage(scoped.replaceAll(/[\u0000-\u001F\u007F]/gu, " "));
6324
6553
  });
6325
- return `${displayed.join(", ")}${arguments_.paths.length > displayed.length ? `, +${arguments_.paths.length - displayed.length} more` : ""}`;
6554
+ return `${displayed.join(", ")}${paths.length > displayed.length ? `, +${paths.length - displayed.length} more` : ""}`;
6326
6555
  }
6327
- if (arguments_.diff !== undefined)
6328
- return "committed changes";
6329
- if (arguments_.workingTree)
6330
- return "working-tree changes";
6556
+ if (arguments_.target instanceof DiffTarget)
6557
+ return arguments_.target.kind === "refs"
6558
+ ? "committed changes"
6559
+ : "working-tree changes";
6331
6560
  return null;
6332
6561
  }
6333
6562
  async function readDeepScanStop(result, maxCostUsd, runWorkbench) {
@@ -6375,7 +6604,7 @@ async function readDeepScanStop(result, maxCostUsd, runWorkbench) {
6375
6604
  reason: "Stopped before the review finished. See the report for details.",
6376
6605
  };
6377
6606
  }
6378
- function printScanSummary(result, progress, errorOutput, color, deepScanStop) {
6607
+ function printScanSummary(result, progress, errorOutput, color, showCost, deepScanStop) {
6379
6608
  const paint = (value, code) => color ? `\u001B[${code}m${value}\u001B[0m` : value;
6380
6609
  const repositoryFindings = result.repositoryFindings;
6381
6610
  const findings = repositoryFindings ?? result.findings.findings;
@@ -6395,7 +6624,7 @@ function printScanSummary(result, progress, errorOutput, color, deepScanStop) {
6395
6624
  Number.isFinite(completed) &&
6396
6625
  completed >= started
6397
6626
  ? Math.floor((completed - started) / 1_000)
6398
- : progress?.elapsedSeconds ?? 0;
6627
+ : (progress?.elapsedSeconds ?? 0);
6399
6628
  const duration = elapsed < 60
6400
6629
  ? `${elapsed}s`
6401
6630
  : `${Math.floor(elapsed / 60)}m ${elapsed % 60}s`;
@@ -6423,16 +6652,18 @@ function printScanSummary(result, progress, errorOutput, color, deepScanStop) {
6423
6652
  if (tokenSummary !== null) {
6424
6653
  errorOutput.write(` ${paint("TOKENS", 1)} ${tokenSummary}\n`);
6425
6654
  }
6426
- const costSummary = result.cost === null
6427
- ? "unavailable (model pricing or usage missing)"
6428
- : `${formatUsd(result.cost.estimatedUsd)} (standard, short context)`;
6429
- errorOutput.write(` ${paint("COST", 1)} ${costSummary}\n`);
6655
+ if (showCost) {
6656
+ const costSummary = result.cost === null
6657
+ ? "unavailable (model pricing or usage missing)"
6658
+ : formatScanCost(result.cost);
6659
+ errorOutput.write(` ${paint("COST", 1)} ${costSummary}\n`);
6660
+ }
6430
6661
  errorOutput.write(` ${paint("RESULTS", 1)} ${errorMessage(result.scanDir)}\n`);
6431
6662
  if (deepScanStop?.nextStep !== undefined) {
6432
6663
  errorOutput.write(`\n ${deepScanStop.nextStep}\n`);
6433
6664
  }
6434
6665
  }
6435
- function componentScanEventLine(componentName, event) {
6666
+ function componentScanEventLine(componentName, event, showCost) {
6436
6667
  if (event.type === "progress") {
6437
6668
  const progress = event.value;
6438
6669
  return `codex-security: ${componentName} ${scanPhase(progress.phase)} | Files: ${progress.filesCompleted.toLocaleString("en-US")}/${progress.filesTotal.toLocaleString("en-US")}\n`;
@@ -6440,7 +6671,7 @@ function componentScanEventLine(componentName, event) {
6440
6671
  if (event.type !== "cost")
6441
6672
  return null;
6442
6673
  const cost = event.value;
6443
- return `codex-security: ${componentName} | Tokens: ${formatScanCostTokens(cost)} | Cost: ${formatUsd(cost.estimatedUsd)}\n`;
6674
+ return `codex-security: ${componentName} | Tokens: ${formatScanCostTokens(cost)}${showCost ? ` | Cost: ${formatScanCost(cost)}` : ""}\n`;
6444
6675
  }
6445
6676
  function protectedRootErrorMessage(error) {
6446
6677
  const description = error.pathKind === "output"
@@ -6502,21 +6733,67 @@ function quoteCliPath(path) {
6502
6733
  ? `"${path}"`
6503
6734
  : `'${path.replaceAll("'", `'"'"'`)}'`;
6504
6735
  }
6505
- function targetFromArguments(arguments_) {
6506
- if (arguments_.paths.length > 0)
6507
- return arguments_.paths;
6508
- if (arguments_.diff !== undefined) {
6509
- return DiffTarget.refs({
6510
- base: arguments_.diff,
6511
- head: arguments_.head ?? "HEAD",
6512
- });
6513
- }
6514
- if (arguments_.workingTree) {
6515
- return DiffTarget.workingTree({ base: arguments_.base ?? "HEAD" });
6736
+ async function selectedProjectConfig(file, dependencies) {
6737
+ const selected = file ??
6738
+ environmentValue(dependencies.environment, "CODEX_SECURITY_PROJECT_CONFIG");
6739
+ return selected === undefined
6740
+ ? undefined
6741
+ : readProjectConfig(selected, dependencies.currentDirectory());
6742
+ }
6743
+ function resolveCliScope(configured, overrides) {
6744
+ const sources = {};
6745
+ const explicitScopes = Number(!!overrides.paths?.length) +
6746
+ Number(overrides.diff !== undefined) +
6747
+ Number(overrides.workingTree === true);
6748
+ if (explicitScopes > 1)
6749
+ throw new ConfigurationError("--path, --diff, and --working-tree are mutually exclusive.");
6750
+ if (explicitScopes === 0 &&
6751
+ overrides.workingTree !== false &&
6752
+ overrides.head === undefined &&
6753
+ overrides.base === undefined) {
6754
+ return { sources };
6755
+ }
6756
+ let scope = configured;
6757
+ let changed = false;
6758
+ sources["scan.scope"] = scope === undefined ? "default" : "project";
6759
+ if (overrides.paths?.length)
6760
+ scope = { paths: overrides.paths };
6761
+ else if (overrides.diff !== undefined)
6762
+ scope = { diff: { base: overrides.diff } };
6763
+ else if (overrides.workingTree === true)
6764
+ scope = { working_tree: {} };
6765
+ else if (overrides.workingTree === false &&
6766
+ scope !== undefined &&
6767
+ "working_tree" in scope) {
6768
+ scope = undefined;
6769
+ changed = true;
6770
+ }
6771
+ if (explicitScopes > 0 || changed) {
6772
+ changed = true;
6773
+ sources["scan.scope"] = "cli";
6774
+ }
6775
+ // A ref-only override refines the selected project scope; it does not take
6776
+ // ownership of the whole scope variant.
6777
+ if (overrides.head !== undefined) {
6778
+ if (scope === undefined || !("diff" in scope))
6779
+ throw new ConfigurationError("--head requires --diff.");
6780
+ scope = { diff: { ...scope.diff, head: overrides.head } };
6781
+ sources["scan.scope.diff.head"] = "cli";
6782
+ changed = true;
6783
+ }
6784
+ if (overrides.base !== undefined) {
6785
+ if (scope === undefined || !("working_tree" in scope))
6786
+ throw new ConfigurationError("--base requires --working-tree.");
6787
+ scope = { working_tree: { base: overrides.base } };
6788
+ sources["scan.scope.working_tree.base"] = "cli";
6789
+ changed = true;
6516
6790
  }
6517
- return "repository";
6791
+ return {
6792
+ ...(changed ? { target: projectScopeTarget(scope) ?? "repository" } : {}),
6793
+ sources,
6794
+ };
6518
6795
  }
6519
- export function parseCodexOverrides(values, model, effort, provider) {
6796
+ export function parseCodexOverrides(values, model, effort, provider, defaults) {
6520
6797
  const result = Object.create(null);
6521
6798
  if (model !== undefined)
6522
6799
  result["model"] = model;
@@ -6583,9 +6860,13 @@ export function parseCodexOverrides(values, model, effort, provider) {
6583
6860
  }
6584
6861
  cursor[final] = parsed;
6585
6862
  }
6586
- if ((isExternalModelProvider(provider) || provider === "amazon-bedrock") &&
6587
- !("model" in result)) {
6588
- throw new CodexSecurityError(`--model is required when using --provider ${provider}`);
6863
+ if (isExternalModelProvider(provider) || provider === "amazon-bedrock") {
6864
+ const selectedModel = scanModel(mergeCodexOverrides(defaults ?? {}, result));
6865
+ if (typeof selectedModel !== "string" || !selectedModel.trim()) {
6866
+ throw new CodexSecurityError(selectedModel === undefined
6867
+ ? `--model is required when using --provider ${provider}`
6868
+ : `--model must be a nonempty string when using --provider ${provider}`);
6869
+ }
6589
6870
  }
6590
6871
  return result;
6591
6872
  }