@openai/codex-security 0.1.16 → 0.1.17

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 (107) hide show
  1. package/README.md +184 -4
  2. package/_bundled_plugin/.app.json +1 -1
  3. package/_bundled_plugin/.mcp.json +9 -3
  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/config-preflight.md +1 -1
  7. package/_bundled_plugin/references/sarif-adapter.md +2 -0
  8. package/_bundled_plugin/scripts/deep_scan_workbench.py +34 -6
  9. package/_bundled_plugin/scripts/finalize_scan_contract.py +54 -26
  10. package/_bundled_plugin/scripts/generate_in_scope_files.py +20 -0
  11. package/_bundled_plugin/scripts/generate_rank_input.py +23 -7
  12. package/_bundled_plugin/scripts/launch_codex_security_mcp +32 -0
  13. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +27 -0
  14. package/_bundled_plugin/scripts/workbench_cli.py +22 -15
  15. package/_bundled_plugin/scripts/workbench_db.py +35 -35
  16. package/_bundled_plugin/scripts/workbench_progress.py +6 -3
  17. package/_bundled_plugin/scripts/workbench_scan_history.py +17 -2
  18. package/_bundled_plugin/scripts/workbench_target.py +36 -5
  19. package/_bundled_plugin/scripts/workbench_validation.py +9 -0
  20. package/_bundled_plugin/skills/fix-finding/SKILL.md +17 -1
  21. package/dist/api.d.ts +16 -1
  22. package/dist/api.d.ts.map +1 -1
  23. package/dist/api.js +180 -11
  24. package/dist/api.js.map +1 -1
  25. package/dist/cli.d.ts +5 -3
  26. package/dist/cli.d.ts.map +1 -1
  27. package/dist/cli.js +335 -43
  28. package/dist/cli.js.map +1 -1
  29. package/dist/component-plan.d.ts +15 -0
  30. package/dist/component-plan.d.ts.map +1 -0
  31. package/dist/component-plan.js +145 -0
  32. package/dist/component-plan.js.map +1 -0
  33. package/dist/component-scan.d.ts +83 -0
  34. package/dist/component-scan.d.ts.map +1 -0
  35. package/dist/component-scan.js +279 -0
  36. package/dist/component-scan.js.map +1 -0
  37. package/dist/contract.d.ts +8 -2
  38. package/dist/contract.d.ts.map +1 -1
  39. package/dist/contract.js +27 -8
  40. package/dist/contract.js.map +1 -1
  41. package/dist/cost-model.d.ts +20 -0
  42. package/dist/cost-model.d.ts.map +1 -0
  43. package/dist/cost-model.js +86 -0
  44. package/dist/cost-model.js.map +1 -0
  45. package/dist/cost.d.ts +2 -11
  46. package/dist/cost.d.ts.map +1 -1
  47. package/dist/cost.js +15 -98
  48. package/dist/cost.js.map +1 -1
  49. package/dist/custom-validation-prompt.d.ts +4 -0
  50. package/dist/custom-validation-prompt.d.ts.map +1 -0
  51. package/dist/custom-validation-prompt.js +94 -0
  52. package/dist/custom-validation-prompt.js.map +1 -0
  53. package/dist/custom-validation.d.ts +45 -0
  54. package/dist/custom-validation.d.ts.map +1 -0
  55. package/dist/custom-validation.js +292 -0
  56. package/dist/custom-validation.js.map +1 -0
  57. package/dist/errors.d.ts +1 -1
  58. package/dist/errors.d.ts.map +1 -1
  59. package/dist/errors.js +1 -1
  60. package/dist/errors.js.map +1 -1
  61. package/dist/index.d.ts +6 -1
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +2 -0
  64. package/dist/index.js.map +1 -1
  65. package/dist/multiscan.d.ts +1 -0
  66. package/dist/multiscan.d.ts.map +1 -1
  67. package/dist/multiscan.js +53 -5
  68. package/dist/multiscan.js.map +1 -1
  69. package/dist/patch-tui.js +1 -1
  70. package/dist/patch-tui.js.map +1 -1
  71. package/dist/publication.d.ts.map +1 -1
  72. package/dist/publication.js +3 -4
  73. package/dist/publication.js.map +1 -1
  74. package/dist/runtime.d.ts +4 -2
  75. package/dist/runtime.d.ts.map +1 -1
  76. package/dist/runtime.js +109 -38
  77. package/dist/runtime.js.map +1 -1
  78. package/dist/scan-comparison.d.ts +12 -5
  79. package/dist/scan-comparison.d.ts.map +1 -1
  80. package/dist/scan-comparison.js +72 -28
  81. package/dist/scan-comparison.js.map +1 -1
  82. package/dist/scan-dashboard.d.ts +9 -2
  83. package/dist/scan-dashboard.d.ts.map +1 -1
  84. package/dist/scan-dashboard.js +198 -3
  85. package/dist/scan-dashboard.js.map +1 -1
  86. package/dist/scan-logs.d.ts.map +1 -1
  87. package/dist/scan-logs.js +5 -21
  88. package/dist/scan-logs.js.map +1 -1
  89. package/dist/scan-sessions.d.ts +4 -0
  90. package/dist/scan-sessions.d.ts.map +1 -0
  91. package/dist/scan-sessions.js +35 -0
  92. package/dist/scan-sessions.js.map +1 -0
  93. package/dist/targets.d.ts.map +1 -1
  94. package/dist/targets.js +16 -1
  95. package/dist/targets.js.map +1 -1
  96. package/dist/version.d.ts.map +1 -1
  97. package/dist/version.js +2 -20
  98. package/dist/version.js.map +1 -1
  99. package/dist/windows-path.d.ts +3 -0
  100. package/dist/windows-path.d.ts.map +1 -0
  101. package/dist/windows-path.js +16 -0
  102. package/dist/windows-path.js.map +1 -0
  103. package/dist/worker-progress.d.ts +1 -0
  104. package/dist/worker-progress.d.ts.map +1 -1
  105. package/dist/worker-progress.js +12 -0
  106. package/dist/worker-progress.js.map +1 -1
  107. package/package.json +8 -2
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
11
11
  import { promisify, stripVTControlCharacters } from "node:util";
