Skip to main content

lean_ctx/hooks/agents/
codex.rs

1use super::super::{
2    ensure_codex_hooks_enabled as shared_ensure_codex_hooks_enabled,
3    install_codex_instruction_docs, mcp_server_quiet_mode, resolve_binary_path,
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    let _ = std::fs::create_dir_all(&codex_dir);
13
14    let hook_config_changed = install_codex_hook_config(&codex_dir);
15    let installed_docs = install_codex_instruction_docs(&codex_dir);
16
17    if !mcp_server_quiet_mode() {
18        if hook_config_changed {
19            eprintln!(
20                "Installed Codex-compatible SessionStart/PreToolUse hooks at {}",
21                codex_dir.display()
22            );
23        }
24        if installed_docs {
25            eprintln!("Installed Codex instructions at {}", codex_dir.display());
26        } else {
27            eprintln!("Codex AGENTS.md already configured.");
28        }
29    }
30}
31
32fn install_codex_hook_config(codex_dir: &std::path::Path) -> bool {
33    let binary = resolve_binary_path();
34    let session_start_cmd = format!("{binary} hook codex-session-start");
35    let pre_tool_use_cmd = format!("{binary} hook codex-pretooluse");
36    let hooks_json_path = codex_dir.join("hooks.json");
37
38    let mut changed = false;
39    let mut root = if hooks_json_path.exists() {
40        if let Some(parsed) = std::fs::read_to_string(&hooks_json_path)
41            .ok()
42            .and_then(|content| crate::core::jsonc::parse_jsonc(&content).ok())
43        {
44            parsed
45        } else {
46            changed = true;
47            serde_json::json!({ "hooks": {} })
48        }
49    } else {
50        changed = true;
51        serde_json::json!({ "hooks": {} })
52    };
53
54    if upsert_lean_ctx_codex_hook_entries(&mut root, &session_start_cmd, &pre_tool_use_cmd) {
55        changed = true;
56    }
57    if changed {
58        write_file(
59            &hooks_json_path,
60            &serde_json::to_string_pretty(&root).unwrap_or_default(),
61        );
62    }
63
64    let rewrite_path = codex_dir.join("hooks").join("lean-ctx-rewrite-codex.sh");
65    if rewrite_path.exists() && std::fs::remove_file(&rewrite_path).is_ok() {
66        changed = true;
67    }
68
69    let config_toml_path = codex_dir.join("config.toml");
70    let config_content = std::fs::read_to_string(&config_toml_path).unwrap_or_default();
71
72    // Hybrid mode: ensure MCP server entry exists in config.toml so Codex
73    // Desktop/Cloud can reach lean-ctx even without CLI hooks.
74    let mcp_updated = ensure_codex_mcp_server(&config_content, &binary);
75    let hooks_updated =
76        ensure_codex_hooks_enabled(mcp_updated.as_deref().unwrap_or(&config_content));
77
78    let final_content = hooks_updated
79        .or(mcp_updated)
80        .unwrap_or_else(|| config_content.clone());
81    if final_content != config_content {
82        write_file(&config_toml_path, &final_content);
83        changed = true;
84        if !mcp_server_quiet_mode() {
85            eprintln!(
86                "Updated Codex config (MCP server + hooks) in {}",
87                config_toml_path.display()
88            );
89        }
90    }
91
92    changed
93}
94
95fn toml_quote_value(value: &str) -> String {
96    if value.contains('\\') {
97        format!("'{value}'")
98    } else {
99        format!("\"{value}\"")
100    }
101}
102
103fn ensure_codex_mcp_server(config_content: &str, binary: &str) -> Option<String> {
104    if config_content.contains("[mcp_servers.lean-ctx]") {
105        return None;
106    }
107
108    let quoted = toml_quote_value(binary);
109    let section = format!("[mcp_servers.lean-ctx]\ncommand = {quoted}\nargs = []\n");
110
111    if let Some(pos) = config_content.find("[mcp_servers.lean-ctx.") {
112        let insert_at = config_content[..pos].rfind('\n').map_or(0, |nl| nl + 1);
113        let mut out = String::with_capacity(config_content.len() + section.len() + 2);
114        out.push_str(&config_content[..insert_at]);
115        out.push_str(&section);
116        out.push('\n');
117        out.push_str(&config_content[insert_at..]);
118        return Some(out);
119    }
120
121    let mut out = config_content.to_string();
122    if !out.is_empty() && !out.ends_with('\n') {
123        out.push('\n');
124    }
125    out.push_str(&format!("\n{section}"));
126    Some(out)
127}
128
129fn ensure_codex_hooks_enabled(config_content: &str) -> Option<String> {
130    shared_ensure_codex_hooks_enabled(config_content)
131}
132
133#[cfg(test)]
134mod tests {
135    use super::{
136        ensure_codex_hooks_enabled, ensure_codex_mcp_server, upsert_lean_ctx_codex_hook_entries,
137    };
138    use serde_json::json;
139
140    #[test]
141    fn upsert_replaces_legacy_codex_rewrite_but_keeps_custom_hooks() {
142        let mut input = json!({
143            "hooks": {
144                "PreToolUse": [
145                    {
146                        "matcher": "Bash",
147                        "hooks": [{
148                            "type": "command",
149                            "command": "/opt/homebrew/bin/lean-ctx hook rewrite",
150                            "timeout": 15
151                        }]
152                    },
153                    {
154                        "matcher": "Bash",
155                        "hooks": [{
156                            "type": "command",
157                            "command": "echo keep-me",
158                            "timeout": 5
159                        }]
160                    }
161                ],
162                "SessionStart": [
163                    {
164                        "matcher": "startup|resume|clear",
165                        "hooks": [{
166                            "type": "command",
167                            "command": "lean-ctx hook codex-session-start",
168                            "timeout": 15
169                        }]
170                    }
171                ],
172                "PostToolUse": [
173                    {
174                        "matcher": "Bash",
175                        "hooks": [{
176                            "type": "command",
177                            "command": "echo keep-post",
178                            "timeout": 5
179                        }]
180                    }
181                ]
182            }
183        });
184
185        let changed = upsert_lean_ctx_codex_hook_entries(
186            &mut input,
187            "lean-ctx hook codex-session-start",
188            "lean-ctx hook codex-pretooluse",
189        );
190        assert!(changed, "legacy hooks should be migrated");
191
192        let pre_tool_use = input["hooks"]["PreToolUse"]
193            .as_array()
194            .expect("PreToolUse array should remain");
195        assert_eq!(pre_tool_use.len(), 2, "custom hook should be preserved");
196        assert_eq!(
197            pre_tool_use[0]["hooks"][0]["command"].as_str(),
198            Some("echo keep-me")
199        );
200        assert_eq!(
201            pre_tool_use[1]["hooks"][0]["command"].as_str(),
202            Some("lean-ctx hook codex-pretooluse")
203        );
204        assert_eq!(
205            input["hooks"]["SessionStart"][0]["hooks"][0]["command"].as_str(),
206            Some("lean-ctx hook codex-session-start")
207        );
208        assert_eq!(
209            input["hooks"]["PostToolUse"][0]["hooks"][0]["command"].as_str(),
210            Some("echo keep-post")
211        );
212    }
213
214    #[test]
215    fn ignores_non_lean_ctx_codex_entries() {
216        let custom = json!({
217            "matcher": "Bash",
218            "hooks": [{
219                "type": "command",
220                "command": "echo keep-me",
221                "timeout": 5
222            }]
223        });
224        assert!(
225            !crate::hooks::support::is_lean_ctx_codex_managed_entry("PreToolUse", &custom),
226            "custom Codex hooks must be preserved"
227        );
228    }
229
230    #[test]
231    fn detects_managed_codex_session_start_entry() {
232        let managed = json!({
233            "matcher": "startup|resume|clear",
234            "hooks": [{
235                "type": "command",
236                "command": "/opt/homebrew/bin/lean-ctx hook codex-session-start",
237                "timeout": 15
238            }]
239        });
240        assert!(crate::hooks::support::is_lean_ctx_codex_managed_entry(
241            "SessionStart",
242            &managed
243        ));
244    }
245
246    #[test]
247    fn ensure_codex_hooks_enabled_updates_existing_features_flag() {
248        let input = "\
249[features]
250other = true
251codex_hooks = false
252
253[mcp_servers.other]
254command = \"other\"
255";
256
257        let output =
258            ensure_codex_hooks_enabled(input).expect("codex_hooks=false should be migrated");
259
260        assert!(output.contains("[features]\nother = true\nhooks = true\n"));
261        assert!(!output.contains("codex_hooks = false"));
262    }
263
264    #[test]
265    fn ensure_codex_hooks_enabled_moves_stray_assignment_into_features_section() {
266        let input = "\
267[features]
268other = true
269
270[mcp_servers.lean-ctx]
271command = \"lean-ctx\"
272codex_hooks = true
273";
274
275        let output = ensure_codex_hooks_enabled(input)
276            .expect("stray codex_hooks assignment should be normalized");
277
278        assert!(output.contains("[features]\nother = true\nhooks = true\n"));
279        assert_eq!(output.matches("hooks = true").count(), 1);
280        assert!(!output.contains("[mcp_servers.lean-ctx]\ncommand = \"lean-ctx\"\nhooks = true"));
281    }
282
283    #[test]
284    fn ensure_codex_hooks_enabled_adds_features_section_when_missing() {
285        let input = "\
286[mcp_servers.lean-ctx]
287command = \"lean-ctx\"
288";
289
290        let output =
291            ensure_codex_hooks_enabled(input).expect("missing features section should be added");
292
293        assert!(output.ends_with("\n[features]\nhooks = true\n"));
294    }
295
296    #[test]
297    fn install_codex_docs_preserves_existing_user_instructions() {
298        let tmp = std::env::temp_dir().join("lean-ctx-test-codex-preserve");
299        let _ = std::fs::remove_dir_all(&tmp);
300        std::fs::create_dir_all(&tmp).unwrap();
301
302        let agents_md = tmp.join("AGENTS.md");
303        let user_content = "# My Custom Instructions\n\nDo not change my codebase style.\n\n## Rules\n- Always use tabs\n- No semicolons\n";
304        std::fs::write(&agents_md, user_content).unwrap();
305
306        crate::hooks::support::install_codex_instruction_docs(&tmp);
307
308        let result = std::fs::read_to_string(&agents_md).unwrap();
309        assert!(
310            result.contains("My Custom Instructions"),
311            "user content must be preserved"
312        );
313        assert!(
314            result.contains("Always use tabs"),
315            "user rules must be preserved"
316        );
317        assert!(
318            result.contains("<!-- lean-ctx -->"),
319            "lean-ctx block must be appended"
320        );
321        let expected_ref = tmp.join("LEAN-CTX.md").display().to_string();
322        assert!(
323            result.contains(&expected_ref),
324            "lean-ctx reference must use codex_dir path"
325        );
326
327        let _ = std::fs::remove_dir_all(&tmp);
328    }
329
330    #[test]
331    fn install_codex_docs_updates_only_marked_block() {
332        let tmp = std::env::temp_dir().join("lean-ctx-test-codex-marked");
333        let _ = std::fs::remove_dir_all(&tmp);
334        std::fs::create_dir_all(&tmp).unwrap();
335
336        let agents_md = tmp.join("AGENTS.md");
337        let content_with_block = "# My Instructions\n\nCustom rule here.\n\n<!-- lean-ctx -->\n## lean-ctx\n\n@OLD-LEAN-CTX.md\n<!-- /lean-ctx -->\n\n## Other Section\nKeep this.\n";
338        std::fs::write(&agents_md, content_with_block).unwrap();
339
340        crate::hooks::support::install_codex_instruction_docs(&tmp);
341
342        let result = std::fs::read_to_string(&agents_md).unwrap();
343        assert!(
344            result.contains("Custom rule here."),
345            "user content before block preserved"
346        );
347        assert!(
348            result.contains("Other Section"),
349            "user content after block preserved"
350        );
351        let expected_ref = tmp.join("LEAN-CTX.md").display().to_string();
352        assert!(
353            result.contains(&expected_ref),
354            "block updated to current reference"
355        );
356        assert!(
357            !result.contains("OLD-LEAN-CTX"),
358            "old block content replaced"
359        );
360
361        let _ = std::fs::remove_dir_all(&tmp);
362    }
363
364    #[test]
365    fn ensure_mcp_server_adds_section_when_missing() {
366        let input = "[features]\ncodex_hooks = true\n";
367        let result = ensure_codex_mcp_server(input, "lean-ctx").expect("should add MCP section");
368        assert!(result.contains("[mcp_servers.lean-ctx]"));
369        assert!(result.contains("command = \"lean-ctx\""));
370        assert!(result.contains("args = []"));
371        assert!(result.contains("[features]\ncodex_hooks = true\n"));
372    }
373
374    #[test]
375    fn ensure_mcp_server_noop_when_present() {
376        let input = "[mcp_servers.lean-ctx]\ncommand = \"lean-ctx\"\nargs = []\n";
377        assert!(
378            ensure_codex_mcp_server(input, "lean-ctx").is_none(),
379            "should not modify config when MCP section already exists"
380        );
381    }
382
383    #[test]
384    fn ensure_mcp_server_preserves_existing_sections() {
385        let input = "[mcp_servers.other]\ncommand = \"other\"\n";
386        let result = ensure_codex_mcp_server(input, "/usr/bin/lean-ctx")
387            .expect("should add lean-ctx section");
388        assert!(result.contains("[mcp_servers.other]"));
389        assert!(result.contains("[mcp_servers.lean-ctx]"));
390        assert!(result.contains("command = \"/usr/bin/lean-ctx\""));
391    }
392
393    #[test]
394    fn ensure_mcp_server_inserts_before_orphaned_env_subtable() {
395        let input = "\
396[mcp_servers.lean-ctx.env]
397LEAN_CTX_DATA_DIR = \"/Users/user/.lean-ctx\"
398";
399        let result = ensure_codex_mcp_server(input, "/usr/local/bin/lean-ctx")
400            .expect("should insert parent section before orphaned env");
401        let parent_pos = result
402            .find("[mcp_servers.lean-ctx]")
403            .expect("parent section must exist");
404        let env_pos = result
405            .find("[mcp_servers.lean-ctx.env]")
406            .expect("env sub-table must be preserved");
407        assert!(
408            parent_pos < env_pos,
409            "parent section must come before env sub-table"
410        );
411        assert!(result.contains("command = \"/usr/local/bin/lean-ctx\""));
412        assert!(result.contains("LEAN_CTX_DATA_DIR"));
413    }
414
415    #[test]
416    fn ensure_mcp_server_handles_issue_189_scenario() {
417        let input = "\
418source = \"/Users/user/.cache/codex-runtimes/codex-primary-runtime/plugins/openai-primary-runtime\"
419source_type = \"local\"
420
421[mcp_servers.lean-ctx.env]
422LEAN_CTX_DATA_DIR = \"/Users/user/.lean-ctx\"
423";
424        let result = ensure_codex_mcp_server(input, "/usr/local/bin/lean-ctx")
425            .expect("should fix orphaned config from issue #189");
426        assert!(result.contains("[mcp_servers.lean-ctx]\n"));
427        assert!(result.contains("command = \"/usr/local/bin/lean-ctx\""));
428        assert!(result.contains("[mcp_servers.lean-ctx.env]"));
429        assert!(result.contains("LEAN_CTX_DATA_DIR"));
430
431        let parent_pos = result.find("[mcp_servers.lean-ctx]\n").unwrap();
432        let env_pos = result.find("[mcp_servers.lean-ctx.env]").unwrap();
433        assert!(parent_pos < env_pos);
434    }
435
436    #[test]
437    fn ensure_mcp_server_quotes_windows_backslash_paths() {
438        let input = "[features]\ncodex_hooks = true\n";
439        let win_path = r"C:\Users\Foo\AppData\Roaming\npm\lean-ctx.cmd";
440        let result = ensure_codex_mcp_server(input, win_path).expect("should add MCP section");
441        assert!(
442            result.contains(&format!("command = '{win_path}'")),
443            "Windows paths must use TOML single quotes: {result}"
444        );
445    }
446
447    #[test]
448    fn ensure_mcp_server_does_not_match_similarly_named_section() {
449        let input = "\
450[mcp_servers.lean-ctx-other]
451command = \"other\"
452";
453        let result = ensure_codex_mcp_server(input, "lean-ctx")
454            .expect("should add lean-ctx section despite similarly-named section");
455        assert!(result.contains("[mcp_servers.lean-ctx]\n"));
456        assert!(result.contains("[mcp_servers.lean-ctx-other]"));
457    }
458}