From 1288313772f2e0defbd9c0e5b7b29fbb41111079 Mon Sep 17 00:00:00 2001 From: Brent Traut Date: Wed, 3 Jun 2026 16:18:26 -0700 Subject: [PATCH] Add project-local config override layers --- .../codex_app_server_protocol.schemas.json | 21 ++ .../codex_app_server_protocol.v2.schemas.json | 21 ++ .../schema/json/v2/ConfigReadResponse.json | 21 ++ .../schema/json/v2/ConfigWriteResponse.json | 21 ++ .../schema/typescript/v2/ConfigLayerSource.ts | 2 +- .../src/protocol/v2/config.rs | 9 +- codex-rs/app-server/README.md | 2 +- .../app-server/src/config_manager_service.rs | 5 + .../app-server/tests/suite/v2/config_rpc.rs | 10 +- codex-rs/config/src/config_layer_source.rs | 7 + codex-rs/config/src/diagnostics.rs | 5 + codex-rs/config/src/lib.rs | 1 + codex-rs/config/src/loader/mod.rs | 210 ++++++++++-------- codex-rs/config/src/state.rs | 64 ++++-- codex-rs/config/src/state_tests.rs | 36 +++ codex-rs/core-skills/src/loader.rs | 6 +- codex-rs/core/src/agents_md.rs | 5 +- codex-rs/core/src/config/agent_roles.rs | 5 +- .../core/src/config/config_loader_tests.rs | 187 +++++++++++++++- codex-rs/core/src/exec_policy.rs | 7 +- codex-rs/core/src/mcp_tool_call.rs | 27 ++- codex-rs/core/src/mcp_tool_call_tests.rs | 56 +++++ codex-rs/core/src/network_proxy_loader.rs | 5 + .../core/src/network_proxy_loader_tests.rs | 48 ++++ codex-rs/hooks/src/engine/discovery.rs | 8 +- codex-rs/tui/src/debug_config.rs | 2 + 26 files changed, 658 insertions(+), 133 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index c75ae416fa..f42b8fdc2d 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -8123,6 +8123,27 @@ "title": "ProjectConfigLayerSource", "type": "object" }, + { + "description": "Project override layer from a sibling `.codex/config.override.toml`.", + "properties": { + "dotCodexFolder": { + "$ref": "#/definitions/v2/AbsolutePathBuf" + }, + "type": { + "enum": [ + "projectOverride" + ], + "title": "ProjectOverrideConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "dotCodexFolder", + "type" + ], + "title": "ProjectOverrideConfigLayerSource", + "type": "object" + }, { "description": "Session-layer overrides supplied via `-c`/`--config`.", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index a4a0267dc5..14a85c1d10 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -4408,6 +4408,27 @@ "title": "ProjectConfigLayerSource", "type": "object" }, + { + "description": "Project override layer from a sibling `.codex/config.override.toml`.", + "properties": { + "dotCodexFolder": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": { + "enum": [ + "projectOverride" + ], + "title": "ProjectOverrideConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "dotCodexFolder", + "type" + ], + "title": "ProjectOverrideConfigLayerSource", + "type": "object" + }, { "description": "Session-layer overrides supplied via `-c`/`--config`.", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json index c7fa352940..ebb97f54b4 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json @@ -609,6 +609,27 @@ "title": "ProjectConfigLayerSource", "type": "object" }, + { + "description": "Project override layer from a sibling `.codex/config.override.toml`.", + "properties": { + "dotCodexFolder": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": { + "enum": [ + "projectOverride" + ], + "title": "ProjectOverrideConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "dotCodexFolder", + "type" + ], + "title": "ProjectOverrideConfigLayerSource", + "type": "object" + }, { "description": "Session-layer overrides supplied via `-c`/`--config`.", "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigWriteResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigWriteResponse.json index d1a2254a92..89af9b59b1 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigWriteResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigWriteResponse.json @@ -154,6 +154,27 @@ "title": "ProjectConfigLayerSource", "type": "object" }, + { + "description": "Project override layer from a sibling `.codex/config.override.toml`.", + "properties": { + "dotCodexFolder": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": { + "enum": [ + "projectOverride" + ], + "title": "ProjectOverrideConfigLayerSourceType", + "type": "string" + } + }, + "required": [ + "dotCodexFolder", + "type" + ], + "title": "ProjectOverrideConfigLayerSource", + "type": "object" + }, { "description": "Session-layer overrides supplied via `-c`/`--config`.", "properties": { diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ConfigLayerSource.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ConfigLayerSource.ts index 963c331b5d..1c4ccdbe78 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ConfigLayerSource.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ConfigLayerSource.ts @@ -28,4 +28,4 @@ file: AbsolutePathBuf, * Name of the selected profile-v2 config layered on top of the base * user config, when this layer represents one. */ -profile: string | null, } | { "type": "project", dotCodexFolder: AbsolutePathBuf, } | { "type": "sessionFlags" } | { "type": "legacyManagedConfigTomlFromFile", file: AbsolutePathBuf, } | { "type": "legacyManagedConfigTomlFromMdm" }; +profile: string | null, } | { "type": "project", dotCodexFolder: AbsolutePathBuf, } | { "type": "projectOverride", dotCodexFolder: AbsolutePathBuf, } | { "type": "sessionFlags" } | { "type": "legacyManagedConfigTomlFromFile", file: AbsolutePathBuf, } | { "type": "legacyManagedConfigTomlFromMdm" }; diff --git a/codex-rs/app-server-protocol/src/protocol/v2/config.rs b/codex-rs/app-server-protocol/src/protocol/v2/config.rs index b37f10dce7..145d177860 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/config.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/config.rs @@ -80,6 +80,13 @@ pub enum ConfigLayerSource { dot_codex_folder: AbsolutePathBuf, }, + /// Project override layer from a sibling `.codex/config.override.toml`. + #[serde(rename_all = "camelCase")] + #[ts(rename_all = "camelCase")] + ProjectOverride { + dot_codex_folder: AbsolutePathBuf, + }, + /// Session-layer overrides supplied via `-c`/`--config`. SessionFlags, @@ -111,7 +118,7 @@ impl ConfigLayerSource { 20 } } - ConfigLayerSource::Project { .. } => 25, + ConfigLayerSource::Project { .. } | ConfigLayerSource::ProjectOverride { .. } => 25, ConfigLayerSource::SessionFlags => 30, ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. } => 40, ConfigLayerSource::LegacyManagedConfigTomlFromMdm => 50, diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index a6c5ddab7d..89610709c3 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -230,7 +230,7 @@ Example with notification opt-out: - `mcpServer/tool/call` — call a tool on a thread's configured MCP server by `threadId`, `server`, `tool`, optional `arguments`, and optional `_meta`, returning the MCP tool result. - `windowsSandbox/setupStart` — start Windows sandbox setup for the selected mode (`elevated` or `unelevated`); accepts an optional absolute `cwd` to target setup for a specific workspace, returns `{ started: true }` immediately, and later emits `windowsSandbox/setupCompleted`. - `feedback/upload` — submit a feedback report (classification + optional reason/logs, conversation_id, and optional `extraLogFiles` attachments array); returns the tracking thread id. -- `config/read` — fetch the effective config on disk after resolving config layering, including opaque `desktop` values stored in `config.toml`. +- `config/read` — fetch the effective config on disk after resolving config layering, including project-local `.codex/config.override.toml` layers and opaque `desktop` values stored in `config.toml`. - `externalAgentConfig/detect` — detect migratable external-agent artifacts with `includeHome` and optional `cwds`; each detected item includes `cwd` (`null` for home), and plugin/session migration items may additionally include structured `details` grouping plugin ids or session metadata. - `externalAgentConfig/import` — apply selected external-agent migration items by passing explicit `migrationItems` with `cwd` (`null` for home) and any plugin/session `details` returned by detect. Callers may pass `source` to identify the product that initiated the import; omitted or `null` means unspecified. The response acknowledges the synchronous import phase with an `importId`. Expected migration failures are reported as per-item failures rather than JSON-RPC errors, so the server still returns that `importId` and emits `externalAgentConfig/import/completed` with the same ID once all synchronous and background work finishes. The completion notification contains type-level `itemTypeResults` with successes and failures, including raw failure messages for the client to report separately. - `config/value/write` — write a single config key/value to the user's config.toml on disk; dotted paths such as `desktop.someKey` use the same generic write surface. diff --git a/codex-rs/app-server/src/config_manager_service.rs b/codex-rs/app-server/src/config_manager_service.rs index 4b42c28aa9..4a27a14759 100644 --- a/codex-rs/app-server/src/config_manager_service.rs +++ b/codex-rs/app-server/src/config_manager_service.rs @@ -631,6 +631,11 @@ fn override_message(layer: &ConfigLayerSource) -> String { "Overridden by project config: {}/{CONFIG_TOML_FILE}", dot_codex_folder.display(), ), + ConfigLayerSource::ProjectOverride { dot_codex_folder } => format!( + "Overridden by project config override: {}/{}", + dot_codex_folder.display(), + codex_config::CONFIG_OVERRIDE_TOML_FILE, + ), ConfigLayerSource::SessionFlags => "Overridden by session flags".to_string(), ConfigLayerSource::User { file, .. } => { format!("Overridden by user config: {}", file.display()) diff --git a/codex-rs/app-server/tests/suite/v2/config_rpc.rs b/codex-rs/app-server/tests/suite/v2/config_rpc.rs index 81ef145ef0..7064eff603 100644 --- a/codex-rs/app-server/tests/suite/v2/config_rpc.rs +++ b/codex-rs/app-server/tests/suite/v2/config_rpc.rs @@ -541,6 +541,12 @@ async fn config_read_includes_project_layers_for_cwd() -> Result<()> { project_config_dir.join("config.toml"), r#" model_reasoning_effort = "high" +"#, + )?; + std::fs::write( + project_config_dir.join("config.override.toml"), + r#" +model_reasoning_effort = "xhigh" "#, )?; set_project_trust_level(codex_home.path(), workspace.path(), TrustLevel::Trusted)?; @@ -564,10 +570,10 @@ model_reasoning_effort = "high" config, origins, .. } = to_response(resp)?; - assert_eq!(config.model_reasoning_effort, Some(ReasoningEffort::High)); + assert_eq!(config.model_reasoning_effort, Some(ReasoningEffort::XHigh)); assert_eq!( origins.get("model_reasoning_effort").expect("origin").name, - ConfigLayerSource::Project { + ConfigLayerSource::ProjectOverride { dot_codex_folder: project_config } ); diff --git a/codex-rs/config/src/config_layer_source.rs b/codex-rs/config/src/config_layer_source.rs index 7bff779b19..6b578d7343 100644 --- a/codex-rs/config/src/config_layer_source.rs +++ b/codex-rs/config/src/config_layer_source.rs @@ -20,6 +20,13 @@ pub fn format_config_layer_source(source: &ConfigLayerSource, config_toml_file: dot_codex_folder.as_path().display() ) } + ConfigLayerSource::ProjectOverride { dot_codex_folder } => { + format!( + "project override ({}/{})", + dot_codex_folder.as_path().display(), + crate::CONFIG_OVERRIDE_TOML_FILE + ) + } ConfigLayerSource::SessionFlags => "session-flags".to_string(), ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => { format!("legacy managed_config.toml ({})", file.as_path().display()) diff --git a/codex-rs/config/src/diagnostics.rs b/codex-rs/config/src/diagnostics.rs index ca7df712d6..a11abdd0bd 100644 --- a/codex-rs/config/src/diagnostics.rs +++ b/codex-rs/config/src/diagnostics.rs @@ -253,6 +253,11 @@ fn config_path_for_layer(layer: &ConfigLayerEntry, config_toml_file: &str) -> Op ConfigLayerSource::Project { dot_codex_folder } => { Some(dot_codex_folder.as_path().join(config_toml_file)) } + ConfigLayerSource::ProjectOverride { dot_codex_folder } => Some( + dot_codex_folder + .as_path() + .join(crate::CONFIG_OVERRIDE_TOML_FILE), + ), ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => Some(file.to_path_buf()), ConfigLayerSource::Mdm { .. } | ConfigLayerSource::EnterpriseManaged { .. } diff --git a/codex-rs/config/src/lib.rs b/codex-rs/config/src/lib.rs index ed26757715..4489220abd 100644 --- a/codex-rs/config/src/lib.rs +++ b/codex-rs/config/src/lib.rs @@ -31,6 +31,7 @@ mod tui_keymap; pub mod types; pub const CONFIG_TOML_FILE: &str = "config.toml"; +pub const CONFIG_OVERRIDE_TOML_FILE: &str = "config.override.toml"; pub use cloud_config_bundle::CloudConfigBundle; pub use cloud_config_bundle::CloudConfigBundleLayers; diff --git a/codex-rs/config/src/loader/mod.rs b/codex-rs/config/src/loader/mod.rs index e3c7ee1128..f6a9168880 100644 --- a/codex-rs/config/src/loader/mod.rs +++ b/codex-rs/config/src/loader/mod.rs @@ -5,6 +5,7 @@ mod macos; mod tests; use self::layer_io::LoadedConfigLayers; +use crate::CONFIG_OVERRIDE_TOML_FILE; use crate::CONFIG_TOML_FILE; use crate::CloudConfigBundleLayers; use crate::ProfileV2Name; @@ -917,15 +918,11 @@ impl ProjectTrustContext { } fn project_layer_entry( - dot_codex_folder: &AbsolutePathBuf, + source: ConfigLayerSource, config: TomlValue, disabled_reason: Option, hooks_config_folder_override: Option, ) -> ConfigLayerEntry { - let source = ConfigLayerSource::Project { - dot_codex_folder: dot_codex_folder.clone(), - }; - let entry = if let Some(reason) = disabled_reason { ConfigLayerEntry::new_disabled(source, config, reason) } else { @@ -955,10 +952,9 @@ fn sanitize_project_config(config: &mut TomlValue) -> Vec { } fn project_ignored_config_keys_warning( - dot_codex_folder: &AbsolutePathBuf, + config_path: &AbsolutePathBuf, ignored_keys: &[String], ) -> String { - let config_path = dot_codex_folder.join(CONFIG_TOML_FILE); let ignored_keys = ignored_keys.join(", "); format!( concat!( @@ -966,11 +962,67 @@ fn project_ignored_config_keys_warning( "If you want these settings to apply, manually set them in your ", "user-level config.toml." ), - config_path = config_path.display(), + config_path = config_path.as_path().display(), ignored_keys = ignored_keys, ) } +async fn load_project_config_file( + fs: &dyn ExecutorFileSystem, + config_file: &AbsolutePathBuf, + dot_codex_folder: &AbsolutePathBuf, + decision: &ProjectTrustDecision, + strict_config: bool, + startup_warnings: &mut Vec, +) -> io::Result> { + let config_file_uri = PathUri::from_abs_path(config_file); + let contents = match fs.read_file_text(&config_file_uri, /*sandbox*/ None).await { + Ok(contents) => contents, + Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(err) => { + return Err(io::Error::new( + err.kind(), + format!( + "Failed to read project config file {}: {err}", + config_file.as_path().display() + ), + )); + } + }; + let mut config = match toml::from_str(&contents) { + Ok(config) => config, + Err(_) if !decision.is_trusted() => { + return Ok(Some(TomlValue::Table(toml::map::Map::new()))); + } + Err(err) => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "Error parsing project config file {}: {err}", + config_file.as_path().display() + ), + )); + } + }; + if strict_config && decision.is_trusted() { + validate_config_toml_strictly( + config_file.as_path(), + &contents, + &config, + dot_codex_folder.as_path(), + )?; + } + let ignored_project_config_keys = sanitize_project_config(&mut config); + let config = resolve_relative_paths_in_config_toml(config, dot_codex_folder.as_path())?; + if decision.is_trusted() && !ignored_project_config_keys.is_empty() { + startup_warnings.push(project_ignored_config_keys_warning( + config_file, + &ignored_project_config_keys, + )); + } + Ok(Some(config)) +} + async fn project_trust_context( fs: &dyn ExecutorFileSystem, merged_config: &TomlValue, @@ -1241,89 +1293,62 @@ async fn load_project_layers( continue; } let config_file = dot_codex_abs.join(CONFIG_TOML_FILE); - let config_file_uri = PathUri::from_abs_path(&config_file); - match fs.read_file_text(&config_file_uri, /*sandbox*/ None).await { - Ok(contents) => { - let config: TomlValue = match toml::from_str(&contents) { - Ok(config) => config, - Err(e) => { - if decision.is_trusted() { - let config_file_display = config_file.as_path().display(); - return Err(io::Error::new( - io::ErrorKind::InvalidData, - format!( - "Error parsing project config file {config_file_display}: {e}" - ), - )); - } - layers.push(project_layer_entry( - &dot_codex_abs, - TomlValue::Table(toml::map::Map::new()), - disabled_reason.clone(), - hooks_config_folder_override.clone(), - )); - continue; - } - }; - let mut config = config; - if disabled_reason.is_none() && strict_config { - validate_config_toml_strictly( - config_file.as_path(), - &contents, - &config, - dot_codex_abs.as_path(), - )?; - } - let ignored_project_config_keys = sanitize_project_config(&mut config); - let config = - resolve_relative_paths_in_config_toml(config, dot_codex_abs.as_path())?; - let config = merge_root_checkout_project_hooks( - fs, - config, - hooks_config_folder_override.as_ref(), - decision.is_trusted(), - ) - .await?; - if disabled_reason.is_none() && !ignored_project_config_keys.is_empty() { - startup_warnings.push(project_ignored_config_keys_warning( - &dot_codex_abs, - &ignored_project_config_keys, - )); - } - let entry = project_layer_entry( - &dot_codex_abs, - config, - disabled_reason.clone(), - hooks_config_folder_override.clone(), - ); - layers.push(entry); - } - Err(err) => { - if err.kind() == io::ErrorKind::NotFound { - // If there is no config.toml file, record an empty entry - // for this project layer, as this may still have subfolders - // that are significant in the overall ConfigLayerStack. - let config = merge_root_checkout_project_hooks( - fs, - TomlValue::Table(toml::map::Map::new()), - hooks_config_folder_override.as_ref(), - decision.is_trusted(), - ) - .await?; - layers.push(project_layer_entry( - &dot_codex_abs, - config, - disabled_reason, - hooks_config_folder_override, - )); - } else { - let config_file_display = config_file.as_path().display(); - return Err(io::Error::new( - err.kind(), - format!("Failed to read project config file {config_file_display}: {err}"), - )); - } - } + // Record an empty base layer when config.toml is absent because its + // sibling folders may still contribute project-local sidecars. + let config = load_project_config_file( + fs, + &config_file, + &dot_codex_abs, + &decision, + strict_config, + &mut startup_warnings, + ) + .await? + .unwrap_or_else(|| TomlValue::Table(toml::map::Map::new())); + let config = merge_root_checkout_project_hooks( + fs, + config, + hooks_config_folder_override.as_ref(), + decision.is_trusted(), + CONFIG_TOML_FILE, + ) + .await?; + layers.push(project_layer_entry( + ConfigLayerSource::Project { + dot_codex_folder: dot_codex_abs.clone(), + }, + config, + disabled_reason.clone(), + hooks_config_folder_override.clone(), + )); + + let override_file = dot_codex_abs.join(CONFIG_OVERRIDE_TOML_FILE); + if let Some(config) = load_project_config_file( + fs, + &override_file, + &dot_codex_abs, + &decision, + strict_config, + &mut startup_warnings, + ) + .await? + { + let config = merge_root_checkout_project_hooks( + fs, + config, + hooks_config_folder_override.as_ref(), + decision.is_trusted(), + CONFIG_OVERRIDE_TOML_FILE, + ) + .await?; + layers.push(project_layer_entry( + ConfigLayerSource::ProjectOverride { + dot_codex_folder: dot_codex_abs, + }, + config, + disabled_reason, + hooks_config_folder_override, + )); } } @@ -1340,11 +1365,12 @@ async fn merge_root_checkout_project_hooks( mut config: TomlValue, hooks_config_folder_override: Option<&AbsolutePathBuf>, is_trusted: bool, + config_file_name: &str, ) -> io::Result { let Some(hooks_config_folder) = hooks_config_folder_override else { return Ok(config); }; - let hooks_config_file = hooks_config_folder.join(CONFIG_TOML_FILE); + let hooks_config_file = hooks_config_folder.join(config_file_name); let hooks_config_file_uri = PathUri::from_abs_path(&hooks_config_file); let root_config = match fs .read_file_text(&hooks_config_file_uri, /*sandbox*/ None) diff --git a/codex-rs/config/src/state.rs b/codex-rs/config/src/state.rs index 9d8de1c885..af3d5131c2 100644 --- a/codex-rs/config/src/state.rs +++ b/codex-rs/config/src/state.rs @@ -210,7 +210,10 @@ impl ConfigLayerEntry { ConfigLayerSource::System { file } => file.parent(), ConfigLayerSource::EnterpriseManaged { .. } => None, ConfigLayerSource::User { file, .. } => file.parent(), - ConfigLayerSource::Project { dot_codex_folder } => Some(dot_codex_folder.clone()), + ConfigLayerSource::Project { dot_codex_folder } + | ConfigLayerSource::ProjectOverride { dot_codex_folder } => { + Some(dot_codex_folder.clone()) + } ConfigLayerSource::SessionFlags => None, ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. } => None, ConfigLayerSource::LegacyManagedConfigTomlFromMdm => None, @@ -560,30 +563,51 @@ fn verify_layer_ordering(layers: &[ConfigLayerEntry]) -> std::io::Result { + if let Some(previous) = previous_project_dot_codex_folder { + let Some(parent) = previous.as_path().parent() else { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "project layer has no parent directory", + )); + }; + if previous == current_project_dot_codex_folder + || !current_project_dot_codex_folder + .as_path() + .ancestors() + .any(|ancestor| ancestor == parent) + { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "project layers are not ordered from root to cwd", + )); + } + } + previous_project_dot_codex_folder = Some(current_project_dot_codex_folder); + } + ConfigLayerSource::ProjectOverride { dot_codex_folder } => { + let follows_project_layer = index + .checked_sub(1) + .and_then(|index| layers.get(index)) + .is_some_and(|previous| { + matches!( + &previous.name, + ConfigLayerSource::Project { + dot_codex_folder: previous_dot_codex_folder, + } if previous_dot_codex_folder == dot_codex_folder + ) + }); + if !follows_project_layer { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, - "project layer has no parent directory", - )); - }; - if previous == current_project_dot_codex_folder - || !current_project_dot_codex_folder - .as_path() - .ancestors() - .any(|ancestor| ancestor == parent) - { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - "project layers are not ordered from root to cwd", + "project override layer must follow its project layer", )); } } - previous_project_dot_codex_folder = Some(current_project_dot_codex_folder); + _ => {} } } diff --git a/codex-rs/config/src/state_tests.rs b/codex-rs/config/src/state_tests.rs index fb6e26968b..9492e67448 100644 --- a/codex-rs/config/src/state_tests.rs +++ b/codex-rs/config/src/state_tests.rs @@ -139,3 +139,39 @@ fn with_user_config_updates_matching_user_layer_without_replacing_active_profile Some("on-failure") ); } + +#[test] +fn project_override_layer_must_immediately_follow_its_project_layer() { + let temp_dir = TempDir::new().expect("tempdir"); + let dot_codex_folder = AbsolutePathBuf::from_absolute_path(temp_dir.path().join(".codex")) + .expect("project config folder should be absolute"); + let empty_config = || toml::Value::Table(toml::map::Map::new()); + let project_override = || { + ConfigLayerEntry::new( + ConfigLayerSource::ProjectOverride { + dot_codex_folder: dot_codex_folder.clone(), + }, + empty_config(), + ) + }; + let err = ConfigLayerStack::new( + vec![ + ConfigLayerEntry::new( + ConfigLayerSource::Project { + dot_codex_folder: dot_codex_folder.clone(), + }, + empty_config(), + ), + project_override(), + project_override(), + ], + ConfigRequirements::default(), + ConfigRequirementsToml::default(), + ) + .expect_err("duplicate project override layer should be rejected"); + + assert_eq!( + err.to_string(), + "project override layer must follow its project layer" + ); +} diff --git a/codex-rs/core-skills/src/loader.rs b/codex-rs/core-skills/src/loader.rs index 64861c45eb..d30b6d0d9f 100644 --- a/codex-rs/core-skills/src/loader.rs +++ b/codex-rs/core-skills/src/loader.rs @@ -361,6 +361,7 @@ fn skill_roots_from_layer_stack_inner( } ConfigLayerSource::Mdm { .. } | ConfigLayerSource::EnterpriseManaged { .. } + | ConfigLayerSource::ProjectOverride { .. } | ConfigLayerSource::SessionFlags | ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. } | ConfigLayerSource::LegacyManagedConfigTomlFromMdm => {} @@ -413,7 +414,10 @@ fn project_root_markers_from_stack(config_layer_stack: &ConfigLayerStack) -> Vec ConfigLayerStackOrdering::LowestPrecedenceFirst, /*include_disabled*/ false, ) { - if matches!(layer.name, ConfigLayerSource::Project { .. }) { + if matches!( + layer.name, + ConfigLayerSource::Project { .. } | ConfigLayerSource::ProjectOverride { .. } + ) { continue; } merge_toml_values(&mut merged, &layer.config); diff --git a/codex-rs/core/src/agents_md.rs b/codex-rs/core/src/agents_md.rs index 861e7b4ac7..c78c0fa032 100644 --- a/codex-rs/core/src/agents_md.rs +++ b/codex-rs/core/src/agents_md.rs @@ -179,7 +179,10 @@ async fn agents_md_paths( ConfigLayerStackOrdering::LowestPrecedenceFirst, /*include_disabled*/ false, ) { - if matches!(layer.name, ConfigLayerSource::Project { .. }) { + if matches!( + layer.name, + ConfigLayerSource::Project { .. } | ConfigLayerSource::ProjectOverride { .. } + ) { continue; } merge_toml_values(&mut merged, &layer.config); diff --git a/codex-rs/core/src/config/agent_roles.rs b/codex-rs/core/src/config/agent_roles.rs index 483cd3a98d..0eb1144226 100644 --- a/codex-rs/core/src/config/agent_roles.rs +++ b/codex-rs/core/src/config/agent_roles.rs @@ -1,4 +1,5 @@ use super::AgentRoleConfig; +use codex_config::ConfigLayerSource; use codex_config::ConfigLayerStack; use codex_config::ConfigLayerStackOrdering; use codex_config::config_toml::AgentRoleToml; @@ -71,7 +72,9 @@ pub(crate) async fn load_agent_roles( } } - if let Some(config_folder) = layer.config_folder() { + if let Some(config_folder) = config_folder + && !matches!(layer.name, ConfigLayerSource::ProjectOverride { .. }) + { for (role_name, role) in discover_agent_roles_in_dir( fs, &config_folder.join("agents"), diff --git a/codex-rs/core/src/config/config_loader_tests.rs b/codex-rs/core/src/config/config_loader_tests.rs index c01c555519..1642c8141e 100644 --- a/codex-rs/core/src/config/config_loader_tests.rs +++ b/codex-rs/core/src/config/config_loader_tests.rs @@ -2,6 +2,7 @@ use crate::config::ConfigBuilder; use crate::config::ConfigOverrides; use crate::config::ConstraintError; use codex_app_server_protocol::ConfigLayerSource; +use codex_config::CONFIG_OVERRIDE_TOML_FILE; use codex_config::CONFIG_TOML_FILE; use codex_config::CloudConfigBundleLoadError; use codex_config::CloudConfigBundleLoader; @@ -106,13 +107,22 @@ async fn write_project_hook_config( dot_codex_folder: &Path, foo: Option<&str>, command: &str, +) -> std::io::Result<()> { + write_project_hook_config_file(dot_codex_folder, CONFIG_TOML_FILE, foo, command).await +} + +async fn write_project_hook_config_file( + dot_codex_folder: &Path, + config_file: &str, + foo: Option<&str>, + command: &str, ) -> std::io::Result<()> { tokio::fs::create_dir_all(dot_codex_folder).await?; let foo = foo .map(|value| format!("foo = \"{value}\"\n\n")) .unwrap_or_default(); tokio::fs::write( - dot_codex_folder.join(CONFIG_TOML_FILE), + dot_codex_folder.join(config_file), format!( r#"{foo}[hooks] @@ -128,6 +138,181 @@ command = "{command}" .await } +#[tokio::test] +async fn sibling_override_layers_load_after_their_base_scope() -> std::io::Result<()> { + let tmp = tempdir()?; + let project_root = tmp.path().join("project"); + let dot_codex = project_root.join(".codex"); + let codex_home = tmp.path().join("home"); + tokio::fs::create_dir_all(&dot_codex).await?; + tokio::fs::create_dir_all(&codex_home).await?; + tokio::fs::write(project_root.join(".git"), "gitdir: here").await?; + tokio::fs::write(dot_codex.join(CONFIG_TOML_FILE), "foo = \"project\"\n").await?; + tokio::fs::write( + dot_codex.join(CONFIG_OVERRIDE_TOML_FILE), + "foo = \"project-override\"\n", + ) + .await?; + make_config_for_test( + &codex_home, + &project_root, + TrustLevel::Trusted, + /*project_root_markers*/ None, + ) + .await?; + + let layers = load_config_layers_state( + LOCAL_FS.as_ref(), + &codex_home, + Some(AbsolutePathBuf::from_absolute_path(&project_root)?), + &[] as &[(String, TomlValue)], + LoaderOverrides::default(), + &codex_config::NoopThreadConfigLoader, + ) + .await?; + let sources = layers + .get_layers( + ConfigLayerStackOrdering::LowestPrecedenceFirst, + /*include_disabled*/ false, + ) + .into_iter() + .filter_map(|layer| match &layer.name { + ConfigLayerSource::Project { .. } | ConfigLayerSource::ProjectOverride { .. } => { + Some(layer.name.clone()) + } + _ => None, + }) + .collect::>(); + + assert!(matches!( + sources.as_slice(), + [ + ConfigLayerSource::Project { .. }, + ConfigLayerSource::ProjectOverride { .. }, + ] + )); + assert_eq!( + layers + .effective_config() + .get("foo") + .and_then(TomlValue::as_str), + Some("project-override") + ); + Ok(()) +} + +#[tokio::test] +async fn project_override_partially_merges_nested_mcp_server_config() -> std::io::Result<()> { + let tmp = tempdir()?; + let project_root = tmp.path().join("project"); + let dot_codex = project_root.join(".codex"); + let codex_home = tmp.path().join("home"); + tokio::fs::create_dir_all(&dot_codex).await?; + tokio::fs::create_dir_all(&codex_home).await?; + tokio::fs::write(project_root.join(".git"), "gitdir: here").await?; + tokio::fs::write( + dot_codex.join(CONFIG_TOML_FILE), + "[mcp_servers.sentry]\nurl = \"https://mcp.sentry.dev/mcp\"\nenabled = true\n", + ) + .await?; + tokio::fs::write( + dot_codex.join(CONFIG_OVERRIDE_TOML_FILE), + "[mcp_servers.sentry]\nenabled = false\n", + ) + .await?; + make_config_for_test( + &codex_home, + &project_root, + TrustLevel::Trusted, + /*project_root_markers*/ None, + ) + .await?; + + let config = ConfigBuilder::default() + .codex_home(codex_home) + .fallback_cwd(Some(project_root)) + .build() + .await?; + let server = config + .mcp_servers + .get() + .get("sentry") + .expect("project MCP server should load"); + + assert!(!server.enabled); + assert_eq!( + server.transport, + codex_config::types::McpServerTransportConfig::StreamableHttp { + url: "https://mcp.sentry.dev/mcp".to_string(), + bearer_token_env_var: None, + http_headers: None, + env_http_headers: None, + } + ); + Ok(()) +} + +#[tokio::test] +async fn linked_worktree_override_layer_keeps_worktree_config_but_uses_root_repo_hooks() +-> std::io::Result<()> { + let tmp = tempdir()?; + let repo_root = tmp.path().join("repo"); + let worktree_root = tmp.path().join("worktree"); + tokio::fs::create_dir_all(worktree_root.join(".codex")).await?; + write_linked_worktree_pointer(&repo_root, &worktree_root).await?; + write_project_hook_config_file( + &repo_root.join(".codex"), + CONFIG_OVERRIDE_TOML_FILE, + Some("repo-override"), + "echo repo override hook", + ) + .await?; + write_project_hook_config_file( + &worktree_root.join(".codex"), + CONFIG_OVERRIDE_TOML_FILE, + Some("worktree-override"), + "echo worktree override hook", + ) + .await?; + let codex_home = tmp.path().join("home"); + tokio::fs::create_dir_all(&codex_home).await?; + make_config_for_test( + &codex_home, + &repo_root, + TrustLevel::Trusted, + /*project_root_markers*/ None, + ) + .await?; + + let layers = load_config_layers_state( + LOCAL_FS.as_ref(), + &codex_home, + Some(AbsolutePathBuf::from_absolute_path(&worktree_root)?), + &[] as &[(String, TomlValue)], + LoaderOverrides::default(), + &codex_config::NoopThreadConfigLoader, + ) + .await?; + let layer = layers + .layers_high_to_low() + .into_iter() + .find(|layer| matches!(layer.name, ConfigLayerSource::ProjectOverride { .. })) + .expect("project override layer"); + + assert_eq!( + layer.hooks_config_folder(), + Some(AbsolutePathBuf::from_absolute_path( + repo_root.join(".codex") + )?) + ); + assert_eq!( + layer.config.get("foo").and_then(TomlValue::as_str), + Some("worktree-override") + ); + assert_eq!(project_hook_command(layer), Some("echo repo override hook")); + Ok(()) +} + #[tokio::test] async fn cli_overrides_resolve_relative_paths_against_cwd() -> std::io::Result<()> { let codex_home = tempdir().expect("tempdir"); diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs index 7b33a196b0..00b69dac6b 100644 --- a/codex-rs/core/src/exec_policy.rs +++ b/codex-rs/core/src/exec_policy.rs @@ -579,11 +579,16 @@ pub async fn load_exec_policy(config_stack: &ConfigLayerStack) -> Result anyhow::Result> { - if let Some(project_config_folder) = project_mcp_tool_approval_config_folder(config, server) { - return Ok(Some(ConfigEditsBuilder::new(&project_config_folder))); + if let Some(project_config_file) = project_mcp_tool_approval_config_file(config, server) { + return Ok(Some(ConfigEditsBuilder::for_config_path( + project_config_file.as_path(), + ))); } Ok(user_mcp_server_is_configured(config, server)? @@ -2071,18 +2075,21 @@ fn user_mcp_server_is_configured(config: &Config, server: &str) -> anyhow::Resul Ok(servers.contains_key(server)) } -fn project_mcp_tool_approval_config_folder( - config: &Config, - server: &str, -) -> Option { +fn project_mcp_tool_approval_config_file(config: &Config, server: &str) -> Option { config .config_layer_stack .layers_high_to_low() .into_iter() .find_map(|layer| { - if !matches!(layer.name, ConfigLayerSource::Project { .. }) { - return None; - } + let config_file = match &layer.name { + ConfigLayerSource::Project { dot_codex_folder } => { + dot_codex_folder.join(CONFIG_TOML_FILE) + } + ConfigLayerSource::ProjectOverride { dot_codex_folder } => { + dot_codex_folder.join(CONFIG_OVERRIDE_TOML_FILE) + } + _ => return None, + }; let servers = layer .config @@ -2093,7 +2100,7 @@ fn project_mcp_tool_approval_config_folder( HashMap::::deserialize(value).ok() })?; if servers.contains_key(server) { - layer.config_folder() + Some(config_file) } else { None } diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index 56d1ff9b6c..ccf7fd6f1b 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -7,6 +7,7 @@ use crate::state::ActiveTurn; use crate::test_support::models_manager_with_provider; use crate::tools::hook_names::HookToolName; use crate::turn_metadata::McpTurnMetadataContext; +use codex_config::CONFIG_OVERRIDE_TOML_FILE; use codex_config::CONFIG_TOML_FILE; use codex_config::config_toml::ConfigToml; use codex_config::types::AppConfig; @@ -2273,6 +2274,61 @@ async fn maybe_persist_mcp_tool_approval_writes_project_config_for_project_serve assert_eq!(mcp_tool_approval_is_remembered(&session, &key).await, true); } +#[tokio::test] +async fn maybe_persist_mcp_tool_approval_writes_project_override_for_override_only_server() { + let (session, mut turn_context) = make_session_and_context().await; + let codex_home = session.codex_home().await; + let project_dir = tempdir().expect("tempdir"); + std::fs::write(project_dir.path().join(".git"), "gitdir: nowhere").expect("seed git marker"); + let project_codex_dir = project_dir.path().join(".codex"); + std::fs::create_dir_all(&project_codex_dir).expect("create project .codex dir"); + std::fs::write( + project_codex_dir.join(CONFIG_OVERRIDE_TOML_FILE), + "[mcp_servers.docs]\ncommand = \"docs-server\"\n", + ) + .expect("seed project override"); + ConfigEditsBuilder::new(&codex_home) + .set_project_trust_level( + project_dir.path(), + codex_protocol::config_types::TrustLevel::Trusted, + ) + .apply() + .await + .expect("trust project"); + let config = ConfigBuilder::default() + .codex_home(codex_home.to_path_buf()) + .fallback_cwd(Some(project_dir.path().to_path_buf())) + .build() + .await + .expect("load project config"); + turn_context.config = Arc::new(config); + let key = McpToolApprovalKey { + server: "docs".to_string(), + connector_id: None, + tool_name: "search".to_string(), + }; + + maybe_persist_mcp_tool_approval(&session, &turn_context, key.clone()).await; + + let contents = std::fs::read_to_string(project_codex_dir.join(CONFIG_OVERRIDE_TOML_FILE)) + .expect("read project override"); + let parsed: ConfigToml = toml::from_str(&contents).expect("parse project override"); + let tool = parsed + .mcp_servers + .get("docs") + .and_then(|server| server.tools.get("search")) + .expect("docs/search tool config exists"); + + assert_eq!( + tool, + &McpServerToolConfig { + approval_mode: Some(AppToolApproval::Approve), + } + ); + assert!(!project_codex_dir.join(CONFIG_TOML_FILE).exists()); + assert_eq!(mcp_tool_approval_is_remembered(&session, &key).await, true); +} + #[tokio::test] async fn approve_mode_skips_when_annotations_do_not_require_approval() { let (session, turn_context) = make_session_and_context().await; diff --git a/codex-rs/core/src/network_proxy_loader.rs b/codex-rs/core/src/network_proxy_loader.rs index e0ffe99259..f8d0fe254d 100644 --- a/codex-rs/core/src/network_proxy_loader.rs +++ b/codex-rs/core/src/network_proxy_loader.rs @@ -8,6 +8,7 @@ use crate::exec_policy::load_exec_policy; use anyhow::Context; use anyhow::Result; use codex_app_server_protocol::ConfigLayerSource; +use codex_config::CONFIG_OVERRIDE_TOML_FILE; use codex_config::CONFIG_TOML_FILE; use codex_config::ConfigLayerStack; use codex_config::ConfigLayerStackOrdering; @@ -100,6 +101,9 @@ fn collect_layer_mtimes(stack: &ConfigLayerStack) -> Vec { ConfigLayerSource::Project { dot_codex_folder } => { Some(dot_codex_folder.join(CONFIG_TOML_FILE)) } + ConfigLayerSource::ProjectOverride { dot_codex_folder } => { + Some(dot_codex_folder.join(CONFIG_OVERRIDE_TOML_FILE)) + } ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => Some(file.clone()), _ => None, }; @@ -321,6 +325,7 @@ fn is_user_controlled_layer(layer: &ConfigLayerSource) -> bool { layer, ConfigLayerSource::User { .. } | ConfigLayerSource::Project { .. } + | ConfigLayerSource::ProjectOverride { .. } | ConfigLayerSource::SessionFlags ) } diff --git a/codex-rs/core/src/network_proxy_loader_tests.rs b/codex-rs/core/src/network_proxy_loader_tests.rs index 33ca54019e..1a62d3096b 100644 --- a/codex-rs/core/src/network_proxy_loader_tests.rs +++ b/codex-rs/core/src/network_proxy_loader_tests.rs @@ -535,6 +535,54 @@ fn trusted_constraints_use_only_the_final_selected_profile_network() { assert_eq!(constraints.denied_domains, None); } +#[test] +fn project_override_is_user_controlled_and_watched_for_reload() { + let dot_codex_folder = + AbsolutePathBuf::try_from(std::path::PathBuf::from("/tmp/project/.codex")) + .expect("project config folder should be absolute"); + let layers = ConfigLayerStack::new( + vec![ + ConfigLayerEntry::new( + ConfigLayerSource::Project { + dot_codex_folder: dot_codex_folder.clone(), + }, + toml::Value::Table(toml::map::Map::new()), + ), + ConfigLayerEntry::new( + ConfigLayerSource::ProjectOverride { + dot_codex_folder: dot_codex_folder.clone(), + }, + toml::toml! { + default_permissions = "dev" + + [permissions.dev.network] + enabled = true + } + .into(), + ), + ], + ConfigRequirements::default(), + ConfigRequirementsToml::default(), + ) + .expect("project config stack should be valid"); + + assert_eq!( + network_constraints_from_trusted_layers(&layers) + .expect("project override should not become a trusted constraint"), + NetworkProxyConstraints::default() + ); + assert_eq!( + collect_layer_mtimes(&layers) + .into_iter() + .map(|layer| layer.path) + .collect::>(), + vec![ + dot_codex_folder.join(CONFIG_TOML_FILE), + dot_codex_folder.join(CONFIG_OVERRIDE_TOML_FILE), + ] + ); +} + #[test] fn trusted_constraints_normalize_profile_network_domains_before_merging_layers() { let lower_layer = ConfigLayerEntry::new( diff --git a/codex-rs/hooks/src/engine/discovery.rs b/codex-rs/hooks/src/engine/discovery.rs index cab28b64a1..de7c21483e 100644 --- a/codex-rs/hooks/src/engine/discovery.rs +++ b/codex-rs/hooks/src/engine/discovery.rs @@ -372,6 +372,10 @@ fn config_toml_source_path(layer: &ConfigLayerEntry) -> AbsolutePathBuf { .hooks_config_folder() .unwrap_or_else(|| dot_codex_folder.clone()) .join(CONFIG_TOML_FILE), + ConfigLayerSource::ProjectOverride { dot_codex_folder } => layer + .hooks_config_folder() + .unwrap_or_else(|| dot_codex_folder.clone()) + .join(codex_config::CONFIG_OVERRIDE_TOML_FILE), ConfigLayerSource::Mdm { domain, key } => { synthetic_layer_path(&format!("/{CONFIG_TOML_FILE}")) } @@ -616,7 +620,9 @@ fn hook_metadata_for_config_layer_source(source: &ConfigLayerSource) -> (HookSou match source { ConfigLayerSource::System { .. } => (HookSource::System, true), ConfigLayerSource::User { .. } => (HookSource::User, false), - ConfigLayerSource::Project { .. } => (HookSource::Project, false), + ConfigLayerSource::Project { .. } | ConfigLayerSource::ProjectOverride { .. } => { + (HookSource::Project, false) + } ConfigLayerSource::Mdm { .. } => (HookSource::Mdm, true), ConfigLayerSource::EnterpriseManaged { .. } => (HookSource::CloudManagedConfig, true), ConfigLayerSource::SessionFlags => (HookSource::SessionFlags, false), diff --git a/codex-rs/tui/src/debug_config.rs b/codex-rs/tui/src/debug_config.rs index faacca458a..dc39579f22 100644 --- a/codex-rs/tui/src/debug_config.rs +++ b/codex-rs/tui/src/debug_config.rs @@ -313,6 +313,7 @@ fn render_non_file_layer_details(layer: &ConfigLayerEntry) -> Vec> ConfigLayerSource::System { .. } | ConfigLayerSource::User { .. } | ConfigLayerSource::Project { .. } + | ConfigLayerSource::ProjectOverride { .. } | ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. } => Vec::new(), } } @@ -377,6 +378,7 @@ fn non_file_layer_value_label(source: &ConfigLayerSource) -> &'static str { | ConfigLayerSource::System { .. } | ConfigLayerSource::User { .. } | ConfigLayerSource::Project { .. } + | ConfigLayerSource::ProjectOverride { .. } | ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. } => "Layer value", } }