@openai/codex-security 0.1.15 → 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 (109) hide show
  1. package/README.md +204 -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 +5 -1
  8. package/_bundled_plugin/scripts/deep_scan_workbench.py +34 -6
  9. package/_bundled_plugin/scripts/finalize_scan_contract.py +121 -32
  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/_bundled_plugin/skills/verify-fix/SKILL.md +44 -0
  22. package/_bundled_plugin/skills/verify-fix/agents/openai.yaml +4 -0
  23. package/dist/api.d.ts +16 -1
  24. package/dist/api.d.ts.map +1 -1
  25. package/dist/api.js +180 -11
  26. package/dist/api.js.map +1 -1
  27. package/dist/cli.d.ts +12 -5
  28. package/dist/cli.d.ts.map +1 -1
  29. package/dist/cli.js +781 -62
  30. package/dist/cli.js.map +1 -1
  31. package/dist/component-plan.d.ts +15 -0
  32. package/dist/component-plan.d.ts.map +1 -0
  33. package/dist/component-plan.js +145 -0
  34. package/dist/component-plan.js.map +1 -0
  35. package/dist/component-scan.d.ts +83 -0
  36. package/dist/component-scan.d.ts.map +1 -0
  37. package/dist/component-scan.js +279 -0
  38. package/dist/component-scan.js.map +1 -0
  39. package/dist/contract.d.ts +8 -2
  40. package/dist/contract.d.ts.map +1 -1
  41. package/dist/contract.js +27 -8
  42. package/dist/contract.js.map +1 -1
  43. package/dist/cost-model.d.ts +20 -0
  44. package/dist/cost-model.d.ts.map +1 -0
  45. package/dist/cost-model.js +86 -0
  46. package/dist/cost-model.js.map +1 -0
  47. package/dist/cost.d.ts +2 -11
  48. package/dist/cost.d.ts.map +1 -1
  49. package/dist/cost.js +15 -95
  50. package/dist/cost.js.map +1 -1
  51. package/dist/custom-validation-prompt.d.ts +4 -0
  52. package/dist/custom-validation-prompt.d.ts.map +1 -0
  53. package/dist/custom-validation-prompt.js +94 -0
  54. package/dist/custom-validation-prompt.js.map +1 -0
  55. package/dist/custom-validation.d.ts +45 -0
  56. package/dist/custom-validation.d.ts.map +1 -0
  57. package/dist/custom-validation.js +292 -0
  58. package/dist/custom-validation.js.map +1 -0
  59. package/dist/errors.d.ts +1 -1
  60. package/dist/errors.d.ts.map +1 -1
  61. package/dist/errors.js +1 -1
  62. package/dist/errors.js.map +1 -1
  63. package/dist/index.d.ts +6 -1
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +2 -0
  66. package/dist/index.js.map +1 -1
  67. package/dist/multiscan.d.ts +1 -0
  68. package/dist/multiscan.d.ts.map +1 -1
  69. package/dist/multiscan.js +53 -5
  70. package/dist/multiscan.js.map +1 -1
  71. package/dist/patch-tui.js +1 -1
  72. package/dist/patch-tui.js.map +1 -1
  73. package/dist/publication.d.ts.map +1 -1
  74. package/dist/publication.js +3 -4
  75. package/dist/publication.js.map +1 -1
  76. package/dist/runtime.d.ts +4 -2
  77. package/dist/runtime.d.ts.map +1 -1
  78. package/dist/runtime.js +109 -38
  79. package/dist/runtime.js.map +1 -1
  80. package/dist/scan-comparison.d.ts +12 -5
  81. package/dist/scan-comparison.d.ts.map +1 -1
  82. package/dist/scan-comparison.js +72 -28
  83. package/dist/scan-comparison.js.map +1 -1
  84. package/dist/scan-dashboard.d.ts +9 -2
  85. package/dist/scan-dashboard.d.ts.map +1 -1
  86. package/dist/scan-dashboard.js +205 -7
  87. package/dist/scan-dashboard.js.map +1 -1
  88. package/dist/scan-logs.d.ts.map +1 -1
  89. package/dist/scan-logs.js +5 -21
  90. package/dist/scan-logs.js.map +1 -1
  91. package/dist/scan-sessions.d.ts +4 -0
  92. package/dist/scan-sessions.d.ts.map +1 -0
  93. package/dist/scan-sessions.js +35 -0
  94. package/dist/scan-sessions.js.map +1 -0
  95. package/dist/targets.d.ts.map +1 -1
  96. package/dist/targets.js +16 -1
  97. package/dist/targets.js.map +1 -1
  98. package/dist/version.d.ts.map +1 -1
  99. package/dist/version.js +2 -20
  100. package/dist/version.js.map +1 -1
  101. package/dist/windows-path.d.ts +3 -0
  102. package/dist/windows-path.d.ts.map +1 -0
  103. package/dist/windows-path.js +16 -0
  104. package/dist/windows-path.js.map +1 -0
  105. package/dist/worker-progress.d.ts +1 -0
  106. package/dist/worker-progress.d.ts.map +1 -1
  107. package/dist/worker-progress.js +12 -0
  108. package/dist/worker-progress.js.map +1 -1
  109. 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
  }
@@ -352,6 +358,148 @@ class PublicationProgressPresenter {
352
358
  this.#stream.write(`${visible}\n`);
353
359
  }
354
360
  }
