Skip to main content

lean_ctx_cli/cli/
init_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2use lean_ctx_hooks::hooks::to_bash_compatible_path;
3
4pub(crate) fn quiet_enabled() -> bool {
5    lean_ctx::core::runtime_flags::quiet_enabled()
6}
7
8macro_rules! qprintln {
9    ($($t:tt)*) => {
10        if !quiet_enabled() {
11            println!($($t)*);
12        }
13    };
14}
15
16pub fn cmd_init(args: &[String]) {
17    // Safety (#476 class, #1849): asking about init must never *run* it —
18    // `init --agent claude --help` used to write the agent's rules file. The
19    // guard sits here rather than in the dispatcher so every entry point
20    // (`cmd_init_quiet`, `doctor --fix`) inherits it.
21    if args.iter().any(|a| a == "--help" || a == "-h") {
22        print_init_help();
23        return;
24    }
25    // Opt-in value surfaces: each is its own step, never part of the alias setup.
26    if let Some(enable) = opt_in_flag(args, "--prompt") {
27        let binary = lean_ctx::core::portable_binary::stable_shell_binary(
28            &lean_ctx::core::portable_binary::resolve_portable_binary(),
29        );
30        super::prompt_init::cmd_init_prompt(enable, &binary);
31        return;
32    }
33    if let Some(enable) = opt_in_flag(args, "--git-trailer") {
34        super::git_trailer::cmd_init_git_trailer(enable);
35        return;
36    }
37    let global = args.iter().any(|a| a == "--global" || a == "-g");
38    let project = args.iter().any(|a| a == "--project");
39    let dry_run = args.iter().any(|a| a == "--dry-run");
40    let no_hook = args.iter().any(|a| a == "--no-shell-hook")
41        || lean_ctx::core::config::Config::load().shell_hook_disabled_effective();
42
43    let explicit_mode = args
44        .windows(2)
45        .find(|w| w[0] == "--mode")
46        .and_then(|w| lean_ctx_hooks::hooks::HookMode::from_str_loose(&w[1]));
47    let governor_arm = args.windows(2).find(|w| w[0] == "--mode").and_then(|w| {
48        lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm::from_mode(&w[1])
49    });
50
51    if args.windows(2).any(|w| w[0] == "--mode")
52        && explicit_mode.is_none()
53        && governor_arm.is_none()
54    {
55        let bad = args
56            .windows(2)
57            .find(|w| w[0] == "--mode")
58            .map_or("?", |w| w[1].as_str());
59        eprintln!(
60            "Unknown hook mode: '{bad}'. Valid: mcp, hybrid, replace, governor, governor-mcp"
61        );
62        std::process::exit(1);
63    }
64
65    let agents: Vec<&str> = args
66        .windows(2)
67        .filter(|w| w[0] == "--agent")
68        .map(|w| w[1].as_str())
69        .collect();
70
71    // `--dry-run` with `--agent` must write nothing: the agent and governor
72    // paths below run before the shell-hook dry run (reimplements community
73    // PR #2169 by ZacKienzle2).
74    if dry_run && !agents.is_empty() {
75        let mode = args
76            .windows(2)
77            .find(|w| w[0] == "--mode")
78            .map_or("default", |w| w[1].as_str());
79        qprintln!("\nlean-ctx init --dry-run\n");
80        qprintln!("  Would configure: {} (mode: {mode})", agents.join(", "));
81        qprintln!("\n  Run without --dry-run to apply.");
82        return;
83    }
84
85    if !agents.is_empty() {
86        // An explicit agent setup: an older build's silent refresh yields to it.
87        lean_ctx_hooks::hooks::setup_writer::record();
88    }
89    if let Some(arm) = governor_arm {
90        init_governor(&agents, arm);
91        return;
92    }
93    // An explicit standard mode is a pinned choice (no later update switches
94    // it to the governor) and switches a governor install back first.
95    if let Some(mode) = explicit_mode
96        && let Some(home) = lean_ctx::core::home::resolve_home_dir()
97    {
98        let mode = mode.to_string().to_ascii_lowercase();
99        for agent in &agents {
100            let Some(host) = lean_ctx_hooks::hooks::governor_default::host(agent) else {
101                continue;
102            };
103            lean_ctx_hooks::hooks::governor_default::pin(host, Some(&mode));
104            let reverted = if host.key == "claude" {
105                lean_ctx_hooks::hooks::agents::claude_governor::revert(&home)
106            } else {
107                lean_ctx_hooks::hooks::agents::governor_hosts::governor_available(agent)
108                    .is_some_and(|spec| (spec.revert)(&home))
109            };
110            if reverted {
111                qprintln!("  ✓ governor setup reverted for {}", host.name);
112            }
113        }
114    }
115
116    if !agents.is_empty() {
117        let cwd = std::env::current_dir().unwrap_or_default();
118        for agent_name in &agents {
119            if explicit_mode.is_none() && init_governor_default(agent_name) {
120                continue;
121            }
122            let mode = explicit_mode
123                .unwrap_or_else(|| lean_ctx_hooks::hooks::recommend_hook_mode(agent_name));
124            let result = crate::setup::setup_single_agent(agent_name, global, mode);
125            for name in &result.rules.injected {
126                qprintln!("  ✓ {name} rules injected");
127            }
128            for name in &result.rules.updated {
129                qprintln!("  ✓ {name} rules updated");
130            }
131            for name in &result.rules.already {
132                qprintln!("  ✓ {name} rules up-to-date");
133            }
134            if result.skill_installed {
135                qprintln!("  ✓ SKILL.md installed for {agent_name}");
136            }
137            if result.mcp_skipped {
138                qprintln!("  • MCP registration skipped for {agent_name} (auto_update_mcp=false)");
139            }
140            for e in &result.errors {
141                eprintln!("  ✗ {agent_name}: {e}");
142            }
143            if result.errors.is_empty()
144                && let Err(e) = crate::setup::agent_selection::remember_connected_agent(agent_name)
145            {
146                eprintln!("  ✗ {agent_name}: {e}");
147            }
148            if agent_name.eq_ignore_ascii_case("hermes") {
149                qprintln!("\n  Beyond MCP, lean-ctx can be Hermes' active context engine");
150                qprintln!("  (replaces the built-in ContextCompressor). Install the plugin from");
151                qprintln!("  integrations/hermes-lean-ctx (scripts/install.sh), then set");
152                qprintln!("  context.engine: \"lean-ctx\" in ~/.hermes/config.yaml.");
153            }
154            if project {
155                lean_ctx_hooks::hooks::install_agent_project_hooks(agent_name, &cwd);
156            }
157        }
158        if !global {
159            lean_ctx_hooks::hooks::install_project_rules_for_agents(&agents);
160        }
161        qprintln!("\nRun 'lean-ctx cockpit' after using some commands to see your savings.");
162        return;
163    }
164
165    let eval_shell = args
166        .iter()
167        .find(|a| matches!(a.as_str(), "bash" | "zsh" | "fish" | "powershell" | "pwsh"));
168    if let Some(shell) = eval_shell
169        && !global
170    {
171        super::shell_init::print_hook_stdout(shell);
172        return;
173    }
174
175    let shell_name = std::env::var("SHELL").unwrap_or_default();
176    let is_zsh = shell_name.contains("zsh");
177    let is_fish = shell_name.contains("fish");
178    let is_powershell = cfg!(windows) && shell_name.is_empty();
179
180    // Shell hooks outlive the build that wrote them: embed the stable PATH
181    // entry, not a versioned package-manager directory (#1851).
182    let binary = lean_ctx::core::portable_binary::stable_shell_binary(
183        &lean_ctx::core::portable_binary::resolve_portable_binary(),
184    );
185
186    if dry_run {
187        let rc = if is_powershell {
188            dirs::home_dir().map_or_else(
189                || "PowerShell profile".to_string(),
190                |h| {
191                    lean_ctx::shell::platform::resolve_powershell_profile_path(&h)
192                        .to_string_lossy()
193                        .into_owned()
194                },
195            )
196        } else if is_fish {
197            "~/.config/fish/config.fish".to_string()
198        } else if is_zsh {
199            "~/.zshrc".to_string()
200        } else {
201            "~/.bashrc".to_string()
202        };
203        qprintln!("\nlean-ctx init --dry-run\n");
204        qprintln!("  Would modify:  {rc}");
205        qprintln!("  Would backup:  {rc}.lean-ctx.bak");
206        qprintln!("  Would alias:   git npm pnpm yarn cargo docker docker-compose kubectl");
207        qprintln!("                 gh pip pip3 ruff go golangci-lint eslint prettier tsc");
208        qprintln!("                 curl wget php composer (24 commands + k)");
209        let data_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().map_or_else(
210            |_| "~/.config/lean-ctx/".to_string(),
211            |p| p.to_string_lossy().to_string(),
212        );
213        qprintln!("  Would create:  {data_dir}");
214        qprintln!("  Binary:        {binary}");
215        qprintln!("\n  Safety: aliases auto-fallback to original command if lean-ctx is removed.");
216        qprintln!("\n  Run without --dry-run to apply.");
217        return;
218    }
219
220    if no_hook {
221        qprintln!("Shell hook disabled (--no-shell-hook or shell_hook_disabled config).");
222        qprintln!("MCP tools remain active. Set LEAN_CTX_NO_HOOK=1 to disable at runtime.");
223    } else if is_powershell {
224        super::shell_init::init_powershell(&binary);
225    } else {
226        let bash_binary = to_bash_compatible_path(&binary);
227        if is_fish {
228            super::shell_init::init_fish(&bash_binary);
229        } else {
230            super::shell_init::init_posix(is_zsh, &bash_binary);
231        }
232    }
233
234    if let Ok(lean_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir()
235        && !lean_dir.exists()
236    {
237        let _ = std::fs::create_dir_all(&lean_dir);
238        qprintln!("Created {}", lean_dir.display());
239    }
240
241    let rc = if is_powershell {
242        "$PROFILE"
243    } else if is_fish {
244        "config.fish"
245    } else if is_zsh {
246        ".zshrc"
247    } else {
248        ".bashrc"
249    };
250
251    qprintln!("\nlean-ctx init complete (24 aliases installed)");
252    qprintln!();
253    qprintln!("  Disable temporarily:  lean-ctx-off");
254    qprintln!("  Re-enable:            lean-ctx-on");
255    qprintln!("  Check status:         lean-ctx-status");
256    qprintln!("  Full uninstall:       lean-ctx uninstall");
257    qprintln!("  Diagnose issues:      lean-ctx doctor");
258    qprintln!("  Preview changes:      lean-ctx init --global --dry-run");
259    qprintln!();
260    if is_powershell {
261        qprintln!("  Restart PowerShell or run: . {rc}");
262    } else {
263        qprintln!("  Restart your shell or run: source ~/{rc}");
264    }
265    qprintln!();
266    qprintln!("For AI tool integration: lean-ctx init --agent <tool> [--mode <mode>]");
267    qprintln!("  Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
268    qprintln!(
269        "    claude, cline, codewhale, codex, commandcode, continue, copilot, crush, cursor, emacs, gemini, goose,"
270    );
271    qprintln!("    grok, hermes, jetbrains, kiro, muse, neovim, omp, openclaw, opencode, pi,");
272    qprintln!("    qoder, qodercli, qoderwork, qwen, roo, sublime, trae, verdent, vscode,");
273    qprintln!("    windsurf, zed");
274    qprintln!("  Modes: mcp, hybrid, replace  (auto-detected per agent, override with --mode)");
275    qprintln!("  New Claude Code installs get governor-mcp; existing setups keep their mode");
276}
277
278pub fn cmd_init_quiet(args: &[String]) {
279    let _quiet_guard = lean_ctx::core::runtime_flags::scoped_quiet();
280    cmd_init(args);
281}
282
283/// `--flag` → enable, `--flag off` / `--flag=off` → disable, absent → `None`.
284fn opt_in_flag(args: &[String], flag: &str) -> Option<bool> {
285    let pos = args
286        .iter()
287        .position(|a| a == flag || a.starts_with(&format!("{flag}=")))?;
288    let value = args[pos]
289        .strip_prefix(&format!("{flag}="))
290        .or_else(|| args.get(pos + 1).map(String::as_str));
291    Some(!matches!(value, Some("off" | "false" | "0")))
292}
293
294fn is_claude_agent(agent: &str) -> bool {
295    matches!(
296        agent.to_ascii_lowercase().as_str(),
297        "claude" | "claude-code"
298    )
299}
300
301/// `init --agent <host> --mode governor|governor-mcp`: the zero-overhead
302/// governor profile (`governor-mcp` is Claude Code only).
303fn init_governor(
304    agents: &[&str],
305    arm: lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm,
306) {
307    let Some(home) = lean_ctx::core::home::resolve_home_dir() else {
308        eprintln!("  ✗ cannot resolve the home directory");
309        std::process::exit(1);
310    };
311    if agents.is_empty() {
312        eprintln!("  ✗ --mode governor needs --agent <host>");
313        std::process::exit(1);
314    }
315    for agent in agents {
316        if !is_claude_agent(agent) {
317            init_host_governor(agent, arm, &home);
318            continue;
319        }
320        lean_ctx_hooks::hooks::agents::claude_governor::install(&home, arm);
321        if let Some(host) = lean_ctx_hooks::hooks::governor_default::host(agent) {
322            // A chosen governor is pinned like a chosen standard mode: no
323            // update or repair of the 3.12.1 migration switches it back.
324            lean_ctx_hooks::hooks::governor_default::pin(host, Some(arm.label()));
325        }
326        qprintln!("  ✓ Claude Code governor setup installed (revert: --mode hybrid)");
327        if let Err(e) = crate::setup::agent_selection::remember_connected_agent(agent) {
328            eprintln!("  ✗ {agent}: {e}");
329        }
330    }
331}
332
333/// `init --agent <host>` without `--mode` on a host with a governor: apply the
334/// default (a new Claude Code install gets governor-mcp; an automatic 3.12.1
335/// migration is switched back). Returns whether the host is handled; `false`
336/// runs the standard setup (in the mode `recommend_hook_mode` reads, which
337/// includes the host's pin).
338fn init_governor_default(agent: &str) -> bool {
339    use lean_ctx_hooks::hooks::governor_default::{Outcome, apply_default, host};
340    let (Some(host), Some(home)) = (host(agent), lean_ctx::core::home::resolve_home_dir()) else {
341        return false;
342    };
343    let outcome = apply_default(host, &home);
344    if outcome.ran_steps() {
345        let _ = crate::setup::agent_selection::remember_connected_agent(host.key);
346    }
347    if let Some(notice) = outcome.notice(host) {
348        qprintln!("  ✓ {notice}");
349    } else if outcome == Outcome::AlreadyGovernor {
350        (host.refresh)(&home);
351        qprintln!("  ✓ {} governor setup up to date", host.name);
352    }
353    !outcome.standard_setup_runs()
354}
355
356/// `init --agent <host> --mode governor` for a host other than Claude Code.
357fn init_host_governor(
358    agent: &str,
359    arm: lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm,
360    home: &std::path::Path,
361) {
362    use lean_ctx_hooks::hooks::agents::{claude_governor::GovernorArm, governor_hosts};
363    let Some(spec) = governor_hosts::governor_available(agent) else {
364        eprintln!("  • {agent}: no tool hooks LeanCTX can govern; keeps the MCP setup");
365        return;
366    };
367    if arm == GovernorArm::McpDeferred {
368        eprintln!("  • {agent}: governor-mcp is Claude Code only; use --mode governor");
369        return;
370    }
371    governor_hosts::install(spec, home);
372    // A chosen governor is pinned, so the repair of 3.12.1's automatic
373    // migration never switches it back.
374    if let Some(host) = lean_ctx_hooks::hooks::governor_default::host(agent) {
375        lean_ctx_hooks::hooks::governor_default::pin(host, Some(arm.label()));
376    }
377    qprintln!(
378        "  ✓ {} {} setup installed (switch back: {})",
379        spec.name,
380        spec.class.label(),
381        spec.switch_back
382    );
383    if let Err(e) = crate::setup::agent_selection::remember_connected_agent(agent) {
384        eprintln!("  ✗ {agent}: {e}");
385    }
386}
387
388/// Help for `lean-ctx init`. Printed for `--help`/`-h`, whatever else is on
389/// the line, and never followed by an init.
390fn print_init_help() {
391    println!("Usage: lean-ctx init [options]");
392    println!("       lean-ctx init <bash|zsh|fish|powershell|pwsh>");
393    println!();
394    println!("Installs the shell aliases, or connects an AI tool with --agent.");
395    println!("The second form prints the shell hook to stdout for `eval` and writes nothing.");
396    println!();
397    println!("Options:");
398    println!("  --global, -g        Install the shell aliases into your shell profile");
399    println!("  --agent <tool>      Configure an AI tool: MCP, hooks and rules (repeatable)");
400    println!("  --mode <mode>       Hook mode for --agent: mcp, hybrid or replace");
401    println!("                      (auto-detected per agent when omitted). A new Claude");
402    println!("                      Code install gets governor-mcp (governor hooks + MCP");
403    println!("                      server); existing setups keep their mode. Claude Code,");
404    println!("                      CodeBuddy, Cursor, Codex, Gemini and Copilot CLI also");
405    println!("                      take governor; an explicit mode is kept by later updates");
406    println!("  --project           With --agent: also install project-local hooks");
407    println!("  --no-shell-hook     Skip the shell aliases; MCP tools stay active");
408    println!("  --dry-run           Show what the shell setup would change, change nothing");
409    println!("  --prompt [off]      Show what lean-ctx did in your shell prompt (zsh, bash,");
410    println!("                      fish; prints a module for Starship). `off` removes it");
411    println!("  --git-trailer [off] Add a `lean-ctx:` trailer to this repo's commit messages.");
412    println!("                      `off` removes the hook");
413    println!("  --help, -h          Show this help (never runs init)");
414    println!();
415    println!("Examples:");
416    println!("  lean-ctx init --global --dry-run");
417    println!("  lean-ctx init --global");
418    println!("  lean-ctx init --prompt");
419    println!("  lean-ctx init --agent claude");
420    println!("  lean-ctx init --agent codex --mode hybrid");
421}
422
423#[cfg(test)]
424mod tests {
425    use super::opt_in_flag;
426
427    fn args(a: &[&str]) -> Vec<String> {
428        a.iter().map(ToString::to_string).collect()
429    }
430
431    #[test]
432    fn opt_in_flags_parse_on_and_off() {
433        assert_eq!(opt_in_flag(&args(&["--prompt"]), "--prompt"), Some(true));
434        assert_eq!(
435            opt_in_flag(&args(&["--prompt", "off"]), "--prompt"),
436            Some(false)
437        );
438        assert_eq!(
439            opt_in_flag(&args(&["--prompt=false"]), "--prompt"),
440            Some(false)
441        );
442        assert_eq!(
443            opt_in_flag(&args(&["--git-trailer", "0"]), "--git-trailer"),
444            Some(false)
445        );
446        assert_eq!(opt_in_flag(&args(&["--global"]), "--prompt"), None);
447        // `--prompt-foo` is not `--prompt`.
448        assert_eq!(opt_in_flag(&args(&["--prompt-foo"]), "--prompt"), None);
449    }
450
451    /// `init --agent claude` after an automatic 3.12.1 governor migration
452    /// (backups next to the files, governor hooks, no MCP entry) restores the
453    /// standard setup and pins it, so the next update leaves it alone.
454    #[test]
455    fn init_restores_an_automatically_migrated_setup_pinned() {
456        use lean_ctx::test_env;
457        use lean_ctx_hooks::hooks::agents::claude_governor;
458        use lean_ctx_hooks::hooks::governor_default::{Outcome, apply_default, host, pinned_mode};
459
460        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
461        let home = tempfile::tempdir().unwrap();
462        let prev_home = std::env::var_os("HOME");
463        test_env::set_var("HOME", home.path());
464        test_env::set_var("LEAN_CTX_HOOK_BINARY", "lean-ctx");
465        for var in ["CLAUDE_CONFIG_DIR", "LEAN_CTX_HOOK_MODE", "LEAN_CTX_QUIET"] {
466            test_env::remove_var(var);
467        }
468        let h = home.path();
469        let read = |p: &str| std::fs::read_to_string(h.join(p)).unwrap_or_default();
470        let mcp = || serde_json::from_str::<serde_json::Value>(&read(".claude.json")).unwrap();
471        // The standard install the migration found, backed up as 3.12.1 did.
472        std::fs::create_dir_all(h.join(".claude")).unwrap();
473        std::fs::write(
474            h.join(".claude/settings.json"),
475            r#"{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"lean-ctx hook rewrite"}]},{"matcher":"Read|Grep|Glob","hooks":[{"type":"command","command":"lean-ctx hook redirect"}]}]},"permissions":{"deny":["Grep","Glob"]}}"#,
476        )
477        .unwrap();
478        std::fs::write(
479            h.join(".claude.json"),
480            r#"{"projects":{"/x":{}},"mcpServers":{"lean-ctx":{"command":"lean-ctx","alwaysLoad":true},"other":{"command":"o"}}}"#,
481        )
482        .unwrap();
483        std::fs::write(
484            h.join(".claude/CLAUDE.md"),
485            "# My notes\nkeep me\n\n<!-- lean-ctx -->\nstandard block: use ctx_read\n<!-- /lean-ctx -->\n",
486        )
487        .unwrap();
488        for f in [".claude/settings.json", ".claude.json", ".claude/CLAUDE.md"] {
489            std::fs::copy(h.join(f), h.join(format!("{f}.pre-governor-3.12.1.bak"))).unwrap();
490        }
491        claude_governor::install(h, claude_governor::GovernorArm::NoMcp);
492        assert!(mcp().pointer("/mcpServers/lean-ctx").is_none(), "migrated");
493
494        super::cmd_init_quiet(&args(&["--agent", "claude", "--global"]));
495
496        assert!(!claude_governor::is_installed(h));
497        let settings = read(".claude/settings.json");
498        assert!(settings.contains("lean-ctx hook rewrite"), "{settings}");
499        assert!(!settings.contains("hook govern"), "{settings}");
500        assert!(mcp().pointer("/mcpServers/lean-ctx").is_some(), "MCP back");
501        assert!(mcp().pointer("/mcpServers/other").is_some(), "foreign kept");
502        assert!(
503            settings.contains("\"Grep\""),
504            "the deny returns with the MCP entry: {settings}"
505        );
506        assert!(read(".claude/CLAUDE.md").starts_with("# My notes\nkeep me\n"));
507        assert_eq!(
508            pinned_mode(host("claude").unwrap()).as_deref(),
509            Some("hybrid")
510        );
511        // The next update leaves the pinned choice alone.
512        let before = (read(".claude/settings.json"), read(".claude/CLAUDE.md"));
513        assert_eq!(
514            apply_default(host("claude").unwrap(), h),
515            Outcome::Pinned("hybrid".into())
516        );
517        assert_eq!(
518            (read(".claude/settings.json"), read(".claude/CLAUDE.md")),
519            before
520        );
521
522        test_env::remove_var("LEAN_CTX_HOOK_BINARY");
523        match prev_home {
524            Some(p) => test_env::set_var("HOME", p),
525            None => test_env::remove_var("HOME"),
526        }
527    }
528
529    /// `init --agent claude` on a new home installs governor-mcp: governor
530    /// hooks plus the lean-ctx MCP server with deferred tools.
531    #[test]
532    fn a_new_claude_install_gets_governor_mcp() {
533        use lean_ctx::test_env;
534        use lean_ctx_hooks::hooks::agents::claude_governor;
535
536        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
537        let home = tempfile::tempdir().unwrap();
538        let prev_home = std::env::var_os("HOME");
539        test_env::set_var("HOME", home.path());
540        test_env::set_var("LEAN_CTX_HOOK_BINARY", "lean-ctx");
541        for var in ["CLAUDE_CONFIG_DIR", "LEAN_CTX_HOOK_MODE", "LEAN_CTX_QUIET"] {
542            test_env::remove_var(var);
543        }
544        let h = home.path();
545        std::fs::create_dir_all(h.join(".claude")).unwrap();
546
547        super::cmd_init_quiet(&args(&["--agent", "claude", "--global"]));
548
549        assert_eq!(
550            claude_governor::installed_arm(h),
551            Some(claude_governor::GovernorArm::McpDeferred)
552        );
553        let mcp: serde_json::Value =
554            serde_json::from_str(&std::fs::read_to_string(h.join(".claude.json")).unwrap())
555                .unwrap();
556        assert_eq!(mcp["mcpServers"]["lean-ctx"]["alwaysLoad"], false);
557
558        test_env::remove_var("LEAN_CTX_HOOK_BINARY");
559        match prev_home {
560            Some(p) => test_env::set_var("HOME", p),
561            None => test_env::remove_var("HOME"),
562        }
563    }
564}