Skip to content

Commit 934a40c

Browse files
authored
Use root repo hooks in linked worktrees (#21969)
# Why Linked worktrees currently load their own project hook declarations, so the same repo can present different hook definitions depending on which checkout is active. #21762 tried to share trust by giving matching worktree hooks a shared synthetic key, but review pointed out that divergent worktree hook definitions would then fight over one `trusted_hash`. Instead of introducing a second trust model, this makes linked worktrees use the root checkout as the single source of truth for project hook declarations. Worktree-local project config can still diverge for unrelated settings, but project hooks now keep one real source path and one trust state per repo. # What - Teach project config loading to remember the matching root-checkout `.codex/` folder for actual linked-worktree project layers. - Keep ordinary project config sourced from the worktree, but replace project hook declarations with the root checkout's matching layer before hook discovery runs, including linked-worktree layers with `.codex/` but no local `config.toml`. - Make hook discovery use that authoritative hook folder for both `hooks.json` and TOML hook source paths, so linked worktrees produce the same hook key and trust state as the root checkout. - Cover the linked-worktree path plus regressions for missing worktree `config.toml` and nested non-worktree project roots.
1 parent 2304ec4 commit 934a40c

6 files changed

Lines changed: 567 additions & 39 deletions

File tree

‎codex-rs/app-server/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1546,6 +1546,8 @@ To enable or disable a skill by name:
15461546

15471547
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.
15481548

1549+
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.
1550+
15491551
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.
15501552

15511553
For unmanaged hooks, `currentHash` and `trustStatus` describe whether the current definition is first-seen, approved, or changed since approval. Only trusted unmanaged hooks become runnable. Hook keys combine the source identity with a trailing event/group/handler selector that is currently positional.

‎codex-rs/app-server/tests/suite/v2/hooks_list.rs‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,29 @@ enabled = true
107107
Ok(())
108108
}
109109

110+
fn write_project_hook_config(dot_codex_folder: &std::path::Path, command: &str) -> Result<()> {
111+
std::fs::create_dir_all(dot_codex_folder)?;
112+
std::fs::write(
113+
dot_codex_folder.join("config.toml"),
114+
format!(
115+
r#"[features]
116+
hooks = true
117+
118+
[hooks]
119+
120+
[[hooks.PreToolUse]]
121+
matcher = "Bash"
122+
123+
[[hooks.PreToolUse.hooks]]
124+
type = "command"
125+
command = "{command}"
126+
timeout = 5
127+
"#
128+
),
129+
)?;
130+
Ok(())
131+
}
132+
110133
#[tokio::test]
111134
async fn hooks_list_shows_discovered_hook() -> Result<()> {
112135
let codex_home = TempDir::new()?;
@@ -368,6 +391,88 @@ timeout = 5
368391
Ok(())
369392
}
370393

