@openai/codex-security 0.1.25 → 0.1.27

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 (197) hide show
  1. package/README.md +616 -34
  2. package/_bundled_plugin/.app.json +0 -5
  3. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  4. package/_bundled_plugin/.mcp.json +2 -0
  5. package/_bundled_plugin/mcp/helpers.mjs +24 -0
  6. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  7. package/_bundled_plugin/mcp/native/COPYRIGHT-library.html +5556 -0
  8. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +5989 -0
  9. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  10. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  11. package/_bundled_plugin/mcp/native/licenses/Apache-2.0.txt +73 -0
  12. package/_bundled_plugin/mcp/native/licenses/BSD-2-Clause.txt +9 -0
  13. package/_bundled_plugin/mcp/native/licenses/MIT.txt +9 -0
  14. package/_bundled_plugin/mcp/native/licenses/Unicode-3.0.txt +39 -0
  15. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  16. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  17. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  18. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  19. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  20. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  21. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  22. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  23. package/_bundled_plugin/references/config-preflight.md +4 -2
  24. package/_bundled_plugin/references/core-scan.md +1 -1
  25. package/_bundled_plugin/references/final-report.md +5 -3
  26. package/_bundled_plugin/references/scan-artifacts.md +5 -1
  27. package/_bundled_plugin/references/scan-contract.md +42 -38
  28. package/_bundled_plugin/references/security-guidance.md +7 -1
  29. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +27 -1
  30. package/_bundled_plugin/scripts/deep_scan_workbench.py +6 -1
  31. package/_bundled_plugin/scripts/finalize_scan_contract.py +2 -5
  32. package/_bundled_plugin/scripts/generate_in_scope_files.py +2 -2
  33. package/_bundled_plugin/scripts/generate_rank_input.py +8 -1
  34. package/_bundled_plugin/scripts/launch_codex_security_mcp +6 -0
  35. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +43 -9
  36. package/_bundled_plugin/scripts/rank_preview.py +4 -1
  37. package/_bundled_plugin/scripts/report_projection.py +1 -1
  38. package/_bundled_plugin/scripts/workbench_cli.py +7 -0
  39. package/_bundled_plugin/scripts/workbench_db.py +44 -31
  40. package/_bundled_plugin/scripts/workbench_saved_results.py +41 -22
  41. package/_bundled_plugin/scripts/workbench_scan_history.py +117 -2
  42. package/_bundled_plugin/scripts/workbench_scan_usage.py +7 -6
  43. package/_bundled_plugin/scripts/workbench_schema.py +31 -0
  44. package/_bundled_plugin/scripts/workbench_severity.py +119 -0
  45. package/_bundled_plugin/scripts/workbench_validation.py +4 -0
  46. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +5 -3
  47. package/_bundled_plugin/skills/define-security-policy/SKILL.md +3 -3
  48. package/_bundled_plugin/skills/verify-fix/SKILL.md +5 -1
  49. package/dist/api.d.ts +7 -1
  50. package/dist/api.d.ts.map +1 -1
  51. package/dist/api.js +485 -65
  52. package/dist/api.js.map +1 -1
  53. package/dist/auth.js +10 -0
  54. package/dist/auth.js.map +1 -1
  55. package/dist/classify-scan-severity.d.ts +16 -0
  56. package/dist/classify-scan-severity.d.ts.map +1 -0
  57. package/dist/classify-scan-severity.js +96 -0
  58. package/dist/classify-scan-severity.js.map +1 -0
  59. package/dist/classify-severity.d.ts +38 -0
  60. package/dist/classify-severity.d.ts.map +1 -0
  61. package/dist/classify-severity.js +185 -0
  62. package/dist/classify-severity.js.map +1 -0
  63. package/dist/cli.d.ts +23 -4
  64. package/dist/cli.d.ts.map +1 -1
  65. package/dist/cli.js +1277 -357
  66. package/dist/cli.js.map +1 -1
  67. package/dist/cloud-publish.d.ts.map +1 -1
  68. package/dist/cloud-publish.js +2 -207
  69. package/dist/cloud-publish.js.map +1 -1
  70. package/dist/component-plan.d.ts.map +1 -1
  71. package/dist/component-plan.js +116 -32
  72. package/dist/component-plan.js.map +1 -1
  73. package/dist/config.d.ts +1 -0
  74. package/dist/config.d.ts.map +1 -1
  75. package/dist/config.js +17 -2
  76. package/dist/config.js.map +1 -1
  77. package/dist/contract.d.ts +5 -10
  78. package/dist/contract.d.ts.map +1 -1
  79. package/dist/contract.js.map +1 -1
  80. package/dist/cost-model.d.ts +16 -0
  81. package/dist/cost-model.d.ts.map +1 -1
  82. package/dist/cost-model.js +57 -3
  83. package/dist/cost-model.js.map +1 -1
  84. package/dist/cost.d.ts.map +1 -1
  85. package/dist/cost.js +38 -9
  86. package/dist/cost.js.map +1 -1
  87. package/dist/custom-validation-prompt.js +1 -1
  88. package/dist/custom-validation-prompt.js.map +1 -1
  89. package/dist/deduplication/codex-review.d.ts +6 -1
  90. package/dist/deduplication/codex-review.d.ts.map +1 -1
  91. package/dist/deduplication/codex-review.js +72 -17
  92. package/dist/deduplication/codex-review.js.map +1 -1
  93. package/dist/deduplication/deduplication-reviewer.js +1 -1
  94. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  95. package/dist/deduplication/deduplication.d.ts +2 -0
  96. package/dist/deduplication/deduplication.d.ts.map +1 -1
  97. package/dist/deduplication/deduplication.js +99 -26
  98. package/dist/deduplication/deduplication.js.map +1 -1
  99. package/dist/deduplication/retry.d.ts +3 -0
  100. package/dist/deduplication/retry.d.ts.map +1 -0
  101. package/dist/deduplication/retry.js +15 -0
  102. package/dist/deduplication/retry.js.map +1 -0
  103. package/dist/deduplication/scan.d.ts +2 -0
  104. package/dist/deduplication/scan.d.ts.map +1 -1
  105. package/dist/deduplication/scan.js +4 -2
  106. package/dist/deduplication/scan.js.map +1 -1
  107. package/dist/feedback.d.ts +20 -0
  108. package/dist/feedback.d.ts.map +1 -0
  109. package/dist/feedback.js +121 -0
  110. package/dist/feedback.js.map +1 -0
  111. package/dist/finding-catalogue.d.ts +11 -0
  112. package/dist/finding-catalogue.d.ts.map +1 -0
  113. package/dist/finding-catalogue.js +150 -0
  114. package/dist/finding-catalogue.js.map +1 -0
  115. package/dist/findings-client.d.ts +7 -1
  116. package/dist/findings-client.d.ts.map +1 -1
  117. package/dist/findings-client.js +55 -10
  118. package/dist/findings-client.js.map +1 -1
  119. package/dist/findings-import.d.ts +44 -0
  120. package/dist/findings-import.d.ts.map +1 -0
  121. package/dist/findings-import.js +302 -0
  122. package/dist/findings-import.js.map +1 -0
  123. package/dist/import-scan.d.ts +27 -0
  124. package/dist/import-scan.d.ts.map +1 -0
  125. package/dist/import-scan.js +236 -0
  126. package/dist/import-scan.js.map +1 -0
  127. package/dist/index.d.ts +8 -0
  128. package/dist/index.d.ts.map +1 -1
  129. package/dist/index.js +4 -0
  130. package/dist/index.js.map +1 -1
  131. package/dist/knowledge-base.d.ts +1 -1
  132. package/dist/knowledge-base.d.ts.map +1 -1
  133. package/dist/knowledge-base.js +2 -2
  134. package/dist/knowledge-base.js.map +1 -1
  135. package/dist/multiscan.d.ts +2 -0
  136. package/dist/multiscan.d.ts.map +1 -1
  137. package/dist/multiscan.js +144 -52
  138. package/dist/multiscan.js.map +1 -1
  139. package/dist/patch-tui.js +1 -1
  140. package/dist/patch-tui.js.map +1 -1
  141. package/dist/publication-events.d.ts.map +1 -1
  142. package/dist/publication-events.js +7 -2
  143. package/dist/publication-events.js.map +1 -1
  144. package/dist/publication-store.d.ts.map +1 -1
  145. package/dist/publication-store.js +9 -4
  146. package/dist/publication-store.js.map +1 -1
  147. package/dist/publication.d.ts +9 -0
  148. package/dist/publication.d.ts.map +1 -1
  149. package/dist/publication.js +45 -5
  150. package/dist/publication.js.map +1 -1
  151. package/dist/publish.d.ts +4 -2
  152. package/dist/publish.d.ts.map +1 -1
  153. package/dist/publish.js +2 -2
  154. package/dist/publish.js.map +1 -1
  155. package/dist/runtime.d.ts +5 -1
  156. package/dist/runtime.d.ts.map +1 -1
  157. package/dist/runtime.js +8 -2
  158. package/dist/runtime.js.map +1 -1
  159. package/dist/scan-comparison.d.ts +42 -37
  160. package/dist/scan-comparison.d.ts.map +1 -1
  161. package/dist/scan-comparison.js +535 -161
  162. package/dist/scan-comparison.js.map +1 -1
  163. package/dist/scan-dashboard.d.ts.map +1 -1
  164. package/dist/scan-dashboard.js +19 -6
  165. package/dist/scan-dashboard.js.map +1 -1
  166. package/dist/scan-history-renderer.d.ts.map +1 -1
  167. package/dist/scan-history-renderer.js +5 -0
  168. package/dist/scan-history-renderer.js.map +1 -1
  169. package/dist/scan-logs.d.ts +29 -0
  170. package/dist/scan-logs.d.ts.map +1 -1
  171. package/dist/scan-logs.js +36 -5
  172. package/dist/scan-logs.js.map +1 -1
  173. package/dist/security-policy-cli.d.ts +39 -0
  174. package/dist/security-policy-cli.d.ts.map +1 -0
  175. package/dist/security-policy-cli.js +193 -0
  176. package/dist/security-policy-cli.js.map +1 -0
  177. package/dist/security-policy.d.ts +80 -0
  178. package/dist/security-policy.d.ts.map +1 -0
  179. package/dist/security-policy.js +672 -0
  180. package/dist/security-policy.js.map +1 -0
  181. package/dist/severity-store.d.ts +2 -0
  182. package/dist/severity-store.d.ts.map +1 -0
  183. package/dist/severity-store.js +111 -0
  184. package/dist/severity-store.js.map +1 -0
  185. package/dist/targets.d.ts +8 -1
  186. package/dist/targets.d.ts.map +1 -1
  187. package/dist/targets.js +243 -14
  188. package/dist/targets.js.map +1 -1
  189. package/dist/thread-source.d.ts +1 -0
  190. package/dist/thread-source.d.ts.map +1 -1
  191. package/dist/thread-source.js +1 -0
  192. package/dist/thread-source.js.map +1 -1
  193. package/dist/version.d.ts +1 -1
  194. package/dist/version.js +1 -1
  195. package/dist/version.js.map +1 -1
  196. package/package.json +10 -6
  197. package/_bundled_plugin/scripts/resolve_security_md.py +0 -158
