From 55d9c76f523a4d97073c45c236e8b03884e7b48c Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Thu, 28 May 2026 14:18:03 -0700 Subject: [PATCH] Canonicalize linked worktree hook trust keys --- codex-rs/app-server/README.md | 2 +- .../app-server/tests/suite/v2/hooks_list.rs | 87 +++++++++++++++++- codex-rs/config/src/loader/mod.rs | 91 +++---------------- codex-rs/config/src/state.rs | 31 ++++--- .../core/src/config/config_loader_tests.rs | 31 +++++-- codex-rs/hooks/src/engine/discovery.rs | 22 ++++- 6 files changed, 155 insertions(+), 109 deletions(-) diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 88edc22f9e..4110ef0528 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -1550,7 +1550,7 @@ To enable or disable a skill by name: Use `hooks/list` to fetch discovered hooks for one or more `cwds`. Each result is evaluated with that `cwd`'s effective config, so feature gates and discovered config layers can differ within a single response. -For linked Git worktrees, project hook declarations come from the matching `.codex/` folders in the root checkout rather than from divergent hook declarations stored only in the linked worktree. This keeps each repo on one authoritative project-hook definition and one trust state. +For linked Git worktrees, project hook declarations come from the active worktree, while hook trust keys are canonicalized to the matching `.codex/` folders in the root checkout. This lets identical hook definitions share trust across worktrees without making hook path resolution ignore the active worktree. Hooks are returned even when disabled so clients can render and re-enable them. User-controlled state lives under `hooks.state`. Managed hooks are non-configurable, and user entries for managed hook keys are ignored during loading. diff --git a/codex-rs/app-server/tests/suite/v2/hooks_list.rs b/codex-rs/app-server/tests/suite/v2/hooks_list.rs index 1c8f76fe51..fb916aa0b3 100644 --- a/codex-rs/app-server/tests/suite/v2/hooks_list.rs +++ b/codex-rs/app-server/tests/suite/v2/hooks_list.rs @@ -391,7 +391,7 @@ timeout = 5 } #[tokio::test] -async fn hooks_list_uses_root_repo_hooks_for_linked_worktrees() -> Result<()> { +async fn hooks_list_uses_worktree_hooks_with_root_repo_keys_for_linked_worktrees() -> Result<()> { let codex_home = TempDir::new()?; let workspace = TempDir::new()?; let repo_root = workspace.path().join("repo"); @@ -428,10 +428,91 @@ async fn hooks_list_uses_root_repo_hooks_for_linked_worktrees() -> Result<()> { AbsolutePathBuf::from_absolute_path(repo_root.join(".codex/config.toml"))?; assert_eq!(repo_hook.command.as_deref(), Some("echo root hook")); - assert_eq!(worktree_hook.command.as_deref(), Some("echo root hook")); + assert_eq!(worktree_hook.command.as_deref(), Some("echo worktree hook")); assert_eq!(repo_hook.key, worktree_hook.key); assert_eq!(repo_hook.source_path, repo_config_path); - assert_eq!(worktree_hook.source_path, repo_config_path); + assert_eq!( + worktree_hook.source_path, + AbsolutePathBuf::from_absolute_path(worktree_root.join(".codex/config.toml"))? + ); + assert_eq!(repo_hook.trust_status, HookTrustStatus::Untrusted); + assert_eq!(worktree_hook.trust_status, HookTrustStatus::Untrusted); + + let write_id = mcp + .send_config_batch_write_request(ConfigBatchWriteParams { + edits: vec![ConfigEdit { + key_path: "hooks.state".to_string(), + value: serde_json::json!({ + repo_hook.key.clone(): { + "trusted_hash": repo_hook.current_hash.clone() + } + }), + merge_strategy: MergeStrategy::Upsert, + }], + file_path: None, + expected_version: None, + reload_user_config: true, + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(write_id)), + ) + .await??; + let _: codex_app_server_protocol::ConfigWriteResponse = to_response(response)?; + + let list_id = mcp + .send_hooks_list_request(HooksListParams { + cwds: vec![worktree_root], + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(list_id)), + ) + .await??; + let HooksListResponse { data } = to_response(response)?; + assert_eq!(data[0].hooks[0].trust_status, HookTrustStatus::Modified); + + Ok(()) +} + +#[tokio::test] +async fn hooks_list_shares_trust_for_identical_linked_worktree_hooks() -> Result<()> { + let codex_home = TempDir::new()?; + let workspace = TempDir::new()?; + let repo_root = workspace.path().join("repo"); + let worktree_root = workspace.path().join("worktree"); + let worktree_git_dir = repo_root.join(".git/worktrees/feature-x"); + + std::fs::create_dir_all(&worktree_git_dir)?; + std::fs::create_dir_all(&worktree_root)?; + std::fs::write( + worktree_root.join(".git"), + format!("gitdir: {}\n", worktree_git_dir.display()), + )?; + write_project_hook_config(&repo_root.join(".codex"), "echo shared hook")?; + write_project_hook_config(&worktree_root.join(".codex"), "echo shared hook")?; + set_project_trust_level(codex_home.path(), &repo_root, TrustLevel::Trusted)?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let list_id = mcp + .send_hooks_list_request(HooksListParams { + cwds: vec![repo_root, worktree_root.clone()], + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(list_id)), + ) + .await??; + let HooksListResponse { data } = to_response(response)?; + let repo_hook = data[0].hooks[0].clone(); + let worktree_hook = data[1].hooks[0].clone(); + assert_eq!(repo_hook.key, worktree_hook.key); + assert_eq!(repo_hook.current_hash, worktree_hook.current_hash); let write_id = mcp .send_config_batch_write_request(ConfigBatchWriteParams { diff --git a/codex-rs/config/src/loader/mod.rs b/codex-rs/config/src/loader/mod.rs index 3c1723e51b..b2ee0c071b 100644 --- a/codex-rs/config/src/loader/mod.rs +++ b/codex-rs/config/src/loader/mod.rs @@ -848,7 +848,10 @@ impl ProjectTrustContext { } } - fn root_checkout_hooks_folder_for_dir(&self, dir: &AbsolutePathBuf) -> Option { + fn root_checkout_hook_key_folder_for_dir( + &self, + dir: &AbsolutePathBuf, + ) -> Option { let checkout_root = self.checkout_root.as_ref()?; let repo_root = self.repo_root.as_ref()?; // Regular checkouts resolve both paths to the same root; linked worktrees do not. @@ -865,7 +868,7 @@ fn project_layer_entry( dot_codex_folder: &AbsolutePathBuf, config: TomlValue, disabled_reason: Option, - hooks_config_folder_override: Option, + hook_key_config_folder_override: Option, ) -> ConfigLayerEntry { let source = ConfigLayerSource::Project { dot_codex_folder: dot_codex_folder.clone(), @@ -876,7 +879,7 @@ fn project_layer_entry( } else { ConfigLayerEntry::new(source, config) }; - entry.with_hooks_config_folder_override(hooks_config_folder_override) + entry.with_hook_key_config_folder_override(hook_key_config_folder_override) } fn sanitize_project_config(config: &mut TomlValue) -> Vec { @@ -1166,7 +1169,8 @@ async fn load_project_layers( let decision = trust_context.decision_for_dir(&dir); let disabled_reason = trust_context.disabled_reason_for_decision(&decision); - let hooks_config_folder_override = trust_context.root_checkout_hooks_folder_for_dir(&dir); + let hook_key_config_folder_override = + trust_context.root_checkout_hook_key_folder_for_dir(&dir); let dot_codex_normalized = normalize_path(dot_codex_abs.as_path()).unwrap_or_else(|_| dot_codex_abs.to_path_buf()); if dot_codex_abs == codex_home_abs || dot_codex_normalized == codex_home_normalized { @@ -1191,7 +1195,7 @@ async fn load_project_layers( &dot_codex_abs, TomlValue::Table(toml::map::Map::new()), disabled_reason.clone(), - hooks_config_folder_override.clone(), + hook_key_config_folder_override.clone(), )); continue; } @@ -1208,13 +1212,6 @@ async fn load_project_layers( 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, @@ -1225,7 +1222,7 @@ async fn load_project_layers( &dot_codex_abs, config, disabled_reason.clone(), - hooks_config_folder_override.clone(), + hook_key_config_folder_override.clone(), ); layers.push(entry); } @@ -1234,18 +1231,11 @@ async fn load_project_layers( // 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, + TomlValue::Table(toml::map::Map::new()), disabled_reason, - hooks_config_folder_override, + hook_key_config_folder_override, )); } else { let config_file_display = config_file.as_path().display(); @@ -1264,63 +1254,6 @@ async fn load_project_layers( }) } -/// For linked worktrees, preserve ordinary worktree-local project config while -/// replacing only hook declarations with the matching root-checkout layer. -async fn merge_root_checkout_project_hooks( - fs: &dyn ExecutorFileSystem, - mut config: TomlValue, - hooks_config_folder_override: Option<&AbsolutePathBuf>, - is_trusted: bool, -) -> 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 root_config = match fs - .read_file_text(&hooks_config_file, /*sandbox*/ None) - .await - { - Ok(contents) => { - let parsed: TomlValue = match toml::from_str(&contents) { - Ok(parsed) => parsed, - Err(err) => { - if is_trusted { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - format!( - "Error parsing project hooks config file {}: {err}", - hooks_config_file.as_path().display() - ), - )); - } - TomlValue::Table(toml::map::Map::new()) - } - }; - resolve_relative_paths_in_config_toml(parsed, hooks_config_folder.as_path())? - } - Err(err) if err.kind() == io::ErrorKind::NotFound => { - TomlValue::Table(toml::map::Map::new()) - } - Err(err) => { - return Err(io::Error::new( - err.kind(), - format!( - "Failed to read project hooks config file {}: {err}", - hooks_config_file.as_path().display() - ), - )); - } - }; - - let Some(config_table) = config.as_table_mut() else { - return Ok(config); - }; - config_table.remove("hooks"); - if let Some(hooks) = root_config.get("hooks") { - config_table.insert("hooks".to_string(), hooks.clone()); - } - Ok(config) -} /// The legacy mechanism for specifying admin-enforced configuration is to read /// from a file like `/etc/codex/managed_config.toml` that has the same /// structure as `config.toml` where fields like `approval_policy` can specify diff --git a/codex-rs/config/src/state.rs b/codex-rs/config/src/state.rs index 3ec0bfb314..3730a4bd2a 100644 --- a/codex-rs/config/src/state.rs +++ b/codex-rs/config/src/state.rs @@ -100,7 +100,7 @@ pub struct ConfigLayerEntry { pub raw_toml: Option, pub version: String, pub disabled_reason: Option, - hooks_config_folder_override: Option, + hook_key_config_folder_override: Option, } impl ConfigLayerEntry { @@ -112,7 +112,7 @@ impl ConfigLayerEntry { raw_toml: None, version, disabled_reason: None, - hooks_config_folder_override: None, + hook_key_config_folder_override: None, } } @@ -124,7 +124,7 @@ impl ConfigLayerEntry { raw_toml: Some(raw_toml), version, disabled_reason: None, - hooks_config_folder_override: None, + hook_key_config_folder_override: None, } } @@ -140,7 +140,7 @@ impl ConfigLayerEntry { raw_toml: None, version, disabled_reason: Some(disabled_reason.into()), - hooks_config_folder_override: None, + hook_key_config_folder_override: None, } } @@ -152,11 +152,11 @@ impl ConfigLayerEntry { self.raw_toml.as_deref() } - pub(crate) fn with_hooks_config_folder_override( + pub(crate) fn with_hook_key_config_folder_override( mut self, - hooks_config_folder_override: Option, + hook_key_config_folder_override: Option, ) -> Self { - self.hooks_config_folder_override = hooks_config_folder_override; + self.hook_key_config_folder_override = hook_key_config_folder_override; self } @@ -190,13 +190,18 @@ impl ConfigLayerEntry { } /// Returns the `.codex/` folder that should be used for hook declarations. - /// - /// Project layers normally use their own config folder. Linked Git worktrees - /// can instead point hook discovery at the matching folder from the root - /// checkout while the rest of the project config still comes from the - /// worktree. pub fn hooks_config_folder(&self) -> Option { - self.hooks_config_folder_override + self.config_folder() + } + + /// Returns the `.codex/` folder that should be used for hook trust keys. + /// + /// Project layers normally use their own config folder for both declarations + /// and trust keys. Linked Git worktrees can instead key hook trust against + /// the matching root-checkout folder while loading declarations from the + /// active worktree. + pub fn hook_key_config_folder(&self) -> Option { + self.hook_key_config_folder_override .clone() .or_else(|| self.config_folder()) } diff --git a/codex-rs/core/src/config/config_loader_tests.rs b/codex-rs/core/src/config/config_loader_tests.rs index 2682e6ef41..cbeb050553 100644 --- a/codex-rs/core/src/config/config_loader_tests.rs +++ b/codex-rs/core/src/config/config_loader_tests.rs @@ -1936,7 +1936,7 @@ async fn project_layers_prefer_closest_cwd() -> std::io::Result<()> { } #[tokio::test] -async fn linked_worktree_project_layers_keep_worktree_config_but_use_root_repo_hooks() +async fn linked_worktree_project_layers_keep_worktree_config_but_use_root_repo_hook_keys() -> std::io::Result<()> { let tmp = tempdir()?; let repo_root = tmp.path().join("repo"); @@ -2003,11 +2003,23 @@ async fn linked_worktree_project_layers_keep_worktree_config_but_use_root_repo_h assert_eq!( project_layers[0].hooks_config_folder(), Some(AbsolutePathBuf::from_absolute_path( - repo_child.join(".codex") + worktree_child.join(".codex") )?) ); assert_eq!( project_layers[1].hooks_config_folder(), + Some(AbsolutePathBuf::from_absolute_path( + worktree_root.join(".codex") + )?) + ); + assert_eq!( + project_layers[0].hook_key_config_folder(), + Some(AbsolutePathBuf::from_absolute_path( + repo_child.join(".codex") + )?) + ); + assert_eq!( + project_layers[1].hook_key_config_folder(), Some(AbsolutePathBuf::from_absolute_path( repo_root.join(".codex") )?) @@ -2021,7 +2033,7 @@ async fn linked_worktree_project_layers_keep_worktree_config_but_use_root_repo_h ); assert_eq!( project_hook_command(project_layers[0]), - Some("echo repo child hook") + Some("echo worktree child hook") ); assert_eq!( project_layers[1] @@ -2032,14 +2044,14 @@ async fn linked_worktree_project_layers_keep_worktree_config_but_use_root_repo_h ); assert_eq!( project_hook_command(project_layers[1]), - Some("echo repo root hook") + Some("echo worktree root hook") ); Ok(()) } #[tokio::test] -async fn linked_worktree_project_layers_use_root_repo_hooks_without_worktree_config_toml() +async fn linked_worktree_project_layers_keep_empty_worktree_config_with_root_repo_hook_keys() -> std::io::Result<()> { let tmp = tempdir()?; let repo_root = tmp.path().join("repo"); @@ -2085,13 +2097,16 @@ async fn linked_worktree_project_layers_use_root_repo_hooks_without_worktree_con assert_eq!( project_layers[0].hooks_config_folder(), Some(AbsolutePathBuf::from_absolute_path( - repo_root.join(".codex") + worktree_root.join(".codex") )?) ); assert_eq!( - project_hook_command(project_layers[0]), - Some("echo repo root hook") + project_layers[0].hook_key_config_folder(), + Some(AbsolutePathBuf::from_absolute_path( + repo_root.join(".codex") + )?) ); + assert_eq!(project_hook_command(project_layers[0]), None); Ok(()) } diff --git a/codex-rs/hooks/src/engine/discovery.rs b/codex-rs/hooks/src/engine/discovery.rs index 3ddf8f2387..107b071cc1 100644 --- a/codex-rs/hooks/src/engine/discovery.rs +++ b/codex-rs/hooks/src/engine/discovery.rs @@ -127,6 +127,7 @@ pub(crate) fn discover_handlers( } for (source_path, hook_events) in [json_hooks, toml_hooks].into_iter().flatten() { + let key_source_path = hook_key_source_path_for_layer(layer, &source_path); append_hook_events( &mut handlers, &mut hook_entries, @@ -134,7 +135,7 @@ pub(crate) fn discover_handlers( &mut display_order, HookHandlerSource { path: &source_path, - key_source: source_path.display().to_string(), + key_source: key_source_path.display().to_string(), source: hook_source, is_managed, bypass_hook_trust: policy.bypass_hook_trust, @@ -354,10 +355,7 @@ fn config_toml_source_path(layer: &ConfigLayerEntry) -> AbsolutePathBuf { ConfigLayerSource::System { file } | ConfigLayerSource::User { file, .. } | ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => file.clone(), - ConfigLayerSource::Project { dot_codex_folder } => layer - .hooks_config_folder() - .unwrap_or_else(|| dot_codex_folder.clone()) - .join(CONFIG_TOML_FILE), + ConfigLayerSource::Project { dot_codex_folder } => dot_codex_folder.join(CONFIG_TOML_FILE), ConfigLayerSource::Mdm { domain, key } => { synthetic_layer_path(&format!("/{CONFIG_TOML_FILE}")) } @@ -368,6 +366,20 @@ fn config_toml_source_path(layer: &ConfigLayerEntry) -> AbsolutePathBuf { } } +fn hook_key_source_path_for_layer( + layer: &ConfigLayerEntry, + source_path: &AbsolutePathBuf, +) -> AbsolutePathBuf { + if matches!(layer.name, ConfigLayerSource::Project { .. }) + && let Some(config_folder) = layer.hook_key_config_folder() + && let Some(file_name) = source_path.as_path().file_name() + { + return config_folder.join(file_name); + } + + source_path.clone() +} + fn synthetic_layer_path(path: &str) -> AbsolutePathBuf { #[cfg(windows)] {