394+
#[tokio::test]
395+
async fn hooks_list_uses_root_repo_hooks_for_linked_worktrees() -> Result<()> {
396+
let codex_home = TempDir::new()?;
397+
let workspace = TempDir::new()?;
398+
let repo_root = workspace.path().join("repo");
399+
let worktree_root = workspace.path().join("worktree");
400+
let worktree_git_dir = repo_root.join(".git/worktrees/feature-x");
401+
402+
std::fs::create_dir_all(&worktree_git_dir)?;
403+
std::fs::create_dir_all(&worktree_root)?;
404+
std::fs::write(
405+
worktree_root.join(".git"),
406+
format!("gitdir: {}\n", worktree_git_dir.display()),
407+
)?;
408+
write_project_hook_config(&repo_root.join(".codex"), "echo root hook")?;
409+
write_project_hook_config(&worktree_root.join(".codex"), "echo worktree hook")?;
410+
set_project_trust_level(codex_home.path(), &repo_root, TrustLevel::Trusted)?;
411+
412+
let mut mcp = McpProcess::new(codex_home.path()).await?;
413+
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
414+
415+
let list_id = mcp
416+
.send_hooks_list_request(HooksListParams {
417+
cwds: vec![repo_root.clone(), worktree_root.clone()],
418+
})
419+
.await?;
420+
let response: JSONRPCResponse = timeout(
421+
DEFAULT_TIMEOUT,
422+
mcp.read_stream_until_response_message(RequestId::Integer(list_id)),
423+
)
424+
.await??;
425+
let HooksListResponse { data } = to_response(response)?;
426+
let repo_hook = data[0].hooks[0].clone();
427+
let worktree_hook = data[1].hooks[0].clone();
428+
let repo_config_path =
429+
AbsolutePathBuf::from_absolute_path(repo_root.join(".codex/config.toml"))?;
430+
431+
assert_eq!(repo_hook.command.as_deref(), Some("echo root hook"));
432+
assert_eq!(worktree_hook.command.as_deref(), Some("echo root hook"));
433+
assert_eq!(repo_hook.key, worktree_hook.key);
434+
assert_eq!(repo_hook.source_path, repo_config_path);
435+
assert_eq!(worktree_hook.source_path, repo_config_path);
436+
437+
let write_id = mcp
438+
.send_config_batch_write_request(ConfigBatchWriteParams {
439+
edits: vec![ConfigEdit {
440+
key_path: "hooks.state".to_string(),
441+
value: serde_json::json!({
442+
repo_hook.key.clone(): {
443+
"trusted_hash": repo_hook.current_hash.clone()
444+
}
445+
}),
446+
merge_strategy: MergeStrategy::Upsert,
447+
}],
448+
file_path: None,
449+
expected_version: None,
450+
reload_user_config: true,
451+
})
452+
.await?;
453+
let response: JSONRPCResponse = timeout(
454+
DEFAULT_TIMEOUT,
455+
mcp.read_stream_until_response_message(RequestId::Integer(write_id)),
456+
)
457+
.await??;
458+
let _: codex_app_server_protocol::ConfigWriteResponse = to_response(response)?;
459+
460+
let list_id = mcp
461+
.send_hooks_list_request(HooksListParams {
462+
cwds: vec![worktree_root],
463+
})
464+
.await?;
465+
let response: JSONRPCResponse = timeout(
466+
DEFAULT_TIMEOUT,
467+
mcp.read_stream_until_response_message(RequestId::Integer(list_id)),
468+
)
469+
.await??;
470+
let HooksListResponse { data } = to_response(response)?;
471+
assert_eq!(data[0].hooks[0].trust_status, HookTrustStatus::Trusted);
472+
473+
Ok(())
474+
}
475+
371476
#[tokio::test]
372477
async fn config_batch_write_toggles_user_hook() -> Result<()> {
373478
let codex_home = TempDir::new()?;

‎codex-rs/config/src/loader/mod.rs‎

Lines changed: 121 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,8 @@ struct ProjectTrustContext {
627627
project_root: AbsolutePathBuf,
628628
project_root_key: String,
629629
project_root_lookup_keys: Vec<String>,
630+
checkout_root: Option<AbsolutePathBuf>,
631+
repo_root: Option<AbsolutePathBuf>,
630632
repo_root_key: Option<String>,
631633
repo_root_lookup_keys: Option<Vec<String>>,
632634
projects_trust: std::collections::HashMap<String, TrustLevel>,
@@ -712,22 +714,36 @@ impl ProjectTrustContext {
712714
)),
713715
}
714716
}
717+
718+
fn root_checkout_hooks_folder_for_dir(&self, dir: &AbsolutePathBuf) -> Option<AbsolutePathBuf> {
719+
let checkout_root = self.checkout_root.as_ref()?;
720+
let repo_root = self.repo_root.as_ref()?;
721+
// Regular checkouts resolve both paths to the same root; linked worktrees do not.
722+
if checkout_root == repo_root {
723+
return None;
724+
}
725+
726+
let relative_dir = dir.as_path().strip_prefix(checkout_root.as_path()).ok()?;
727+
Some(repo_root.join(relative_dir).join(".codex"))
728+
}
715729
}
716730