package/dist/api.js CHANGED
@@ -7,26 +7,28 @@ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep,
7
7
  import { Codex, } from "@openai/codex-sdk";
8
8
  import { parse as parseToml, stringify as stringifyToml, } from "smol-toml";
9
9
  import { z } from "incur";
10
- import { accountStatus, configuredCodexHome, CodexLoginHandle, loginApiKey as persistApiKey, logout as codexLogout, } from "./auth.js";
10
+ import { CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, accountStatus, configuredCodexHome, CodexLoginHandle, loginApiKey as persistApiKey, logout as codexLogout, } from "./auth.js";
11
11
  import { jsonForPrompt, pluginPythonCommand, shellEnvironmentReference, } from "./codex-prompt.js";
12
- import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, hasCommandAuth, mergedCodexConfig, modelProviderConfigOverride, resolveCommandAuthConfig, scanApprovalPolicy, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
12
+ import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, inlineToml, isExternalModelProvider, hasCommandAuth, mergedCodexConfig, resolveCodexProfile, modelProviderConfigOverride, resolveCommandAuthConfig, scanApprovalPolicy, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
13
13
  import { estimateScanCost, ScanCostTracker, } from "./cost.js";
14
14
  import { DeepScanProgressTracker, } from "./deep-progress.js";
15
+ import { findScanSession } from "./scan-logs.js";
15
16
  import { loadContract, readScanFile, requireScanFile, } from "./contract.js";
16
17
  import { runCustomValidation, writeCustomValidationStatus, } from "./custom-validation.js";
17
18
  import { customDiscoveryPrompt, customValidationConfig, } from "./custom-validation-prompt.js";
