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)]
208mod tests {
209 use super::{
210 ensure_codex_hooks_enabled, ensure_codex_mcp_server, upsert_lean_ctx_codex_hook_entries,
211 };
212 use serde_json::json;
213
214 fn data_dir_pairs() -> Vec<(String, String)> {
217 vec![(
218 "LEAN_CTX_DATA_DIR".to_string(),
219 "/Users/user/.lean-ctx".to_string(),
220 )]
221 }
222
223 #[test]
224 fn upsert_replaces_legacy_codex_rewrite_but_keeps_custom_hooks() {
225 let mut input = json!({
226 "hooks": {
227 "PreToolUse": [
228 {
229 "matcher": "Bash",
230 "hooks": [{
231 "type": "command",
232 "command": "/opt/homebrew/bin/lean-ctx hook rewrite",
233 "timeout": 15
234 }]
235 },
236 {
237 "matcher": "Bash",
238 "hooks": [{
239 "type": "command",
240 "command": "echo keep-me",
241 "timeout": 5
242 }]
243 }
244 ],
245 "SessionStart": [
246 {
247 "matcher": "startup|resume|clear",
248 "hooks": [{
249 "type": "command",
250 "command": "lean-ctx hook codex-session-start",
251 "timeout": 15
252 }]
253 }
254 ],
255 "PostToolUse": [
256 {
257 "matcher": "Bash",
258 "hooks": [{
259 "type": "command",
260 "command": "echo keep-post",
261 "timeout": 5
262 }]
263 }
264 ]
265 }
266 });
267
268 let changed = upsert_lean_ctx_codex_hook_entries(
269 &mut input,
270 "lean-ctx hook codex-session-start",
271 "lean-ctx hook codex-pretooluse",
272 );
273 assert!(changed, "legacy hooks should be migrated");
274
275 let pre_tool_use = input["hooks"]["PreToolUse"]
276 .as_array()
277 .expect("PreToolUse array should remain");
278 assert_eq!(pre_tool_use.len(), 2, "custom hook should be preserved");
279 assert_eq!(
280 pre_tool_use[0]["hooks"][0]["command"].as_str(),
281 Some("echo keep-me")
282 );
283 assert_eq!(
284 pre_tool_use[1]["hooks"][0]["command"].as_str(),
285 Some("lean-ctx hook codex-pretooluse")
286 );
287 assert_eq!(
288 input["hooks"]["SessionStart"][0]["hooks"][0]["command"].as_str(),
289 Some("lean-ctx hook codex-session-start")
290 );
291 assert_eq!(
292 input["hooks"]["PostToolUse"][0]["hooks"][0]["command"].as_str(),
293 Some("echo keep-post")
294 );
295 }
296
297 #[test]
298 fn ignores_non_lean_ctx_codex_entries() {
299 let custom = json!({
300 "matcher": "Bash",
301 "hooks": [{
302 "type": "command",
303 "command": "echo keep-me",
304 "timeout": 5
305 }]
306 });
307 assert!(
308 !crate::hooks::support::is_lean_ctx_codex_managed_entry("PreToolUse", &custom),
309 "custom Codex hooks must be preserved"
310 );
311 }
312
313 #[test]
314 fn detects_managed_codex_session_start_entry() {
315 let managed = json!({
316 "matcher": "startup|resume|clear",
317 "hooks": [{
318 "type": "command",
319 "command": "/opt/homebrew/bin/lean-ctx hook codex-session-start",
320 "timeout": 15
321 }]
322 });
323 assert!(crate::hooks::support::is_lean_ctx_codex_managed_entry(
324 "SessionStart",
325 &managed
326 ));
327 }
328
329 #[test]
330 fn ensure_codex_hooks_enabled_updates_existing_features_flag() {
331 let input = "\
332[features]
333other = true
334codex_hooks = false
335
336[mcp_servers.other]
337command = \"other\"
338";
339
340 let output =
341 ensure_codex_hooks_enabled(input).expect("codex_hooks=false should be migrated");
342
343 assert!(output.contains("[features]\nother = true\nhooks = true\n"));
344 assert!(!output.contains("codex_hooks = false"));
345 }
346
347 #[test]
348 fn ensure_codex_hooks_enabled_moves_stray_assignment_into_features_section() {
349 let input = "\
350[features]
351other = true
352
353[mcp_servers.lean-ctx]
354command = \"lean-ctx\"
355codex_hooks = true
356";
357
358 let output = ensure_codex_hooks_enabled(input)
359 .expect("stray codex_hooks assignment should be normalized");
360
361 assert!(output.contains("[features]\nother = true\nhooks = true\n"));
362 assert_eq!(output.matches("hooks = true").count(), 1);
363 assert!(!output.contains("[mcp_servers.lean-ctx]\ncommand = \"lean-ctx\"\nhooks = true"));
364 }
365
366 #[test]
367 fn ensure_codex_hooks_enabled_adds_features_section_when_missing() {
368 let input = "\
369[mcp_servers.lean-ctx]
370command = \"lean-ctx\"
371";
372
373 let output =
374 ensure_codex_hooks_enabled(input).expect("missing features section should be added");
375
376 assert!(output.ends_with("\n[features]\nhooks = true\n"));
377 }
378
379 #[test]
380 fn codex_docs_steer_to_reliable_mcp_path_without_false_hook_claim() {
381 let tmp = std::env::temp_dir().join("lean-ctx-test-codex-desktop-note");
382 let _ = std::fs::remove_dir_all(&tmp);
383 std::fs::create_dir_all(&tmp).unwrap();
384
385 crate::hooks::support::install_codex_instruction_docs(&tmp);
386
387 let lean_ctx_md = std::fs::read_to_string(tmp.join("LEAN-CTX.md")).unwrap();
388 assert!(
389 lean_ctx_md.contains("ctx_shell") && lean_ctx_md.contains("ctx_read"),
390 "LEAN-CTX.md must steer the agent to the MCP tools"
391 );
392 let normalized = lean_ctx_md.replace('\n', " ");
395 assert!(
396 !normalized.contains("hooks do not run")
397 && !normalized.contains("no automatic compression"),
398 "LEAN-CTX.md must not make the false blanket claim that Codex Desktop hooks never run (#350)"
399 );
400
401 let agents_md = std::fs::read_to_string(tmp.join("AGENTS.md")).unwrap();
402 assert!(
403 agents_md.contains("ctx_shell") && agents_md.contains("ctx_search"),
404 "AGENTS.md block must steer to the reliable MCP tools"
405 );
406 let agents_norm = agents_md.replace('\n', " ");
407 assert!(
408 !agents_norm.contains("hooks do not run"),
409 "AGENTS.md must not claim Codex hooks never run (#350)"
410 );
411
412 let _ = std::fs::remove_dir_all(&tmp);
413 }
414
415 #[test]
416 fn install_codex_docs_preserves_existing_user_instructions() {
417 let tmp = std::env::temp_dir().join("lean-ctx-test-codex-preserve");
418 let _ = std::fs::remove_dir_all(&tmp);
419 std::fs::create_dir_all(&tmp).unwrap();
420
421 let agents_md = tmp.join("AGENTS.md");
422 let user_content = "# My Custom Instructions\n\nDo not change my codebase style.\n\n## Rules\n- Always use tabs\n- No semicolons\n";
423 std::fs::write(&agents_md, user_content).unwrap();
424
425 crate::hooks::support::install_codex_instruction_docs(&tmp);
426
427 let result = std::fs::read_to_string(&agents_md).unwrap();
428 assert!(
429 result.contains("My Custom Instructions"),
430 "user content must be preserved"
431 );
432 assert!(
433 result.contains("Always use tabs"),
434 "user rules must be preserved"
435 );
436 assert!(
437 result.contains(crate::core::rules_canonical::AGENTS_BLOCK_START),
438 "lean-ctx block must be appended"
439 );
440 let expected_ref = tmp.join("LEAN-CTX.md").display().to_string();
441 assert!(
442 result.contains(&expected_ref),
443 "lean-ctx reference must use codex_dir path"
444 );
445
446 let _ = std::fs::remove_dir_all(&tmp);
447 }
448
449 #[test]
450 fn install_codex_docs_updates_only_marked_block() {
451 let tmp = std::env::temp_dir().join("lean-ctx-test-codex-marked");
452 let _ = std::fs::remove_dir_all(&tmp);
453 std::fs::create_dir_all(&tmp).unwrap();
454
455 let agents_md = tmp.join("AGENTS.md");
456 let content_with_block = format!(
457 "# 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",
458 crate::core::rules_canonical::AGENTS_BLOCK_START,
459 crate::core::rules_canonical::AGENTS_BLOCK_END,
460 );
461 std::fs::write(&agents_md, content_with_block).unwrap();
462
463 crate::hooks::support::install_codex_instruction_docs(&tmp);
464
465 let result = std::fs::read_to_string(&agents_md).unwrap();
466 assert!(
467 result.contains("Custom rule here."),
468 "user content before block preserved"
469 );
470 assert!(
471 result.contains("Other Section"),
472 "user content after block preserved"
473 );
474 let expected_ref = tmp.join("LEAN-CTX.md").display().to_string();
475 assert!(
476 result.contains(&expected_ref),
477 "block updated to current reference"
478 );
479 assert!(
480 !result.contains("OLD-LEAN-CTX"),
481 "old block content replaced"
482 );
483
484 let _ = std::fs::remove_dir_all(&tmp);
485 }
486
487 #[test]
488 fn ensure_mcp_server_adds_section_when_missing() {
489 let input = "[features]\ncodex_hooks = true\n";
490 let result = ensure_codex_mcp_server(input, "lean-ctx", &data_dir_pairs())
491 .expect("should add MCP section");
492 assert!(result.contains("[mcp_servers.lean-ctx]"));
493 assert!(result.contains("command = \"lean-ctx\""));
494 assert!(result.contains("args = []"));
495 assert!(result.contains("[features]\ncodex_hooks = true\n"));
496 }
497
498 #[test]
499 fn ensure_mcp_server_noop_when_already_complete() {
500 let input = "[mcp_servers.lean-ctx]\ncommand = \"lean-ctx\"\nargs = []\n\n\
503 [mcp_servers.lean-ctx.env]\nLEAN_CTX_DATA_DIR = \"/Users/user/.lean-ctx\"\n";
504 assert!(
505 ensure_codex_mcp_server(input, "lean-ctx", &data_dir_pairs()).is_none(),
506 "should not modify config when MCP section already has all keys"
507 );
508 }
509
510 #[test]
511 fn ensure_mcp_server_preserves_existing_sections() {
512 let input = "[mcp_servers.other]\ncommand = \"other\"\n";
513 let result = ensure_codex_mcp_server(input, "/usr/bin/lean-ctx", &data_dir_pairs())
514 .expect("should add lean-ctx section");
515 assert!(result.contains("[mcp_servers.other]"));
516 assert!(result.contains("[mcp_servers.lean-ctx]"));
517 assert!(result.contains("command = \"/usr/bin/lean-ctx\""));
518 }
519
520 #[test]
521 fn ensure_mcp_server_inserts_before_orphaned_env_subtable() {
522 let input = "\
523[mcp_servers.lean-ctx.env]
524LEAN_CTX_DATA_DIR = \"/Users/user/.lean-ctx\"
525";
526 let result = ensure_codex_mcp_server(input, "/usr/local/bin/lean-ctx", &data_dir_pairs())
527 .expect("should insert parent section before orphaned env");
528 let parent_pos = result
529 .find("[mcp_servers.lean-ctx]")
530 .expect("parent section must exist");
531 let env_pos = result
532 .find("[mcp_servers.lean-ctx.env]")
533 .expect("env sub-table must be preserved");
534 assert!(
535 parent_pos < env_pos,
536 "parent section must come before env sub-table"
537 );
538 assert!(result.contains("command = \"/usr/local/bin/lean-ctx\""));
539 assert!(result.contains("LEAN_CTX_DATA_DIR"));
540 assert_eq!(
541 result.matches("[mcp_servers.lean-ctx.env]").count(),
542 1,
543 "must not duplicate the env table (would be invalid TOML)"
544 );
545 }
546
547 #[test]
548 fn ensure_mcp_server_handles_issue_189_scenario() {
549 let input = "\
550source = \"/Users/user/.cache/codex-runtimes/codex-primary-runtime/plugins/openai-primary-runtime\"
551source_type = \"local\"
552
553[mcp_servers.lean-ctx.env]
554LEAN_CTX_DATA_DIR = \"/Users/user/.lean-ctx\"
555";
556 let result = ensure_codex_mcp_server(input, "/usr/local/bin/lean-ctx", &data_dir_pairs())
557 .expect("should fix orphaned config from issue #189");
558 assert!(result.contains("[mcp_servers.lean-ctx]\n"));
559 assert!(result.contains("command = \"/usr/local/bin/lean-ctx\""));
560 assert!(result.contains("[mcp_servers.lean-ctx.env]"));
561 assert!(result.contains("LEAN_CTX_DATA_DIR"));
562
563 let parent_pos = result.find("[mcp_servers.lean-ctx]\n").unwrap();
564 let env_pos = result.find("[mcp_servers.lean-ctx.env]").unwrap();
565 assert!(parent_pos < env_pos);
566 assert_eq!(
567 result.matches("[mcp_servers.lean-ctx.env]").count(),
568 1,
569 "issue #189 fix must merge into one env table, not duplicate it"
570 );
571 assert!(result.contains("source_type = \"local\""));
573 }
574
575 #[test]
576 fn ensure_mcp_server_quotes_windows_backslash_paths() {
577 let input = "[features]\ncodex_hooks = true\n";
578 let win_path = r"C:\Users\Foo\AppData\Roaming\npm\lean-ctx.cmd";
579 let result = ensure_codex_mcp_server(input, win_path, &data_dir_pairs())
580 .expect("should add MCP section");
581 let doc = result
584 .parse::<toml_edit::DocumentMut>()
585 .expect("output must be valid TOML");
586 assert_eq!(
587 doc["mcp_servers"]["lean-ctx"]["command"].as_str(),
588 Some(win_path),
589 "Windows backslash path must round-trip exactly: {result}"
590 );
591 }
592
593 #[test]
594 fn ensure_mcp_server_does_not_match_similarly_named_section() {
595 let input = "\
596[mcp_servers.lean-ctx-other]
597command = \"other\"
598";
599 let result = ensure_codex_mcp_server(input, "lean-ctx", &data_dir_pairs())
600 .expect("should add lean-ctx section despite similarly-named section");
601 assert!(result.contains("[mcp_servers.lean-ctx]\n"));
602 assert!(result.contains("[mcp_servers.lean-ctx-other]"));
603 }
604
605 #[test]
606 fn ensure_mcp_server_writes_project_and_extra_roots() {
607 let pairs = vec![
611 (
612 "LEAN_CTX_DATA_DIR".to_string(),
613 "/home/u/.lean-ctx".to_string(),
614 ),
615 (
616 "LEAN_CTX_PROJECT_ROOT".to_string(),
617 "/work/main".to_string(),
618 ),
619 (
620 "LEAN_CTX_EXTRA_ROOTS".to_string(),
621 "/work/wt-a:/work/wt-b".to_string(),
622 ),
623 ];
624 let result =
625 ensure_codex_mcp_server("", "lean-ctx", &pairs).expect("fresh config must be created");
626
627 let doc = result
628 .parse::<toml_edit::DocumentMut>()
629 .expect("output must be valid TOML");
630 let env = &doc["mcp_servers"]["lean-ctx"]["env"];
631 assert_eq!(env["LEAN_CTX_PROJECT_ROOT"].as_str(), Some("/work/main"));
632 assert_eq!(
633 env["LEAN_CTX_EXTRA_ROOTS"].as_str(),
634 Some("/work/wt-a:/work/wt-b")
635 );
636 assert_eq!(env["LEAN_CTX_DATA_DIR"].as_str(), Some("/home/u/.lean-ctx"));
637 }
638
639 #[test]
640 fn ensure_mcp_server_upserts_missing_keys_into_existing_env() {
641 let input = "[mcp_servers.lean-ctx]\ncommand = \"lean-ctx\"\nargs = []\n\n\
644 [mcp_servers.lean-ctx.env]\nLEAN_CTX_DATA_DIR = \"/home/u/.lean-ctx\"\n";
645 let pairs = vec![
646 (
647 "LEAN_CTX_DATA_DIR".to_string(),
648 "/home/u/.lean-ctx".to_string(),
649 ),
650 (
651 "LEAN_CTX_PROJECT_ROOT".to_string(),
652 "/work/main".to_string(),
653 ),
654 ];
655
656 let result = ensure_codex_mcp_server(input, "lean-ctx", &pairs)
657 .expect("should upsert the missing project root");
658 assert_eq!(
659 result.matches("[mcp_servers.lean-ctx]").count(),
660 1,
661 "must not duplicate the parent section"
662 );
663 let doc = result
664 .parse::<toml_edit::DocumentMut>()
665 .expect("output must be valid TOML");
666 assert_eq!(
667 doc["mcp_servers"]["lean-ctx"]["env"]["LEAN_CTX_PROJECT_ROOT"].as_str(),
668 Some("/work/main")
669 );
670
671 assert!(
673 ensure_codex_mcp_server(&result, "lean-ctx", &pairs).is_none(),
674 "upsert must be idempotent"
675 );
676 }
677}