717731
fn project_layer_entry(
718732
dot_codex_folder: &AbsolutePathBuf,
719733
config: TomlValue,
720734
disabled_reason: Option<String>,
735+
hooks_config_folder_override: Option<AbsolutePathBuf>,
721736
) -> ConfigLayerEntry {
722737
let source = ConfigLayerSource::Project {
723738
dot_codex_folder: dot_codex_folder.clone(),
724739
};
725740

726-
if let Some(reason) = disabled_reason {
741+
let entry = if let Some(reason) = disabled_reason {
727742
ConfigLayerEntry::new_disabled(source, config, reason)
728743
} else {
729744
ConfigLayerEntry::new(source, config)
730-
}
745+
};
746+
entry.with_hooks_config_folder_override(hooks_config_folder_override)
731747
}
732748

733749
fn sanitize_project_config(config: &mut TomlValue) -> Vec<String> {
@@ -786,6 +802,7 @@ async fn project_trust_context(
786802
.first()
787803
.cloned()
788804
.unwrap_or_else(|| project_trust_key(project_root.as_path()));
805+
let checkout_root = find_git_checkout_root(fs, cwd).await;
789806
let repo_root = resolve_root_git_project_for_trust(fs, cwd).await;
790807
let repo_root_lookup_keys = repo_root
791808
.as_ref()
@@ -803,6 +820,8 @@ async fn project_trust_context(
803820
project_root,
804821
project_root_key,
805822
project_root_lookup_keys,
823+
checkout_root,
824+
repo_root,
806825
repo_root_key,
807826
repo_root_lookup_keys,
808827
projects_trust,
@@ -944,6 +963,24 @@ async fn find_project_root(
944963
Ok(cwd.clone())
945964
}
946965

966+
async fn find_git_checkout_root(
967+
fs: &dyn ExecutorFileSystem,
968+
cwd: &AbsolutePathBuf,
969+
) -> Option<AbsolutePathBuf> {
970+
let base = match fs.get_metadata(cwd, /*sandbox*/ None).await {
971+
Ok(metadata) if metadata.is_directory => cwd.clone(),
972+
_ => cwd.parent()?,
973+
};
974+
975+
for dir in base.ancestors() {
976+
let dot_git = dir.join(".git");
977+
if fs.get_metadata(&dot_git, /*sandbox*/ None).await.is_ok() {
978+
return Some(dir);
979+
}
980+
}
981+
None
982+
}
983+
947984
struct LoadedProjectLayers {
948985
layers: Vec<ConfigLayerEntry>,
949986
startup_warnings: Vec<String>,
@@ -995,6 +1032,7 @@ async fn load_project_layers(
9951032

9961033
let decision = trust_context.decision_for_dir(&dir);
9971034
let disabled_reason = trust_context.disabled_reason_for_decision(&decision);
1035+
let hooks_config_folder_override = trust_context.root_checkout_hooks_folder_for_dir(&dir);
9981036
let dot_codex_normalized =
9991037
normalize_path(dot_codex_abs.as_path()).unwrap_or_else(|_| dot_codex_abs.to_path_buf());
10001038
if dot_codex_abs == codex_home_abs || dot_codex_normalized == codex_home_normalized {
@@ -1019,6 +1057,7 @@ async fn load_project_layers(
10191057
&dot_codex_abs,
10201058
TomlValue::Table(toml::map::Map::new()),
10211059
disabled_reason.clone(),
1060+
hooks_config_folder_override.clone(),
10221061
));
10231062
continue;
10241063
}
@@ -1027,24 +1066,44 @@ async fn load_project_layers(
10271066
let ignored_project_config_keys = sanitize_project_config(&mut config);
10281067
let config =
10291068
resolve_relative_paths_in_config_toml(config, dot_codex_abs.as_path())?;
1069+
let config = merge_root_checkout_project_hooks(
1070+
fs,
1071+
config,
1072+
hooks_config_folder_override.as_ref(),
1073+
decision.is_trusted(),
1074+
)
1075+
.await?;
10301076
if disabled_reason.is_none() && !ignored_project_config_keys.is_empty() {
10311077
startup_warnings.push(project_ignored_config_keys_warning(
10321078
&dot_codex_abs,
10331079
&ignored_project_config_keys,
10341080
));
10351081
}
1036-
let entry = project_layer_entry(&dot_codex_abs, config, disabled_reason.clone());
1082+
let entry = project_layer_entry(
1083+
&dot_codex_abs,
1084+
config,
1085+
disabled_reason.clone(),
1086+
hooks_config_folder_override.clone(),
1087+
);
10371088
layers.push(entry);
10381089
}
10391090
Err(err) => {
10401091
if err.kind() == io::ErrorKind::NotFound {
10411092
// If there is no config.toml file, record an empty entry
10421093
// for this project layer, as this may still have subfolders
10431094
// that are significant in the overall ConfigLayerStack.
1095+
let config = merge_root_checkout_project_hooks(
1096+
fs,
1097+
TomlValue::Table(toml::map::Map::new()),
1098+
hooks_config_folder_override.as_ref(),
1099+
decision.is_trusted(),
1100+
)
1101+
.await?;
10441102
layers.push(project_layer_entry(
10451103
&dot_codex_abs,
1046-
TomlValue::Table(toml::map::Map::new()),
1104+
config,
10471105
disabled_reason,
1106+
hooks_config_folder_override,
10481107
));
10491108
} else {
10501109
let config_file_display = config_file.as_path().display();
@@ -1062,6 +1121,64 @@ async fn load_project_layers(
10621121
startup_warnings,
10631122
})
10641123
}
1124+
1125+
/// For linked worktrees, preserve ordinary worktree-local project config while
1126+
/// replacing only hook declarations with the matching root-checkout layer.
1127+
async fn merge_root_checkout_project_hooks(
1128+
fs: &dyn ExecutorFileSystem,
1129+
mut config: TomlValue,
1130+
hooks_config_folder_override: Option<&AbsolutePathBuf>,
1131+
is_trusted: bool,
1132+
) -> io::Result<TomlValue> {
1133+
let Some(hooks_config_folder) = hooks_config_folder_override else {
1134+
return Ok(config);
1135+
};
1136+
let hooks_config_file = hooks_config_folder.join(CONFIG_TOML_FILE);
1137+
let root_config = match fs
1138+
.read_file_text(&hooks_config_file, /*sandbox*/ None)
1139+
.await
1140+
{
1141+
Ok(contents) => {
1142+
let parsed: TomlValue = match toml::from_str(&contents) {
1143+
Ok(parsed) => parsed,
1144+
Err(err) => {
1145+
if is_trusted {
1146+
return Err(io::Error::new(
1147+
io::ErrorKind::InvalidData,
1148+
format!(
1149+
"Error parsing project hooks config file {}: {err}",
1150+
hooks_config_file.as_path().display()
1151+
),
1152+
));
1153+
}
1154+
TomlValue::Table(toml::map::Map::new())
1155+
}
1156+
};
1157+
resolve_relative_paths_in_config_toml(parsed, hooks_config_folder.as_path())?
1158+
}
1159+
Err(err) if err.kind() == io::ErrorKind::NotFound => {
1160+
TomlValue::Table(toml::map::Map::new())
1161+
}
1162+
Err(err) => {
1163+
return Err(io::Error::new(
1164+
err.kind(),
1165+
format!(
1166+
"Failed to read project hooks config file {}: {err}",
1167+
hooks_config_file.as_path().display()
1168+
),
1169+
));
1170+
}
1171+
};
1172+
1173+
let Some(config_table) = config.as_table_mut() else {
1174+
return Ok(config);
1175+
};
1176+
config_table.remove("hooks");
1177+
if let Some(hooks) = root_config.get("hooks") {
1178+
config_table.insert("hooks".to_string(), hooks.clone());
1179+
}
1180+
Ok(config)
1181+
}
10651182
/// The legacy mechanism for specifying admin-enforced configuration is to read
10661183
/// from a file like `/etc/codex/managed_config.toml` that has the same
10671184
/// structure as `config.toml` where fields like `approval_policy` can specify

0 commit comments

Comments
 (0)