18
- import { AuthenticationRequiredError, CodexSecurityError, ConfigurationError, IncompleteScanError, OutputDirectoryError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
19
+ import { AuthenticationRequiredError, CodexSecurityError, ConfigurationError, IncompleteScanError, OutputDirectoryError, OutputDirectoryNotEmptyError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
19
20
  import { prepareKnowledgeBase, } from "./knowledge-base.js";
20
21
  import { FindingWorkflow, workflowDigest } from "./finding-workflow.js";
21
22
  import { ScanResult, } from "./result.js";
23
+ import { formatSecurityPolicyText, inspectSecurityPolicySources, readSecurityPolicySnapshot, requireUnchangedSecurityPolicy, resolveSecurityPolicyGuidance, resolveSecurityPolicyTarget, runSecurityPolicyStages, parseSecurityPolicyStageResult, securityPolicyDiff, securityPolicyProtectedRoots, requireSecurityPolicyRepositoryBinding, securityPolicyStageOutputSchema, } from "./security-policy.js";
22
24
  import { writeMockScanDraft } from "./mock-scan.js";
23
25
  import { scanActivitiesFromEvent } from "./scan-activity.js";
24
26
  import { matchCompletedScan, matchScanFindingsInternal, } from "./scan-comparison.js";
25
27
  import { scanProgressUpdatesFromEvent, workerStatusFromEvent, } from "./worker-progress.js";
26
28
  import { CODEX_SECURITY_THREAD_SOURCES } from "./thread-source.js";
27
29
  import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";
28
- import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, bundledPluginRoot, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, executablePathForSpawn, expandHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, pluginMetadata, planOutputArchive, prepareScanArtifactRestorer, prepareOutputDir, preparePersistentOutputRoot, requireModelSafeOutputDir, requireOutputOutsideRepository, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
29
- import { enclosingGitWorktreeRoot, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateCommittedDiffCheckout, validateMode, } from "./targets.js";
30
+ import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, bundledPluginRoot, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, executablePathForSpawn, expandHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, pluginMetadata, planOutputArchive, prepareScanArtifactRestorer, prepareOutputDir, preparePersistentOutputRoot, requireModelSafeOutputDir, requireOutputOutsideRepositories, requireOutputOutsideRepository, requirePrivatePolicyOutputDirectory, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
31
+ import { enclosingGitWorktreeRoot, enclosingGitWorktreeRoots, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateCommittedDiffCheckout, validateMode, } from "./targets.js";
30
32
  const DEEP_SCAN_CONFIG_PATH_ENVIRONMENT = "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH";
31
33
  const VALIDATION_DISPOSITIONS = [
32
34
  "reportable",
@@ -46,6 +48,7 @@ const DEFAULT_DEPENDENCIES = {
46
48
  environment: process.env,
47
49
  };
48
50
  const SCAN_PERMISSION_PROFILE = "codex_security_scan";
51
+ const POLICY_PERMISSION_PROFILE = "codex_security_policy";
49
52
  const SAFETY_IDENTIFIER_ENV = "CODEX_SAFETY_IDENTIFIER";
50
53
  const PERSONAL_TRUSTED_ACCESS_URL = "https://chatgpt.com/cyber";
51
54
  const ORGANIZATIONAL_TRUSTED_ACCESS_URL = "https://openai.com/form/enterprise-trusted-access-for-cyber/";
@@ -257,7 +260,7 @@ export class CodexSecurity {
257
260
  return await this.#preflightInputs(inputs, options);
258
261
  }
259
262
  async #preflightInputs(inputs, options) {
260
- requireOutputOutsideRepository(inputs.protectedRoot, await realpath(tmpdir()), "temporary");
263
+ requireOutputOutsideRepositories(inputs.protectedRoots, await realpath(tmpdir()), "temporary");
261
264
  if (options.knowledgeBasePaths?.length) {
262
265
  const knowledgeBase = await prepareKnowledgeBase(options.knowledgeBasePaths, options.signal);
263
266
  await knowledgeBase.cleanup();
@@ -288,6 +291,241 @@ export class CodexSecurity {
288
291
  : { maxCostUsd: options.maxCostUsd }),
289
292
  };
290
293
  }
294
+ async preflightPolicy(repository, options = {}) {
295
+ this.#requireOpen();
296
+ const target = await resolveSecurityPolicyTarget(repository, options.path, options.signal);
297
+ const inputs = await this.#validatePolicyInputs(target, options, options.signal).catch(rethrowPolicyOutputError);
298
+ await readSecurityPolicySnapshot(target, options.signal, inputs.gitMetadataPaths);
299
+ const preflight = await this.#preflightInputs(inputs, options);
300
+ return {
301
+ ...target,
302
+ outputDir: preflight.outputDir,
303
+ authentication: preflight.authentication,
304
+ model: preflight.model,
305
+ reasoningEffort: preflight.reasoningEffort,
306
+ ...(options.maxCostUsd === undefined
307
+ ? {}
308
+ : { maxCostUsd: options.maxCostUsd }),
309
+ };
310
+ }
311
+ async generatePolicy(repository, options = {}) {
312
+ return await this.#trackOperation(() => this.#generatePolicy(repository, options)).catch(rethrowPolicyOutputError);
313
+ }
314
+ async previewPolicy(draft, options = {}) {
315
+ return await this.#trackOperation(async () => {
316
+ const signal = AbortSignal.any([
317
+ this.#abortController.signal,
318
+ ...(options.signal === undefined ? [] : [options.signal]),
319
+ ]);
320
+ return formatSecurityPolicyText(await securityPolicyDiff(draft, async () => await (this.#dependencies.resolvePluginPython ?? resolvePluginPython)({
321
+ configuredPath: this.config.pythonPath,
322
+ environment: this.#dependencies.environment,
323
+ protectedRoot: (await enclosingGitWorktreeRoots(draft.repository, signal)).at(-1) ?? draft.repository,
324
+ signal,
325
+ }), signal), true);
326
+ });
327
+ }
328
+ async #generatePolicy(repository, options) {
329
+ const budgetController = new AbortController();
330
+ const signal = AbortSignal.any([
331
+ this.#abortController.signal,
332
+ budgetController.signal,
333
+ ...(options.signal === undefined ? [] : [options.signal]),
334
+ ]);
335
+ let outputDir = "";
336
+ let knowledgeBase = null;
337
+ let accumulatedCost = null;
338
+ let completeCost = true;
339
+ const warn = (message) => notifyObserver("onWarning", options.onWarning, options.onObserverError, message);
340
+ try {
341
+ const target = await resolveSecurityPolicyTarget(repository, options.path, signal);
342
+ const inputs = await this.#validatePolicyInputs(target, options, signal);
343
+ const snapshot = await readSecurityPolicySnapshot(target, signal, inputs.gitMetadataPaths);
344
+ const temporaryRoot = await realpath(tmpdir());
345
+ requireOutputOutsideRepositories(inputs.protectedRoots, temporaryRoot, "temporary");
346
+ const session = await this.#prepareSession(inputs, options, signal, temporaryRoot);
347
+ const { runtime, effectiveConfig } = session;
348
+ const model = scanModelConfiguration(effectiveConfig);
349
+ validateScanCostLimit(options.maxCostUsd, model.model);
350
+ for (const path of [
351
+ "references/threat-model.md",
352
+ "references/security-guidance.md",
353
+ "skills/define-security-policy/SKILL.md",
354
+ "mcp/helpers.mjs",
355
+ ]) {
356
+ const metadata = await lstat(join(runtime.plugin.pluginRoot, path)).catch(() => null);
357
+ if (metadata === null ||
358
+ !metadata.isFile() ||
359
+ metadata.isSymbolicLink()) {
360
+ throw new CodexSecurityError(`Installed plugin is missing policy-generation support: ${path}`);
361
+ }
362
+ }
363
+ const root = inputs.outputDir === null &&
364
+ this.#dependencies.prepareOutputDir === undefined
365
+ ? await preparePersistentOutputRoot(inputs.stateDirectory, "policies", basename(target.repository))
366
+ : temporaryRoot;
367
+ outputDir = await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(inputs.outputDir ?? undefined, `${basename(target.repository)}-policy`, root, (path) => requireOutputOutsideRepositories(inputs.protectedRoots, path));
368
+ requireOutputOutsideRepositories(inputs.protectedRoots, outputDir);
369
+ requireModelSafeOutputDir(outputDir);
370
+ await (this.#dependencies.requirePrivatePolicyOutputDirectory ??
371
+ requirePrivatePolicyOutputDirectory)(outputDir);
372
+ if (options.knowledgeBasePaths?.length) {
373
+ knowledgeBase = await prepareKnowledgeBase(options.knowledgeBasePaths, signal, outputDir);
374
+ }
375
+ notifyObserver("onOutputDirReady", options.onOutputDirReady, options.onObserverError, outputDir);
376
+ const guidance = await resolveSecurityPolicyGuidance(target, runtime.plugin.pluginRoot, session.scanEnvironment, signal, inputs.policyPaths, inputs.gitMetadataPaths);
377
+ await requireUnchangedSecurityPolicy(target, snapshot, signal, inputs.gitMetadataPaths);
378
+ await requireSecurityPolicyRepositoryBinding(target, signal);
379
+ const policyReadRoots = [
380
+ dirname(target.targetPath),
381
+ runtime.plugin.pluginRoot,
382
+ ...(knowledgeBase === null ? [] : [knowledgeBase.path]),
383
+ ].filter((path, index, roots) => roots.indexOf(path) === index);
384
+ const { codex } = this.#createSessionCodex(session, {
385
+ CODEX_SECURITY_REPOSITORY: target.repository,
386
+ CODEX_SECURITY_PLUGIN_ROOT: runtime.plugin.pluginRoot,
387
+ CODEX_SECURITY_STATE_DIR: inputs.stateDirectory,
388
+ CODEX_SECURITY_SURFACE: this.#surface,
389
+ ...(knowledgeBase === null
390
+ ? {}
391
+ : { CODEX_SECURITY_KNOWLEDGE_BASE: knowledgeBase.path }),
392
+ }, options.auth, policyCodexConfig(session.sessionConfig), inputs.gitMetadataPaths.length === 0
393
+ ? []
394
+ : [
395
+ // CLI override keys split on dots, so keep paths inside the TOML value.
396
+ `permissions.${POLICY_PERMISSION_PROFILE}.filesystem=${inlineToml(policyFilesystemPermissions(inputs.gitMetadataPaths))}`,
397
+ ]);
398
+ const reportCost = (current) => {
399
+ const total = addScanCosts(accumulatedCost, current);
400
+ if (completeCost)
401
+ notifyObserver("onCost", options.onCost, options.onObserverError, total);
402
+ if (options.maxCostUsd !== undefined &&
403
+ total.estimatedUsd > options.maxCostUsd) {
404
+ budgetController.abort(new CodexSecurityError(`Security-policy generation exceeded its $${options.maxCostUsd} cost limit; partial output remains at ${outputDir}.`));
405
+ }
406
+ };
407
+ const outputSchema = securityPolicyStageOutputSchema();
408
+ const run = async (stage, prompt) => {
409
+ const thread = codex.startThread({
410
+ workingDirectory: outputDir,
411
+ additionalDirectories: policyReadRoots,
412
+ skipGitRepoCheck: true,
413
+ approvalPolicy: "never",
414
+ networkAccessEnabled: false,
415
+ webSearchMode: "disabled",
416
+ });
417
+ const tracker = new ScanCostTracker({
418
+ codexHome: runtime.codexHome,
419
+ model: model.model,
420
+ repository: target.repository,
421
+ scanDirectory: outputDir,
422
+ maxCostUsd: options.maxCostUsd,
423
+ onCost: options.onCost === undefined && options.maxCostUsd === undefined
424
+ ? undefined
425
+ : reportCost,
426
+ onError: (error) => {
427
+ if (options.maxCostUsd !== undefined)
428
+ budgetController.abort(error);
429
+ else
430
+ warn(`Could not track policy-generation cost: ${safeErrorMessage(error)}`);
431
+ },
432
+ });
433
+ let stopped = false;
434
+ let usage = null;
435
+ try {
436
+ const { events } = await thread.runStreamed(prompt, {
437
+ signal,
438
+ outputSchema,
439
+ });
440
+ const turn = await readCodexTurn({
441
+ thread,
442
+ events,
443
+ onEvent: (event) => {
444
+ if (event.type === "thread.started" &&
445
+ typeof event["thread_id"] === "string") {
446
+ tracker.start(event["thread_id"]);
447
+ }
448
+ },
449
+ onReconnect: (message) => warn(safeErrorMessage(message)),
450
+ });
451
+ usage = turn.usage;
452
+ signal.throwIfAborted();
453
+ if (turn.status !== "completed")
454
+ throw new CodexSecurityError(turn.lastStreamError ??
455
+ `Security-policy ${stage} stage ended before the turn completed.`);
456
+ const snapshot = await tracker.stop(usage).catch((error) => {
457
+ if (options.maxCostUsd !== undefined)
458
+ throw error;
459
+ warn(`Could not track policy-generation cost: ${safeErrorMessage(error)}`);
460
+ const cost = estimateScanCost(model.model, usage);
461
+ if (cost !== null)
462
+ reportCost(cost);
463
+ return { usage, cost };
464
+ });
465
+ stopped = true;
466
+ if (snapshot.cost === null) {
467
+ completeCost = false;
468
+ if (options.maxCostUsd !== undefined)
469
+ throw new CodexSecurityError("Could not verify the requested policy-generation cost limit.");
470
+ }
471
+ else {
472
+ accumulatedCost = addScanCosts(accumulatedCost, snapshot.cost);
473
+ }
474
+ signal.throwIfAborted();
475
+ try {
476
+ return parseSecurityPolicyStageResult(JSON.parse(turn.finalResponse));
477
+ }
478
+ catch (error) {
479
+ throw new CodexSecurityError(`Security-policy ${stage} stage returned an invalid document response.`, { cause: error });
480
+ }
481
+ }
482
+ finally {
483
+ if (!stopped)
484
+ await tracker
485
+ .stop(usage)
486
+ .catch((error) => warn(safeErrorMessage(error)));
487
+ }
488
+ };
489
+ return await runSecurityPolicyStages({
490
+ target,
491
+ snapshot,
492
+ policyPaths: inputs.policyPaths,
493
+ gitMetadataPaths: inputs.gitMetadataPaths,
494
+ outputDir,
495
+ guidance,
496
+ pluginRoot: runtime.plugin.pluginRoot,
497
+ ...(this.config.pluginPath === undefined
498
+ ? {}
499
+ : { pluginPath: resolve(expandHome(this.config.pluginPath)) }),
500
+ ...(knowledgeBase === null
501
+ ? {}
502
+ : { knowledgeBasePath: knowledgeBase.path }),
503
+ revision: await (this.#dependencies.repositoryRevision ?? repositoryRevision)(target.repository, signal),
504
+ ...model,
505
+ pluginVersion: runtime.plugin.version,
506
+ signal,
507
+ onStage: (stage) => notifyObserver("onStage", options.onStage, options.onObserverError, stage),
508
+ answerQuestions: options.answerQuestions,
509
+ run,
510
+ cost: () => (completeCost ? accumulatedCost : null),
511
+ });
512
+ }
513
+ catch (error) {
514
+ if (budgetController.signal.aborted)
515
+ throw budgetController.signal.reason;
516
+ if (signal.aborted)
517
+ throw new CodexSecurityError(`Security-policy generation was interrupted${outputDir ? `; partial output remains at ${outputDir}` : ""}.`, { cause: error });
518
+ throw error;
519
+ }
520
+ finally {
521
+ try {
522
+ await knowledgeBase?.cleanup();
523
+ }
524
+ catch (error) {
525
+ warnCleanupFailed(options, error, "policy generation");
526
+ }
527
+ }
528
+ }
291
529
  async #run(repository, options) {
