@openai/codex-security 0.1.9 → 0.1.11

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 (87) hide show
  1. package/README.md +43 -18
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  3. package/_bundled_plugin/.mcp.json +3 -1
  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/preflight/capability-profiles.toml +1 -1
  7. package/_bundled_plugin/references/scan-contract.md +1 -1
  8. package/_bundled_plugin/scripts/deep_scan_config.py +21 -1
  9. package/_bundled_plugin/scripts/deep_scan_workbench.py +66 -14
  10. package/_bundled_plugin/scripts/finalize_scan_contract.py +15 -207
  11. package/_bundled_plugin/scripts/generate_in_scope_files.py +127 -2
  12. package/_bundled_plugin/scripts/generate_rank_input.py +38 -5
  13. package/_bundled_plugin/scripts/normalize_candidates.py +20 -2
  14. package/_bundled_plugin/scripts/rank_preview.py +4 -0
  15. package/_bundled_plugin/scripts/report_projection.py +39 -1
  16. package/_bundled_plugin/scripts/workbench_cli.py +9 -0
  17. package/_bundled_plugin/scripts/workbench_db.py +295 -4
  18. package/_bundled_plugin/scripts/workbench_native_indexes.py +100 -43
  19. package/_bundled_plugin/scripts/workbench_schema.py +15 -0
  20. package/_bundled_plugin/scripts/workbench_source_excerpt.py +1 -5
  21. package/_bundled_plugin/scripts/workbench_target.py +82 -0
  22. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +5 -3
  23. package/_bundled_plugin/skills/finding-discovery/SKILL.md +8 -4
  24. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +21 -140
  25. package/dist/api.d.ts +43 -3
  26. package/dist/api.d.ts.map +1 -1
  27. package/dist/api.js +319 -135
  28. package/dist/api.js.map +1 -1
  29. package/dist/auth.d.ts +2 -3
  30. package/dist/auth.d.ts.map +1 -1
  31. package/dist/auth.js +59 -270
  32. package/dist/auth.js.map +1 -1
  33. package/dist/cli.d.ts +1 -1
  34. package/dist/cli.d.ts.map +1 -1
  35. package/dist/cli.js +107 -43
  36. package/dist/cli.js.map +1 -1
  37. package/dist/contract.js +7 -5
  38. package/dist/contract.js.map +1 -1
  39. package/dist/cost.d.ts +2 -0
  40. package/dist/cost.d.ts.map +1 -1
  41. package/dist/cost.js +24 -2
  42. package/dist/cost.js.map +1 -1
  43. package/dist/errors.d.ts +4 -2
  44. package/dist/errors.d.ts.map +1 -1
  45. package/dist/errors.js +10 -46
  46. package/dist/errors.js.map +1 -1
  47. package/dist/index.d.ts +2 -2
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +1 -1
  50. package/dist/index.js.map +1 -1
  51. package/dist/knowledge-base.d.ts.map +1 -1
  52. package/dist/knowledge-base.js +2 -1
  53. package/dist/knowledge-base.js.map +1 -1
  54. package/dist/multiscan.d.ts.map +1 -1
  55. package/dist/multiscan.js +3 -2
  56. package/dist/multiscan.js.map +1 -1
  57. package/dist/result.d.ts +13 -1
  58. package/dist/result.d.ts.map +1 -1
  59. package/dist/result.js +3 -0
  60. package/dist/result.js.map +1 -1
  61. package/dist/runtime.d.ts +9 -6
  62. package/dist/runtime.d.ts.map +1 -1
  63. package/dist/runtime.js +130 -287
  64. package/dist/runtime.js.map +1 -1
  65. package/dist/scan-comparison.d.ts +14 -0
  66. package/dist/scan-comparison.d.ts.map +1 -1
  67. package/dist/scan-comparison.js +90 -1
  68. package/dist/scan-comparison.js.map +1 -1
  69. package/dist/scan-dashboard.d.ts.map +1 -1
  70. package/dist/scan-dashboard.js +1 -0
  71. package/dist/scan-dashboard.js.map +1 -1
  72. package/dist/scan-history-renderer.d.ts +1 -1
  73. package/dist/scan-history-renderer.d.ts.map +1 -1
  74. package/dist/scan-history-renderer.js +10 -0
  75. package/dist/scan-history-renderer.js.map +1 -1
  76. package/dist/scan-logs.d.ts +17 -0
  77. package/dist/scan-logs.d.ts.map +1 -0
  78. package/dist/scan-logs.js +90 -0
  79. package/dist/scan-logs.js.map +1 -0
  80. package/dist/targets.d.ts +1 -0
  81. package/dist/targets.d.ts.map +1 -1
  82. package/dist/targets.js +22 -0
  83. package/dist/targets.js.map +1 -1
  84. package/dist/version.d.ts +1 -1
  85. package/dist/version.js +1 -1
  86. package/dist/version.js.map +1 -1
  87. package/package.json +2 -2