361
+ class VerificationProgressPresenter {
362
+ #stream;
363
+ #dependencies;
364
+ #repository;
365
+ #total;
366
+ #seenActivities = new Set();
367
+ #reasoning = new Map();
368
+ #dashboard = null;
369
+ constructor(stream, dependencies, repository, total) {
370
+ this.#stream = stream;
371
+ this.#dependencies = dependencies;
372
+ this.#repository = repository;
373
+ this.#total = total;
374
+ }
375
+ start() {
376
+ if (this.#stream.isTTY === true &&
377
+ this.#dependencies.environment["CI"] === undefined &&
378
+ this.#dependencies.environment["TERM"] !== "dumb") {
379
+ const dashboard = new ScanDashboard(this.#stream, {
380
+ repository: this.#repository,
381
+ presentation: "verification",
382
+ clock: this.#dependencies,
383
+ color: this.#dependencies.environment["NO_COLOR"] === undefined,
384
+ sanitize: safeErrorMessage,
385
+ });
386
+ dashboard.setPublicationProgress(0, this.#total);
387
+ dashboard.setStage(`Verifying findings · 0/${this.#total}`);
388
+ try {
389
+ dashboard.start();
390
+ this.#dashboard = dashboard;
391
+ return;
392
+ }
393
+ catch {
394
+ try {
395
+ dashboard.stop();
396
+ }
397
+ catch { }
398
+ }
399
+ }
400
+ this.#write(`Verifying ${this.#total} finding${this.#total === 1 ? "" : "s"} against the current checkout.`);
401
+ }
402
+ observe(event) {
403
+ const method = event["method"];
404
+ const params = event["params"];
405
+ if (typeof params !== "object" ||
406
+ params === null ||
407
+ Array.isArray(params)) {
408
+ return;
409
+ }
410
+ const values = params;
411
+ let normalized;
412
+ if (method === "item/reasoning/summaryTextDelta") {
413
+ const id = values["itemId"];
414
+ const delta = values["delta"];
415
+ if (typeof id !== "string" || typeof delta !== "string")
416
+ return;
417
+ const text = `${this.#reasoning.get(id) ?? ""}${delta}`;
418
+ this.#reasoning.set(id, text);
419
+ normalized = {
420
+ type: "item.updated",
421
+ item: { id, type: "reasoning", text },
422
+ };
423
+ }
424
+ else if (method === "item/started" || method === "item/completed") {
425
+ const item = values["item"];
426
+ if (typeof item !== "object" || item === null || Array.isArray(item)) {
427
+ return;
428
+ }
429
+ const current = item;
430
+ const type = current["type"];
431
+ let converted;
432
+ if (type === "commandExecution") {
433
+ converted = { ...current, type: "command_execution" };
434
+ }
435
+ else if (type === "mcpToolCall") {
436
+ converted = { ...current, type: "mcp_tool_call" };
437
+ }
438
+ else if (type === "agentMessage") {
439
+ if (current["phase"] !== "commentary")
440
+ return;
441
+ converted = { ...current, type: "agent_message" };
442
+ }
443
+ else if (type === "reasoning") {
444
+ const summary = current["summary"];
445
+ const text = Array.isArray(summary)
446
+ ? summary
447
+ .filter((entry) => typeof entry === "string")
448
+ .join("\n")
449
+ : current["text"];
450
+ if (typeof text !== "string")
451
+ return;
452
+ converted = { ...current, text };
453
+ }
454
+ else {
455
+ return;
456
+ }
457
+ normalized = {
458
+ type: method === "item/started" ? "item.started" : "item.completed",
459
+ item: converted,
460
+ };
461
+ }
462
+ else {
463
+ return;
464
+ }
465
+ for (const activity of scanActivitiesFromEvent(normalized, this.#repository)) {
466
+ if (this.#dashboard !== null) {
467
+ this.#dashboard.record(activity);
468
+ continue;
469
+ }
470
+ const key = `${activity.id}\0${activity.description}`;
471
+ if (this.#seenActivities.has(key))
472
+ continue;
473
+ this.#seenActivities.add(key);
474
+ const label = activity.kind === "reasoning" || activity.kind === "message"
475
+ ? "Codex"
476
+ : "Tool";
477
+ this.#write(`${label}: ${activity.description}`);
478
+ }
479
+ }
480
+ complete(results) {
481
+ if (this.#dashboard === null)
482
+ return;
483
+ this.#dashboard.setPublicationProgress(results.length, this.#total);
484
+ this.#dashboard.setStage(`Verification complete · ${results.length}/${this.#total}`);
485
+ for (const result of results) {
486
+ this.#dashboard.note(`${result.status.toUpperCase()} ${result.id}`);
487
+ }
488
+ }
489
+ stop() {
490
+ try {
491
+ this.#dashboard?.stop();
492
+ }
493
+ catch { }
494
+ this.#dashboard = null;
495
+ }
496
+ #write(message) {
497
+ try {
498
+ this.#stream.write(`${safePatchText(message)}\n`);
499
+ }
500
+ catch { }
501
+ }
502
+ }
355
503
  function effortOption() {
356
504
  return z
357
505
  .enum(MODEL_REASONING_EFFORTS, {
@@ -392,17 +540,24 @@ const DEEP_SCAN_OPTION_SCHEMAS = {
392
540
  .optional()
393
541
  .describe("Maximum deep-scan discovery hours (default: 96; maximum: 96)."),
394
542
  };
395
- async function readPromptFiles(directory, scanPromptFile, postScanPromptFile, repository = directory) {
396
- const [scanPrompt, postScanPrompt] = await Promise.all([
543
+ async function readPromptFiles(directory, scanPromptFile, postScanPromptFile, repository = directory, validationPromptFile) {
544
+ const [scanPrompt, postScanPrompt, validationPrompt] = await Promise.all([
397
545
  scanPromptFile === undefined
398
546
  ? undefined
399
547
  : readRegularInputFile(resolveCliPath(directory, scanPromptFile), repository),
400
548
  postScanPromptFile === undefined
401
549
  ? undefined
402
550
  : readRegularInputFile(resolveCliPath(directory, postScanPromptFile), repository),
551
+ validationPromptFile === undefined
552
+ ? undefined
553
+ : readRegularInputFile(resolveCliPath(directory, validationPromptFile), repository),
403
554
  ]);
555
+ if (validationPrompt !== undefined && !validationPrompt.trim()) {
556
+ throw new CodexSecurityError("The validation prompt must not be empty.");
557
+ }
404
558
  return {
405
559
  ...(scanPrompt?.trim() ? { scanPrompt } : {}),
560
+ ...(validationPrompt === undefined ? {} : { validationPrompt }),
406
561
  ...(postScanPrompt?.trim() ? { postScanPrompt } : {}),
407
562
  };
408
563
  }
@@ -449,6 +604,11 @@ const findingPatchSchema = z.object({
449
604
  verification: z.string().optional(),
450
605
  reason: z.string().optional(),
451
606
  });
607
+ const findingVerificationSchema = z.object({
608
+ id: z.string(),
609
+ status: z.enum(["fixed", "still_vulnerable", "inconclusive"]),
610
+ evidence: z.string().trim().min(1),
611
+ });
452
612
  const DEFAULT_DEPENDENCIES = {
453
613
  createSecurity: (config) => createSecurityInternal(config, { surface: "cli" }),
454
614
  environment: process.env,
@@ -485,7 +645,7 @@ const DEFAULT_DEPENDENCIES = {
485
645
  writeSync(stream.fd, value);
486
646
  },
487
647
  forceExit: (signal) => process.kill(process.pid, signal),
488
- runCodex: (args, output, environment) => runCodexSkillCommand(args, output, resolveCodexCommand(environment), environment),
648
+ runCodex: (args, output, environment, input) => runCodexSkillCommand(args, output, resolveCodexCommand(environment), environment, input),
489
649
  runRepositoryCommand: async (command, args, repository) => {
490
650
  const executable = await resolveTrustedExecutable(command, process.env, repository);
491
651
  if (executable === null) {
@@ -507,6 +667,8 @@ const DEFAULT_DEPENDENCIES = {
507
667
  const plugin = await bundledPluginRoot();
508
668
  const invocation = spawn(python, [
509
669
  "-I",
670
+ "-X",
671
+ "utf8",
510
672
  join(plugin, "scripts", "finalize_scan_contract.py"),
511
673
  "--scan-dir",
512
674
  arguments_.scanDir,
@@ -552,7 +714,7 @@ const DEFAULT_DEPENDENCIES = {
552
714
  }
553
715
  return undefined;
554
716
  },
555
- runWorkbench: async (args) => {
717
+ runWorkbench: async (args, input) => {
556
718
  const environment = {
557
719
  ...exportEnvironment(),
558
720
  CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
@@ -563,11 +725,11 @@ const DEFAULT_DEPENDENCIES = {
563
725
  pluginRoot: await bundledPluginRoot(),
564
726
  environment,
565
727
  failureMessage: "Could not read Codex Security scan history",
566
- }, args);
728
+ }, args, input);
567
729
  },
568
730
  matchFindings: (input, options) => matchScanFindingsInternal(input, options, { surface: "cli" }),
569
731
  };
570
- export async function runCodexSkillCommand(args, output, command = resolveCodexCommand(), processEnvironment = process.env) {
732
+ export async function runCodexSkillCommand(args, output, command = resolveCodexCommand(), processEnvironment = process.env, input) {
571
733
  const configuredHome = processEnvironment["CODEX_HOME"];
572
734
  const environment = { ...processEnvironment };
573
735
  for (const name of Object.keys(environment)) {
@@ -581,10 +743,22 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
581
743
  env: environment,
582
744
  cwd: output?.appServer?.directory ?? parse(process.execPath).root,
583
745
  stdio: output === undefined
584
- ? "inherit"
585
- : [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
+ ],
586
756
  windowsHide: true,
587
757
  });
758
+ if (input !== undefined) {
759
+ invocation.stdin?.on("error", () => { });
760
+ invocation.stdin?.end(input);
761
+ }
588
762
  let requestedSignal = null;
589
763
  let forcedTermination;
590
764
  let forceStatusCompletion = null;
@@ -625,8 +799,11 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
625
799
  readSkillCommandOutput(invocation.stdout, output.appServer === undefined
626
800
  ? undefined
627
801
  : {
802
+ directory: output.appServer.directory,
628
803
  prompt: output.appServer.prompt,
629
804
  input: invocation.stdin,
805
+ sandbox: output.appServer.sandbox,
806
+ onEvent: output.appServer.onEvent,
630
807
  }),
631
808
  new Promise((resolve) => {
632
809
  forceCaptureCompletion = () => resolve(undefined);
@@ -726,7 +903,7 @@ async function writeCliOutput(output, value) {
726
903
  }
727
904
  }
728
905
  export function exportEnvironment(environment = process.env) {
729
- return Object.fromEntries([
906
+ return pythonUtf8Environment(Object.fromEntries([
730
907
  "PATH",
731
908
  "Path",
732
909
  "PATHEXT",
@@ -742,7 +919,7 @@ export function exportEnvironment(environment = process.env) {
742
919
  "LC_CTYPE",
743
920
  ]
744
921
  .filter((key) => environment[key] !== undefined)
745
- .map((key) => [key, environment[key]]));
922
+ .map((key) => [key, environment[key]])));
746
923
  }
747
924
  export async function main(argv = process.argv.slice(2), output = process.stdout, errorOutput = process.stderr, dependencies = DEFAULT_DEPENDENCIES) {
748
925
  argv = defaultListCommand(argv);
@@ -782,7 +959,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
782
959
  catch (error) {
783
960
  errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
784
961
  exitCode = 2;
785
- return undefined;
962
+ throw error;
786
963
  }
787
964
  };
788
965
  const latestScans = async (count = 1, status = "complete") => {
@@ -820,9 +997,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
820
997
  beforeId,
821
998
  "--after-scan-id",
822
999
  afterId,
823
- "--matches-json",
824
- JSON.stringify(await dependencies.matchFindings(matchingInputs)),
825
- ]);
1000
+ "--matches-json-stdin",
1001
+ ], JSON.stringify(await dependencies.matchFindings(matchingInputs)));
826
1002
  });
827
1003
  const presentHistory = (result, command, format, settings = {}) => {
828
1004
  if (result === undefined ||
@@ -923,7 +1099,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
923
1099
  const directory = dependencies.currentDirectory();
924
1100
  const scanRoot = options.scanRoot === undefined
925
1101
  ? undefined
926
- : resolveCliPath(directory, options.scanRoot);
1102
+ : process.platform === "win32"
1103
+ ? await canonicalizeModelSafePath(resolveCliPath(directory, options.scanRoot))
1104
+ : resolveCliPath(directory, options.scanRoot);
927
1105
  const repository = scanRoot !== undefined && args.repository === undefined
928
1106
  ? undefined
929
1107
  : resolveCliPath(directory, args.repository ?? directory);
@@ -1017,6 +1195,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1017
1195
  .describe("Saved scan identifier (default: latest completed scan)."),
1018
1196
  }),
1019
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."),
1020
1201
  verbose: z
1021
1202
  .boolean()
1022
1203
  .default(false)
@@ -1034,7 +1215,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1034
1215
  "--scan-id",
1035
1216
  scanId,
1036
1217
  ]);
1037
- scanArguments = scanArgumentsFromRecipe(recipe, scanId);
1218
+ scanArguments = scanArgumentsFromRecipe(recipe, scanId, options.validationPromptFile);
1038
1219
  scanArguments.verbose = options.verbose;
1039
1220
  }
1040
1221
  catch (error) {
@@ -1096,7 +1277,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1096
1277
  catch (error) {
1097
1278
  errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
1098
1279
  exitCode = 2;
1099
- return undefined;
1280
+ throw error;
1100
1281
  }
1101
1282
  },
1102
1283
  })
@@ -1404,7 +1585,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1404
1585
  },
1405
1586
  });
1406
1587
  const cli = Cli.create("codex-security", {
1407
- description: "Run, validate, patch, export, and publish Codex Security findings.",
1588
+ description: "Run, validate, patch, verify fixes, export, and publish Codex Security findings.",
1408
1589
  version: VERSION,
1409
1590
  mcp: {
1410
1591
  command: "npx --yes @openai/codex-security --mcp",
@@ -1424,7 +1605,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1424
1605
  options: z
1425
1606
  .object({
1426
1607
  auth: z
1427
- .enum(["auto", "chatgpt", "api-key"])
1608
+ .enum(SCAN_AUTH_MODES)
1428
1609
  .default("auto")
1429
1610
  .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
1430
1611
  verbose: z
@@ -1442,6 +1623,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1442
1623
  scanPromptFile: optionValue("--scan-prompt-file")
1443
1624
  .optional()
1444
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)."),
1445
1629
  postScanPromptFile: optionValue("--post-scan-prompt-file")
1446
1630
  .optional()
1447
1631
  .describe("Run FILE after each scan, including failures."),
@@ -1570,6 +1754,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1570
1754
  paths: options.path,
1571
1755
  knowledgeBasePaths: options.knowledgeBase,
1572
1756
  scanPromptFile: options.scanPromptFile,
1757
+ validationPromptFile: options.validationPromptFile,
1573
1758
  postScanPromptFile: options.postScanPromptFile,
1574
1759
  diff: options.diff,
1575
1760
  workingTree: options.workingTree,
@@ -1681,6 +1866,209 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1681
1866
  .command(scanHistory)
1682
1867
  .command(findingFeedback)
1683
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
+ })
1684
2072
  .command("bulk-scan", {
1685
2073
  description: "Discover repositories and run resumable bulk security scans.",
1686
2074
  destructive: true,
@@ -1715,6 +2103,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1715
2103
  scanPromptFile: optionValue("--scan-prompt-file")
1716
2104
  .optional()
1717
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."),
1718
2109
  postScanPromptFile: optionValue("--post-scan-prompt-file")
1719
2110
  .optional()
1720
2111
  .describe("Run FILE after each scan, including failures."),
@@ -1769,7 +2160,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1769
2160
  dependencies.addSignalListener("SIGTERM", onTerminate);
1770
2161
  try {
1771
2162
  const currentDirectory = dependencies.currentDirectory();
1772
- const prompts = await readPromptFiles(currentDirectory, options.scanPromptFile, options.postScanPromptFile);
2163
+ const prompts = await readPromptFiles(currentDirectory, options.scanPromptFile, options.postScanPromptFile, currentDirectory, options.validationPromptFile);
1773
2164
  let inputPath;
1774
2165
  let outputDir;
1775
2166
  let githubHost;
@@ -1914,6 +2305,164 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1914
2305
  errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
1915
2306
  }
1916
2307
  },
2308
+ })
2309
+ .command("verify-fix", {
2310
+ description: "Verify existing security fixes without changing the repository.",
2311
+ destructive: false,
2312
+ mcp: false,
2313
+ args: z.object({
2314
+ "findings...": z
2315
+ .string()
2316
+ .min(1, "A finding must not be empty.")
2317
+ .optional()
2318
+ .describe("Finding text, a file, or a saved finding identifier."),
2319
+ }),
2320
+ options: z.object({
2321
+ effort: effortOption(),
2322
+ scan: optionValue("--scan")
2323
+ .optional()
2324
+ .describe("Verify open findings from a saved scan."),
2325
+ severity: z
2326
+ .enum(REPORTABLE_SEVERITIES)
2327
+ .optional()
2328
+ .describe("Verify saved findings at or above LEVEL."),
2329
+ linearIssue: z
2330
+ .array(optionValue("--linear-issue"))
2331
+ .default([])
2332
+ .describe("Linear issue identifier or URL; repeat for more issues."),
2333
+ linearProject: optionValue("--linear-project")
2334
+ .optional()
2335
+ .describe("Verify issues in this Linear project."),
2336
+ linearFilter: optionValue("--linear-filter")
2337
+ .optional()
2338
+ .describe("JSON Linear issue filter for --linear-project."),
2339
+ linearApiKey: linearApiKeyOption(),
2340
+ codex: z
2341
+ .array(optionValue("--codex"))
2342
+ .default([])
2343
+ .describe('Repeat TOML model="gpt-5.6-terra" or model_reasoning_effort="high" only.'),
2344
+ }),
2345
+ output: z.record(z.string(), z.unknown()).optional(),
2346
+ async run({ format, options }) {
2347
+ try {
2348
+ const linear = options.linearIssue.length > 0 || !!options.linearProject;
2349
+ if (options.linearIssue.length > 0 && options.linearProject) {
2350
+ throw new CodexSecurityError("Use either --linear-issue or --linear-project, not both.");
2351
+ }
2352
+ if (options.linearFilter && !options.linearProject) {
2353
+ throw new CodexSecurityError("--linear-filter requires --linear-project.");
2354
+ }
2355
+ if (options.linearApiKey !== undefined && !linear) {
2356
+ throw new CodexSecurityError("--linear-api-key requires --linear-issue or --linear-project.");
2357
+ }
2358
+ const savedFindings = options.scan !== undefined ||
2359
+ (positionals.length > 0 && positionals.every(isFindingIdentifier));
2360
+ if (savedFindings && linear) {
2361
+ throw new CodexSecurityError("Saved findings cannot be combined with Linear issues or projects.");
2362
+ }
2363
+ if (options.severity !== undefined && !savedFindings) {
2364
+ throw new CodexSecurityError("--severity requires a saved finding identifier or --scan.");
2365
+ }
2366
+ if (positionals.length === 0 && !linear && !savedFindings) {
2367
+ throw new CodexSecurityError("Verify-fix requires a finding, --scan, --linear-issue, or --linear-project.");
2368
+ }
2369
+ const selected = savedFindings
2370
+ ? await selectSavedFindings(positionals, options.scan, options.severity, dependencies)
2371
+ : undefined;
2372
+ const imports = linear
2373
+ ? await importLinearIssues({
2374
+ issues: options.linearIssue,
2375
+ project: options.linearProject,
2376
+ filter: options.linearFilter,
2377
+ apiKey: options.linearApiKey,
2378
+ environment: dependencies.environment,
2379
+ linearClient: dependencies.linearClient,
2380
+ })
2381
+ : [];
2382
+ const identifiers = selected === undefined
2383
+ ? [
2384
+ ...positionals.map((_finding, index) => `finding-${index + 1}`),
2385
+ ...imports.map(({ id }) => id),
2386
+ ]
2387
+ : selected.findings.map(({ occurrenceId }) => occurrenceId);
2388
+ if (new Set(identifiers).size !== identifiers.length) {
2389
+ throw new CodexSecurityError("Verification inputs must have unique finding or issue identifiers.");
2390
+ }
2391
+ const repository = selected?.repository ?? dependencies.currentDirectory();
2392
+ let results = [];
2393
+ if (identifiers.length > 0) {
2394
+ const environment = imports.length === 0
2395
+ ? undefined
2396
+ : Object.fromEntries(Object.entries(dependencies.environment).filter(([name]) => !/^(?:CODEX_SECURITY_)?LINEAR_(?:API_KEY|ACCESS_TOKEN)$/iu.test(name)));
2397
+ let response = "";
2398
+ const verificationOutput = {
2399
+ write(value) {
2400
+ response += value.toString();
2401
+ return true;
2402
+ },
2403
+ };
2404
+ const progress = new VerificationProgressPresenter(errorOutput, dependencies, repository, identifiers.length);
2405
+ progress.start();
2406
+ try {
2407
+ exitCode = await runSkill("verify-fix", selected === undefined ? [...positionals, ...imports] : [], options.codex, options.effort, verificationOutput, errorOutput, dependencies, {
2408
+ directory: repository,
2409
+ ...(selected === undefined
2410
+ ? {}
2411
+ : { findings: selected.findings }),
2412
+ verificationIds: identifiers,
2413
+ environment,
2414
+ onEvent: progress.observe.bind(progress),
2415
+ });
2416
+ if (exitCode !== 0) {
2417
+ if (exitCode !== 130 && exitCode !== 143)
2418
+ exitCode = 2;
2419
+ return undefined;
2420
+ }
2421
+ let reported;
2422
+ try {
2423
+ reported = JSON.parse(response);
2424
+ }
2425
+ catch {
2426
+ throw new CodexSecurityError("Verification results were not valid JSON.");
2427
+ }
2428
+ const parsed = z
2429
+ .object({ results: z.array(findingVerificationSchema) })
2430
+ .safeParse(reported);
2431
+ if (!parsed.success ||
2432
+ parsed.data.results.length !== identifiers.length ||
2433
+ parsed.data.results.some(({ id }, index) => id !== identifiers[index])) {
2434
+ throw new CodexSecurityError("Codex did not return an evidence-backed verification result for every finding.");
2435
+ }
2436
+ results = parsed.data.results;
2437
+ progress.complete(results);
2438
+ exitCode = results.some(({ status }) => status === "inconclusive")
2439
+ ? 2
2440
+ : results.some(({ status }) => status === "still_vulnerable")
2441
+ ? 1
2442
+ : 0;
2443
+ }
2444
+ finally {
2445
+ progress.stop();
2446
+ }
2447
+ }
2448
+ if (format === "json" || format === "jsonl") {
2449
+ return {
2450
+ repository,
2451
+ ...(selected === undefined ? {} : { scanId: selected.scanId }),
2452
+ results,
2453
+ };
2454
+ }
2455
+ for (const result of results) {
2456
+ output.write(`${result.status.toUpperCase()} ${safePatchText(result.id)}: ${safePatchText(result.evidence)}\n`);
2457
+ }
2458
+ return undefined;
2459
+ }
2460
+ catch (error) {
2461
+ exitCode = 2;
2462
+ errorOutput.write(`codex-security: ${safeErrorMessage(error)}\n`);
2463
+ return undefined;
2464
+ }
2465
+ },
1917
2466
  })
1918
2467
  .command("patch", {
1919
2468
  description: "Patch one or more security issues.",
@@ -2227,10 +2776,14 @@ function defaultListCommand(argv) {
2227
2776
  ...argv.slice(commandIndex + 1),
2228
2777
  ];
2229
2778
  }
2230
- function scanArgumentsFromRecipe(recipe, parentScanId) {
2779
+ function scanArgumentsFromRecipe(recipe, parentScanId, validationPromptFile) {
2231
2780
  if (recipe === undefined || !isJsonObject(recipe)) {
2232
2781
  throw new CodexSecurityError("This scan does not have a saved launch recipe.");
2233
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
+ }
2234
2787
  const repository = recipe["repository"];
2235
2788
  if (typeof repository !== "string" || repository.length === 0) {
2236
2789
  throw new CodexSecurityError("The saved scan recipe does not contain a repository.");
@@ -2302,6 +2855,7 @@ function scanArgumentsFromRecipe(recipe, parentScanId) {
2302
2855
  repository,
2303
2856
  paths,
2304
2857
  knowledgeBasePaths,
2858
+ validationPromptFile,
2305
2859
  diff: kind === "refs" ? reference : undefined,
2306
2860
  workingTree: kind === "working_tree",
2307
2861
  head: kind === "refs" ? head ?? "HEAD" : undefined,
@@ -2329,11 +2883,13 @@ function validateCliArguments(argv, positionals) {
2329
2883
  "scan",
2330
2884
  "install-hook",
2331
2885
  "bulk-scan",
2886
+ "scan-components",
2332
2887
  "scans",
2333
2888
  "findings",
2334
2889
  "export",
2335
2890
  "publish",
2336
2891
  "validate",
2892
+ "verify-fix",
2337
2893
  "patch",
2338
2894
  "login",
2339
2895
  "logout",
@@ -2428,6 +2984,7 @@ function validateCliArguments(argv, positionals) {
2428
2984
  }
2429
2985
  }
2430
2986
  if (command !== "validate" &&
2987
+ command !== "verify-fix" &&
2431
2988
  command !== "patch" &&
2432
2989
  positionals.length >
2433
2990
  (command === "logout" || command === "info"
@@ -2475,9 +3032,8 @@ async function matchAllScans(dependencies, force) {
2475
3032
  scanId,
2476
3033
  "--after-scan-id",
2477
3034
  afterScanId,
2478
- "--matches-json",
2479
- JSON.stringify({ matches, uncertain }),
2480
- ]);
3035
+ "--matches-json-stdin",
3036
+ ], JSON.stringify({ matches, uncertain }));
2481
3037
  matchedPairs += 1;
2482
3038
  findingMatches += matches.reduce((count, { beforeOccurrenceIds, afterOccurrenceIds }) => count + beforeOccurrenceIds.length * afterOccurrenceIds.length, 0);
2483
3039
  }
@@ -2637,6 +3193,7 @@ async function publishPatchBranch(repository, branch, stderr, dependencies) {
2637
3193
  url = await run("gh", [
2638
3194
  "pr",
2639
3195
  "create",
3196
+ "--draft",
2640
3197
  "--head",
2641
3198
  branch,
2642
3199
  "--title",
@@ -2688,7 +3245,7 @@ async function createPatchPullRequest(selected, patches, stderr, dependencies) {
2688
3245
  }
2689
3246
  const branch = `codex-security/patch-${selected.scanId.replaceAll(/[^a-z\d._-]/giu, "-")}`;
2690
3247
  const run = (command, args) => dependencies.runRepositoryCommand(command, args, selected.repository);
2691
- stderr.write("Creating a GitHub pull request for verified patches...\n");
3248
+ stderr.write("Creating a draft GitHub pull request for verified patches...\n");
2692
3249
  await run("git", ["switch", "-c", branch]);
2693
3250
  await run("git", ["--literal-pathspecs", "add", "--", ...files]);
2694
3251
  await run("git", [
@@ -2839,13 +3396,25 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
2839
3396
  contents.push(contentsOrLiteral);
2840
3397
  }
2841
3398
  const plugin = await bundledPluginRoot();
2842
- const inputLabel = skill === "validation" ? "Findings" : "Issues";
3399
+ const verify = skill === "verify-fix";
3400
+ const inputLabel = skill === "validation" || verify ? "Findings" : "Issues";
2843
3401
  const prompt = [
2844
- `Use the bundled $codex-security:${skill} skill at ${JSON.stringify(join(plugin, "skills", skill, "SKILL.md"))}.`,
2845
- ...(options.findings === undefined
2846
- ? []
3402
+ ...(verify
3403
+ ? [
3404
+ "Use the bundled $codex-security:verify-fix skill. Its complete instructions and shared assessment reference are provided below; do not reread either file.",
3405
+ await readFile(join(plugin, "skills", "verify-fix", "SKILL.md"), "utf8"),
3406
+ "Shared static finding assessment reference:",
3407
+ await readFile(join(plugin, "references", "static-finding-assessment.md"), "utf8"),
3408
+ `Expected result identifiers (JSON array): ${JSON.stringify(options.verificationIds)}`,
3409
+ "Return exactly one evidence-backed result per expected identifier in the same order, following the skill's JSON result contract.",
3410
+ ]
2847
3411
  : [
2848
- 'Return exactly one JSON object with a "patches" array. Include one object for every supplied finding: {"occurrenceId":"...","status":"verified|no_change|blocked|failed","files":["relative/path"],"verification":"proof that the original issue is fixed and legitimate behavior still works","reason":"required for blocked or failed outcomes"}. Use "verified" only after the original issue no longer reproduces and relevant checks pass. Preserve unrelated local changes.',
3412
+ `Use the bundled $codex-security:${skill} skill at ${JSON.stringify(join(plugin, "skills", skill, "SKILL.md"))}.`,
3413
+ ...(options.findings === undefined
3414
+ ? []
3415
+ : [
3416
+ 'Return exactly one JSON object with a "patches" array. Include one object for every supplied finding: {"occurrenceId":"...","status":"verified|no_change|blocked|failed","files":["relative/path"],"verification":"proof that the original issue is fixed and legitimate behavior still works","reason":"required for blocked or failed outcomes"}. Use "verified" only after the original issue no longer reproduces and relevant checks pass. Preserve unrelated local changes.',
3417
+ ]),
2849
3418
  ]),
2850
3419
  ...(options.findingInstructions === undefined
2851
3420
  ? []
@@ -2857,11 +3426,12 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
2857
3426
  JSON.stringify(contents),
2858
3427
  ].join("\n");
2859
3428
  const patch = skill === "fix-finding";
3429
+ const appServer = patch || verify;
2860
3430
  return dependencies.runCodex([
2861
- ...(patch ? ["app-server"] : ["exec", "--ignore-user-config"]),
3431
+ ...(appServer ? ["app-server"] : ["exec", "--ignore-user-config"]),
2862
3432
  "--disable",
2863
3433
  "plugins",
2864
- ...(patch ? [] : ["--ephemeral", "--color", "never", "--json"]),
3434
+ ...(appServer ? [] : ["--ephemeral", "--color", "never", "--json"]),
2865
3435
  "--config",
2866
3436
  `model=${JSON.stringify(model)}`,
2867
3437
  "--config",
@@ -2874,10 +3444,11 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
2874
3444
  `model_providers.${options.provider}.${key}=${JSON.stringify(value)}`,
2875
3445
  ]),
2876
3446
  "--config",
2877
- 'approval_policy="never"',
3447
+ verify ? 'approval_policy="on-request"' : 'approval_policy="never"',
3448
+ ...(verify ? ["--config", 'approvals_reviewer="auto_review"'] : []),
2878
3449
  "--config",
2879
3450
  'responses_api_metadata.codex_security_surface="cli"',
2880
- ...(patch
3451
+ ...(appServer
2881
3452
  ? []
2882
3453
  : [
2883
3454
  "--sandbox",
@@ -2885,14 +3456,25 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
2885
3456
  "--skip-git-repo-check",
2886
3457
  "--cd",
2887
3458
  directory,
2888
- prompt,
3459
+ "-",
2889
3460
  ]),
2890
3461
  ], {
2891
- command: patch ? "patch" : "validate",
3462
+ command: verify ? "verify-fix" : patch ? "patch" : "validate",
2892
3463
  stdout,
2893
3464
  stderr,
2894
- ...(patch ? { appServer: { directory, prompt } } : {}),
2895
- }, options.environment);
3465
+ ...(appServer
3466
+ ? {
3467
+ appServer: {
3468
+ directory,
3469
+ prompt,
3470
+ ...(verify ? { sandbox: "read-only" } : {}),
3471
+ ...(options.onEvent === undefined
3472
+ ? {}
3473
+ : { onEvent: options.onEvent }),
3474
+ },
3475
+ }
3476
+ : {}),
3477
+ }, options.environment, appServer ? undefined : prompt);
2896
3478
  }
2897
3479
  export async function readSkillCommandOutput(stream, appServer) {
2898
3480
  let message;
@@ -2904,6 +3486,19 @@ export async function readSkillCommandOutput(stream, appServer) {
2904
3486
  const send = (request) => {
2905
3487
  appServer?.input.write(`${JSON.stringify(request)}\n`);
2906
3488
  };
3489
+ const startThread = (config) => {
3490
+ send({
3491
+ id: 2,
3492
+ method: "thread/start",
3493
+ // An explicit cwd makes Codex persist trust for a new project.
3494
+ // Inherit the child process cwd and preserve the user's decision.
3495
+ params: {
3496
+ approvalPolicy: appServer?.sandbox === "read-only" ? "on-request" : "never",
3497
+ sandbox: appServer?.sandbox ?? "workspace-write",
3498
+ ...(config === undefined ? {} : { config }),
3499
+ },
3500
+ });
3501
+ };
2907
3502
  if (appServer !== undefined) {
2908
3503
  send({
2909
3504
  id: 1,
@@ -2928,6 +3523,18 @@ export async function readSkillCommandOutput(stream, appServer) {
2928
3523
  }
2929
3524
  const value = event;
2930
3525
  if (appServer !== undefined) {
3526
+ const params = value["params"];
3527
+ if (typeof params === "object" &&
3528
+ params !== null &&
3529
+ "threadId" in params &&
3530
+ params.threadId === threadId &&
3531
+ "turnId" in params &&
3532
+ params.turnId === turnId) {
3533
+ try {
3534
+ appServer.onEvent?.(value);
3535
+ }
3536
+ catch { }
3537
+ }
2931
3538
  if (value["id"] !== undefined) {
2932
3539
  if (typeof value["method"] === "string") {
2933
3540
  send({
@@ -2941,13 +3548,80 @@ export async function readSkillCommandOutput(stream, appServer) {
2941
3548
  }
2942
3549
  else if (value["id"] === 1) {
2943
3550
  send({ method: "notifications/initialized" });
2944
- send({
2945
- id: 2,
2946
- method: "thread/start",
2947
- // An explicit cwd makes Codex persist trust for a new project.
2948
- // Inherit the child process cwd and preserve the user's decision.
2949
- params: { approvalPolicy: "never", sandbox: "workspace-write" },
2950
- });
3551
+ if (appServer.sandbox === "read-only") {
3552
+ if (appServer.directory === undefined) {
3553
+ error =
3554
+ "Codex did not receive the repository directory required for read-only verification.";
3555
+ appServer.input.end();
3556
+ continue;
3557
+ }
3558
+ send({
3559
+ id: 4,
3560
+ method: "config/read",
3561
+ params: {
3562
+ cwd: appServer.directory,
3563
+ includeLayers: true,
3564
+ },
3565
+ });
3566
+ }
3567
+ else {
3568
+ startThread();
3569
+ }
3570
+ }
3571
+ else if (value["id"] === 4 && appServer.sandbox === "read-only") {
3572
+ const result = value["result"];
3573
+ const layers = typeof result === "object" && result !== null && "layers" in result
3574
+ ? result.layers
3575
+ : undefined;
3576
+ if (!Array.isArray(layers)) {
3577
+ error =
3578
+ "Codex did not provide the configuration layers required for read-only verification.";
3579
+ appServer.input.end();
3580
+ continue;
3581
+ }
3582
+ const repositoryServers = new Set();
3583
+ const configuredServers = new Set();
3584
+ for (const layer of layers) {
3585
+ if (typeof layer !== "object" || layer === null)
3586
+ continue;
3587
+ const name = layer["name"];
3588
+ const configuration = layer["config"];
3589
+ if (typeof name !== "object" ||
3590
+ name === null ||
3591
+ typeof configuration !== "object" ||
3592
+ configuration === null) {
3593
+ continue;
3594
+ }
3595
+ const servers = configuration["mcp_servers"];
3596
+ if (typeof servers !== "object" || servers === null)
3597
+ continue;
3598
+ if (name["type"] === "project") {
3599
+ if (layer["disabledReason"] !== undefined)
3600
+ continue;
3601
+ for (const server of Object.keys(servers)) {
3602
+ repositoryServers.add(server);
3603
+ }
3604
+ }
3605
+ else {
3606
+ for (const server of Object.keys(servers)) {
3607
+ configuredServers.add(server);
3608
+ }
3609
+ }
3610
+ }
3611
+ const conflict = [...repositoryServers].find((server) => configuredServers.has(server));
3612
+ if (conflict !== undefined) {
3613
+ error = `Repository-local MCP server ${JSON.stringify(conflict)} overrides a configured integration; remove the repository override before verifying fixes.`;
3614
+ appServer.input.end();
3615
+ continue;
3616
+ }
3617
+ startThread(repositoryServers.size === 0
3618
+ ? undefined
3619
+ : {
3620
+ mcp_servers: Object.fromEntries([...repositoryServers].map((server) => [
3621
+ server,
3622
+ { enabled: false },
3623
+ ])),
3624
+ });
2951
3625
  }
2952
3626
  else if (value["id"] === 2) {
2953
3627
  threadId = value["result"].thread.id;
@@ -3265,7 +3939,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
3265
3939
  const directory = dependencies.currentDirectory();
3266
3940
  repository = arguments_.repository ?? directory;
3267
3941
  const target = targetFromArguments(arguments_);
3268
- 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);
3269
3943
  const config = {
3270
3944
  pluginPath: arguments_.pluginPath,
3271
3945
  pythonPath: arguments_.pythonPath,
@@ -3704,10 +4378,16 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
3704
4378
  ? result.toJSON()
3705
4379
  : { ...result.toJSON(), warnings: targetWarnings };
3706
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
+ }
3707
4387
  progress?.stage(`Scan complete · ${result.manifest.scan.id.slice(0, 8)}`);
3708
4388
  printScanSummary(result, progress, errorOutput, progress?.interactive === true &&
3709
4389
  dependencies.environment["NO_COLOR"] === undefined &&
3710
- dependencies.environment["TERM"] !== "dumb");
4390
+ dependencies.environment["TERM"] !== "dumb", deepScanStop);
3711
4391
  const completedScan = (exitCode) => {
3712
4392
  diagnostic("scan.completed", {
3713
4393
  coverage: result.coverage.completeness,
@@ -3891,7 +4571,7 @@ function scanScope(arguments_) {
3891
4571
  const scoped = isAbsolute(path) ||
3892
4572
  /^[A-Za-z]:\//u.test(portable) ||
3893
4573
  portable.startsWith("//")
3894
- ? portable.split("/").at(-1) ?? portable
4574
+ ? basename(portable) || portable
3895
4575
  : portable;
3896
4576
  return errorMessage(scoped.replaceAll(/[\u0000-\u001F\u007F]/gu, " "));
3897
4577
  });
@@ -3903,19 +4583,52 @@ function scanScope(arguments_) {
3903
4583
  return "working-tree changes";
3904
4584
  return null;
3905
4585
  }
3906
- 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
+ }
3907
4627
  return {
3908
- preflight: "preflight",
3909
- threat_model: "building threat model",
3910
- discovery: "reviewing files",
3911
- ranking: "ranking scan targets",
3912
- file_review: "reviewing files",
3913
- validation: "validating findings",
3914
- attack_path: "analyzing attack paths",
3915
- reporting: "writing report",
3916
- }[value];
4628
+ reason: "Stopped before the review finished. See the report for details.",
4629
+ };
3917
4630
  }
3918
- function printScanSummary(result, progress, errorOutput, color) {
4631
+ function printScanSummary(result, progress, errorOutput, color, deepScanStop) {
3919
4632
  const paint = (value, code) => color ? `\u001B[${code}m${value}\u001B[0m` : value;
3920
4633
  const repositoryFindings = result.repositoryFindings;
3921
4634
  const findings = repositoryFindings ?? result.findings.findings;
@@ -3955,6 +4668,9 @@ function printScanSummary(result, progress, errorOutput, color) {
3955
4668
  errorOutput.write(`\n ${paint("REPORT", "1;36")} ${paint(errorMessage(result.reportPath), 4)}\n\n` +
3956
4669
  ` ${paint("FINDINGS", 1)} ${paint(`${findingCount}${findingSummary === "" ? "" : ` (${findingSummary})`}`, findingColor)}\n` +
3957
4670
  ` ${paint("COVERAGE", 1)} ${result.coverage.completeness}\n` +
4671
+ (deepScanStop === undefined
4672
+ ? ""
4673
+ : ` ${paint("STOPPED", 1)} ${deepScanStop.reason}\n`) +
3958
4674
  ` ${paint("ELAPSED", 1)} ${duration}\n`);
3959
4675
  const tokenSummary = formatTokenUsage(result.turnResult.usage);
3960
4676
  if (tokenSummary !== null) {
@@ -3964,6 +4680,9 @@ function printScanSummary(result, progress, errorOutput, color) {
3964
4680
  errorOutput.write(` ${paint("COST", 1)} ${formatUsd(result.cost.estimatedUsd)}\n`);
3965
4681
  }
3966
4682
  errorOutput.write(` ${paint("RESULTS", 1)} ${errorMessage(result.scanDir)}\n`);
4683
+ if (deepScanStop?.nextStep !== undefined) {
4684
+ errorOutput.write(`\n ${deepScanStop.nextStep}\n`);
4685
+ }
3967
4686
  }
3968
4687
  function formatTokenUsage(usage) {
3969
4688
  if (usage === null || typeof usage !== "object")