292
530
  this.#requireOpen();
293
531
  if (options.mock)
@@ -360,10 +598,13 @@ export class CodexSecurity {
360
598
  if (scanOutputRoot !== undefined) {
361
599
  requireOutputOutsideRepository(protectedRoot, scanOutputRoot, scanOutputRoot === temporaryRoot ? "temporary" : "output");
362
600
  }
363
- scanDir = await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(requestedOutput ?? undefined, basename(repo), scanOutputRoot, (path) => requireOutputOutsideRepository(protectedRoot, path), options.archiveExisting, (archiveDir) => {
364
- archivedScanDir = archiveDir;
365
- notifyObserver("onOutputArchived", options.onOutputArchived, options.onObserverError, archiveDir);
366
- });
601
+ scanDir =
602
+ options.resumeScanId !== undefined
603
+ ? requestedOutput
604
+ : await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(requestedOutput ?? undefined, basename(repo), scanOutputRoot, (path) => requireOutputOutsideRepository(protectedRoot, path), options.archiveExisting, (archiveDir) => {
605
+ archivedScanDir = archiveDir;
606
+ notifyObserver("onOutputArchived", options.onOutputArchived, options.onObserverError, archiveDir);
607
+ });
367
608
  requireOutputOutsideRepository(protectedRoot, scanDir);
368
609
  requireModelSafeOutputDir(scanDir);
369
610
  notifyObserver("onOutputDirReady", options.onOutputDirReady, options.onObserverError, scanDir);
@@ -497,6 +738,10 @@ export class CodexSecurity {
497
738
  });