package/dist/api.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /// <reference lib="esnext.disposable" preserve="true" />
2
- import { chmod, lstat, mkdir, readFile, realpath, rm, writeFile, } from "node:fs/promises";
2
+ import { chmod, lstat, mkdir, readFile, realpath, rename, rm, writeFile, } from "node:fs/promises";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
@@ -9,14 +9,15 @@ import { accountStatus, CodexLoginHandle, loginApiKey as persistApiKey, logout a
9
9
  import { EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
10
10
  import { estimateScanCost, ScanCostTracker } from "./cost.js";
11
11
  import { loadContract, requireScanFile, } from "./contract.js";
12
- import { AuthenticationRequiredError, CodexSecurityError, IncompleteScanError, OutputDirectoryError, OutputInsideProtectedRootError, redactedErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
12
+ import { AuthenticationRequiredError, CodexSecurityError, IncompleteScanError, OutputDirectoryError, OutputInsideProtectedRootError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
13
13
  import { prepareKnowledgeBase, } from "./knowledge-base.js";
14
- import { ScanResult } from "./result.js";
14
+ import { ScanResult, } from "./result.js";
15
15
  import { scanActivitiesFromEvent } from "./scan-activity.js";
16
+ import { matchCompletedScan, } from "./scan-comparison.js";
16
17
  import { scanProgressUpdatesFromEvent, workerStatusFromEvent, } from "./worker-progress.js";
17
18
  import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";
18
- import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, planOutputArchive, prepareOutputDir, preparePersistentScanRoot, requireModelSafeOutputDir, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
19
- import { enclosingGitWorktreeRoot, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateMode, } from "./targets.js";
19
+ import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, planOutputArchive, prepareOutputDir, preparePersistentScanRoot, requireModelSafeOutputDir, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
20
+ import { enclosingGitWorktreeRoot, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateCommittedDiffCheckout, validateMode, } from "./targets.js";
20
21
  const DEFAULT_DEPENDENCIES = {
21
22
  createCodex: (options) => new Codex(options),
22
23
  environment: process.env,
@@ -29,6 +30,7 @@ const DEEP_SCAN_SETTINGS = [
29
30
  ["subagents", "subagents", 0],
30
31
  ["stopAfterNoNew", "stop_after_no_new", 1],
31
32
  ["maxDiscoveryRuns", "max_discovery_runs", 1],
33
+ ["maxTimeHours", "max_time_hours", 0],
32
34
  ];
33
35
  export class CodexSecurity {
34
36
  config;
@@ -39,6 +41,7 @@ export class CodexSecurity {
39
41
  executableVersion: CODEX_EXECUTABLE_VERSION,
40
42
  };
41
43
  #dependencies;
44
+ #surface;
42
45
  #loginHandles = new Set();
43
46
  #abortController = new AbortController();
44
47
  #activeOperation = null;
@@ -47,9 +50,10 @@ export class CodexSecurity {
47
50
  #runtimeCredentialSource = null;
48
51
  #closed = false;
49
52
  #closePromise = null;
50
- constructor(config = {}, dependencies = DEFAULT_DEPENDENCIES) {
53
+ constructor(config = {}, dependencies = DEFAULT_DEPENDENCIES, runtimeOptions = { surface: "sdk" }) {
51
54
  this.config = structuredClone(config);
52
55
  this.#dependencies = dependencies;
56
+ this.#surface = runtimeOptions.surface;
53
57
  }
54
58
  async run(repository, options = {}) {
55
59
  return await this.#trackOperation(() => this.#run(repository, options));
@@ -104,6 +108,7 @@ export class CodexSecurity {
104
108
  let releaseCredentialHome = null;
105
109
  let scanFailure = false;
106
110
  let completionCost = null;
111
+ let budgetRecovery = null;
107
112
  let preparedTargetWarnings = [];
108
113
  let runPostScan = null;
109
114
  let activeScan = null;
@@ -145,21 +150,20 @@ export class CodexSecurity {
145
150
  throw new AuthenticationRequiredError(`Set ${externalProvider.env_key} to run a scan through ${externalProvider.name}.`);
146
151
  }
147
152
  const scanEnvironment = selectedScanEnvironment(this.#dependencies.environment, options.auth, modelProvider);
148
- if (authentication.method === "stored_credentials" &&
149
- this.#dependencies.prepareRuntime === undefined) {
153
+ if (this.#dependencies.prepareRuntime === undefined) {
150
154
  const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"));
151
155
  releaseCredentialHome = await acquireCodexSecurityCredentialHomeLock(credentialHome, signal);
152
156
  }
153
157
  const previousRuntime = this.#runtime;
154
- const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"), options.auth, modelProvider);
158
+ const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"), options.auth, requestedConfig);
155
159
  if (runtime === previousRuntime &&
156
- runtime.persistentCredentialHome === true &&
157
160
  this.#dependencies.prepareRuntime === undefined) {
158
- await this.#refreshPersistentRuntime(runtime, scanEnvironment, signal);
161
+ await this.#refreshPersistentRuntime(runtime, scanEnvironment, signal, requestedConfig);
159
162
  }
160
163
  const effectiveConfig = runtime.effectiveConfig ?? requestedConfig;
164
+ const preflightConfig = scanPreflightCodexConfig(effectiveConfig);
161
165
  if (runtime.configPath !== undefined) {
162
- await writeCodexConfig(runtime.configPath, scanPreflightCodexConfig(effectiveConfig));
166
+ await writeCodexConfig(runtime.configPath, preflightConfig);
163
167
  }
164
168
  const runtimeHome = await realpath(runtime.codexHome);
165
169
  requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");
@@ -199,6 +203,10 @@ export class CodexSecurity {
199
203
  "OPENAI_API_KEY or CODEX_API_KEY for CI.");
200
204
  }
201
205
  authentication = await runtimeScanAuthentication(this.#dependencies.environment, runtime.codexHome, options.auth, modelProvider);
206
+ if (authentication.method !== "stored_credentials") {
207
+ await releaseCredentialHome?.();
208
+ releaseCredentialHome = null;
209
+ }
202
210
  notifyObserver("onAuthentication", options.onAuthentication, options.onObserverError, authentication);
203
211
  const python = await (this.#dependencies.resolvePluginPython ?? resolvePluginPython)({
204
212
  configuredPath: this.config.pythonPath,
@@ -231,7 +239,14 @@ export class CodexSecurity {
231
239
  !isAbsolute(pluginRelativeToHome))) {
232
240
  throw new OutputDirectoryError(`Shell-visible plugin root must be outside CODEX_HOME: ${canonicalShellPluginRoot}`);
233
241
  }
234
- const basePrompt = await scanPrompt(shellPluginRoot, normalized, mode, runtime.configPath !== undefined, knowledgeBase !== null, options.scanPrompt);
242
+ const skillName = skillNameFor(normalized, mode);
243
+ const skillPath = join(shellPluginRoot, "skills", skillName, "SKILL.md");
244
+ const skillMetadata = await lstat(skillPath).catch(() => null);
245
+ if (skillMetadata === null ||
246
+ !skillMetadata.isFile() ||
247
+ skillMetadata.isSymbolicLink()) {
248
+ throw new IncompleteScanError(`Installed plugin is missing scan skill: ${skillName}`);
249
+ }
235
250
  checkOpen();
236
251
  const expectation = {
237
252
  repository: repo,
@@ -242,6 +257,14 @@ export class CodexSecurity {
242
257
  };
243
258
  const { model } = scanModelConfiguration(effectiveConfig);
244
259
  validateScanCostLimit(options.maxCostUsd, model);
260
+ if (mode === "deep" && options.maxCostUsd !== undefined) {
261
+ budgetRecovery = {
262
+ expectation,
263
+ pluginRoot: runtime.plugin.installedRoot,
264
+ model,
265
+ threadId: null,
266
+ };
267
+ }
245
268
  let scopeFileCount = null;
246
269
  let reviewedFileCount = 0;
247
270
  const reportProgress = (progress) => {
@@ -258,12 +281,13 @@ export class CodexSecurity {
258
281
  costAbortController.abort(error);
259
282
  return;
260
283
  }
261
- notifyObserver("onWarning", options.onWarning, options.onObserverError, `Could not track scan activity: ${redactedErrorMessage(error)}`);
284
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, `Could not track scan activity: ${errorMessage(error)}`);
262
285
  };
263
286
  const tracker = new ScanCostTracker({
264
287
  codexHome: runtime.codexHome,
265
288
  model,
266
289
  repository: repo,
290
+ scanDirectory: scanDir,
267
291
  maxCostUsd: options.maxCostUsd,
268
292
  onActivity: options.onActivity === undefined
269
293
  ? undefined
@@ -281,7 +305,7 @@ export class CodexSecurity {
281
305
  onError: reportTrackingError,
282
306
  });
283
307
  costTracker = tracker;
284
- const recipe = scanRecipe(repo, normalized, mode, expectation.repositoryRevision, runtime.plugin.version, effectiveConfig, options.failureSeverity, knowledgeBase?.sources, options.maxCostUsd, deepScanOptions(options));
308
+ const recipe = scanRecipe(repo, normalized, mode, expectation.repositoryRevision, runtime.plugin.version, preflightConfig, options.failureSeverity, knowledgeBase?.sources, options.maxCostUsd, deepScanOptions(options));
285
309
  const workbenchOptions = {
286
310
  python,
287
311
  pluginRoot: runtime.plugin.pluginRoot,
@@ -364,6 +388,8 @@ export class CodexSecurity {
364
388
  }
365
389
  activeScan = { id: scanId, options: workbenchOptions };
366
390
  checkOpen();
391
+ const basePrompt = scanPrompt(normalized, mode, skillName, scanId, runtime.configPath !== undefined, knowledgeBase !== null, options.scanPrompt);
392
+ checkOpen();
367
393
  const feedback = await workbench({
368
394
  ...workbenchOptions,
369
395
  failureMessage: "Could not load Codex Security false-positive feedback",
@@ -432,12 +458,20 @@ export class CodexSecurity {
432
458
  CODEX_HOME: runtime.codexHome,
433
459
  ...runtimePaths,
434
460
  };
461
+ const sdkCodexConfig = { ...preflightConfig };
462
+ delete sdkCodexConfig["projects"];
463
+ const codexPathOverride = environmentValue(this.#dependencies.environment, "CODEX_CLI_PATH")?.trim();
435
464
  const codex = this.#dependencies.createCodex({
465
+ ...(codexPathOverride === undefined ? {} : { codexPathOverride }),
436
466
  ...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
437
467
  env: definedEnvironment(selectedScanEnvironment(environment, "chatgpt")),
438
468
  config: {
469
+ ...sdkCodexConfig,
439
470
  default_permissions: SCAN_PERMISSION_PROFILE,
440
471
  allow_login_shell: false,
472
+ responses_api_metadata: {
473
+ codex_security_surface: this.#surface,
474
+ },
441
475
  },
442
476
  });
443
477
  const thread = codex.startThread({
@@ -479,7 +513,23 @@ export class CodexSecurity {
479
513
  authentication,
480
514
  workbenchValidated: true,
481
515
  model,
482
- onThreadStarted: (threadId) => tracker.start(threadId),
516
+ onThreadStarted: async (threadId) => {
517
+ if (budgetRecovery !== null)
518
+ budgetRecovery.threadId = threadId;
519
+ tracker.start(threadId);
520
+ try {
521
+ await workbench(workbenchOptions, [
522
+ "set-scan-thread",
523
+ "--scan-id",
524
+ scanId,
525
+ "--thread-id",
526
+ threadId,
527
+ ]);
528
+ }
529
+ catch (error) {
530
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, `Could not save scan session: ${safeErrorMessage(error)}`);
531
+ }
532
+ },
483
533
  onFinalize: async (usage) => {
484
534
  const snapshot = await tracker.stop(usage).catch((error) => {
485
535
  if (options.maxCostUsd !== undefined)
@@ -549,19 +599,84 @@ export class CodexSecurity {
549
599
  if (runPostScan !== null) {
550
600
  const followUp = runPostScan;
551
601
  runPostScan = null;
552
- await runScanEvents({
553
- thread,
554
- events: (await followUp()).events,
555
- signal,
556
- scanDir,
557
- pluginRoot: runtime.plugin.installedRoot,
558
- expectation,
559
- model,
560
- onReconnect: options.onReconnect,
561
- onWorkerStatus: options.onWorkerStatus,
562
- onObserverError: options.onObserverError,
563
- });
564
- checkOpen();
602
+ const completedArtifacts = await Promise.all([
603
+ ...new Set([
604
+ "scan-manifest.json",
605
+ "findings.json",
606
+ "coverage.json",
607
+ "report.md",
608
+ ...result.manifest.scan.artifacts.map((artifact) => artifact.path),
609
+ ]),
610
+ ].map(async (name) => ({
611
+ name,
612
+ contents: await readFile(await requireScanFile(scanDir, name, name, signal), { signal }),
613
+ })));
614
+ try {
615
+ await runScanEvents({
616
+ thread,
617
+ events: (await followUp()).events,
618
+ signal,
619
+ scanDir,
620
+ pluginRoot: runtime.plugin.installedRoot,
621
+ expectation,
622
+ model,
623
+ onReconnect: options.onReconnect,
624
+ onWorkerStatus: options.onWorkerStatus,
625
+ onObserverError: options.onObserverError,
626
+ });
627
+ checkOpen();
628
+ }
629
+ catch (error) {
630
+ if (signal.aborted || this.#closed)
631
+ throw error;
632
+ for (const artifact of completedArtifacts) {
633
+ const path = join(scanDir, artifact.name);
634
+ const current = await readFile(path, { signal }).catch((readError) => {
635
+ if (readError.code !== "ENOENT")
636
+ throw readError;
637
+ return null;
638
+ });
639
+ if (current?.equals(artifact.contents))
640
+ continue;
641
+ const temporary = join(dirname(path), `.${randomUUID()}.${basename(path)}.restore`);
642
+ try {
643
+ await writeFile(temporary, artifact.contents, {
644
+ flag: "wx",
645
+ mode: 0o600,
646
+ signal,
647
+ });
648
+ await rename(temporary, path);
649
+ }
650
+ finally {
651
+ await rm(temporary, { force: true });
652
+ }
653
+ }
654
+ await collectResult(result.turnResult, result.threadId, scanDir, runtime.plugin.installedRoot, expectation, signal, true);
655
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, `Could not run post-scan instructions: ${errorMessage(error)}`);
656
+ }
657
+ }
658
+ try {
659
+ const runWorkbench = (args) => workbench(workbenchOptions, args);
660
+ const previousFindings = await listRepositoryFindings(runWorkbench, targetId, "all");
661
+ if (previousFindings !== undefined) {
662
+ await matchCompletedScan({
663
+ scanId,
664
+ repository: repo,
665
+ previousFindings: previousFindings.filter((finding) => finding["scanId"] !== scanId &&
666
+ finding["targetId"] === targetId),
667
+ falsePositives: falsePositiveExamples,
668
+ findings: result.findings.findings,
669
+ workbench: runWorkbench,
670
+ matchFindings: this.#dependencies.matchFindings,
671
+ environment,
672
+ model,
673
+ signal,
674
+ });
675
+ result.repositoryFindings = (await listRepositoryFindings(runWorkbench, targetId));
676
+ }
677
+ }
678
+ catch (error) {
679
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, `Could not update repository findings: ${errorMessage(error)}`);
565
680
  }
566
681
  return result;
567
682
  }
@@ -573,16 +688,63 @@ export class CodexSecurity {
573
688
  const failure = signal.reason instanceof ScanCostLimitExceededError
574
689
  ? signal.reason
575
690
  : error;
691
+ if (failure instanceof ScanCostLimitExceededError &&
692
+ budgetRecovery !== null &&
693
+ budgetRecovery.threadId !== null &&
694
+ activeScan !== null &&
695
+ !this.#abortController.signal.aborted &&
696
+ options.signal?.aborted !== true) {
697
+ try {
698
+ const completion = await workbench({ ...activeScan.options, signal: undefined }, [
699
+ "complete-budget-exhausted-scan",
700
+ "--scan-id",
701
+ activeScan.id,
702
+ "--cost-json",
703
+ JSON.stringify(snapshot?.cost ?? failure.cost),
704
+ "--message",
705
+ failure.message.slice(0, 2400),
706
+ ]);
707
+ activeScan = null;
708
+ runPostScan = null;
709
+ const result = await collectResult({
710
+ status: "completed",
711
+ model: budgetRecovery.model,
712
+ usage: snapshot?.usage ?? null,
713
+ }, budgetRecovery.threadId, scanDir, budgetRecovery.pluginRoot, budgetRecovery.expectation, AbortSignal.any([
714
+ this.#abortController.signal,
715
+ ...(options.signal === undefined ? [] : [options.signal]),
716
+ ]), true);
717
+ if (result.coverage.completeness !== "partial") {
718
+ throw new IncompleteScanError("Budget-exhausted scan recovery did not report partial coverage.");
719
+ }
720
+ const completedScan = completion["scan"];
721
+ const targetWarnings = new Set(Array.isArray(completion["targetWarnings"])
722
+ ? completion["targetWarnings"].filter((warning) => typeof warning === "string")
723
+ : []);
724
+ const warnings = isRecord(completedScan) && Array.isArray(completedScan["warnings"])
725
+ ? completedScan["warnings"].filter((warning) => typeof warning === "string")
726
+ : [];
727
+ for (const warning of warnings.length > 0
728
+ ? warnings
729
+ : [failure.message]) {
730
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, warning, targetWarnings.has(warning)
731
+ ? { kind: "target_changed" }
732
+ : undefined);
733
+ }
734
+ scanFailure = false;
735
+ return result;
736
+ }
737
+ catch { }
738
+ }
576
739
  if (activeScan !== null) {
577
740
  try {
578
741
  await workbench({ ...activeScan.options, signal: undefined }, [
579
742
  "fail-scan",
580
743
  "--scan-id",
581
744
  activeScan.id,
582
- // Redact before truncating: the stored message is read back by
583
- // `scans show` and travels inside the results directory.
745
+ // Scan history can be shared; never persist credential-bearing failures.
584
746
  "--message",
585
- redactedErrorMessage(failure).slice(0, 2400),
747
+ safeErrorMessage(failure).slice(0, 2400),
586
748
  ...(snapshot?.cost
587
749
  ? ["--cost-json", JSON.stringify(snapshot.cost)]
588
750
  : []),
@@ -599,7 +761,7 @@ export class CodexSecurity {
599
761
  }
600
762
  }
601
763
  catch (postScanError) {
602
- notifyObserver("onWarning", options.onWarning, options.onObserverError, `Could not run post-scan instructions: ${redactedErrorMessage(postScanError)}`);
764
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, `Could not run post-scan instructions: ${errorMessage(postScanError)}`);
603
765
  }
604
766
  }
605
767
  if (this.#closed)
@@ -649,43 +811,33 @@ export class CodexSecurity {
649
811
  }
650
812
  }
651
813
  async loginApiKey(apiKey) {
652
- const { result, runtime } = await this.#runOperation(async (preparedRuntime, signal) => ({
653
- runtime: preparedRuntime,
654
- result: await persistApiKey(this.#codexCommand(), preparedRuntime.environment, apiKey, signal),
655
- }), "chatgpt");
656
- if (!result.success) {
657
- throw new CodexSecurityError(`Codex API-key login failed: ${result.stderr.trim() || result.stdout.trim() || "unknown error"}`);
658
- }
659
- if (runtime.persistentCredentialHome === true) {
660
- await setCodexSecurityCredentialLogout(runtime.codexHome, false);
661
- }
662
- runtime.credentialsAvailable = true;
663
- this.#runtimeCredentialSource = "api_key";
814
+ await this.#trackOperation(async () => {
815
+ const authentication = await this.#authentication();
816
+ this.#requireOpen();
817
+ const result = await persistApiKey(this.#codexCommand(), authentication.environment, apiKey, this.#abortController.signal);
818
+ if (!result.success) {
819
+ throw new CodexSecurityError(`Codex API-key login failed: ${result.stderr.trim() || result.stdout.trim() || "unknown error"}`);
820
+ }
821
+ await this.#recordLogin(authentication.codexHome, "api_key");
822
+ this.#requireOpen();
823
+ });
664
824
  }
665
825
  async loginChatGPT() {
666
- const runtime = await this.#ensureRuntime(undefined, undefined, undefined, "chatgpt");
667
- this.#requireOpen();
668
- const handle = this.#trackLoginHandle(new CodexLoginHandle(this.#codexCommand(), ["login"], runtime.environment, () => {
669
- runtime.credentialsAvailable = true;
670
- this.#runtimeCredentialSource = "stored_credentials";
671
- }));
672
- await handle.waitForInstructions();
673
- this.#requireOpen();
674
- return handle;
826
+ return await this.#startLogin(false);
675
827
  }
676
828
  async loginChatGPTDeviceCode() {
677
- const runtime = await this.#ensureRuntime(undefined, undefined, undefined, "chatgpt");
829
+ return await this.#startLogin(true);
830
+ }
831
+ async #startLogin(deviceCode) {
832
+ const authentication = await this.#authentication();
678
833
  this.#requireOpen();
679
- const handle = this.#trackLoginHandle(new CodexLoginHandle(this.#codexCommand(), ["login", "--device-auth"], runtime.environment, () => {
680
- runtime.credentialsAvailable = true;
681
- this.#runtimeCredentialSource = "stored_credentials";
682
- }));
683
- await handle.waitForInstructions({ deviceCode: true });
834
+ const handle = this.#trackLoginHandle(new CodexLoginHandle(this.#codexCommand(), deviceCode ? ["login", "--device-auth"] : ["login"], authentication.environment, () => this.#recordLogin(authentication.codexHome, "stored_credentials")));
835
+ await handle.waitForInstructions({ deviceCode });
684
836
  this.#requireOpen();
685
837
  return handle;
686
838
  }
687
839
  async account() {
688
- return await this.#runOperation(async (runtime, signal) => {
840
+ return await this.#trackOperation(async () => {
689
841
  const apiKey = environmentApiKey(this.#dependencies.environment);
690
842
  if (apiKey !== null) {
691
843
  return {
@@ -693,19 +845,25 @@ export class CodexSecurity {
693
845
  details: "Authenticated with an API key.",
694
846
  };
695
847
  }
696
- return await accountStatus(this.#codexCommand(), runtime.environment, signal);
848
+ const authentication = await this.#authentication();
849
+ this.#requireOpen();
850
+ return await accountStatus(this.#codexCommand(), authentication.environment, this.#abortController.signal);
697
851
  });
698
852
  }
699
853
  async logout() {
700
- const runtime = await this.#runOperation(async (preparedRuntime, signal) => {
701
- await codexLogout(this.#codexCommand(), preparedRuntime.environment, signal);
702
- return preparedRuntime;
703
- }, "chatgpt");
704
- if (runtime.persistentCredentialHome === true) {
705
- await setCodexSecurityCredentialLogout(runtime.codexHome, true);
706
- }
707
- runtime.credentialsAvailable = false;
708
- this.#runtimeCredentialSource = null;
854
+ await this.#trackOperation(async () => {
855
+ const authentication = await this.#authentication();
856
+ this.#requireOpen();
857
+ await codexLogout(this.#codexCommand(), authentication.environment, this.#abortController.signal);
858
+ if (this.#runtime === null ||
859
+ this.#runtime.persistentCredentialHome === true) {
860
+ await setCodexSecurityCredentialLogout(authentication.codexHome, true);
861
+ }
862
+ if (this.#runtime !== null)
863
+ this.#runtime.credentialsAvailable = false;
864
+ this.#runtimeCredentialSource = null;
865
+ this.#requireOpen();
866
+ });
709
867
  }
710
868
  async close() {
711
869
  if (this.#closePromise !== null)
@@ -747,15 +905,27 @@ export class CodexSecurity {
747
905
  async [Symbol.asyncDispose]() {
748
906
  await this.close();
749
907
  }
750
- async #runOperation(operation, auth = "auto") {
751
- return await this.#trackOperation(async () => {
752
- const signal = this.#abortController.signal;
753
- const runtime = await this.#ensureRuntime(signal, undefined, undefined, auth);
754
- this.#requireOpen();
755
- const result = await operation(runtime, signal);
756
- this.#requireOpen();
757
- return result;
758
- });
908
+ async #authentication() {
909
+ this.#requireOpen();
910
+ const environment = selectedScanEnvironment(this.#runtime?.environment ?? this.#dependencies.environment, "chatgpt");
911
+ const codexHome = this.#runtime?.codexHome ??
912
+ (await prepareCodexSecurityCredentialHome(environment));
913
+ return {
914
+ codexHome,
915
+ environment: {
916
+ ...withoutCodexHome(environment),
917
+ CODEX_HOME: codexHome,
918
+ },
919
+ };
920
+ }
921
+ async #recordLogin(codexHome, source) {
922
+ if (this.#runtime === null ||
923
+ this.#runtime.persistentCredentialHome === true) {
924
+ await setCodexSecurityCredentialLogout(codexHome, false);
925
+ }
926
+ if (this.#runtime !== null)
927
+ this.#runtime.credentialsAvailable = true;
928
+ this.#runtimeCredentialSource = source;
759
929
  }
760
930
  async #trackOperation(operation) {
761
931
  this.#requireOpen();
@@ -773,24 +943,12 @@ export class CodexSecurity {
773
943
  }
774
944
  }
775
945
  }
776
- async #ensureRuntime(signal, temporaryRoot, validateLocation, auth = "auto", modelProvider) {
946
+ async #ensureRuntime(signal, temporaryRoot, validateLocation, auth = "auto", requestedConfig) {
777
947
  this.#requireOpen();
778
- if (this.#runtime !== null) {
779
- const usePersistentCredentials = scanAuthentication(this.#dependencies.environment, auth, modelProvider)
780
- .method === "stored_credentials";
781
- if (this.#dependencies.prepareRuntime !== undefined ||
782
- this.#runtime.persistentCredentialHome === undefined ||
783
- this.#runtime.persistentCredentialHome === usePersistentCredentials) {
784
- return this.#runtime;
785
- }
786
- await this.#cleanupRuntime(this.#runtime);
787
- this.#runtime = null;
788
- this.#runtimePromise = null;
789
- this.#runtimeCredentialSource = null;
790
- this.#requireOpen();
791
- }
948
+ if (this.#runtime !== null)
949
+ return this.#runtime;
792
950
  if (this.#runtimePromise === null) {
793
- const runtimePromise = this.#prepareRuntime(signal ?? this.#abortController.signal, temporaryRoot, validateLocation, auth, modelProvider);
951
+ const runtimePromise = this.#prepareRuntime(signal ?? this.#abortController.signal, temporaryRoot, validateLocation, auth, requestedConfig);
794
952
  this.#runtimePromise = runtimePromise;
795
953
  void runtimePromise.catch(() => {
796
954
  if (this.#runtimePromise === runtimePromise) {
@@ -812,17 +970,15 @@ export class CodexSecurity {
812
970
  return handle;
813
971
  }
814
972
  #codexCommand() {
815
- return (this.#dependencies.resolveCodexCommand ?? resolveCodexCommand)();
973
+ return (this.#dependencies.resolveCodexCommand?.() ??
974
+ resolveCodexCommand(this.#dependencies.environment));
816
975
  }
817
- async #refreshPersistentRuntime(runtime, environment, signal) {
976
+ async #refreshPersistentRuntime(runtime, environment, signal, mergedConfig) {
818
977
  throwIfAborted(signal);
819
- const mergedConfig = await mergedCodexConfig(this.config);
820
978
  const config = await preserveCodexSecurityPluginRegistration(runtime.codexHome, scanRuntimeCodexConfig(mergedConfig, codexSecurityStateDirectory(environment), runtime.codexHome));
821
979
  await writeCodexConfig(join(runtime.codexHome, "config.toml"), config);
822
- if (runtime.configPath !== undefined) {
823
- await writeCodexConfig(runtime.configPath, scanPreflightCodexConfig(mergedConfig));
824
- }
825
980
  runtime.plugin = await bootstrapPlugin(runtime.codexHome, runtime.plugin.pluginRoot, {
981
+ codexCommand: this.#codexCommand(),
826
982
  environment: withoutCodexHome(environment),
827
983
  signal,
828
984
  });
@@ -843,6 +999,8 @@ export class CodexSecurity {
843
999
  throwIfAborted(signal);
844
1000
  const mode = options.mode ?? "standard";
845
1001
  validateMode(normalized, mode);
1002
+ await validateCommittedDiffCheckout(repo, normalized, signal);
1003
+ throwIfAborted(signal);
846
1004
  const protectedRoot = (await enclosingGitWorktreeRoot(repo, signal)) ?? repo;
847
1005
  const requestedOutput = await validateOutputDir(options.outputDir, options.archiveExisting);
848
1006
  if (requestedOutput !== null) {
@@ -856,16 +1014,17 @@ export class CodexSecurity {
856
1014
  protectedRoot,
857
1015
  };
858
1016
  }
859
- async #prepareRuntime(signal, temporaryRoot, validateLocation, auth = "auto", modelProvider) {
1017
+ async #prepareRuntime(signal, temporaryRoot, validateLocation, auth = "auto", requestedConfig) {
860
1018
  if (this.#dependencies.prepareRuntime !== undefined) {
861
1019
  return await this.#dependencies.prepareRuntime(this.config, signal);
862
1020
  }
1021
+ const modelProvider = requestedConfig === undefined
1022
+ ? undefined
1023
+ : scanModelProvider(requestedConfig);
863
1024
  const processEnvironment = selectedScanEnvironment(this.#dependencies.environment, auth, modelProvider);
864
- const persistentCredentialHome = scanAuthentication(this.#dependencies.environment, auth, modelProvider)
865
- .method === "stored_credentials";
866
- const codexHome = persistentCredentialHome
867
- ? await prepareCodexSecurityCredentialHome(processEnvironment, validateLocation)
868
- : await createIsolatedHome(temporaryRoot, validateLocation);
1025
+ const codexHome = validateLocation === undefined
1026
+ ? await prepareCodexSecurityCredentialHome(processEnvironment)
1027
+ : await realpath(codexSecurityCredentialHome(processEnvironment));
869
1028
  let bootstrapWorkspace;
870
1029
  try {
871
1030
  throwIfAborted(signal);
@@ -874,13 +1033,13 @@ export class CodexSecurity {
874
1033
  const nodeAmbientHome = join(homedir(), ".codex");
875
1034
  const configuredAmbientHome = environmentValue(processEnvironment, "CODEX_HOME");
876
1035
  const ambientHome = configuredAmbientHome ?? nodeAmbientHome;
877
- const mergedConfig = await mergedCodexConfig(this.config);
878
- const codexConfig = await preserveCodexSecurityPluginRegistration(codexHome, scanRuntimeCodexConfig(mergedConfig, codexSecurityStateDirectory(processEnvironment), persistentCredentialHome ? codexHome : undefined));
1036
+ const mergedConfig = requestedConfig ?? (await mergedCodexConfig(this.config));
1037
+ const codexConfig = await preserveCodexSecurityPluginRegistration(codexHome, scanRuntimeCodexConfig(mergedConfig, codexSecurityStateDirectory(processEnvironment), codexHome));
879
1038
  await writeCodexConfig(join(codexHome, "config.toml"), codexConfig);
880
1039
  const configPath = join(bootstrapWorkspace, "config-preflight.toml");
881
- await writeCodexConfig(configPath, scanPreflightCodexConfig(mergedConfig));
882
1040
  throwIfAborted(signal);
883
1041
  const plugin = await bootstrapPlugin(codexHome, pluginRoot, {
1042
+ codexCommand: this.#codexCommand(),
884
1043
  environment: withoutCodexHome(processEnvironment),
885
1044
  signal,
886
1045
  });
@@ -890,7 +1049,7 @@ export class CodexSecurity {
890
1049
  : await initialCredentialsAvailable(processEnvironment, ambientHome, codexHome);
891
1050
  return {
892
1051
  codexHome,
893
- persistentCredentialHome,
1052
+ persistentCredentialHome: true,
894
1053
  bootstrapWorkspace,
895
1054
  configPath,
896
1055
  plugin,
@@ -904,12 +1063,13 @@ export class CodexSecurity {
904
1063
  };
905
1064
  }
906
1065
  catch (error) {
907
- const cleanupResults = await Promise.allSettled([bootstrapWorkspace, persistentCredentialHome ? undefined : codexHome]
908
- .filter((path) => path !== undefined)
909
- .map((path) => cleanupSdkDirectory(path)));
910
- const cleanupFailures = cleanupResults.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
911
- if (cleanupFailures.length > 0) {
912
- throw new AggregateError([error, ...cleanupFailures], "Codex Security runtime preparation failed and its isolated runtime could not be cleaned up.", { cause: error });
1066
+ if (bootstrapWorkspace !== undefined) {
1067
+ try {
1068
+ await cleanupSdkDirectory(bootstrapWorkspace);
1069
+ }
1070
+ catch (cleanupError) {
1071
+ throw new AggregateError([error, cleanupError], "Codex Security runtime preparation failed and its isolated runtime could not be cleaned up.", { cause: error });
1072
+ }
913
1073
  }
914
1074
  throw error;
915
1075
  }
@@ -919,6 +1079,25 @@ export class CodexSecurity {
919
1079
  throw new CodexSecurityError("CodexSecurity is closed.");
920
1080
  }
921
1081
  }
1082
+ export async function listRepositoryFindings(workbench, targetId, status = "open") {
1083
+ const findings = [];
1084
+ let offset;
1085
+ do {
1086
+ const page = await workbench([
1087
+ "list-global-findings",
1088
+ "--target-id",
1089
+ targetId,
1090
+ ...(status === "open" ? ["--status", "open"] : []),
1091
+ ...(offset === undefined ? [] : ["--offset", String(offset)]),
1092
+ ]);
1093
+ if (!Array.isArray(page["findings"]))
1094
+ return undefined;
1095
+ findings.push(...page["findings"]);
1096
+ offset =
1097
+ typeof page["nextOffset"] === "number" ? page["nextOffset"] : undefined;
1098
+ } while (offset !== undefined);
1099
+ return findings;
1100
+ }
922
1101
  function deepScanOptions(options) {
923
1102
  const selected = {};
924
1103
  for (const [name, , minimum] of DEEP_SCAN_SETTINGS) {
@@ -928,7 +1107,12 @@ function deepScanOptions(options) {
928
1107
  if ((options.mode ?? "standard") !== "deep") {
929
1108
  throw new CodexSecurityError("Deep scan settings require deep mode.");
930
1109
  }
931
- if (!Number.isSafeInteger(value) || value < minimum) {
1110
+ if (name === "maxTimeHours") {
1111
+ if (!Number.isFinite(value) || value <= 0 || value > 96) {
1112
+ throw new CodexSecurityError("Deep scan maxTimeHours must be a positive number no greater than 96.");
1113
+ }
1114
+ }
1115
+ else if (!Number.isSafeInteger(value) || value < minimum) {
932
1116
  throw new CodexSecurityError(`Deep scan ${name} must be ${minimum === 0 ? "a non-negative" : "a positive"} integer.`);
933
1117
  }
934
1118
  selected[name] = value;
@@ -973,6 +1157,12 @@ async function prepareDeepScanConfig(codexHome, environment, options, signal) {
973
1157
  deep_scan: { ...existing, ...overrides },
974
1158
  }), { mode: 0o600, signal });
975
1159
  }
1160
+ export function createSecurity(config = {}) {
1161
+ return createSecurityInternal(config, { surface: "sdk" });
1162
+ }
1163
+ export function createSecurityInternal(config = {}, runtimeOptions) {
1164
+ return new CodexSecurity(config, DEFAULT_DEPENDENCIES, runtimeOptions);
1165
+ }
976
1166
  export async function initialCredentialsAvailable(environment, ambientHome, isolatedHome, importer = importAmbientAuth) {
977
1167
  if (environmentApiKey(environment) !== null)
978
1168
  return false;
@@ -985,7 +1175,7 @@ export async function initialCredentialsAvailable(environment, ambientHome, isol
985
1175
  }
986
1176
  // Reports a cleanup failure without letting it decide the result of the scan. Only the
987
1177
  // message is forwarded, and it reaches the onWarning observer alone: unlike the fail-scan
988
- // path it is never written to the workbench, so it adds no persisted, unredacted text.
1178
+ // path it is never written to the workbench, so it adds no persisted warning text.
989
1179
  function warnCleanupFailed(options, reason) {
990
1180
  // This runs where a throw would replace the scan result, so every step is inside the
991
1181
  // guard: reading the reason, coercing it, and reading the observers off the options can
@@ -1048,7 +1238,7 @@ export async function runScanEvents(options) {
1048
1238
  const startedThreadId = event["thread_id"];
1049
1239
  if (typeof startedThreadId === "string") {
1050
1240
  threadId = startedThreadId;
1051
- options.onThreadStarted?.(startedThreadId);
1241
+ await options.onThreadStarted?.(startedThreadId);
1052
1242
  }
1053
1243
  if (!scanStarted) {
1054
1244
  scanStarted = true;
@@ -1179,23 +1369,17 @@ function trustedAccessWarning(status, authentication) {
1179
1369
  const action = apiOrganization ? "your organization's access" : "your access";
1180
1370
  return `Some cybersecurity requests or findings may be refused because ${access} could not be verified. Check ${action} or apply at ${applicationUrl}.`;
1181
1371
  }
1182
- async function scanPrompt(pluginRoot, target, mode, hasConfigPath = false, hasKnowledgeBase = false, additionalPrompt) {
1183
- const skillName = skillNameFor(target, mode);
1184
- const skillPath = join(pluginRoot, "skills", skillName, "SKILL.md");
1185
- const metadata = await lstat(skillPath).catch(() => null);
1186
- if (metadata === null || !metadata.isFile() || metadata.isSymbolicLink()) {
1187
- throw new IncompleteScanError(`Installed plugin is missing scan skill: ${skillName}`);
1188
- }
1372
+ function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasKnowledgeBase = false, additionalPrompt) {
1189
1373
  return [
1190
1374
  `Use the installed $codex-security:${skillName} skill at "$CODEX_SECURITY_PLUGIN_ROOT/skills/${skillName}/SKILL.md".`,
1191
1375
  "Run this Codex Security scan non-interactively.",
1192
1376
  ...(mode === "deep"
1193
1377
  ? [
1194
- 'The SDK has already registered this scan. Call start_codex_security_deep_scan with { scanId: "$CODEX_SECURITY_SCAN_ID" }; never pass targetPath or create another scan.',
1378
+ `The SDK has already registered this scan. Call start_codex_security_deep_scan with ${JSON.stringify({ scanId })}; never pass targetPath or create another scan.`,
1195
1379
  ]
1196
1380
  : skillName === "security-scan"
1197
1381
  ? [
1198
- 'The SDK has already registered this scan. Use exactly "$CODEX_SECURITY_SCAN_ID" and "$CODEX_SECURITY_SCAN_DIR"; never call a scan-start or completion tool, and leave finalization to the SDK.',
1382
+ `The SDK has already registered this scan. Use exactly ${JSON.stringify(scanId)} and "$CODEX_SECURITY_SCAN_DIR"; never call a scan-start or completion tool, and leave finalization to the SDK.`,
1199
1383
  ]
1200
1384
  : []),
1201
1385
  ...(skillName === "security-scan"
@@ -1211,7 +1395,7 @@ async function scanPrompt(pluginRoot, target, mode, hasConfigPath = false, hasKn
1211
1395
  'Use "$PYTHON" as <python_command> for every plugin helper; replace any literal python or python3 helper invocation with this exact interpreter.',
1212
1396
  'Repository root: "$CODEX_SECURITY_REPOSITORY"',
1213
1397
  'Use this exact scan directory for all scan output: "$CODEX_SECURITY_SCAN_DIR"',
1214
- 'Use exactly "$CODEX_SECURITY_SCAN_ID" as the scan ID in the manifest, findings, and coverage.',
1398
+ `Use exactly ${JSON.stringify(scanId)} as the scan ID in the manifest, findings, and coverage.`,
1215
1399
  'Use exactly "$CODEX_SECURITY_TARGET_ID" as scan.target.targetId; do not derive a different target ID.',
1216
1400
  'Use exactly "$CODEX_SECURITY_TARGET_DISPLAY_NAME" as scan.target.displayName; do not infer a display name from the Git remote.',
1217
1401
  'Use exactly "$CODEX_SECURITY_TARGET_KIND" as scan.target.kind; do not infer the target kind from the checkout.',
@@ -1266,7 +1450,7 @@ function targetInstruction(target) {
1266
1450
  }
1267
1451
  return `Scan target: staged and unstaged working-tree changes against ${target.base}.`;
1268
1452
  }
1269
- function scanRecipe(repository, target, mode, repositoryRevision, pluginVersion, effectiveConfig, failOnSeverity, knowledgeBasePaths, maxCostUsd, deepScan) {
1453
+ function scanRecipe(repository, target, mode, repositoryRevision, pluginVersion, preflightConfig, failOnSeverity, knowledgeBasePaths, maxCostUsd, deepScan) {
1270
1454
  return {
1271
1455
  repository,
1272
1456
  target: {
@@ -1280,7 +1464,7 @@ function scanRecipe(repository, target, mode, repositoryRevision, pluginVersion,
1280
1464
  mode,
1281
1465
  ...(repositoryRevision === null ? {} : { repositoryRevision }),
1282
1466
  pluginVersion,
1283
- config: scanPreflightCodexConfig(effectiveConfig),
1467
+ config: preflightConfig,
1284
1468
  ...(failOnSeverity === undefined ? {} : { failOnSeverity }),
1285
1469
  ...(knowledgeBasePaths === undefined ? {} : { knowledgeBasePaths }),
1286
1470
  ...(maxCostUsd === undefined ? {} : { maxCostUsd }),
@@ -1469,8 +1653,8 @@ function reconnectDetails(message) {
1469
1653
  //
1470
1654
  // Only `error.message` is reused, because that is the single shape the previous
1471
1655
  // code already surfaced. No other shape is forwarded or stringified: this message
1472
- // reaches `fail-scan --message` and is stored in `scans.failure_message` without
1473
- // redaction, so widening what is copied out of the payload would add a new
1656
+ // reaches `fail-scan --message` and is stored unchanged in `scans.failure_message`,
1657
+ // so widening what is copied out of the payload would add a new
1474
1658
  // credential-disclosure path to persistent scan history.
1475
1659
  function turnFailureMessage(error) {
1476
1660
  if (isRecord(error) && typeof error["message"] === "string") {