12
12
  import { Cli, z } from "incur";
13
13
  import { parse as parseToml } from "smol-toml";
14
- import { classifyConnectionFailure, createSecurityInternal, listRepositoryFindings, scanAuthentication, } from "./api.js";
14
+ import { classifyConnectionFailure, createSecurityInternal, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, } from "./api.js";
15
15
  import { accountStatus } from "./auth.js";
16
16
  import { createBulkScanDiscoveryDependencies, runBulkScanWizard, } from "./bulk-scan-discovery.js";
17
17
  import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanModelConfiguration, scanModelProvider, } from "./config.js";
@@ -19,13 +19,16 @@ import { formatUsd } from "./cost.js";
19
19
  import { CodexSecurityError, ConfigurationError, InvalidTargetError, OutputDirectoryError, OutputInsideProtectedRootError, PluginPythonUnavailableError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
20
20
  import { importLinearIssues, resolveLinearApiKey, } from "./linear.js";
21
21
  import { runMultiscan } from "./multiscan.js";
22
+ import { componentPlanSchema } from "./component-plan.js";
23
+ import { runComponentScans } from "./component-scan.js";
22
24
  import { publishScan, } from "./publish.js";
23
- import { bundledPluginRoot, codexSecurityCredentialHome, codexSecurityStateDirectory, expandHome, prepareCodexSecurityCredentialHome, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
25
+ import { bundledPluginRoot, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, expandHome, prepareCodexSecurityCredentialHome, pythonUtf8Environment, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
24
26
  import { matchScanFindingsInternal, } from "./scan-comparison.js";
25
27
  import { scanActivitiesFromEvent } from "./scan-activity.js";
26
28
  import { readScanLogs } from "./scan-logs.js";
27
29
  import { renderScanHistory, } from "./scan-history-renderer.js";
28
30
  import { ScanDashboard } from "./scan-dashboard.js";
31
+ import { scanPhaseLabel as scanPhase, } from "./worker-progress.js";
29
32
  import { abortable, DiffTarget, } from "./targets.js";
30
33
  import { resolveTrustedExecutable } from "./trusted-executable.js";
31
34
  import { BUNDLED_PLUGIN_VERSION, checkForUpdate, CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION, formatUpdateNotice, updateNoticeEnabled, VERSION, } from "./version.js";
@@ -70,8 +73,11 @@ const EXPORT_DEFAULT_OUTPUTS = {
70
73
  const VALUE_OPTIONS = new Set([
71
74
  "--auth",
72
75
  "--path",
76
+ "--component",
77
+ "--components-file",
73
78
  "--knowledge-base",
74
79
  "--scan-prompt-file",
80
+ "--validation-prompt-file",
75
81
  "--post-scan-prompt-file",
76
82
  "--diff",
77
83
  "--head",
@@ -121,7 +127,7 @@ const PROVIDER_OPTION = z
121
127
  const CREATE_PR_OPTION = z
122
128
  .boolean()
123
129
  .default(false)
124
- .describe("Create a GitHub pull request after verified patches.");
130
+ .describe("Create a draft GitHub pull request after verified patches.");
125
131
  function optionValue(flag) {
126
132
  return z.string().min(1, `${flag} must not be empty.`);
127
133
  }
@@ -534,17 +540,24 @@ const DEEP_SCAN_OPTION_SCHEMAS = {
534
540
  .optional()
535
541
  .describe("Maximum deep-scan discovery hours (default: 96; maximum: 96)."),
536
542
  };
537
- async function readPromptFiles(directory, scanPromptFile, postScanPromptFile, repository = directory) {
538
- const [scanPrompt, postScanPrompt] = await Promise.all([
543
+ async function readPromptFiles(directory, scanPromptFile, postScanPromptFile, repository = directory, validationPromptFile) {
544
+ const [scanPrompt, postScanPrompt, validationPrompt] = await Promise.all([
539
545
  scanPromptFile === undefined
540
546
  ? undefined
541
547
  : readRegularInputFile(resolveCliPath(directory, scanPromptFile), repository),
542
548
  postScanPromptFile === undefined
543
549
  ? undefined
544
550
  : readRegularInputFile(resolveCliPath(directory, postScanPromptFile), repository),
551
+ validationPromptFile === undefined
552
+ ? undefined
553
+ : readRegularInputFile(resolveCliPath(directory, validationPromptFile), repository),
545
554
  ]);
555
+ if (validationPrompt !== undefined && !validationPrompt.trim()) {
556
+ throw new CodexSecurityError("The validation prompt must not be empty.");
557
+ }
546
558
  return {
547
559
  ...(scanPrompt?.trim() ? { scanPrompt } : {}),
560
+ ...(validationPrompt === undefined ? {} : { validationPrompt }),
548
561
  ...(postScanPrompt?.trim() ? { postScanPrompt } : {}),
549
562
  };
550
563
  }
@@ -632,7 +645,7 @@ const DEFAULT_DEPENDENCIES = {
632
645
  writeSync(stream.fd, value);
633
646
  },
634
647
  forceExit: (signal) => process.kill(process.pid, signal),
635
- runCodex: (args, output, environment) => runCodexSkillCommand(args, output, resolveCodexCommand(environment), environment),
648
+ runCodex: (args, output, environment, input) => runCodexSkillCommand(args, output, resolveCodexCommand(environment), environment, input),
636
649
  runRepositoryCommand: async (command, args, repository) => {
637
650
  const executable = await resolveTrustedExecutable(command, process.env, repository);
638
651
  if (executable === null) {
@@ -654,6 +667,8 @@ const DEFAULT_DEPENDENCIES = {
654
667
  const plugin = await bundledPluginRoot();
655
668
  const invocation = spawn(python, [
656
669
  "-I",
670
+ "-X",
671
+ "utf8",
657
672
  join(plugin, "scripts", "finalize_scan_contract.py"),
658
673
  "--scan-dir",
659
674
  arguments_.scanDir,
@@ -699,7 +714,7 @@ const DEFAULT_DEPENDENCIES = {
699
714
  }
700
715
  return undefined;
701
716
  },
702
- runWorkbench: async (args) => {
717
+ runWorkbench: async (args, input) => {
703
718
  const environment = {
704
719
  ...exportEnvironment(),
705
720
  CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
@@ -710,11 +725,11 @@ const DEFAULT_DEPENDENCIES = {
710
725
  pluginRoot: await bundledPluginRoot(),
711
726
  environment,
712
727
  failureMessage: "Could not read Codex Security scan history",
713
- }, args);
728
+ }, args, input);
714
729
  },
715
730
  matchFindings: (input, options) => matchScanFindingsInternal(input, options, { surface: "cli" }),
716
731
  };
717
- export async function runCodexSkillCommand(args, output, command = resolveCodexCommand(), processEnvironment = process.env) {
732
+ export async function runCodexSkillCommand(args, output, command = resolveCodexCommand(), processEnvironment = process.env, input) {
718
733
  const configuredHome = processEnvironment["CODEX_HOME"];
719
734
  const environment = { ...processEnvironment };
720
735
  for (const name of Object.keys(environment)) {
@@ -728,10 +743,22 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
728
743
  env: environment,
729
744
  cwd: output?.appServer?.directory ?? parse(process.execPath).root,
730
745
  stdio: output === undefined
731
- ? "inherit"
732
- : [output.appServer === undefined ? "ignore" : "pipe", "pipe", "pipe"],
746
+ ? input === undefined
747
+ ? "inherit"
748
+ : ["pipe", "inherit", "inherit"]
749
+ : [
750
+ output.appServer !== undefined || input !== undefined
751
+ ? "pipe"
752
+ : "ignore",
753
+ "pipe",
754
+ "pipe",
755
+ ],
733
756
  windowsHide: true,
734
757
  });
758
+ if (input !== undefined) {
759
+ invocation.stdin?.on("error", () => { });
760
+ invocation.stdin?.end(input);
761
+ }
735
762
  let requestedSignal = null;
736
763
  let forcedTermination;
737
764
  let forceStatusCompletion = null;
@@ -876,7 +903,7 @@ async function writeCliOutput(output, value) {
876
903
  }
877
904
  }
878
905
  export function exportEnvironment(environment = process.env) {
879
- return Object.fromEntries([
906
+ return pythonUtf8Environment(Object.fromEntries([
880
907
  "PATH",
881
908
  "Path",
882
909
  "PATHEXT",
@@ -892,7 +919,7 @@ export function exportEnvironment(environment = process.env) {
892
919
  "LC_CTYPE",
893
920
  ]
894
921
  .filter((key) => environment[key] !== undefined)
895
- .map((key) => [key, environment[key]]));
922
+ .map((key) => [key, environment[key]])));
896
923
  }
897
924
  export async function main(argv = process.argv.slice(2), output = process.stdout, errorOutput = process.stderr, dependencies = DEFAULT_DEPENDENCIES) {
898
925
  argv = defaultListCommand(argv);
@@ -932,7 +959,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
932
959
  catch (error) {
933
960
  errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
934
961
  exitCode = 2;
935
- return undefined;
962
+ throw error;
936
963
  }
937
964
  };
938
965
  const latestScans = async (count = 1, status = "complete") => {
@@ -970,9 +997,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
970
997
  beforeId,
971
998
  "--after-scan-id",
972
999
  afterId,
973
- "--matches-json",
974
- JSON.stringify(await dependencies.matchFindings(matchingInputs)),
975
- ]);
1000
+ "--matches-json-stdin",
1001
+ ], JSON.stringify(await dependencies.matchFindings(matchingInputs)));
976
1002
  });
977
1003
  const presentHistory = (result, command, format, settings = {}) => {
978
1004
  if (result === undefined ||
@@ -1073,7 +1099,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1073
1099
  const directory = dependencies.currentDirectory();
1074
1100
  const scanRoot = options.scanRoot === undefined
1075
1101
  ? undefined
1076
- : resolveCliPath(directory, options.scanRoot);
1102
+ : process.platform === "win32"
1103
+ ? await canonicalizeModelSafePath(resolveCliPath(directory, options.scanRoot))
1104
+ : resolveCliPath(directory, options.scanRoot);
1077
1105
  const repository = scanRoot !== undefined && args.repository === undefined
1078
1106
  ? undefined
1079
1107
  : resolveCliPath(directory, args.repository ?? directory);
@@ -1167,6 +1195,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1167
1195
  .describe("Saved scan identifier (default: latest completed scan)."),
1168
1196
  }),
1169
1197
  options: z.object({
1198
+ validationPromptFile: optionValue("--validation-prompt-file")
1199
+ .optional()
1200
+ .describe("Use FILE for custom validation; required when rerunning a custom-validation scan."),
1170
1201
  verbose: z
1171
1202
  .boolean()
1172
1203
  .default(false)
@@ -1184,7 +1215,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1184
1215
  "--scan-id",
1185
1216
  scanId,
1186
1217
  ]);
1187
- scanArguments = scanArgumentsFromRecipe(recipe, scanId);
1218
+ scanArguments = scanArgumentsFromRecipe(recipe, scanId, options.validationPromptFile);
1188
1219
  scanArguments.verbose = options.verbose;
1189
1220
  }
1190
1221
  catch (error) {
@@ -1246,7 +1277,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1246
1277
  catch (error) {
1247
1278
  errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
1248
1279
  exitCode = 2;
1249
- return undefined;
1280
+ throw error;
1250
1281
  }
1251
1282
  },
1252
1283
  })
@@ -1574,7 +1605,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1574
1605
  options: z
1575
1606
  .object({
1576
1607
  auth: z
1577
- .enum(["auto", "chatgpt", "api-key"])
1608
+ .enum(SCAN_AUTH_MODES)
1578
1609
  .default("auto")
1579
1610
  .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
1580
1611
  verbose: z
@@ -1592,6 +1623,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1592
1623
  scanPromptFile: optionValue("--scan-prompt-file")
1593
1624
  .optional()
1594
1625
  .describe("Append scan instructions from FILE."),
1626
+ validationPromptFile: optionValue("--validation-prompt-file")
1627
+ .optional()
1628
+ .describe("Replace final validation with the workflow in FILE (not Deep)."),
1595
1629
  postScanPromptFile: optionValue("--post-scan-prompt-file")
1596
1630
  .optional()
1597
1631
  .describe("Run FILE after each scan, including failures."),
@@ -1720,6 +1754,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1720
1754
  paths: options.path,
1721
1755
  knowledgeBasePaths: options.knowledgeBase,
1722
1756
  scanPromptFile: options.scanPromptFile,
1757
+ validationPromptFile: options.validationPromptFile,
1723
1758
  postScanPromptFile: options.postScanPromptFile,
1724
1759
  diff: options.diff,
1725
1760
  workingTree: options.workingTree,
@@ -1831,6 +1866,209 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1831
1866
  .command(scanHistory)
1832
1867
  .command(findingFeedback)
1833
1868
  .command(publication)
1869
+ .command("scan-components", {
1870
+ description: "Run standard scans for project components and combine the results.",
1871
+ destructive: true,
1872
+ mcp: false,
1873
+ args: z.object({
1874
+ repository: z
1875
+ .string()
1876
+ .min(1)
1877
+ .optional()
1878
+ .describe("Project directory (default: current directory)."),
1879
+ }),
1880
+ options: z
1881
+ .object({
1882
+ auth: z
1883
+ .enum(SCAN_AUTH_MODES)
1884
+ .default("auto")
1885
+ .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
1886
+ component: z
1887
+ .array(optionValue("--component"))
1888
+ .default([])
1889
+ .describe("Scan this repository-relative path as a component; repeat for more."),
1890
+ componentsFile: optionValue("--components-file")
1891
+ .optional()
1892
+ .describe("Read a component plan from JSON."),
1893
+ auto: z
1894
+ .boolean()
1895
+ .default(false)
1896
+ .describe("Ask Codex to divide the project into components."),
1897
+ planOnly: z
1898
+ .boolean()
1899
+ .default(false)
1900
+ .describe("Save components.json without starting scans."),
1901
+ headless: z
1902
+ .boolean()
1903
+ .default(false)
1904
+ .describe("Print status lines instead of the interactive dashboard."),
1905
+ outputDir: optionValue("--output-dir").describe("Empty results directory outside the repository."),
1906
+ workers: z
1907
+ .number()
1908
+ .int()
1909
+ .positive()
1910
+ .default(4)
1911
+ .describe("Concurrent standard component scans."),
1912
+ knowledgeBase: z
1913
+ .array(optionValue("--knowledge-base"))
1914
+ .default([])
1915
+ .describe("Read shared security docs for every component."),
1916
+ scanPromptFile: optionValue("--scan-prompt-file")
1917
+ .optional()
1918
+ .describe("Append instructions from FILE to every scan."),
1919
+ postScanPromptFile: optionValue("--post-scan-prompt-file")
1920
+ .optional()
1921
+ .describe("Run FILE after each scan, including failures."),
1922
+ model: optionValue("--model")
1923
+ .optional()
1924
+ .describe("Model for planning and component scans."),
1925
+ effort: effortOption(),
1926
+ provider: PROVIDER_OPTION,
1927
+ maxCost: z
1928
+ .number()
1929
+ .positive()
1930
+ .optional()
1931
+ .describe("Stop each component scan if estimated USD cost exceeds AMOUNT."),
1932
+ pluginPath: optionValue("--plugin-path")
1933
+ .optional()
1934
+ .describe(PLUGIN_PATH_DESCRIPTION),
1935
+ python: optionValue("--python")
1936
+ .optional()
1937
+ .describe(PYTHON_PATH_DESCRIPTION),
1938
+ codex: z
1939
+ .array(optionValue("--codex"))
1940
+ .default([])
1941
+ .describe(CODEX_OVERRIDE_DESCRIPTION),
1942
+ })
1943
+ .refine((options) => Number(options.component.length > 0) +
1944
+ Number(options.componentsFile !== undefined) +
1945
+ Number(options.auto) ===
1946
+ 1, {
1947
+ message: "Choose exactly one of --component, --components-file, or --auto.",
1948
+ }),
1949
+ output: z.record(z.string(), z.unknown()).optional(),
1950
+ async run({ args, options }) {
1951
+ const controller = new AbortController();
1952
+ let dashboard = null;
1953
+ const stopDashboard = () => {
1954
+ try {
1955
+ dashboard?.stop();
1956
+ }
1957
+ catch { }
1958
+ };
1959
+ const onInterrupt = () => controller.abort("SIGINT");
1960
+ const onTerminate = () => controller.abort("SIGTERM");
1961
+ const interruptedExitCode = () => controller.signal.reason === "SIGINT"
1962
+ ? 130
1963
+ : controller.signal.reason === "SIGTERM"
1964
+ ? 143
1965
+ : undefined;
1966
+ dependencies.addSignalListener("SIGINT", onInterrupt);
1967
+ dependencies.addSignalListener("SIGTERM", onTerminate);
1968
+ try {
1969
+ const directory = dependencies.currentDirectory();
1970
+ const repository = resolveCliPath(directory, args.repository ?? ".");
1971
+ const config = {
1972
+ pluginPath: options.pluginPath,
1973
+ pythonPath: options.python,
1974
+ codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider),
1975
+ };
1976
+ const components = options.componentsFile === undefined
1977
+ ? options.component.map((path) => ({ name: path, paths: [path] }))
1978
+ : componentPlanSchema.parse(JSON.parse(await readRegularInputFile(resolveCliPath(directory, options.componentsFile), repository))).components;
1979
+ if (!options.headless &&
1980
+ !options.planOnly &&
1981
+ errorOutput.isTTY === true &&
1982
+ dependencies.environment["CI"] === undefined &&
1983
+ dependencies.environment["TERM"] !== "dumb") {
1984
+ const candidate = new ScanDashboard(errorOutput, {
1985
+ repository,
1986
+ presentation: "components",
1987
+ model: scanModelConfiguration(await mergedCodexConfig(config)),
1988
+ maxCostUsd: options.maxCost,
1989
+ clock: dependencies,
1990
+ color: dependencies.environment["NO_COLOR"] === undefined,
1991
+ sanitize: safeErrorMessage,
1992
+ input: process.stdin,
1993
+ onInterrupt,
1994
+ });
1995
+ candidate.setStage(options.auto ? "Planning components" : "Preparing components");
1996
+ try {
1997
+ candidate.start();
1998
+ dashboard = candidate;
1999
+ }
2000
+ catch {
2001
+ try {
2002
+ candidate.stop();
2003
+ }
2004
+ catch { }
2005
+ }
2006
+ }
2007
+ const result = await runComponentScans({
2008
+ repository,
2009
+ outputDir: resolveCliPath(directory, options.outputDir),
2010
+ ...(options.auto ? { auto: true } : { components }),
2011
+ planOnly: options.planOnly,
2012
+ workers: options.workers,
2013
+ config,
2014
+ scanOptions: {
2015
+ auth: options.auth,
2016
+ knowledgeBasePaths: options.knowledgeBase.map((path) => resolveCliPath(directory, path)),
2017
+ ...(await readPromptFiles(directory, options.scanPromptFile, options.postScanPromptFile, repository)),
2018
+ ...(options.maxCost === undefined
2019
+ ? {}
2020
+ : { maxCostUsd: options.maxCost }),
2021
+ },
2022
+ createSecurity: dependencies.createSecurity,
2023
+ planComponents: dependencies.planComponents,
2024
+ matchFindings: dependencies.matchFindings,
2025
+ onPlan: (components) => dashboard?.setComponents(components),
2026
+ onScanEvent: dashboard === null
2027
+ ? undefined
2028
+ : (event) => dashboard?.recordComponentEvent(event),
2029
+ onDeduplicationStarted: () => {
2030
+ if (dashboard !== null)
2031
+ dashboard.showComponents("Combining duplicate findings");
2032
+ else
2033
+ errorOutput.write("codex-security: Matching component findings by root cause...\n");
2034
+ },
2035
+ environment: dependencies.environment,
2036
+ signal: controller.signal,
2037
+ onProgress: (component) => {
2038
+ if (dashboard !== null)
2039
+ dashboard.updateComponent(component);
2040
+ else
2041
+ errorOutput.write(`codex-security: ${component.name} ${component.status}${component.error === undefined ? "" : `: ${component.error}`}\n`);
2042
+ },
2043
+ onComplete: (result) => {
2044
+ dashboard?.finishComponents(result);
2045
+ stopDashboard();
2046
+ errorOutput.write(`Component scans: ${result.completed} complete, ${result.incomplete} incomplete, ${result.failed} failed.\n${result.sourceFindingCount} findings → ${result.findingCount} groups${result.deduplication?.status === "incomplete" ? " (matching incomplete)" : ""}.\nReport: ${errorMessage(result.reportPath)}\n`);
2047
+ if (result.retryPlanPath !== undefined)
2048
+ errorOutput.write(`Retry with --components-file ${JSON.stringify(errorMessage(result.retryPlanPath))} and a new --output-dir.\n`);
2049
+ },
2050
+ });
2051
+ exitCode =
2052
+ interruptedExitCode() ??
2053
+ (result.failed ||
2054
+ result.incomplete ||
2055
+ result.deduplication?.status === "incomplete"
2056
+ ? 2
2057
+ : 0);
2058
+ return { ...result };
2059
+ }
2060
+ catch (error) {
2061
+ stopDashboard();
2062
+ exitCode = interruptedExitCode() ?? 2;
2063
+ errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
2064
+ }
2065
+ finally {
2066
+ stopDashboard();
2067
+ dependencies.removeSignalListener("SIGINT", onInterrupt);
2068
+ dependencies.removeSignalListener("SIGTERM", onTerminate);
2069
+ }
2070
+ },
2071
+ })
1834
2072
  .command("bulk-scan", {
1835
2073
  description: "Discover repositories and run resumable bulk security scans.",
1836
2074
  destructive: true,
@@ -1865,6 +2103,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1865
2103
  scanPromptFile: optionValue("--scan-prompt-file")
1866
2104
  .optional()
1867
2105
  .describe("Append instructions from FILE to every scan."),
2106
+ validationPromptFile: optionValue("--validation-prompt-file")
2107
+ .optional()
2108
+ .describe("Replace final validation with FILE for every standard scan."),
1868
2109
  postScanPromptFile: optionValue("--post-scan-prompt-file")
1869
2110
  .optional()
1870
2111
  .describe("Run FILE after each scan, including failures."),
@@ -1919,7 +2160,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1919
2160
  dependencies.addSignalListener("SIGTERM", onTerminate);
1920
2161
  try {
1921
2162
  const currentDirectory = dependencies.currentDirectory();
1922
- const prompts = await readPromptFiles(currentDirectory, options.scanPromptFile, options.postScanPromptFile);
2163
+ const prompts = await readPromptFiles(currentDirectory, options.scanPromptFile, options.postScanPromptFile, currentDirectory, options.validationPromptFile);
1923
2164
  let inputPath;
1924
2165
  let outputDir;
1925
2166
  let githubHost;
@@ -2535,10 +2776,14 @@ function defaultListCommand(argv) {
2535
2776
  ...argv.slice(commandIndex + 1),
2536
2777
  ];
2537
2778
  }
2538
- function scanArgumentsFromRecipe(recipe, parentScanId) {
2779
+ function scanArgumentsFromRecipe(recipe, parentScanId, validationPromptFile) {
2539
2780
  if (recipe === undefined || !isJsonObject(recipe)) {
2540
2781
  throw new CodexSecurityError("This scan does not have a saved launch recipe.");
2541
2782
  }
2783
+ if (recipe["validationMode"] === "custom" &&
2784
+ validationPromptFile === undefined) {
2785
+ throw new CodexSecurityError("This scan used custom validation. Supply --validation-prompt-file to rerun it.");
2786
+ }
2542
2787
  const repository = recipe["repository"];
2543
2788
  if (typeof repository !== "string" || repository.length === 0) {
2544
2789
  throw new CodexSecurityError("The saved scan recipe does not contain a repository.");
@@ -2610,6 +2855,7 @@ function scanArgumentsFromRecipe(recipe, parentScanId) {
2610
2855
  repository,
2611
2856
  paths,
2612
2857
  knowledgeBasePaths,
2858
+ validationPromptFile,
2613
2859
  diff: kind === "refs" ? reference : undefined,
2614
2860
  workingTree: kind === "working_tree",
2615
2861
  head: kind === "refs" ? head ?? "HEAD" : undefined,
@@ -2637,6 +2883,7 @@ function validateCliArguments(argv, positionals) {
2637
2883
  "scan",
2638
2884
  "install-hook",
2639
2885
  "bulk-scan",
2886
+ "scan-components",
2640
2887
  "scans",
2641
2888
  "findings",
2642
2889
  "export",
@@ -2785,9 +3032,8 @@ async function matchAllScans(dependencies, force) {
2785
3032
  scanId,
2786
3033
  "--after-scan-id",
2787
3034
  afterScanId,
2788
- "--matches-json",
2789
- JSON.stringify({ matches, uncertain }),
2790
- ]);
3035
+ "--matches-json-stdin",
3036
+ ], JSON.stringify({ matches, uncertain }));
2791
3037
  matchedPairs += 1;
2792
3038
  findingMatches += matches.reduce((count, { beforeOccurrenceIds, afterOccurrenceIds }) => count + beforeOccurrenceIds.length * afterOccurrenceIds.length, 0);
2793
3039
  }
@@ -2947,6 +3193,7 @@ async function publishPatchBranch(repository, branch, stderr, dependencies) {
2947
3193
  url = await run("gh", [
2948
3194
  "pr",
2949
3195
  "create",
3196
+ "--draft",
2950
3197
  "--head",
2951
3198
  branch,
2952
3199
  "--title",
@@ -2998,7 +3245,7 @@ async function createPatchPullRequest(selected, patches, stderr, dependencies) {
2998
3245
  }
2999
3246
  const branch = `codex-security/patch-${selected.scanId.replaceAll(/[^a-z\d._-]/giu, "-")}`;
3000
3247
  const run = (command, args) => dependencies.runRepositoryCommand(command, args, selected.repository);
3001
- stderr.write("Creating a GitHub pull request for verified patches...\n");
3248
+ stderr.write("Creating a draft GitHub pull request for verified patches...\n");
3002
3249
  await run("git", ["switch", "-c", branch]);
3003
3250
  await run("git", ["--literal-pathspecs", "add", "--", ...files]);
3004
3251
  await run("git", [
@@ -3209,7 +3456,7 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
3209
3456
  "--skip-git-repo-check",
3210
3457
  "--cd",
3211
3458
  directory,
3212
- prompt,
3459
+ "-",
3213
3460
  ]),
3214
3461
  ], {
3215
3462
  command: verify ? "verify-fix" : patch ? "patch" : "validate",
@@ -3227,7 +3474,7 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
3227
3474
  },
3228
3475
  }
3229
3476
  : {}),
3230
- }, options.environment);
3477
+ }, options.environment, appServer ? undefined : prompt);
3231
3478
  }
3232
3479
  export async function readSkillCommandOutput(stream, appServer) {
3233
3480
  let message;
@@ -3692,7 +3939,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
3692
3939
  const directory = dependencies.currentDirectory();
3693
3940
  repository = arguments_.repository ?? directory;
3694
3941
  const target = targetFromArguments(arguments_);
3695
- const prompts = await readPromptFiles(directory, arguments_.scanPromptFile, arguments_.postScanPromptFile, resolve(directory, repository));
3942
+ const prompts = await readPromptFiles(directory, arguments_.scanPromptFile, arguments_.postScanPromptFile, resolve(directory, repository), arguments_.validationPromptFile);
3696
3943
  const config = {
3697
3944
  pluginPath: arguments_.pluginPath,
3698
3945
  pythonPath: arguments_.pythonPath,
@@ -4131,10 +4378,16 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
4131
4378
  ? result.toJSON()
4132
4379
  : { ...result.toJSON(), warnings: targetWarnings };
4133
4380
  const incomplete = result.coverage.completeness !== "complete";
4381
+ let deepScanStop;
4382
+ if (arguments_.mode === "deep") {
4383
+ deepScanStop = (await readDeepScanStop(result, arguments_.maxCostUsd, dependencies.runWorkbench).catch(() => undefined)) ?? {
4384
+ reason: "Stop reason unavailable. See the report for details.",
4385
+ };
4386
+ }
4134
4387
  progress?.stage(`Scan complete · ${result.manifest.scan.id.slice(0, 8)}`);
4135
4388
  printScanSummary(result, progress, errorOutput, progress?.interactive === true &&
4136
4389
  dependencies.environment["NO_COLOR"] === undefined &&
4137
- dependencies.environment["TERM"] !== "dumb");
4390
+ dependencies.environment["TERM"] !== "dumb", deepScanStop);
4138
4391
  const completedScan = (exitCode) => {
4139
4392
  diagnostic("scan.completed", {
4140
4393
  coverage: result.coverage.completeness,
@@ -4318,7 +4571,7 @@ function scanScope(arguments_) {
4318
4571
  const scoped = isAbsolute(path) ||
4319
4572
  /^[A-Za-z]:\//u.test(portable) ||
4320
4573
  portable.startsWith("//")
4321
- ? portable.split("/").at(-1) ?? portable
4574
+ ? basename(portable) || portable
4322
4575
  : portable;
4323
4576
  return errorMessage(scoped.replaceAll(/[\u0000-\u001F\u007F]/gu, " "));
4324
4577
  });
@@ -4330,19 +4583,52 @@ function scanScope(arguments_) {
4330
4583
  return "working-tree changes";
4331
4584
  return null;
4332
4585
  }
4333
- function scanPhase(value) {
4586
+ async function readDeepScanStop(result, maxCostUsd, runWorkbench) {
4587
+ if (maxCostUsd !== undefined &&
4588
+ result.cost !== null &&
4589
+ result.cost.estimatedUsd > maxCostUsd) {
4590
+ return {
4591
+ reason: `Reached the ${formatUsd(maxCostUsd)} cost limit. More issues may remain.`,
4592
+ nextStep: "To scan further, rerun with a higher --max-cost.",
4593
+ };
4594
+ }
4595
+ const response = await runWorkbench([
4596
+ "get-deep-scan",
4597
+ "--scan-id",
4598
+ result.manifest.scan.id,
4599
+ "--thread-id",
4600
+ result.threadId,
4601
+ ]);
4602
+ const state = response["deepScan"];
4603
+ if (state?.terminalReason === "saturated") {
4604
+ return {
4605
+ reason: `The last ${state.noNewStreak} review rounds found no new issues. More issues may remain.`,
4606
+ };
4607
+ }
4608
+ if (state?.terminalReason !== "capped")
4609
+ return undefined;
4610
+ const { maxDiscoveryRuns, maxTimeHours } = state.config;
4611
+ if (state.dispatchedCount >= maxDiscoveryRuns) {
4612
+ const stillFindingIssues = state.completionSequence > 0 && state.noNewStreak === 0;
4613
+ return {
4614
+ reason: `Reached the limit of ${maxDiscoveryRuns} review rounds. ${stillFindingIssues ? "The latest review still found new issues." : "More issues may remain."}`,
4615
+ nextStep: `To scan further, rerun with --max-discovery-runs greater than ${maxDiscoveryRuns}.`,
4616
+ };
4617
+ }
4618
+ const elapsedHours = (Date.parse(state.completedAt) - Date.parse(state.createdAt)) / 3_600_000;
4619
+ if (elapsedHours >= maxTimeHours) {
4620
+ return {
4621
+ reason: `Reached the ${maxTimeHours}-hour time limit. More issues may remain.`,
4622
+ nextStep: maxTimeHours < 96
4623
+ ? "To scan further, rerun with a higher --max-time-hours."
4624
+ : "To scan a smaller part of the repository, rerun with --path.",
4625
+ };
4626
+ }
4334
4627
  return {
4335
- preflight: "preflight",
4336
- threat_model: "building threat model",
4337
- discovery: "reviewing files",
4338
- ranking: "ranking scan targets",
4339
- file_review: "reviewing files",
4340
- validation: "validating findings",
4341
- attack_path: "analyzing attack paths",
4342
- reporting: "writing report",
4343
- }[value];
4628
+ reason: "Stopped before the review finished. See the report for details.",
4629
+ };
4344
4630
  }
4345
- function printScanSummary(result, progress, errorOutput, color) {
4631
+ function printScanSummary(result, progress, errorOutput, color, deepScanStop) {
4346
4632
  const paint = (value, code) => color ? `\u001B[${code}m${value}\u001B[0m` : value;
4347
4633
  const repositoryFindings = result.repositoryFindings;
4348
4634
  const findings = repositoryFindings ?? result.findings.findings;
@@ -4382,6 +4668,9 @@ function printScanSummary(result, progress, errorOutput, color) {
4382
4668
  errorOutput.write(`\n ${paint("REPORT", "1;36")} ${paint(errorMessage(result.reportPath), 4)}\n\n` +
4383
4669
  ` ${paint("FINDINGS", 1)} ${paint(`${findingCount}${findingSummary === "" ? "" : ` (${findingSummary})`}`, findingColor)}\n` +
4384
4670
  ` ${paint("COVERAGE", 1)} ${result.coverage.completeness}\n` +
4671
+ (deepScanStop === undefined
4672
+ ? ""
4673
+ : ` ${paint("STOPPED", 1)} ${deepScanStop.reason}\n`) +
4385
4674
  ` ${paint("ELAPSED", 1)} ${duration}\n`);
4386
4675
  const tokenSummary = formatTokenUsage(result.turnResult.usage);
4387
4676
  if (tokenSummary !== null) {
@@ -4391,6 +4680,9 @@ function printScanSummary(result, progress, errorOutput, color) {
4391
4680
  errorOutput.write(` ${paint("COST", 1)} ${formatUsd(result.cost.estimatedUsd)}\n`);
4392
4681
  }
4393
4682
  errorOutput.write(` ${paint("RESULTS", 1)} ${errorMessage(result.scanDir)}\n`);
4683
+ if (deepScanStop?.nextStep !== undefined) {
4684
+ errorOutput.write(`\n ${deepScanStop.nextStep}\n`);
4685
+ }
4394
4686
  }
4395
4687
  function formatTokenUsage(usage) {
4396
4688
  if (usage === null || typeof usage !== "object")