498
739
  costTracker = tracker;
499
740
  const recipe = scanRecipe(repo, normalized, mode, expectation.repositoryRevision, runtime.plugin.version, { ...preflightConfig, approval_policy: approvalPolicy }, options.failureSeverity, knowledgeBase?.sources, options.maxCostUsd, deepScanOptions(options));
741
+ if (options.safetyIdentifier !== undefined)
742
+ recipe["safetyIdentifier"] = options.safetyIdentifier;
743
+ if (options.postScanPrompt !== undefined)
744
+ recipe["postScanPrompt"] = options.postScanPrompt;
500
745
  if (options.validationPrompt !== undefined)
501
746
  recipe["validationMode"] = "custom";
502
747
  const workbenchOptions = {
@@ -509,28 +754,59 @@ export class CodexSecurity {
509
754
  signal,
510
755
  failureMessage: "Could not save the Codex Security scan",
511
756
  };
512
- const registration = await workbench(workbenchOptions, [
513
- "register-cli-scan",
514
- "--repository",
515
- repo,
516
- "--scan-dir",
517
- scanDir,
518
- "--registration-json-stdin",
519
- ...(options.archiveExisting === true ? ["--archive-existing"] : []),
520
- ...(archivedScanDir === null
521
- ? []
522
- : ["--archived-scan-dir", archivedScanDir]),
523
- ...(options.parentScanId === undefined
524
- ? []
525
- : ["--parent-scan-id", options.parentScanId]),
526
- ], JSON.stringify({
527
- recipe,
528
- userContext: options.scanPrompt,
529
- ...(options.workflowId === undefined
530
- ? {}
531
- : { workflowId: options.workflowId }),
532
- }));
757
+ const registration = options.resumeScanId !== undefined
758
+ ? await workbench(workbenchOptions, [
759
+ "get-cli-scan-resume",
760
+ "--scan-id",
761
+ options.resumeScanId,
762
+ ])
763
+ : await workbench(workbenchOptions, [
764
+ "register-cli-scan",
765
+ "--repository",
766
+ repo,
767
+ "--scan-dir",
768
+ scanDir,
769
+ "--registration-json-stdin",
770
+ ...(options.archiveExisting === true
771
+ ? ["--archive-existing"]
772
+ : []),
773
+ ...(archivedScanDir === null
774
+ ? []
775
+ : ["--archived-scan-dir", archivedScanDir]),
776
+ ...(options.parentScanId === undefined
777
+ ? []
778
+ : ["--parent-scan-id", options.parentScanId]),
779
+ ], JSON.stringify({
780
+ recipe,
781
+ userContext: options.scanPrompt,
782
+ ...(options.workflowId === undefined
783
+ ? {}
784
+ : { workflowId: options.workflowId }),
785
+ }));
533
786
  const scanId = registration["scanId"];
787
+ const resumeThreadId = options.resumeScanId === undefined
788
+ ? undefined
789
+ : registration["threadId"];
790
+ if (options.resumeScanId !== undefined) {
791
+ const savedRecipe = registration["recipe"];
792
+ if (scanId !== options.resumeScanId ||
793
+ !isRecord(savedRecipe) ||
794
+ savedRecipe["repository"] !== repo ||
795
+ typeof resumeThreadId !== "string" ||
796
+ !resumeThreadId ||
797
+ JSON.stringify(savedRecipe["target"]) !==
798
+ JSON.stringify(recipe["target"])) {
799
+ throw new CodexSecurityError("The workbench returned mismatched scan resume context.");
800
+ }
801
+ const savedSession = await findScanSession(runtime.codexHome, resumeThreadId);
802
+ if (savedSession === null ||
803
+ savedSession.workingDirectory !== scanDir) {
804
+ throw new CodexSecurityError(`The original Codex session for scan ${scanId} is unavailable. Restore its session logs in the original Codex Security state directory before resuming.`);
805
+ }
806
+ if (typeof registration["sealedProducerVersion"] === "string") {
807
+ expectation.pluginVersion = registration["sealedProducerVersion"];
808
+ }
809
+ }
534
810
  const targetId = registration["targetId"];
535
811
  const contract = registration["contract"];
536
812
  const contractTarget = isRecord(contract)
@@ -606,7 +882,10 @@ export class CodexSecurity {
606
882
  await writeCustomValidationStatus(scanDir, { scanId, status: "pending" }, signal);
607
883
  }
608
884
  checkOpen();
609
- const basePrompt = scanPrompt(normalized, mode, skillName, scanId, runtime.configPath !== undefined, knowledgeBase !== null, options.scanPrompt, options.maxCostUsd !== undefined, discoveryPrompt);
885
+ const basePrompt = scanPrompt(normalized, mode, skillName, scanId, runtime.configPath !== undefined, knowledgeBase !== null, options.resumeScanId !== undefined &&
886
+ typeof registration["userContext"] === "string"
887
+ ? registration["userContext"]
888
+ : options.scanPrompt, options.maxCostUsd !== undefined, discoveryPrompt);
610
889
  checkOpen();
611
890
  const feedback = await workbench({
612
891
  ...workbenchOptions,
@@ -626,7 +905,12 @@ export class CodexSecurity {
626
905
  let prompt = scopeFileCount === null
627
906
  ? basePrompt
628
907
  : `${basePrompt}\nThe SDK's current in-scope file-count estimate is ${scopeFileCount}; use it for scan progress unless exact scoped-source enumeration establishes a different total before review begins.`;
629
- if (falsePositiveExamples.length > 0) {
908
+ if (options.resumeScanId !== undefined) {
909
+ prompt +=
910
+ "\nResume the existing Deep Scan through its coordinator. Preserve completed workers and saved artifacts; do not recreate the scan directory or restart completed analysis. If the coordinator already finished, continue with completion of this same scan.";
911
+ }
912
+ if (falsePositiveExamples.length > 0 &&
913
+ options.resumeScanId === undefined) {
630
914
  const feedbackPath = join(scanDir, "artifacts", "01_context", "false_positive_feedback.json");
631
915
  await mkdir(dirname(feedbackPath), { recursive: true, mode: 0o700 });
632
916
  await writeFile(feedbackPath, `${JSON.stringify(falsePositiveExamples)}\n`, { flag: "wx", mode: 0o600, signal });
@@ -643,7 +927,10 @@ export class CodexSecurity {
643
927
  : null;
644
928
  const runtimePaths = {
645
929
  PYTHON: python,
646
- CODEX_SECURITY_STARTED_AT: new Date().toISOString(),
930
+ CODEX_SECURITY_STARTED_AT: options.resumeScanId !== undefined &&
931
+ typeof registration["startedAt"] === "string"
932
+ ? registration["startedAt"]
933
+ : new Date().toISOString(),
647
934
  CODEX_SECURITY_REPOSITORY: repo,
648
935
  CODEX_SECURITY_SCAN_DIR: scanDir,
649
936
  CODEX_SECURITY_PLUGIN_ROOT: shellPluginRoot,
@@ -675,12 +962,27 @@ export class CodexSecurity {
675
962
  : { CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile }),
676
963
  };
677
964
  const { codex, environment } = this.#createSessionCodex(session, runtimePaths, options.auth);
678
- const thread = codex.startThread({
965
+ const threadOptions = {
679
966
  threadSource: CODEX_SECURITY_THREAD_SOURCES.scan,
680
967
  workingDirectory: scanDir,
681
968
  skipGitRepoCheck: true,
682
969
  approvalPolicy,
683
- });
970
+ };
971
+ let thread;
972
+ if (typeof resumeThreadId === "string") {
973
+ if (codex.resumeThread === undefined) {
974
+ throw new CodexSecurityError("The configured Codex client does not support resuming sessions.");
975
+ }
976
+ thread = codex.resumeThread(resumeThreadId, threadOptions);
977
+ tracker.start(resumeThreadId);
978
+ if (budgetRecovery !== null)
979
+ budgetRecovery.threadId = resumeThreadId;
980
+ await tracker.refresh().catch(reportTrackingError);
981
+ checkOpen();
982
+ }
983
+ else {
984
+ thread = codex.startThread(threadOptions);
985
+ }
684
986
  const serializedPaths = normalized.kind === "paths" ? jsonForPrompt(normalized.paths) : null;
685
987
  checkOpen();
686
988
  if (serializedPaths !== null && targetPathsFile !== null) {
@@ -711,6 +1013,12 @@ export class CodexSecurity {
711
1013
  workbenchValidated: true,
712
1014
  model,
713
1015
  onThreadStarted: async (threadId) => {
1016
+ if (resumeThreadId !== undefined) {
1017
+ if (threadId !== resumeThreadId) {
1018
+ throw new CodexSecurityError("Codex did not resume the original scan session.");
1019
+ }
1020
+ return;
1021
+ }
714
1022
  if (budgetRecovery !== null)
715
1023
  budgetRecovery.threadId = threadId;
716
1024
  tracker.start(threadId);
@@ -928,11 +1236,10 @@ export class CodexSecurity {
928
1236
  falsePositives: falsePositiveExamples,
929
1237
  findings: result.findings.findings,
930
1238
  workbench: runWorkbench,
931
- matchFindings: this.#dependencies.matchFindings ??
932
- ((input, comparisonOptions) => matchScanFindingsInternal(input, comparisonOptions, {
933
- surface: this.#surface,
934
- allowBatching: false,
935
- })),
1239
+ matchFindings: (input, comparisonOptions) => (this.#dependencies.matchFindings ?? matchScanFindingsInternal)(input, comparisonOptions, {
1240
+ surface: this.#surface,
1241
+ singleTurn: options.maxCostUsd !== undefined,
1242
+ }),
936
1243
  environment,
937
1244
  model,
938
1245
  signal,
@@ -1006,7 +1313,9 @@ export class CodexSecurity {
1006
1313
  }
1007
1314
  catch { }
1008
1315
  }
1009
- if (activeScan !== null) {
1316
+ // A failed attachment must not turn a resumable coordinator into a terminal failure.
1317
+ // Deep Scan orchestration persists its own terminal failures and cancellations.
1318
+ if (activeScan !== null && options.resumeScanId === undefined) {
1010
1319
  if (options.validationPrompt !== undefined &&
1011
1320
  !customValidationComplete) {
1012
1321
  await writeCustomValidationStatus(scanDir, {
@@ -1220,7 +1529,7 @@ export class CodexSecurity {
1220
1529
  }
1221
1530
  }
1222
1531
  }
1223
- #createSessionCodex(session, runtimePaths, auth = "auto") {
1532
+ #createSessionCodex(session, runtimePaths, auth = "auto", config, configOverrides = []) {
1224
1533
  const { runtime, python, modelProvider, externalProvider, apiKey, sessionConfig, } = session;
1225
1534
  const commandAuth = hasCommandAuth(sessionConfig);
1226
1535
  const environment = {
@@ -1240,7 +1549,7 @@ export class CodexSecurity {
1240
1549
  if (session.safetyIdentifier !== undefined) {
1241
1550
  environment[SAFETY_IDENTIFIER_ENV] = session.safetyIdentifier;
1242
1551
  }
1243
- const sdkCodexConfig = { ...sessionConfig };
1552
+ const sdkCodexConfig = { ...(config ?? sessionConfig) };
1244
1553
  // Projects and permissions already live in generated TOML files; the SDK
1245
1554
  // cannot safely encode their path and selector keys as dotted overrides.
1246
1555
  delete sdkCodexConfig["projects"];
@@ -1264,8 +1573,15 @@ export class CodexSecurity {
1264
1573
  ? {}
1265
1574
  : { codexPathOverride: executablePathForSpawn(codexPathOverride) }),
1266
1575
  ...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
1267
- ...(commandAuth
1268
- ? { configOverrides: modelProviderConfigOverride(sessionConfig) }
1576
+ ...(commandAuth || configOverrides.length > 0
1577
+ ? {
1578
+ configOverrides: [
1579
+ ...(commandAuth
1580
+ ? modelProviderConfigOverride(sessionConfig)
1581
+ : []),
1582
+ ...configOverrides,
1583
+ ],
1584
+ }
1269
1585
  : {}),
1270
1586
  env: sdkEnvironment,
1271
1587
  config: {
@@ -1278,7 +1594,7 @@ export class CodexSecurity {
1278
1594
  });
1279
1595
  return { codex, environment };
1280
1596
  }
1281
- async #prepareSession({ protectedRoot }, options, signal, temporaryRoot, keepCredentialLock = false) {
1597
+ async #prepareSession({ protectedRoot, protectedRoots = [protectedRoot], }, options, signal, temporaryRoot, keepCredentialLock = false) {
1282
1598
  let releaseCredentialHome = null;
1283
1599
  const checkOpen = () => {
1284
1600
  this.#requireOpen();
@@ -1302,11 +1618,11 @@ export class CodexSecurity {
1302
1618
  ? withoutOpenAiApiKeys(this.#dependencies.environment)
1303
1619
  : this.#dependencies.environment, options.auth, modelProvider);
1304
1620
  if (this.#dependencies.prepareRuntime === undefined) {
1305
- const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"));
1621
+ const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) => requireOutputOutsideRepositories(protectedRoots, path, "runtime"));
1306
1622
  releaseCredentialHome = await acquireCodexSecurityCredentialHomeLock(credentialHome, signal);
1307
1623
  }
1308
1624
  const previousRuntime = this.#runtime;
1309
- const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"), options.auth, requestedConfig);
1625
+ const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepositories(protectedRoots, path, "runtime"), options.auth, requestedConfig);
1310
1626
  if (runtime === previousRuntime &&
1311
1627
  this.#dependencies.prepareRuntime === undefined) {
1312
1628
  await this.#refreshPersistentRuntime(runtime, scanEnvironment, signal, requestedConfig);
@@ -1318,7 +1634,7 @@ export class CodexSecurity {
1318
1634
  await writeCodexConfig(runtime.configPath, preflightConfig);
1319
1635
  }
1320
1636
  const runtimeHome = await realpath(runtime.codexHome);
1321
- requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");
1637
+ requireOutputOutsideRepositories(protectedRoots, runtimeHome, "runtime");
1322
1638
  const sessionConfig = scanRuntimeCodexConfig(effectiveConfig, runtimeHome);
1323
1639
  if (options.expectedPluginVersion !== undefined &&
1324
1640
  runtime.plugin.version !== options.expectedPluginVersion) {
@@ -1353,9 +1669,7 @@ export class CodexSecurity {
1353
1669
  apiKey === null &&
1354
1670
  !commandAuth &&
1355
1671
  authentication.method !== "aws_credentials") {
1356
- throw new AuthenticationRequiredError("No credentials were found. Run 'codex-security login', use " +
1357
- "'codex-security login --device-auth' on a remote or headless machine, or set " +
1358
- "OPENAI_API_KEY or CODEX_API_KEY for CI.");
1672
+ throw new AuthenticationRequiredError(NO_CREDENTIALS_MESSAGE);
1359
1673
  }
1360
1674
  if (!commandAuth)
1361
1675
  authentication = await runtimeScanAuthentication(this.#dependencies.environment, runtime.codexHome, options.auth, modelProvider);
@@ -1446,6 +1760,29 @@ export class CodexSecurity {
1446
1760
  : undefined;
1447
1761
  runtime.effectiveConfig = mergedConfig;
1448
1762
  }
1763
+ async #validatePolicyInputs(target, options, signal) {
1764
+ policyCodexConfig(await mergedCodexConfig(this.config));
1765
+ const sources = await inspectSecurityPolicySources(target, signal);
1766
+ const protectedRoots = [
1767
+ ...new Set([
1768
+ ...(await securityPolicyProtectedRoots(target, signal)),
1769
+ ...sources.gitMetadataPaths,
1770
+ ]),
1771
+ ];
1772
+ const inputs = await this.#validateLocalInputs(target.repository, {
1773
+ auth: options.auth,
1774
+ target: target.scope === "." ? "repository" : [dirname(target.targetPath)],
1775
+ outputDir: options.outputDir,
1776
+ maxCostUsd: options.maxCostUsd,
1777
+ }, signal, protectedRoots);
1778
+ return {
1779
+ ...inputs,
1780
+ policyPaths: sources.policyPaths,
1781
+ gitMetadataPaths: [
1782
+ ...new Set([...protectedRoots.slice(1), ...sources.gitMetadataPaths]),
1783
+ ],
1784
+ };
1785
+ }
1449
1786
  async #runMock(repository, options) {
1450
1787
  const signal = AbortSignal.any([
1451
1788
  this.#abortController.signal,
@@ -1598,7 +1935,16 @@ export class CodexSecurity {
1598
1935
  await cleanupSdkDirectory(workspace);
1599
1936
  }
1600
1937
  }
1601
- async #validateLocalInputs(repository, options, signal) {
1938
+ async #validateLocalInputs(repository, options, signal, protectedRoots) {
1939
+ if (options.resumeScanId !== undefined &&
1940
+ (options.mode !== "deep" ||
1941
+ !options.outputDir ||
1942
+ options.archiveExisting ||
1943
+ options.parentScanId !== undefined ||
1944
+ options.workflowId !== undefined ||
1945
+ options.mock)) {
1946
+ throw new CodexSecurityError("Resume requires the original Deep Scan output directory without archive, rerun, or workflow options.");
1947
+ }
1602
1948
  if (options.mock &&
1603
1949
  (options.mode === "deep" ||
1604
1950
  options.validationPrompt !== undefined ||
@@ -1637,10 +1983,13 @@ export class CodexSecurity {
1637
1983
  }
1638
1984
  await validateCommittedDiffCheckout(repo, normalized, signal);
1639
1985
  throwIfAborted(signal);
1640
- const protectedRoot = (await enclosingGitWorktreeRoot(repo, signal)) ?? repo;
1641
- const requestedOutput = await validateOutputDir(options.outputDir, options.archiveExisting);
1986
+ const protectedRoot = protectedRoots?.[0] ??
1987
+ (await enclosingGitWorktreeRoot(repo, signal)) ??
1988
+ repo;
1989
+ protectedRoots ??= [protectedRoot];
1990
+ const requestedOutput = await validateOutputDir(options.outputDir, options.resumeScanId !== undefined || options.archiveExisting);
1642
1991
  if (requestedOutput !== null) {
1643
- requireOutputOutsideRepository(protectedRoot, requestedOutput);
1992
+ requireOutputOutsideRepositories(protectedRoots, requestedOutput);
1644
1993
  }
1645
1994
  const stateDirectory = codexSecurityStateDirectory(this.#dependencies.environment);
1646
1995
  let canonicalStateDirectory = stateDirectory;
@@ -1658,13 +2007,14 @@ export class CodexSecurity {
1658
2007
  canonicalStateDirectory = parent;
1659
2008
  }
1660
2009
  }
1661
- requireOutputOutsideRepository(protectedRoot, canonicalStateDirectory);
2010
+ requireOutputOutsideRepositories(protectedRoots, canonicalStateDirectory);
1662
2011
  return {
1663
2012
  repository: repo,
1664
2013
  target: normalized,
1665
2014
  mode,
1666
2015
  outputDir: requestedOutput,
1667
2016
  protectedRoot,
2017
+ protectedRoots,
1668
2018
  stateDirectory,
1669
2019
  };
1670
2020
  }
@@ -2096,7 +2446,7 @@ function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasK
2096
2446
  "This exhaustive scan authorizes the delegated-worker phases required by the selected skill; use available subagent tools and continue with parent-agent fallback if capacity changes.",
2097
2447
  ]),
2098
2448
  "This SDK host does not render MCP Apps; use the terminal/chat workflow.",
2099
- `Use ${python} as <python_command> for every plugin helper; replace any literal python or python3 helper invocation with this exact interpreter.`,
2449
+ `Use ${python} as <python_command> for plugin Python helper scripts (.py files); replace any literal python or python3 helper invocation with this exact interpreter.`,
2100
2450
  `Repository root: ${shellEnvironmentReference("CODEX_SECURITY_REPOSITORY")}`,
2101
2451
  `Use this exact scan directory for all scan output: ${shellEnvironmentReference("CODEX_SECURITY_SCAN_DIR")}`,
2102
2452
  `Use exactly ${JSON.stringify(scanId)} as the scan ID in the manifest, findings, and coverage.`,
@@ -2197,6 +2547,18 @@ function validateScanCostLimit(maxCostUsd, model) {
2197
2547
  throw new CodexSecurityError(`A scan cost limit is not available for the configured model: ${model}.`);
2198
2548
  }
2199
2549
  }
2550
+ function addScanCosts(previous, current) {
2551
+ if (previous === null)
2552
+ return { ...current };
2553
+ return {
2554
+ model: current.model,
2555
+ inputTokens: previous.inputTokens + current.inputTokens,
2556
+ cachedInputTokens: previous.cachedInputTokens + current.cachedInputTokens,
2557
+ cacheWriteInputTokens: previous.cacheWriteInputTokens + current.cacheWriteInputTokens,
2558
+ outputTokens: previous.outputTokens + current.outputTokens,
2559
+ estimatedUsd: previous.estimatedUsd + current.estimatedUsd,
2560
+ };
2561
+ }
2200
2562
  async function collectResult(turnResult, threadId, scanDir, pluginRoot, expectation, signal, workbenchValidated = false) {
2201
2563
  const required = [
2202
2564
  "scan-manifest.json",
@@ -2291,7 +2653,8 @@ export function formatEnvironmentVariableRemovalGuidance(names) {
2291
2653
  }
2292
2654
  return `remove ${names.slice(0, -1).join(", ")}, and ${names[names.length - 1]} from the environment`;
2293
2655
  }
2294
- async function runtimeScanAuthentication(environment, codexHome, auth = "auto", modelProvider) {
2656
+ /** @internal */
2657
+ export async function runtimeScanAuthentication(environment, codexHome, auth = "auto", modelProvider) {
2295
2658
  const authentication = scanAuthentication(environment, auth, modelProvider);
2296
2659
  if (authentication.method !== "stored_credentials")
2297
2660
  return authentication;
@@ -2453,7 +2816,62 @@ export function scanRuntimeCodexConfig(config, protectedCredentialHome) {
2453
2816
  : { [protectedCredentialHome]: "read" }),
2454
2817
  },
2455
2818
  },
2819
+ [POLICY_PERMISSION_PROFILE]: {
2820
+ filesystem: policyFilesystemPermissions(),
2821
+ network: { enabled: false },
2822
+ },
2823
+ },
2824
+ };
2825
+ }
2826
+ function policyFilesystemPermissions(gitMetadataPaths = []) {
2827
+ return {
2828
+ ":minimal": "read",
2829
+ ":workspace_roots": "read",
2830
+ // A scoped "." keeps native permission paths literal, including glob characters.
2831
+ ...Object.fromEntries(gitMetadataPaths.map((path) => [path, { ".": "deny" }])),
2832
+ };
2833
+ }
2834
+ function rethrowPolicyOutputError(error) {
2835
+ if (error instanceof OutputDirectoryNotEmptyError)
2836
+ throw new OutputDirectoryNotEmptyError(error.directory, "policy");
2837
+ throw error;
2838
+ }
2839
+ function requirePolicyConfigKeys(config) {
2840
+ const tables = [config];
2841
+ if (isRecord(config["features"]))
2842
+ tables.push(config["features"]);
2843
+ // The Codex SDK flattens these keys without quoting their components.
2844
+ if (tables.some((table) => Object.keys(table).some((key) => !/^[A-Za-z0-9_-]+$/u.test(key))))
2845
+ throw new ConfigurationError("Policy generation does not accept dotted or quoted Codex override keys. Use nested objects instead.");
2846
+ }
2847
+ function policyCodexConfig(config) {
2848
+ const resolved = resolveCodexProfile(config);
2849
+ requirePolicyConfigKeys(resolved);
2850
+ // The selected provider is already written as TOML. The SDK cannot quote
2851
+ // provider names when it flattens this table into command-line overrides.
2852
+ delete resolved["model_providers"];
2853
+ const features = isRecord(resolved["features"]) ? resolved["features"] : {};
2854
+ return {
2855
+ ...resolved,
2856
+ approval_policy: "never",
2857
+ default_permissions: POLICY_PERMISSION_PROFILE,
2858
+ // The artifact directory may be inside an unrelated checkout.
2859
+ project_doc_max_bytes: 0,
2860
+ project_root_markers: [],
2861
+ allow_login_shell: false,
2862
+ shell_environment_policy: {
2863
+ inherit: "core",
2864
+ ignore_default_excludes: false,
2456
2865
  },
2866
+ features: {
2867
+ ...features,
2868
+ plugins: false,
2869
+ apps: false,
2870
+ shell_snapshot: false,
2871
+ },
2872
+ mcp_servers: {},
2873
+ web_search: "disabled",
2874
+ sandbox_workspace_write: { network_access: false },
2457
2875
  };
2458
2876
  }
2459
2877
  function sharedCredentialCodexConfig(config, credentialHome) {
@@ -2461,11 +2879,7 @@ function sharedCredentialCodexConfig(config, credentialHome) {
2461
2879
  approval_policy: scanApprovalPolicy(config),
2462
2880
  features: { plugins: true },
2463
2881
  };
2464
- for (const key of [
2465
- "cli_auth_credentials_store",
2466
- "forced_login_method",
2467
- "forced_chatgpt_workspace_id",
2468
- ]) {
2882
+ for (const key of CODEX_AUTH_CONFIG_KEYS) {
2469
2883
  if (Object.hasOwn(config, key))
2470
2884
  shared[key] = structuredClone(config[key]);
2471
2885
  }
@@ -2525,6 +2939,7 @@ export function scanPreflightCodexConfig(config) {
2525
2939
  for (const key of [
2526
2940
  "model",
2527
2941
  "model_reasoning_effort",
2942
+ "model_reasoning_summary",
2528
2943
  "model_provider",
2529
2944
  "service_tier",
2530
2945
  ]) {
@@ -2555,6 +2970,11 @@ export function scanPreflightCodexConfig(config) {
2555
2970
  return result;
2556
2971
  };
2557
2972
  const result = executionConfig(config);
2973
+ // Keep the effective summary even when preflight filters the profile name.
2974
+ const reasoningSummary = resolveCodexProfile(config)["model_reasoning_summary"];
2975
+ if (safeString(reasoningSummary)) {
2976
+ result["model_reasoning_summary"] = reasoningSummary;
2977
+ }
2558
2978
  const selectedProfile = safeProfileName(config["profile"])
2559
2979
  ? config["profile"]
2560
2980
  : undefined;