OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(telemetry): preserve request attribution across CLI, SDK, and Deep Scan (#1424)
mldangelo-oaifb41bcb18f97
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.tsindex abcde7f96..c6a061161 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts@@ -485,11 +485,18 @@ async function workerRuntimeSettings(? profiles[config.profile]: undefined;const selected = { ...config, ...(isRecord(profile) ? profile : {}) };+ for (const key of ["analytics", "responses_api_metadata"]) {+ if (isRecord(config[key]) && isRecord(profile) && isRecord(profile[key])) {+ selected[key] = { ...config[key], ...profile[key] };+ }+ }const inherited = Object.fromEntries(- ["model_reasoning_summary", "service_tier"].map((key) => [- key,- selected[key],- ]),+ [+ "model_reasoning_summary",+ "service_tier",+ "analytics",+ "responses_api_metadata",+ ].map((key) => [key, selected[key]]),);const settings: CodexSdkWorkerRuntimeSettings = { config: inherited };const workerConfigPath = environmentVariable(diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.tsindex af59fb837..829575ad2 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts@@ -1361,8 +1361,9 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,string,Record<string, unknown>>;+ const noWorkerSnapshot = index === 0 && configuration !== "";const endpoint =- index === 1+ index === 1 || noWorkerSnapshot? undefined: `https://synthetic-user:synthetic-password@worker-${index}.example.test/v1?token=synthetic-${index}-token`;const serviceTier =@@ -1380,6 +1381,47 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,: "elevated";const webSearch =index === 0 ? undefined : ["disabled", "cached", "live"][index % 3];+ // Cover missing settings, native config inheritance, and snapshot overrides.+ const mergeProfileTelemetry = index === 0 && configuration !== "";+ const telemetry =+ index === 0 && configuration === ""+ ? {}+ : {+ analytics: { enabled: index % 2 === 0 },+ responses_api_metadata: {+ codex_security_surface: index % 2 === 0 ? "cli" : "sdk",+ codex_security_command: "scan",+ codex_security_package_version: `0.2.${index}`,+ codex_security_plugin_version: `0.1.${index}`,+ custom_tag: `synthetic-scan-${index}`,+ ...(mergeProfileTelemetry+ ? {+ root_only: "native-root",+ profile_only: "selected-profile",+ }+ : {}),+ },+ };+ const overrideTelemetry = index === 1 || index === 2;+ const inheritedTelemetry =+ overrideTelemetry || index === 4+ ? {+ analytics: { enabled: index % 2 !== 0 },+ responses_api_metadata: { custom_tag: "preflight-default" },+ }+ : mergeProfileTelemetry+ ? {+ analytics: { enabled: true },+ responses_api_metadata: {+ codex_security_surface: "cli",+ codex_security_command: "scan",+ codex_security_package_version: "0.2.0",+ codex_security_plugin_version: "0.1.0",+ custom_tag: "preflight-default",+ root_only: "native-root",+ },+ }+ : telemetry;const features =index === 0? undefined@@ -1438,6 +1480,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,},path: entryPath,deepPath,+ workerConfigPath: noWorkerSnapshot ? undefined : deepPath,nativeProfile,profilePath,parentSandbox,@@ -1472,12 +1515,18 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,windowsSandbox,webSearch,features,+ telemetry,+ workerTelemetry: overrideTelemetry ? telemetry : {},configuration: {...parsedConfiguration,+ ...inheritedTelemetry,...(index === 0? {}: { service_tier: index === 2 ? "flex" : serviceTier }),- ...(index === 2 || index === 3+ ...(index === 2 ||+ index === 3 ||+ index === 4 ||+ mergeProfileTelemetry? {profile: "selected",profiles: {@@ -1485,6 +1534,16 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,selected: {...profiles.selected,...(index === 2 ? { service_tier: serviceTier } : {}),+ ...(index === 4 ? telemetry : {}),+ ...(mergeProfileTelemetry+ ? {+ analytics: {},+ responses_api_metadata: {+ custom_tag: "synthetic-scan-0",+ profile_only: "selected-profile",+ },+ }+ : {}),},unselected: { service_tier: "fast" },},@@ -1510,6 +1569,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,entry.deepPath,stringifyToml({worker_runtime: {+ ...entry.workerTelemetry,...(entry.endpoint === undefined? {}: { openai_base_url: entry.endpoint }),@@ -1619,8 +1679,10 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,fixture.root,`cache-${index} `,);- process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH =- workerConfigurations[index].deepPath;+ restoreEnv(+ "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",+ workerConfigurations[index].workerConfigPath,+ );return executor.run(workerRequest(promptPath, fixture.root, {kind,@@ -1679,7 +1741,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,);assert.equal(workerLaunch.environment!.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,- workerConfigurations[index].deepPath,+ workerConfigurations[index].workerConfigPath,);assert.deepEqual(JSON.parse(@@ -1730,6 +1792,22 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,web_search: workerConfigurations[index].webSearch,"windows.sandbox": workerConfigurations[index].windowsSandbox,});+ assert.deepEqual(+ JSON.parse(+ JSON.stringify(+ parseToml(+ nativeConfigOverrides(invocation.argv)+ .filter((override) =>+ /^(analytics|responses_api_metadata)[.=]/.test(+ override,+ ),+ )+ .join("\n"),+ ),+ ),+ ),+ workerConfigurations[index].telemetry,+ );assert.equal(invocation.cacheDirectory,path.join(fixture.root, `cache-${index} `),@@ -1825,7 +1903,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,assert.equal(process.env.PYTHON, python);assert.equal(invocation.deepConfigPath,- workerConfigurations[index].deepPath,+ workerConfigurations[index].workerConfigPath,);const workerFeatures = parseToml(invocation.argv@@ -1945,11 +2023,11 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,Promise.all([writeFile(entry.path,- 'model_reasoning_summary = "detailed"\nservice_tier = "changed"\nmodel_provider = "changed"\n',+ 'model_reasoning_summary = "detailed"\nservice_tier = "changed"\nmodel_provider = "changed"\n[analytics]\nenabled = false\n[responses_api_metadata]\ncustom_tag = "changed"\n',),writeFile(entry.deepPath,- '[worker_runtime.features]\nshell_tool = true\nunified_exec = true\nview_image = true\n[worker_runtime]\nopenai_base_url = "https://changed-snapshot.example.test/v1"\nweb_search = "live"\nmodel_provider = "changed"\nnative_profile = "changed"\nmodel_instructions_file = "changed-instructions.md"\nmodel_verbosity = "changed"\nmodel_context_window = 999000\nmodel_auto_compact_token_limit = 888000\n[worker_runtime.windows]\nsandbox = "changed"\n[worker_runtime.environment]\nSYNTHETIC_GATEWAY_KEY = "changed"\nSYNTHETIC_HEADER_VALUE = "changed"\n',+ '[worker_runtime.features]\nshell_tool = true\nunified_exec = true\nview_image = true\n[worker_runtime]\nopenai_base_url = "https://changed-snapshot.example.test/v1"\nweb_search = "live"\nmodel_provider = "changed"\nnative_profile = "changed"\nmodel_instructions_file = "changed-instructions.md"\nmodel_verbosity = "changed"\nmodel_context_window = 999000\nmodel_auto_compact_token_limit = 888000\n[worker_runtime.windows]\nsandbox = "changed"\n[worker_runtime.environment]\nSYNTHETIC_GATEWAY_KEY = "changed"\nSYNTHETIC_HEADER_VALUE = "changed"\n[worker_runtime.analytics]\nenabled = false\n[worker_runtime.responses_api_metadata]\ncustom_tag = "changed"\n',),]),),diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex 9508ca53b..085800fec 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -555,11 +555,21 @@ account authentication. Explicit `--auth chatgpt` selects stored account auth,omits the provider key, and clears any configured experimental bearer token forthat command. Model, effort, and provider choices carry into patch-risk assessment.+Model requests include Codex Security attribution in `responses_api_metadata`:+`codex_security_surface` (`cli` or `sdk`), `codex_security_command`,+`codex_security_package_version`, and `codex_security_plugin_version` when the+selected plugin declares a version. These fields identify the workflow and+versions producing a model request; they do not record command starts,+completions, or failures.+Disable Codex usage analytics and built-in metrics with-`--codex 'analytics.enabled=false'`. The setting carries into `scan --patch`-and patch-risk assessment. It does not control configured OpenTelemetry exporters,-integrations, authentication, or CLI update checks. Validation uses isolated-configuration; patching and verification preserve ambient project trust.+`--codex 'analytics.enabled=false'`. The setting carries into `scan --patch`,+patch-risk assessment, and Deep Scan discovery and reducer workers, including+resumed workers. Deep Scan workers also preserve the scan's request metadata.+Model-request attribution metadata remains attached when analytics are disabled.+The setting does not control configured OpenTelemetry exporters, integrations,+authentication, or CLI update checks. Validation uses isolated configuration;+patching and verification preserve ambient project trust.For filesystem and approval behavior, see the[local security model](../README.md#local-security-model).diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjsindex 6cd8748e5..00d3affc2 100644--- a/sdk/typescript/scripts/check-package.mjs+++ b/sdk/typescript/scripts/check-package.mjs@@ -198,6 +198,7 @@ const allowedFiles = new Set(["publish","result","record",+ "request-metadata","runtime","scan-activity","scan-comparison",diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 6d192d602..ca543f194 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -178,6 +178,7 @@ import {type ScanWorkerStatus,} from "./worker-progress.js";import { CODEX_SECURITY_THREAD_SOURCES } from "./thread-source.js";+import { codexSecurityRequestMetadata } from "./request-metadata.js";import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";import { bundledCodexSdkEnvironment } from "./codex-sdk-environment.js";import {@@ -719,6 +720,7 @@ export class CodexSecurity {};const { codex } = await this.#createSessionCodex(session,+ "validate",{CODEX_SECURITY_REPOSITORY: inputs.repository,CODEX_SECURITY_PLUGIN_ROOT: runtime.plugin.pluginRoot,@@ -1018,6 +1020,7 @@ export class CodexSecurity {].filter((path, index, roots) => roots.indexOf(path) === index);const { codex } = await this.#createSessionCodex(session,+ "policy",{CODEX_SECURITY_REPOSITORY: target.repository,CODEX_SECURITY_PLUGIN_ROOT: runtime.plugin.pluginRoot,@@ -1404,6 +1407,16 @@ export class CodexSecurity {);const workerSnapshot: JsonObject = {...workerRuntimeConfig,+ responses_api_metadata: {+ ...(isRecord(workerRuntimeConfig["responses_api_metadata"])+ ? workerRuntimeConfig["responses_api_metadata"]+ : {}),+ ...codexSecurityRequestMetadata(+ this.#surface,+ "scan",+ runtime.plugin.version,+ ),+ },...(workerEnvironment === undefined? {}: { environment: workerEnvironment }),@@ -1936,6 +1949,7 @@ export class CodexSecurity {};const { codex, environment } = await this.#createSessionCodex(session,+ "scan",runtimePaths,options.auth,git,@@ -2708,6 +2722,7 @@ export class CodexSecurity {async #createSessionCodex(session: PreparedSession,+ command: string,runtimePaths: Record<string, string>,auth: ScanAuthMode = "auto",git?: InspectedExecutable,@@ -2811,7 +2826,11 @@ export class CodexSecurity {...(sdkCodexConfig as NonNullable<CodexOptions["config"]>),responses_api_metadata: {...configuredResponsesMetadata,- codex_security_surface: this.#surface,+ ...codexSecurityRequestMetadata(+ this.#surface,+ command,+ runtime.plugin.version,+ ),},},});@@ -4931,6 +4950,8 @@ function selectedWorkerRuntimeConfig(return {...Object.fromEntries([+ "analytics",+ "responses_api_metadata","openai_base_url","features","model_auto_compact_token_limit",diff --git a/sdk/typescript/src/classify-severity.ts b/sdk/typescript/src/classify-severity.tsindex 85b49dbb7..571eb5a15 100644--- a/sdk/typescript/src/classify-severity.ts+++ b/sdk/typescript/src/classify-severity.ts@@ -193,6 +193,7 @@ export async function classifySeverityInternal(options,{surface,+ command: "classify-severity",threadSource: CODEX_SECURITY_THREAD_SOURCES.severityClassification,},);diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 90909c50a..057682919 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -200,6 +200,7 @@ import {prepareCodexSecurityCredentialHome,resolveCodexCommand,resolvePluginPython,+ pluginMetadata,runWorkbench,sameFile,setCodexSecurityCredentialLogout,@@ -216,6 +217,7 @@ import {type ScanMatchingBatch,} from "./scan-comparison.js";import { scanActivitiesFromEvent } from "./scan-activity.js";+import { codexSecurityRequestMetadata } from "./request-metadata.js";import {CODEX_SECURITY_THREAD_SOURCES,type CodexSecurityThreadSource,@@ -4148,6 +4150,7 @@ export async function main({environment: dependencies.environment,currentDirectory: dependencies.currentDirectory,+ surface: "cli",...(defaultWorkbench? {}: { runWorkbench: dependencies.runWorkbench }),@@ -4359,6 +4362,7 @@ export async function main(}}const result = await runComponentScans({+ surface: "cli",repository,outputDir: settings.outputDir,...(options.auto ? { auto: true } : { components }),@@ -7603,6 +7607,10 @@ async function runSkill(contents.push(contentsOrLiteral);}const plugin = await bundledPluginRoot();+ const pluginVersion = await pluginMetadata(plugin).then(+ (metadata) => metadata.version,+ () => undefined,+ );const verify = skill === "verify-fix";const assess = skill === "assess-patch-risk";const inputLabel = skill === "validation" || verify ? "Findings" : "Issues";@@ -7704,8 +7712,22 @@ async function runSkill(...(verify || assess? ["--config", 'approvals_reviewer="auto_review"']: []),- "--config",- 'responses_api_metadata.codex_security_surface="cli"',+ ...Object.entries(+ codexSecurityRequestMetadata(+ "cli",+ assess+ ? "assess-patch-risk"+ : verify+ ? "verify-fix"+ : patch+ ? "patch"+ : "validate",+ pluginVersion,+ ),+ ).flatMap(([key, value]) => [+ "--config",+ `responses_api_metadata.${key}=${JSON.stringify(value)}`,+ ]),...(options.safetyIdentifier === undefined? []: [diff --git a/sdk/typescript/src/component-plan.ts b/sdk/typescript/src/component-plan.tsindex e908cfc0b..7108e0a78 100644--- a/sdk/typescript/src/component-plan.ts+++ b/sdk/typescript/src/component-plan.ts@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";import { join, posix } from "node:path";import { promisify } from "node:util";import { z } from "incur";-import type { ScanAuthMode } from "./api.js";+import type { CodexSecuritySurface, ScanAuthMode } from "./api.js";import type { CodexSecurityConfig } from "./config.js";import {runReadOnlyCodex,@@ -42,6 +42,8 @@ export interface ComponentPlan {}export interface ComponentPlanningOptions {+ /** @internal Calling surface, inherited from the component scan. */+ surface?: CodexSecuritySurface;/** @internal Authentication already selected by the calling scan. */auth?: ScanAuthMode;/** @internal Cyber access program already selected by the calling scan. */@@ -83,7 +85,8 @@ export async function planComponents(z.toJSONSchema(componentPlanSchema, { target: "openapi-3.0" }),{ ...options, config: options.config ?? {}, workingDirectory: tmpdir() },{- surface: "cli",+ surface: options.surface ?? "sdk",+ command: "scan-components",threadSource: CODEX_SECURITY_THREAD_SOURCES.scan,},);diff --git a/sdk/typescript/src/component-scan.ts b/sdk/typescript/src/component-scan.tsindex ad83457be..4760530ce 100644--- a/sdk/typescript/src/component-scan.ts+++ b/sdk/typescript/src/component-scan.ts@@ -5,6 +5,7 @@ import {CodexSecurity,scanAuthentication,selectedScanEnvironment,+ type CodexSecuritySurface,type ScanOptions,} from "./api.js";import {@@ -28,13 +29,15 @@ import type { ScanActivity } from "./scan-activity.js";import type { ScanSettings } from "./scan-settings.js";import type { ScanProgress, ScanWorkerStatus } from "./worker-progress.js";import {- matchScanFindings,+ matchScanFindingsInternal,type ScanComparisonResult,} from "./scan-comparison.js";import { prepareOutputDir, requireOutputOutsideRepository } from "./runtime.js";import { enclosingGitWorktreeRoot, normalizeRepository } from "./targets.js";export interface ComponentScanOptions {+ /** @internal Calling surface, inherited by planning, scans, and matching. */+ surface?: CodexSecuritySurface;repository: string;outputDir: string;components?: ComponentPlan["components"];@@ -53,7 +56,7 @@ export interface ComponentScanOptions {) => Promise<ComponentPlan>;environment?: NodeJS.ProcessEnv;/** @internal */- matchFindings?: typeof matchScanFindings;+ matchFindings?: typeof matchScanFindingsInternal;onPlan?: (components: ComponentReceipt[]) => void;onScanEvent?: (event: ComponentScanEvent) => void;onComplete?: (result: ComponentScanResult) => void;@@ -154,6 +157,7 @@ export async function runComponentScans(options.auto? await (options.planComponents ?? planComponents)(repository, {auth,+ surface: options.surface ?? "sdk",cyberAccessProgram: options.scanOptions?.cyberAccessProgram,config: options.config,environment,@@ -187,7 +191,11 @@ export async function runComponentScans(const settled = await Promise.allSettled(Array.from({ length: Math.min(workers, receipts.length) }, async () => {const security = (- options.createSecurity ?? ((config) => new CodexSecurity(config))+ options.createSecurity ??+ ((config) =>+ new CodexSecurity(config, undefined, {+ surface: options.surface ?? "sdk",+ })))(options.config ?? {});try {while (!options.signal?.aborted) {@@ -367,7 +375,9 @@ async function deduplicateFindings(if (remaining.length) notify(() => options.onDeduplicationStarted?.());for (const component of remaining) {const current = componentFindings(component);- const comparison = await (options.matchFindings ?? matchScanFindings)(+ const comparison = await (+ options.matchFindings ?? matchScanFindingsInternal+ )({ before: [...previous], after: current },{allowHistoricalUncertainty: true,@@ -378,6 +388,7 @@ async function deduplicateFindings(signal: options.signal,workingDirectory: tmpdir(),},+ { surface: options.surface ?? "sdk" },);matching.matches.push(...comparison.matches);matching.uncertain.push(...comparison.uncertain);diff --git a/sdk/typescript/src/deduplication/codex-review.ts b/sdk/typescript/src/deduplication/codex-review.tsindex eebf65c72..739040fc5 100644--- a/sdk/typescript/src/deduplication/codex-review.ts+++ b/sdk/typescript/src/deduplication/codex-review.ts@@ -24,6 +24,8 @@ import {} from "../runtime.js";import { CODEX_SECURITY_THREAD_SOURCES } from "../thread-source.js";import { VERSION } from "../version.js";+import type { CodexSecuritySurface } from "../api.js";+import { codexSecurityRequestMetadata } from "../request-metadata.js";import {DeduplicationReviewError,type DeduplicationReviewFailureCategory,@@ -164,6 +166,7 @@ export class CodexReviewRunner {random?: () => number;} = {},private readonly onDiagnostic?: DeduplicationDiagnosticObserver,+ private readonly surface: CodexSecuritySurface = "sdk",) {}async run<T>(review: CodexReview<T>): Promise<T> {@@ -380,7 +383,11 @@ export class CodexReviewRunner {update_plan: { enabled: false },experimental_request_user_input: { enabled: false },},- responses_api_metadata: { codex_security_surface: "sdk" },+ responses_api_metadata: {+ ...(executionConfig["responses_api_metadata"] as+ Record<string, string> | undefined),+ ...codexSecurityRequestMetadata(this.surface, "dedupe"),+ },features: {code_mode: {direct_only_tool_namespaces: ["review_validator"],diff --git a/sdk/typescript/src/deduplication/scan.ts b/sdk/typescript/src/deduplication/scan.tsindex e9cfce115..5c784228d 100644--- a/sdk/typescript/src/deduplication/scan.ts+++ b/sdk/typescript/src/deduplication/scan.ts@@ -1,4 +1,5 @@import { loadContractWithScanDirectory } from "../contract.js";+import type { CodexSecuritySurface } from "../api.js";import { environmentEntry } from "../auth.js";import {bundledPluginRoot,@@ -96,6 +97,7 @@ export async function deduplicateScanDirectory(}type DeduplicateScanDependencies = Partial<SavedScanDependencies> & {+ surface?: CodexSecuritySurface;environment?: NodeJS.ProcessEnv;reviewer?: DeduplicationReviewer;reviewRunner?: Pick<CodexReviewRunner, "run">;@@ -306,6 +308,7 @@ async function deduplicateResolvedScan(repositoryPath,undefined,options.onDiagnostic,+ dependencies.surface ?? "sdk",);const privateStatePaths: string[] = [];if (workflow && !dependencies.reviewer) {diff --git a/sdk/typescript/src/request-metadata.ts b/sdk/typescript/src/request-metadata.tsnew file mode 100644index 000000000..0460d51ef--- /dev/null+++ b/sdk/typescript/src/request-metadata.ts@@ -0,0 +1,18 @@+import type { CodexSecuritySurface } from "./api.js";+import { VERSION } from "./version.js";++/** Attribution for model requests, independent of native analytics events. */+export function codexSecurityRequestMetadata(+ surface: CodexSecuritySurface,+ command: string,+ pluginVersion?: string,+) {+ return {+ codex_security_surface: surface,+ codex_security_command: command,+ codex_security_package_version: VERSION,+ ...(pluginVersion === undefined+ ? {}+ : { codex_security_plugin_version: pluginVersion }),+ };+}diff --git a/sdk/typescript/src/scan-comparison.ts b/sdk/typescript/src/scan-comparison.tsindex 0826b4ab4..5c0b559a4 100644--- a/sdk/typescript/src/scan-comparison.ts+++ b/sdk/typescript/src/scan-comparison.ts@@ -23,6 +23,7 @@ import {DEFAULT_CODEX_CONFIG,deepMerge,hasCommandAuth,+ inlineToml,mergedCodexConfig,normalizeLegacyWindowsSandboxOverride,resolveCodexProfile,@@ -35,6 +36,7 @@ import {type JsonObject,} from "./config.js";import { CodexSecurityError, ConfigurationError } from "./errors.js";+import { codexSecurityRequestMetadata } from "./request-metadata.js";import {createProfileCodex,createProviderProfile,@@ -316,6 +318,7 @@ export async function matchScanFindingsInternal(}const { thread, cleanup } = await startReadOnlyCodexThread(options, {...runtimeOptions,+ command: "compare",threadSource: CODEX_SECURITY_THREAD_SOURCES.scanComparison,});const remainingPages = new Set(pages.keys());@@ -589,6 +592,16 @@ async function startReadOnlyCodexThread();}const sdkConfig = structuredCodexConfig(config);+ const requestMetadata = {+ ...(homeExecutionConfig["responses_api_metadata"] as+ JsonObject | undefined),+ ...(sdkConfig["responses_api_metadata"] as JsonObject | undefined),+ ...codexSecurityRequestMetadata(+ runtimeOptions.surface,+ runtimeOptions.command,+ ),+ };+ delete sdkConfig["responses_api_metadata"];delete sdkConfig["default_permissions"];const providerSettings = commandAuth ? providerConfig : (config ?? {});const effectiveFeatures = resolveCodexProfile(@@ -603,6 +616,8 @@ async function startReadOnlyCodexThread();const command = resolveCodexCommand(environment);const codexOptions: CodexOptions = {+ // A single table preserves literal keys that the SDK would split on dots.+ configOverrides: [`responses_api_metadata=${inlineToml(requestMetadata)}`],codexPathOverride: executablePathForSpawn(command.command),env: environment,// The SDK forwards its apiKey option as CODEX_API_KEY for Codex exec.@@ -621,9 +636,6 @@ async function startReadOnlyCodexThread(),allow_login_shell: false,project_doc_max_bytes: 0,- responses_api_metadata: {- codex_security_surface: runtimeOptions.surface,- },features: {api_key_cyber_access_programs:effectiveFeatures?.["api_key_cyber_access_programs"],@@ -701,6 +713,7 @@ export async function runReadOnlyCodex(options: ReadOnlyCodexOptions,runtimeOptions: {surface: CodexSecuritySurface;+ command: string;threadSource: ReadOnlyCodexThreadSource;},): Promise<string> {diff --git a/sdk/typescript/src/suggest-owners.ts b/sdk/typescript/src/suggest-owners.tsindex d686f5783..226de28be 100644--- a/sdk/typescript/src/suggest-owners.ts+++ b/sdk/typescript/src/suggest-owners.ts@@ -144,6 +144,7 @@ export async function suggestOwnersInternal(},{surface,+ command: "suggest-owners",threadSource: CODEX_SECURITY_THREAD_SOURCES.suggestOwners,},);diff --git a/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts b/sdk/typescript/tests-ts/api-attribution-concurrency.test.tsindex 6420836f5..dfbce95a2 100644--- a/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts+++ b/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts@@ -10,6 +10,7 @@ import { parse as parseToml } from "smol-toml";import { PLUGIN_ROOT } from "./plugin-root.js";import { createApiTestFixtures } from "./support/temporary-directories.js";import { InternalSecurity } from "./support/internal-security.js";+import { VERSION } from "../src/version.js";const fixtures = createApiTestFixtures();@@ -84,6 +85,13 @@ describe("delegated scan attribution", () => {{pluginPath: PLUGIN_ROOT,codexOverrides: {+ analytics: { enabled: surface === "sdk" },+ responses_api_metadata: {+ custom_attribution: surface,+ codex_security_surface: "spoofed",+ codex_security_command: "spoofed",+ codex_security_package_version: "spoofed",+ },...(rootEndpoint === undefined? {}: { openai_base_url: rootEndpoint }),@@ -178,10 +186,29 @@ describe("delegated scan attribution", () => {);expect(options.config).toMatchObject({features,+ analytics: { enabled: surface === "sdk" },responses_api_metadata: {+ custom_attribution: surface,codex_security_surface: surface,+ codex_security_command: "scan",+ codex_security_package_version: VERSION,},});+ const deepConfigPath =+ options.env?.["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"];+ const deepConfig =+ mode === "deep"+ ? await readFile(deepConfigPath!, "utf8")+ : undefined;+ if (deepConfig !== undefined) {+ expect(+ parseToml(deepConfig)["worker_runtime"],+ ).toMatchObject({+ analytics: { enabled: surface === "sdk" },+ responses_api_metadata:+ options.config?.["responses_api_metadata"],+ });+ }expect(threadOptions.threadSource).toBe("security_scan");const configPath =options.env?.["CODEX_SECURITY_CONFIG_PATH"];@@ -236,6 +263,7 @@ describe("delegated scan attribution", () => {"responses_api_metadata",);expect(sharedConfig).not.toHaveProperty("codex_security");+ expect(sharedConfig).not.toHaveProperty("analytics");expect(JSON.stringify(sharedConfig)).not.toContain("openai_base_url",);@@ -258,6 +286,11 @@ describe("delegated scan attribution", () => {initialConfig,);expect(options.env).toEqual(initialEnvironment);+ if (deepConfig !== undefined) {+ expect(await readFile(deepConfigPath!, "utf8")).toBe(+ deepConfig,+ );+ }throw new Error("delegated attribution observed");} finally {active -= 1;diff --git a/sdk/typescript/tests-ts/api-policy.test.ts b/sdk/typescript/tests-ts/api-policy.test.tsindex 741492e84..1c7902e1d 100644--- a/sdk/typescript/tests-ts/api-policy.test.ts+++ b/sdk/typescript/tests-ts/api-policy.test.ts@@ -1215,7 +1215,7 @@ describe("CodexSecurity policy API", () => {sandbox_workspace_write: { network_access: false },});expect(f.configuration()?.config?.["responses_api_metadata"]).toMatchObject(- { codex_security_surface: "cli" },+ { codex_security_surface: "cli", codex_security_command: "policy" },);expect(f.configuration()?.env?.["CODEX_SECURITY_REPOSITORY"]).toBe(f.repository,diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 192d83500..1c4e3b67d 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -90,6 +90,7 @@ import { writeSession as writeUsageSession } from "./support/usage-rollout.js";import { importScan } from "../src/import-scan.js";import { FindingWorkflow } from "../src/finding-workflow.js";import { DEFAULT_DEEP_SCAN_SETTINGS } from "../src/deep-scan-defaults.js";+import { VERSION } from "../src/version.js";import { createProviderProfile } from "../src/provider-profile.js";import { pythonExecutable, nodeCommand, gitText } from "./support/shell.js";import { fail, rejecting, throwing } from "./support/errors.js";@@ -542,7 +543,13 @@ describe("CodexSecurity finding validation", () => {model_reasoning_effort: "high",features: { plugins: false },analytics: { enabled: false },- responses_api_metadata: { codex_security_surface: "sdk" },+ responses_api_metadata: {+ codex_security_surface: "sdk",+ codex_security_command: "validate",+ codex_security_package_version: VERSION,+ codex_security_plugin_version:+ preparedRuntime("unused").plugin.version,+ },},});expect(captured.codex?.env?.["OPENAI_API_KEY"]).toBeUndefined();@@ -1830,10 +1837,14 @@ describe("CodexSecurity orchestration", () => {[{profile: "cloud",+ analytics: { enabled: true },+ responses_api_metadata: { custom_attribution: "root" },model_context_window: 64_000,model_auto_compact_token_limit: 48_000,profiles: {cloud: {+ analytics: { enabled: false },+ responses_api_metadata: { custom_attribution: "selected" },model_reasoning_summary: "concise",service_tier: "fast",model_context_window: 96_000,@@ -1936,6 +1947,17 @@ describe("CodexSecurity orchestration", () => {const workerConfig = parseToml(await readFile(deepConfigPath, "utf8"),)["worker_runtime"] as JsonObject;+ const selected = resolveCodexProfile(overrides);+ expect(workerConfig["analytics"]).toEqual(+ selected["analytics"],+ );+ expect(workerConfig["responses_api_metadata"]).toMatchObject({+ ...(selected["responses_api_metadata"] as+ JsonObject | undefined),+ codex_security_surface: "sdk",+ codex_security_command: "scan",+ codex_security_package_version: VERSION,+ });const windows = (resolveCodexProfile(overrides)["windows"] ??DEFAULT_CODEX_CONFIG["windows"]) as { sandbox: string };expect(workerConfig["windows"] as JsonObject).toEqual(diff --git a/sdk/typescript/tests-ts/cli-dedupe.test.ts b/sdk/typescript/tests-ts/cli-dedupe.test.tsindex 8b7531a64..ade687cb9 100644--- a/sdk/typescript/tests-ts/cli-dedupe.test.ts+++ b/sdk/typescript/tests-ts/cli-dedupe.test.ts@@ -212,6 +212,7 @@ test.each([false, true])(signal: expect.any(AbortSignal),});expect(dependencies?.runWorkbench).toBe(deps.runWorkbench);+ expect(dependencies?.surface).toBe("cli");return result;};expect(@@ -305,9 +306,10 @@ test("dedupe requires a scan selector and reports SDK failures", async () => {test("dedupe defaults to local storage without a findings URL", async () => {const deps = dependencies();- deps.deduplicateScan = async (scanId, options) => {+ deps.deduplicateScan = async (scanId, options, dependencies) => {expect(scanId).toBe("latest");expect(options.findingsUrl).toBeUndefined();+ expect(dependencies?.surface).toBe("cli");return {scanId,uniqueFindingIds: [],diff --git a/sdk/typescript/tests-ts/cli-patch.test.ts b/sdk/typescript/tests-ts/cli-patch.test.tsindex 0213628bb..f6e686379 100644--- a/sdk/typescript/tests-ts/cli-patch.test.ts+++ b/sdk/typescript/tests-ts/cli-patch.test.ts@@ -1361,6 +1361,9 @@ describe("scan and patch workflow", () => {) {expect(output.command).toBe("patch");expect(output.appServer?.sandbox).toBe("read-only");+ expect(args).toContain(+ 'responses_api_metadata.codex_security_command="assess-patch-risk"',+ );expect(output.appServer?.prompt).toContain("<!-- codex-security:patch-risk-summary:start -->",);diff --git a/sdk/typescript/tests-ts/cli-skills.test.ts b/sdk/typescript/tests-ts/cli-skills.test.tsindex 3b7664cff..ad7562c64 100644--- a/sdk/typescript/tests-ts/cli-skills.test.ts+++ b/sdk/typescript/tests-ts/cli-skills.test.ts@@ -12,6 +12,9 @@ import {skillCommandFailure,} from "../src/cli.js";import type { LinearClientFactory } from "../src/linear.js";+import { pluginMetadata } from "../src/runtime.js";+import { VERSION } from "../src/version.js";+import { PLUGIN_ROOT } from "./plugin-root.js";import { capture, dependencies, type OnCodex } from "./cli-fixtures.js";import { runTestInSubprocess } from "./support/test-subprocess.js";import { temporaryDirectory } from "./support/temporary-directories.js";@@ -103,6 +106,12 @@ describe("CLI skill commands", () => {'approval_policy="never"',"--config",'responses_api_metadata.codex_security_surface="cli"',+ "--config",+ `responses_api_metadata.codex_security_command=${JSON.stringify(command)}`,+ "--config",+ `responses_api_metadata.codex_security_package_version=${JSON.stringify(VERSION)}`,+ "--config",+ `responses_api_metadata.codex_security_plugin_version=${JSON.stringify((await pluginMetadata(PLUGIN_ROOT)).version)}`,...(command === "patch"? []: [diff --git a/sdk/typescript/tests-ts/cli-verify-fix.test.ts b/sdk/typescript/tests-ts/cli-verify-fix.test.tsindex 59b81bcbc..96696e3a0 100644--- a/sdk/typescript/tests-ts/cli-verify-fix.test.ts+++ b/sdk/typescript/tests-ts/cli-verify-fix.test.ts@@ -3,6 +3,7 @@ import { readFile } from "node:fs/promises";import { join } from "node:path";import { stripVTControlCharacters } from "node:util";import { main } from "../src/cli.js";+import { VERSION } from "../src/version.js";import type { Finding, JsonObject } from "../src/index.js";import type { LinearClientFactory } from "../src/linear.js";import { dependencies, fakeResult } from "./cli-fixtures.js";@@ -48,6 +49,12 @@ describe("read-only finding verification", () => {},linearClient,onCodex: (args, output, processEnvironment, input) => {+ expect(args).toContain(+ 'responses_api_metadata.codex_security_command="verify-fix"',+ );+ expect(args).toContain(+ `responses_api_metadata.codex_security_package_version=${JSON.stringify(VERSION)}`,+ );expect(args[0]).toBe("app-server");expect(input).toBeUndefined();expect(args).toContain('approval_policy="on-request"');diff --git a/sdk/typescript/tests-ts/codex-review.test.ts b/sdk/typescript/tests-ts/codex-review.test.tsindex 8a32ddb50..c0ad53fd5 100644--- a/sdk/typescript/tests-ts/codex-review.test.ts+++ b/sdk/typescript/tests-ts/codex-review.test.ts@@ -21,6 +21,8 @@ import { runTestInSubprocess } from "./support/test-subprocess.js";import { retryDelay, waitForRetry } from "../src/deduplication/retry.js";import { isReviewRefusal } from "../src/deduplication/refusal.js";import { temporaryDirectory } from "./support/temporary-directories.js";+import type { CodexSecuritySurface } from "../src/api.js";+import { VERSION } from "../src/version.js";import { workflowFixture } from "./support/workflow-fixture.js";import { readCodexHomeConfig } from "../src/auth.js";import {@@ -283,7 +285,13 @@ const transportCases: {commandAuth?: "direct" | "ambient";windowsConfig?: JsonObject;expectedWindowsSandbox?: string;+ surface?: CodexSecuritySurface;}[] = [+ {+ scenario: "recover-server-error",+ name: "CLI attribution survives a retried review session",+ surface: "cli",+ },{scenario: "correction",name: "command auth without an API key",@@ -351,6 +359,7 @@ for (const {commandAuth,windowsConfig,expectedWindowsSandbox,+ surface,} of transportCases) {const runCase = test.skipIf(windowsOnly && process.platform !== "win32");runCase(`Codex review transport: ${name}`, async () => {@@ -375,6 +384,11 @@ for (const {};const configuration = stringify({mcp_servers: { synthetic: { command: "synthetic-unused-command" } },+ responses_api_metadata: {+ synthetic_caller: "preserved",+ codex_security_surface: "previous",+ codex_security_command: "previous",+ },...windowsConfig,...(commandAuth? {@@ -463,6 +477,8 @@ for (const {}},},+ undefined,+ surface,);const validate = mock((value: unknown) => {if (@@ -651,7 +667,10 @@ for (const {if (scenario !== "cancel") {const messages = parseJsonLines<{method?: string;- params?: { apiKey?: string };+ params?: {+ apiKey?: string;+ config?: { responses_api_metadata?: Record<string, string> };+ };}>(await readFile(transcript, "utf8"));const loginRequest = messages.find((message) => message.method === "account/login/start",@@ -659,6 +678,16 @@ for (const {expect(messages.filter((message) => message.method === "thread/start"),).toHaveLength(sessions);+ for (const message of messages.filter(+ (message) => message.method === "thread/start",+ )) {+ expect(message.params?.config?.responses_api_metadata).toEqual({+ synthetic_caller: "preserved",+ codex_security_surface: surface ?? "sdk",+ codex_security_command: "dedupe",+ codex_security_package_version: VERSION,+ });+ }expect(messages.filter((message) => message.method === "turn/start"),).toHaveLength(diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.tsindex f76aa484f..4f86fa4ad 100644--- a/sdk/typescript/tests-ts/component-scan.test.ts+++ b/sdk/typescript/tests-ts/component-scan.test.ts@@ -1411,6 +1411,7 @@ test.each(["auto", "chatgpt", "api-key"] as const)({...dependencies({ currentDirectory: paths.root, environment }),planComponents: async (_repository, options) => {+ expect(options?.surface).toBe("cli");expect(options?.auth).toBe(auth);expect(options?.cyberAccessProgram).toBe("daybreak_blue");expect(options?.environment).toEqual(expectedEnvironment);diff --git a/sdk/typescript/tests-ts/effort-forwarding.test.ts b/sdk/typescript/tests-ts/effort-forwarding.test.tsindex e11220686..378f38300 100644--- a/sdk/typescript/tests-ts/effort-forwarding.test.ts+++ b/sdk/typescript/tests-ts/effort-forwarding.test.ts@@ -98,7 +98,11 @@ test("forwards resolved efforts through the SDK independently for concurrent thr"Capture the invocation.",{},{ ...options, codex, workingDirectory: repository },- { surface: "sdk", threadSource: "security_scan_comparison" },+ {+ surface: "sdk",+ command: "compare",+ threadSource: "security_scan_comparison",+ },);const args: string[] = JSON.parse(response);expect(diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex aa4797625..d0012e144 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -12,6 +12,7 @@ import {link,lstat,mkdir,+ mkdtemp,readFile,readlink,realpath,@@ -1157,6 +1158,8 @@ ${directNode ? "}" : ""}}const readRoot = async (pluginRoot?: string) => {+ // Share credentials and plugin registration, not native session databases.+ const sqliteHome = await mkdtemp(join(root, "sqlite-"));const child = childProcess.spawn(executablePathForSpawn(command.command),["app-server", "--stdio"],@@ -1165,6 +1168,7 @@ ${directNode ? "}" : ""}env: {...environment,CODEX_HOME: home,+ CODEX_SQLITE_HOME: sqliteHome,...(pluginRoot === undefined? {}: { CODEX_SECURITY_PLUGIN_ROOT: pluginRoot }),@@ -1202,9 +1206,15 @@ ${directNode ? "}" : ""}await closed;}};- // Warm native session storage independently of this concurrent root check.- await readRoot(selected);- const servers = await Promise.all([readRoot(selected), readRoot(second)]);+ // Drain both clients before fixture cleanup, including when one fails.+ const results = await Promise.allSettled([+ readRoot(selected),+ readRoot(second),+ ]);+ const servers = results.map((result) => {+ if (result.status === "rejected") throw result.reason;+ return result.value;+ });const assertServer = async (server: Awaited<ReturnType<typeof readRoot>>,pluginRoot: string,diff --git a/sdk/typescript/tests-ts/scan-comparison.test.ts b/sdk/typescript/tests-ts/scan-comparison.test.tsindex 99f3a6f48..ae56318d7 100644--- a/sdk/typescript/tests-ts/scan-comparison.test.ts+++ b/sdk/typescript/tests-ts/scan-comparison.test.ts@@ -16,6 +16,7 @@ import {writeFile,} from "node:fs/promises";import { join, relative, win32 } from "node:path";+import { pathToFileURL } from "node:url";import { parse, stringify, type TomlTable } from "smol-toml";import {Codex,@@ -48,6 +49,9 @@ import {removeTemporaryDirectory,} from "./support/temporary-directories.js";import { fail } from "./support/errors.js";+import { planComponents } from "../src/component-plan.js";+import { VERSION } from "../src/version.js";+import { nodeCommand } from "./support/shell.js";const temporaryDirectories: string[] = [];@@ -124,6 +128,200 @@ function captureProfileClient() {}describe("semantic scan comparison", () => {+ test.each([+ ["sdk", "matching"],+ ["cli", "matching"],+ ["sdk", "planning"],+ ["cli", "planning"],+ ] as const)(+ "preserves request metadata and attributes %s %s at the model boundary",+ async (surface, helper) => {+ const root = await temporaryDirectory();+ const home = join(root, "home");+ const repository = join(root, "repository");+ await mkdir(home);+ await mkdir(repository);+ await writeFile(join(repository, "source.ts"), "export {};\n");+ await writeFile(+ join(home, "config.toml"),+ stringify({+ responses_api_metadata: {+ synthetic_home: "preserved",+ codex_security_surface: "previous",+ },+ }),+ );+ const options = {+ config: {+ codexOverrides: {+ responses_api_metadata: {+ synthetic_caller: "preserved",+ codex_security_command: "previous",+ },+ },+ },+ environment: {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ CODEX_HOME: home,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ OPENAI_API_KEY: "synthetic-key",+ },+ };+ let captured: CodexOptions | undefined;+ const { codex } = fakeCodex(+ helper === "matching"+ ? { matches: [], uncertain: [] }+ : { components: [{ name: "Source", paths: ["source.ts"] }] },+ );+ const startThread = observeCodexOptions(codex, (options) => {+ captured = options;+ });+ try {+ if (helper === "planning") {+ await planComponents(repository, {+ ...options,+ ...(surface === "cli" ? { surface } : {}),+ });+ } else {+ const input = {+ before: [finding("before")],+ after: [finding("after")],+ };+ if (surface === "sdk") await matchScanFindings(input, options);+ else await matchScanFindingsInternal(input, options, { surface });+ }+ expect(startThread).toHaveBeenCalledTimes(1);+ expect(captured?.config).not.toHaveProperty("responses_api_metadata");+ expect(+ parse(captured!.configOverrides!.join("\n"))[+ "responses_api_metadata"+ ],+ ).toEqual({+ synthetic_home: "preserved",+ synthetic_caller: "preserved",+ codex_security_surface: surface,+ codex_security_command:+ helper === "matching" ? "compare" : "scan-components",+ codex_security_package_version: VERSION,+ });+ } finally {+ startThread.mockRestore();+ }+ },+ );++ test.each([false, true])(+ "preserves literal metadata keys in SDK arguments with provider profile %p",+ async (withProfile) => {+ const home = await temporaryDirectory();+ const preload = join(home, "capture-codex.mjs");+ await writeFile(+ join(home, "config.toml"),+ stringify({+ responses_api_metadata: {+ "team.tag": "from-home",+ "overlap.tag": "home",+ },+ }),+ );+ await writeFile(+ preload,+ [+ "for await (const _chunk of process.stdin) {}",+ "const send = (event) => console.log(JSON.stringify(event));",+ 'send({ type: "thread.started", thread_id: "fixture-thread" });',+ 'send({ type: "item.completed", item: { id: "reply", type: "agent_message", text: JSON.stringify(process.argv.slice(2)) } });',+ 'send({ type: "turn.completed", usage: { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0 } });',+ "process.exit(0);",+ ].join("\n"),+ );+ let captured: CodexOptions | undefined;+ const profileClient = captureProfileClient();+ const { codex } = fakeCodex({ matches: [], uncertain: [] });+ const startThread = observeCodexOptions(codex, (options) => {+ captured = options;+ });+ try {+ await matchScanFindings(+ { before: [finding("before")], after: [finding("after")] },+ {+ environment: {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ CODEX_HOME: home,+ CODEX_SECURITY_STATE_DIR: join(home, "state"),+ OPENAI_API_KEY: "synthetic-key",+ },+ workingDirectory: home,+ config: {+ codexOverrides: {+ responses_api_metadata: {+ "caller.tag": "from-caller",+ "overlap.tag": "caller",+ },+ ...(withProfile+ ? {+ model_provider: "synthetic",+ model_providers: {+ synthetic: {+ name: "Synthetic",+ wire_api: "responses",+ base_url: "https://provider.example.test/v1",+ },+ },+ }+ : {}),+ },+ },+ },+ );+ } finally {+ startThread.mockRestore();+ profileClient.spy.mockRestore();+ }+ expect(captured).toBeDefined();+ expect(profileClient.profiles).toHaveLength(withProfile ? 1 : 0);+ const capture = new Codex({+ ...captured,+ codexPathOverride: nodeCommand().command,+ env: {+ ...captured!.env,+ NODE_OPTIONS: `--import=${pathToFileURL(preload).href}`,+ },+ });+ const turn = await capture+ .startThread({ workingDirectory: home, skipGitRepoCheck: true })+ .run("Capture the invocation.");+ const args: string[] = JSON.parse(turn.finalResponse);+ const metadataOverrides = args+ .flatMap((arg, index) => (arg === "--config" ? [args[index + 1]!] : []))+ .filter((value) => value.startsWith("responses_api_metadata"));+ expect(metadataOverrides).toHaveLength(1);+ expect(parse(metadataOverrides[0]!)).toEqual({+ responses_api_metadata: {+ "team.tag": "from-home",+ "caller.tag": "from-caller",+ "overlap.tag": "caller",+ codex_security_surface: "sdk",+ codex_security_command: "compare",+ codex_security_package_version: VERSION,+ },+ });+ const parsed = await runCodexCommand(+ resolveCodexCommand(captured!.env),+ [+ ...metadataOverrides.flatMap((value) => ["-c", value]),+ "mcp",+ "list",+ "--json",+ ],+ captured!.env!,+ );+ expect(parsed).toMatchObject({ success: true });+ },+ );+test("uses comparison attribution for CLI comparison turns", async () => {const { codex, calls } = fakeCodex({ matches: [], uncertain: [] });await matchScanFindingsInternal(@@ -268,6 +466,11 @@ describe("semantic scan comparison", () => {"synthetic-command-marker",);expect(parse(captured!.configOverrides!.join("\n"))).toEqual({+ responses_api_metadata: {+ codex_security_surface: "sdk",+ codex_security_command: "compare",+ codex_security_package_version: VERSION,+ },default_permissions: "codex_security_deep_scan_worker",permissions: {codex_security_deep_scan_worker: {@@ -852,6 +1055,7 @@ describe("semantic scan comparison", () => {} else {await runReadOnlyCodex("Plan components.", {}, options, {surface: "cli",+ command: "scan-components",threadSource: "security_scan",});}@@ -1015,7 +1219,13 @@ describe("semantic scan comparison", () => {"synthetic-ambient-key",);expect(captured?.config?.["model_provider"]).toBe("openai");- expect(captured?.configOverrides).toBeUndefined();+ expect(parse(captured!.configOverrides!.join("\n"))).toEqual({+ responses_api_metadata: {+ codex_security_surface: "sdk",+ codex_security_command: "compare",+ codex_security_package_version: VERSION,+ },+ });expect(profileClient.profiles).toHaveLength(0);}expect(threadOptions).toMatchObject({