1use super::super::{
2 ensure_codex_hooks_enabled as shared_ensure_codex_hooks_enabled, ensure_state_dir,
3 install_codex_instruction_docs, mcp_server_quiet_mode, resolve_hook_command_binary,
4 upsert_lean_ctx_codex_hook_entries, write_file,
5};
6
7pub fn install_codex_hook() {
8 let Some(codex_dir) = crate::core::home::resolve_codex_dir() else {
9 tracing::error!("Cannot resolve codex directory");
10 return;
11 };
12 if !ensure_state_dir(&codex_dir) {
13 return;
14 }
15
16 let hook_config_changed = install_codex_hook_config(&codex_dir);
17 let installed_docs = install_codex_instruction_docs(&codex_dir);
18
19 if !mcp_server_quiet_mode() {
20 if hook_config_changed {
21 eprintln!(
22 "Installed Codex-compatible SessionStart/PreToolUse hooks at {}",
23 codex_dir.display()
24 );
25 }
26 if installed_docs {
27 eprintln!("Installed Codex instructions at {}", codex_dir.display());
28 } else {
29 eprintln!("Codex AGENTS.md already configured.");
30 }
31 }
32}
33
34fn install_codex_hook_config(codex_dir: &std::path::Path) -> bool {
35 let binary = resolve_hook_command_binary();
36 let session_start_cmd = format!("{binary} hook codex-session-start");
37 let pre_tool_use_cmd = format!("{binary} hook codex-pretooluse");
38 let hooks_json_path = codex_dir.join("hooks.json");
39
40 let mut changed = false;
41 let mut root = if hooks_json_path.exists() {
42 if let Some(parsed) = std::fs::read_to_string(&hooks_json_path)
43 .ok()
44 .and_then(|content| crate::core::jsonc::parse_jsonc(&content).ok())
45 {
46 parsed
47 } else {
48 changed = true;
49 serde_json::json!({ "hooks": {} })
50 }
51 } else {
52 changed = true;
53 serde_json::json!({ "hooks": {} })
54 };
55
56 if upsert_lean_ctx_codex_hook_entries(&mut root, &session_start_cmd, &pre_tool_use_cmd) {
57 changed = true;
58 }
59
60 let observe_cmd = format!("{binary} hook observe");
62 if ensure_codex_observe_hooks(&mut root, &observe_cmd) {
63 changed = true;
64 }
65
66 if changed {
67 write_file(
68 &hooks_json_path,
69 &serde_json::to_string_pretty(&root).unwrap_or_default(),
70 );
71 }
72
73 let rewrite_path = codex_dir.join("hooks").join("lean-ctx-rewrite-codex.sh");
74 if rewrite_path.exists() && std::fs::remove_file(&rewrite_path).is_ok() {
75 changed = true;
76 }
77
78 let config_toml_path = codex_dir.join("config.toml");
79 let config_content = std::fs::read_to_string(&config_toml_path).unwrap_or_default();
80
81 let mcp_updated = ensure_codex_mcp_server(
84 &config_content,
85 &binary,
86 &super::super::mcp_server_env_pairs(),
87 );
88 let hooks_updated =
89 ensure_codex_hooks_enabled(mcp_updated.as_deref().unwrap_or(&config_content));
90
91 let final_content = hooks_updated
92 .or(mcp_updated)
93 .unwrap_or_else(|| config_content.clone());
94 if final_content != config_content {
95 write_file(&config_toml_path, &final_content);
96 changed = true;
97 if !mcp_server_quiet_mode() {
98 eprintln!(
99 "Updated Codex config (MCP server + hooks) in {}",
100 config_toml_path.display()
101 );
102 }
103 }
104
105 changed
106}
107
108fn ensure_codex_observe_hooks(root: &mut serde_json::Value, observe_cmd: &str) -> bool {
109 let original = root.clone();
110 let Some(hooks_obj) = root
111 .as_object_mut()
112 .and_then(|r| r.get_mut("hooks"))
113 .and_then(|h| h.as_object_mut())
114 else {
115 return false;
116 };
117
118 let observe_events = ["PostToolUse", "SessionStart", "SessionEnd"];
119 for event in observe_events {
120 let arr = hooks_obj
121 .entry(event.to_string())
122 .or_insert_with(|| serde_json::json!([]));
123 let Some(entries) = arr.as_array_mut() else {
124 continue;
125 };
126 let already = entries.iter().any(|e| {
127 e.get("hooks")
128 .and_then(|h| h.as_array())
129 .is_some_and(|hooks| {
130 hooks.iter().any(|hook| {
131 hook.get("command")
132 .and_then(|c| c.as_str())
133 .is_some_and(|c| c.contains("hook observe"))
134 })
135 })
136 });
137 if !already {
138 entries.push(serde_json::json!({
139 "matcher": ".*",
140 "hooks": [{ "type": "command", "command": observe_cmd, "timeout": 5 }]
141 }));
142 }
143 }
144
145 *root != original
146}
147
148fn ensure_codex_mcp_server(
162 config_content: &str,
163 binary: &str,
164 env_pairs: &[(String, String)],
165) -> Option<String> {
166 let mut doc = config_content.parse::<toml_edit::DocumentMut>().ok()?;
167 let original = doc.to_string();
168
169 let servers = doc["mcp_servers"].or_insert(toml_edit::table());
171 if let Some(t) = servers.as_table_mut() {
172 t.set_implicit(true);
173 }
174
175 let lean = servers["lean-ctx"].or_insert(toml_edit::table());
178 let lean_tbl = lean.as_table_mut()?;
179 lean_tbl.set_implicit(false);
180
181 if !lean_tbl.contains_key("command") {
183 lean_tbl["command"] = toml_edit::value(binary);
184 }
185 if !lean_tbl.contains_key("args") {
186 lean_tbl["args"] = toml_edit::value(toml_edit::Array::new());
187 }
188
189 let env = lean_tbl["env"].or_insert(toml_edit::table());
190 if let Some(env_tbl) = env.as_table_mut() {
191 for (key, val) in env_pairs {
192 let key = key.as_str();
193 if env_tbl.get(key).and_then(toml_edit::Item::as_str) != Some(val.as_str()) {
194 env_tbl[key] = toml_edit::value(val.as_str());
195 }
196 }
197 }
198
199 let updated = doc.to_string();
200 (updated != original).then_some(updated)
201}
202
203fn ensure_codex_hooks_enabled(config_content: &str) -> Option<String> {
204 shared_ensure_codex_hooks_enabled(config_content)
205}
206
207#[cfg(test)]
212mod tests {
213 use super::{
214 ensure_codex_hooks_enabled, ensure_codex_mcp_server, upsert_lean_ctx_codex_hook_entries,
215 };
216 use serde_json::json;
217
218 fn data_dir_pairs() -> Vec<(String, String)> {
221 vec![(
222 "LEAN_CTX_DATA_DIR".to_string(),
223 "/Users/user/.lean-ctx".to_string(),
224 )]
225 }
226
227 #[test]
228 fn upsert_replaces_legacy_codex_rewrite_but_keeps_custom_hooks() {
229 let mut input = json!({
230 "hooks": {
231 "PreToolUse": [
232 {
233 "matcher": "Bash",
234 "hooks": [{
235 "type": "command",
236 "command": "/opt/homebrew/bin/lean-ctx hook rewrite",
237 "timeout": 15
238 }]
239 },
240 {
241 "matcher": "Bash",
242 "hooks": [{
243 "type": "command",
244 "command": "echo keep-me",
245 "timeout": 5
246 }]
247 }
248 ],
249 "SessionStart": [
250 {
251 "matcher": "startup|resume|clear",
252 "hooks": [{
253 "type": "command",
254 "command": "lean-ctx hook codex-session-start",
255 "timeout": 15
256 }]
257 }
258 ],
259 "PostToolUse": [
260 {
261 "matcher": "Bash",
262 "hooks": [{
263 "type": "command",
264 "command": "echo keep-post",
265 "timeout": 5
266 }]
267 }
268 ]
269 }
270 });
271
272 let changed = upsert_lean_ctx_codex_hook_entries(
273 &mut input,
274 "lean-ctx hook codex-session-start",
275 "lean-ctx hook codex-pretooluse",
276 );
277 assert!(changed, "legacy hooks should be migrated");
278
279 let pre_tool_use = input["hooks"]["PreToolUse"]
280 .as_array()
281 .expect("PreToolUse array should remain");
282 assert_eq!(pre_tool_use.len(), 2, "custom hook should be preserved");
283 assert_eq!(
284 pre_tool_use[0]["hooks"][0]["command"].as_str(),
285 Some("echo keep-me")
286 );
287 assert_eq!(
288 pre_tool_use[1]["hooks"][0]["command"].as_str(),
289 Some("lean-ctx hook codex-pretooluse")
290 );
291 assert_eq!(
292 input["hooks"]["SessionStart"][0]["hooks"][0]["command"].as_str(),
293 Some("lean-ctx hook codex-session-start")
294 );
295 assert_eq!(
296 input["hooks"]["PostToolUse"][0]["hooks"][0]["command"].as_str(),
297 Some("echo keep-post")
298 );
299 }
300
301 #[test]
302 fn ignores_non_lean_ctx_codex_entries() {
303 let custom = json!({
304 "matcher": "Bash",
305 "hooks": [{
306 "type": "command",
307 "command": "echo keep-me",
308 "timeout": 5
309 }]
310 });
311 assert!(
312 !crate::hooks::support::is_lean_ctx_codex_managed_entry("PreToolUse", &custom),
313 "custom Codex hooks must be preserved"
314 );
315 }
316
317 #[test]
318 fn detects_managed_codex_session_start_entry() {
319 let managed = json!({
320 "matcher": "startup|resume|clear",
321 "hooks": [{
322 "type": "command",
323 "command": "/opt/homebrew/bin/lean-ctx hook codex-session-start",
324 "timeout": 15
325 }]
326 });
327 assert!(crate::hooks::support::is_lean_ctx_codex_managed_entry(
328 "SessionStart",
329 &managed
330 ));
331 }
332
333 #[test]
334 fn ensure_codex_hooks_enabled_updates_existing_features_flag() {
335 let input = "\
336[features]
337other = true
338codex_hooks = false
339
340[mcp_servers.other]
341command = \"other\"
342";
343
344 let output =
345 ensure_codex_hooks_enabled(input).expect("codex_hooks=false should be migrated");
346
347 assert!(output.contains("[features]\nother = true\nhooks = true\n"));
348 assert!(!output.contains("codex_hooks = false"));
349 }
350
351 #[test]
352 fn ensure_codex_hooks_enabled_moves_stray_assignment_into_features_section() {
353 let input = "\
354[features]
355other = true
356
357[mcp_servers.lean-ctx]
358command = \"lean-ctx\"
359codex_hooks = true
360";
361
362 let output = ensure_codex_hooks_enabled(input)
363 .expect("stray codex_hooks assignment should be normalized");
364
365 assert!(output.contains("[features]\nother = true\nhooks = true\n"));
366 assert_eq!(output.matches("hooks = true").count(), 1);
367 assert!(!output.contains("[mcp_servers.lean-ctx]\ncommand = \"lean-ctx\"\nhooks = true"));
368 }
369
370 #[test]
371 fn ensure_codex_hooks_enabled_adds_features_section_when_missing() {
372 let input = "\
373[mcp_servers.lean-ctx]
374command = \"lean-ctx\"
375";
376
377 let output =
378 ensure_codex_hooks_enabled(input).expect("missing features section should be added");
379
380 assert!(output.ends_with("\n[features]\nhooks = true\n"));
381 }
382
383 #[test]
384 fn codex_docs_steer_to_reliable_mcp_path_without_false_hook_claim() {
385 let tmp = std::env::temp_dir().join("lean-ctx-test-codex-desktop-note");
386 let _ = std::fs::remove_dir_all(&tmp);
387 std::fs::create_dir_all(&tmp).unwrap();
388
389 crate::hooks::support::install_codex_instruction_docs(&tmp);
390
391 let lean_ctx_md = std::fs::read_to_string(tmp.join("LEAN-CTX.md")).unwrap();
392 assert!(
393 lean_ctx_md.contains("ctx_shell") && lean_ctx_md.contains("ctx_read"),
394 "LEAN-CTX.md must steer the agent to the MCP tools"
395 );
396 let normalized = lean_ctx_md.replace('\n', " ");
399 assert!(
400 !normalized.contains("hooks do not run")
401 && !normalized.contains("no automatic compression"),
402 "LEAN-CTX.md must not make the false blanket claim that Codex Desktop hooks never run (#350)"
403 );
404
405 let agents_md = std::fs::read_to_string(tmp.join("AGENTS.md")).unwrap();
406 assert!(
407 agents_md.contains("ctx_shell") && agents_md.contains("ctx_search"),
408 "AGENTS.md block must steer to the reliable MCP tools"
409 );
410 let agents_norm = agents_md.replace('\n', " ");
411 assert!(
412 !agents_norm.contains("hooks do not run"),
413 "AGENTS.md must not claim Codex hooks never run (#350)"
414 );
415
416 let _ = std::fs::remove_dir_all(&tmp);
417 }
418
419 #[test]
420 fn install_codex_docs_preserves_existing_user_instructions() {
421 let tmp = std::env::temp_dir().join("lean-ctx-test-codex-preserve");
422 let _ = std::fs::remove_dir_all(&tmp);
423 std::fs::create_dir_all(&tmp).unwrap();
424
425 let agents_md = tmp.join("AGENTS.md");
426 let user_content = "# My Custom Instructions\n\nDo not change my codebase style.\n\n## Rules\n- Always use tabs\n- No semicolons\n";
427 std::fs::write(&agents_md, user_content).unwrap();
428
429 crate::hooks::support::install_codex_instruction_docs(&tmp);
430
431 let result = std::fs::read_to_string(&agents_md).unwrap();
432 assert!(
433 result.contains("My Custom Instructions"),
434 "user content must be preserved"
435 );
436 assert!(
437 result.contains("Always use tabs"),
438 "user rules must be preserved"
439 );
440 assert!(
441 result.contains(crate::core::rules_canonical::AGENTS_BLOCK_START),
442 "lean-ctx block must be appended"
443 );
444 let expected_ref = tmp.join("LEAN-CTX.md").display().to_string();
445 assert!(
446 result.contains(&expected_ref),
447 "lean-ctx reference must use codex_dir path"
448 );
449
450 let _ = std::fs::remove_dir_all(&tmp);
451 }
452
453 #[test]
454 fn install_codex_docs_updates_only_marked_block() {
455 let tmp = std::env::temp_dir().join("lean-ctx-test-codex-marked");
456 let _ = std::fs::remove_dir_all(&tmp);
457 std::fs::create_dir_all(&tmp).unwrap();
458
459 let agents_md = tmp.join("AGENTS.md");
460 let content_with_block = format!(
461 "# My Instructions\n\nCustom rule here.\n\n{}\n## lean-ctx\n\n@OLD-LEAN-CTX.md\n{}\n\n## Other Section\nKeep this.\n",
462 crate::core::rules_canonical::AGENTS_BLOCK_START,
463 crate::core::rules_canonical::AGENTS_BLOCK_END,
464 );
465 std::fs::write(&agents_md, content_with_block).unwrap();
466
467 crate::hooks::support::install_codex_instruction_docs(&tmp);
468
469 let result = std::fs::read_to_string(&agents_md).unwrap();
470 assert!(
471 result.contains("Custom rule here."),
472 "user content before block preserved"
473 );
474 assert!(
475 result.contains("Other Section"),
476 "user content after block preserved"
477 );
478 let expected_ref = tmp.join("LEAN-CTX.md").display().to_string();
479 assert!(
480 result.contains(&expected_ref),
481 "block updated to current reference"
482 );
483 assert!(
484 !result.contains("OLD-LEAN-CTX"),
485 "old block content replaced"
486 );
487
488 let _ = std::fs::remove_dir_all(&tmp);
489 }
490
491 #[test]
492 fn ensure_mcp_server_adds_section_when_missing() {
493 let input = "[features]\ncodex_hooks = true\n";
494 let result = ensure_codex_mcp_server(input, "lean-ctx", &data_dir_pairs())
495 .expect("should add MCP section");
496 assert!(result.contains("[mcp_servers.lean-ctx]"));
497 assert!(result.contains("command = \"lean-ctx\""));
498 assert!(result.contains("args = []"));
499 assert!(result.contains("[features]\ncodex_hooks = true\n"));
500 }
501
502 #[test]
503 fn ensure_mcp_server_noop_when_already_complete() {
504 let input = "[mcp_servers.lean-ctx]\ncommand = \"lean-ctx\"\nargs = []\n\n\
507 [mcp_servers.lean-ctx.env]\nLEAN_CTX_DATA_DIR = \"/Users/user/.lean-ctx\"\n";
508 assert!(
509 ensure_codex_mcp_server(input, "lean-ctx", &data_dir_pairs()).is_none(),
510 "should not modify config when MCP section already has all keys"
511 );
512 }
513
514 #[test]
515 fn ensure_mcp_server_preserves_existing_sections() {
516 let input = "[mcp_servers.other]\ncommand = \"other\"\n";
517 let result = ensure_codex_mcp_server(input, "/usr/bin/lean-ctx", &data_dir_pairs())
518 .expect("should add lean-ctx section");
519 assert!(result.contains("[mcp_servers.other]"));
520 assert!(result.contains("[mcp_servers.lean-ctx]"));
521 assert!(result.contains("command = \"/usr/bin/lean-ctx\""));
522 }
523
524 #[test]
525 fn ensure_mcp_server_inserts_before_orphaned_env_subtable() {
526 let input = "\
527[mcp_servers.lean-ctx.env]
528LEAN_CTX_DATA_DIR = \"/Users/user/.lean-ctx\"
529";
530 let result = ensure_codex_mcp_server(input, "/usr/local/bin/lean-ctx", &data_dir_pairs())
531 .expect("should insert parent section before orphaned env");
532 let parent_pos = result
533 .find("[mcp_servers.lean-ctx]")
534 .expect("parent section must exist");
535 let env_pos = result
536 .find("[mcp_servers.lean-ctx.env]")
537 .expect("env sub-table must be preserved");
538 assert!(
539 parent_pos < env_pos,
540 "parent section must come before env sub-table"
541 );
542 assert!(result.contains("command = \"/usr/local/bin/lean-ctx\""));
543 assert!(result.contains("LEAN_CTX_DATA_DIR"));
544 assert_eq!(
545 result.matches("[mcp_servers.lean-ctx.env]").count(),
546 1,
547 "must not duplicate the env table (would be invalid TOML)"
548 );
549 }
550
551 #[test]
552 fn ensure_mcp_server_handles_issue_189_scenario() {
553 let input = "\
554source = \"/Users/user/.cache/codex-runtimes/codex-primary-runtime/plugins/openai-primary-runtime\"
555source_type = \"local\"
556
557[mcp_servers.lean-ctx.env]
558LEAN_CTX_DATA_DIR = \"/Users/user/.lean-ctx\"
559";
560 let result = ensure_codex_mcp_server(input, "/usr/local/bin/lean-ctx", &data_dir_pairs())
561 .expect("should fix orphaned config from issue #189");
562 assert!(result.contains("[mcp_servers.lean-ctx]\n"));
563 assert!(result.contains("command = \"/usr/local/bin/lean-ctx\""));
564 assert!(result.contains("[mcp_servers.lean-ctx.env]"));
565 assert!(result.contains("LEAN_CTX_DATA_DIR"));
566
567 let parent_pos = result.find("[mcp_servers.lean-ctx]\n").unwrap();
568 let env_pos = result.find("[mcp_servers.lean-ctx.env]").unwrap();
569 assert!(parent_pos < env_pos);
570 assert_eq!(
571 result.matches("[mcp_servers.lean-ctx.env]").count(),
572 1,
573 "issue #189 fix must merge into one env table, not duplicate it"
574 );
575 assert!(result.contains("source_type = \"local\""));
577 }
578
579 #[test]
580 fn ensure_mcp_server_quotes_windows_backslash_paths() {
581 let input = "[features]\ncodex_hooks = true\n";
582 let win_path = r"C:\Users\Foo\AppData\Roaming\npm\lean-ctx.cmd";
583 let result = ensure_codex_mcp_server(input, win_path, &data_dir_pairs())
584 .expect("should add MCP section");
585 let doc = result
588 .parse::<toml_edit::DocumentMut>()
589 .expect("output must be valid TOML");
590 assert_eq!(
591 doc["mcp_servers"]["lean-ctx"]["command"].as_str(),
592 Some(win_path),
593 "Windows backslash path must round-trip exactly: {result}"
594 );
595 }
596
597 #[test]
598 fn ensure_mcp_server_does_not_match_similarly_named_section() {
599 let input = "\
600[mcp_servers.lean-ctx-other]
601command = \"other\"
602";
603 let result = ensure_codex_mcp_server(input, "lean-ctx", &data_dir_pairs())
604 .expect("should add lean-ctx section despite similarly-named section");
605 assert!(result.contains("[mcp_servers.lean-ctx]\n"));
606 assert!(result.contains("[mcp_servers.lean-ctx-other]"));
607 }
608
609 #[test]
610 fn ensure_mcp_server_writes_project_and_extra_roots() {
611 let pairs = vec![
615 (
616 "LEAN_CTX_DATA_DIR".to_string(),
617 "/home/u/.lean-ctx".to_string(),
618 ),
619 (
620 "LEAN_CTX_PROJECT_ROOT".to_string(),
621 "/work/main".to_string(),
622 ),
623 (
624 "LEAN_CTX_EXTRA_ROOTS".to_string(),
625 "/work/wt-a:/work/wt-b".to_string(),
626 ),
627 ];
628 let result =
629 ensure_codex_mcp_server("", "lean-ctx", &pairs).expect("fresh config must be created");
630
631 let doc = result
632 .parse::<toml_edit::DocumentMut>()
633 .expect("output must be valid TOML");
634 let env = &doc["mcp_servers"]["lean-ctx"]["env"];
635 assert_eq!(env["LEAN_CTX_PROJECT_ROOT"].as_str(), Some("/work/main"));
636 assert_eq!(
637 env["LEAN_CTX_EXTRA_ROOTS"].as_str(),
638 Some("/work/wt-a:/work/wt-b")
639 );
640 assert_eq!(env["LEAN_CTX_DATA_DIR"].as_str(), Some("/home/u/.lean-ctx"));
641 }
642
643 #[test]
644 fn ensure_mcp_server_upserts_missing_keys_into_existing_env() {
645 let input = "[mcp_servers.lean-ctx]\ncommand = \"lean-ctx\"\nargs = []\n\n\
648 [mcp_servers.lean-ctx.env]\nLEAN_CTX_DATA_DIR = \"/home/u/.lean-ctx\"\n";
649 let pairs = vec![
650 (
651 "LEAN_CTX_DATA_DIR".to_string(),
652 "/home/u/.lean-ctx".to_string(),
653 ),
654 (
655 "LEAN_CTX_PROJECT_ROOT".to_string(),
656 "/work/main".to_string(),
657 ),
658 ];
659
660 let result = ensure_codex_mcp_server(input, "lean-ctx", &pairs)
661 .expect("should upsert the missing project root");
662 assert_eq!(
663 result.matches("[mcp_servers.lean-ctx]").count(),
664 1,
665 "must not duplicate the parent section"
666 );
667 let doc = result
668 .parse::<toml_edit::DocumentMut>()
669 .expect("output must be valid TOML");
670 assert_eq!(
671 doc["mcp_servers"]["lean-ctx"]["env"]["LEAN_CTX_PROJECT_ROOT"].as_str(),
672 Some("/work/main")
673 );
674
675 assert!(
677 ensure_codex_mcp_server(&result, "lean-ctx", &pairs).is_none(),
678 "upsert must be idempotent"
679 );
680 }
681}