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                if host.key == "claude" {
113                    note_claude_mod_left_disabled();
114                }
115            }
116        }
117    }
118
119    if !agents.is_empty() {
120        let cwd = std::env::current_dir().unwrap_or_default();
121        for agent_name in &agents {
122            if explicit_mode.is_none() && init_governor_default(agent_name) {
123                continue;
124            }
125            let mode = explicit_mode
126                .unwrap_or_else(|| lean_ctx_hooks::hooks::recommend_hook_mode(agent_name));
127            let result = crate::setup::setup_single_agent(agent_name, global, mode);
128            for name in &result.rules.injected {
129                qprintln!("  ✓ {name} rules injected");
130            }
131            for name in &result.rules.updated {
132                qprintln!("  ✓ {name} rules updated");
133            }
134            for name in &result.rules.already {
135                qprintln!("  ✓ {name} rules up-to-date");
136            }
137            if result.skill_installed {
138                qprintln!("  ✓ SKILL.md installed for {agent_name}");
139            }
140            if result.mcp_skipped {
141                qprintln!("  • MCP registration skipped for {agent_name} (auto_update_mcp=false)");
142            }
143            for e in &result.errors {
144                eprintln!("  ✗ {agent_name}: {e}");
145            }
146            if result.errors.is_empty()
147                && let Err(e) = crate::setup::agent_selection::remember_connected_agent(agent_name)
148            {
149                eprintln!("  ✗ {agent_name}: {e}");
150            }
151            if agent_name.eq_ignore_ascii_case("hermes") {
152                qprintln!("\n  Beyond MCP, lean-ctx can be Hermes' active context engine");
153                qprintln!("  (replaces the built-in ContextCompressor). Install the plugin from");
154                qprintln!("  integrations/hermes-lean-ctx (scripts/install.sh), then set");
155                qprintln!("  context.engine: \"lean-ctx\" in ~/.hermes/config.yaml.");
156            }
157            if project {
158                lean_ctx_hooks::hooks::install_agent_project_hooks(agent_name, &cwd);
159            }
160        }
161        if !global {
162            lean_ctx_hooks::hooks::install_project_rules_for_agents(&agents);
163        }
164        qprintln!("\nRun 'lean-ctx cockpit' after using some commands to see your savings.");
165        return;
166    }
167
168    let eval_shell = args
169        .iter()
170        .find(|a| matches!(a.as_str(), "bash" | "zsh" | "fish" | "powershell" | "pwsh"));
171    if let Some(shell) = eval_shell
172        && !global
173    {
174        super::shell_init::print_hook_stdout(shell);
175        return;
176    }
177
178    let shell_name = std::env::var("SHELL").unwrap_or_default();
179    let is_zsh = shell_name.contains("zsh");
180    let is_fish = shell_name.contains("fish");
181    let is_powershell = cfg!(windows) && shell_name.is_empty();
182
183    // Shell hooks outlive the build that wrote them: embed the stable PATH
184    // entry, not a versioned package-manager directory (#1851).
185    let binary = lean_ctx::core::portable_binary::stable_shell_binary(
186        &lean_ctx::core::portable_binary::resolve_portable_binary(),
187    );
188
189    if dry_run {
190        let rc = if is_powershell {
191            dirs::home_dir().map_or_else(
192                || "PowerShell profile".to_string(),
193                |h| {
194                    lean_ctx::shell::platform::resolve_powershell_profile_path(&h)
195                        .to_string_lossy()
196                        .into_owned()
197                },
198            )
199        } else if is_fish {
200            "~/.config/fish/config.fish".to_string()
201        } else if is_zsh {
202            "~/.zshrc".to_string()
203        } else {
204            "~/.bashrc".to_string()
205        };
206        qprintln!("\nlean-ctx init --dry-run\n");
207        qprintln!("  Would modify:  {rc}");
208        qprintln!("  Would backup:  {rc}.lean-ctx.bak");
209        qprintln!("  Would alias:   git npm pnpm yarn cargo docker docker-compose kubectl");
210        qprintln!("                 gh pip pip3 ruff go golangci-lint eslint prettier tsc");
211        qprintln!("                 curl wget php composer (24 commands + k)");
212        let data_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().map_or_else(
213            |_| "~/.config/lean-ctx/".to_string(),
214            |p| p.to_string_lossy().to_string(),
215        );
216        qprintln!("  Would create:  {data_dir}");
217        qprintln!("  Binary:        {binary}");
218        qprintln!("\n  Safety: aliases auto-fallback to original command if lean-ctx is removed.");
219        qprintln!("\n  Run without --dry-run to apply.");
220        return;
221    }
222
223    if no_hook {
224        qprintln!("Shell hook disabled (--no-shell-hook or shell_hook_disabled config).");
225        qprintln!("MCP tools remain active. Set LEAN_CTX_NO_HOOK=1 to disable at runtime.");
226    } else if is_powershell {
227        super::shell_init::init_powershell(&binary);
228    } else {
229        let bash_binary = to_bash_compatible_path(&binary);
230        if is_fish {
231            super::shell_init::init_fish(&bash_binary);
232        } else {
233            super::shell_init::init_posix(is_zsh, &bash_binary);
234        }
235    }
236
237    if let Ok(lean_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir()
238        && !lean_dir.exists()
239    {
240        let _ = std::fs::create_dir_all(&lean_dir);
241        qprintln!("Created {}", lean_dir.display());
242    }
243
244    let rc = if is_powershell {
245        "$PROFILE"
246    } else if is_fish {
247        "config.fish"
248    } else if is_zsh {
249        ".zshrc"
250    } else {
251        ".bashrc"
252    };
253
254    qprintln!("\nlean-ctx init complete (24 aliases installed)");
255    qprintln!();
256    qprintln!("  Disable temporarily:  lean-ctx-off");
257    qprintln!("  Re-enable:            lean-ctx-on");
258    qprintln!("  Check status:         lean-ctx-status");
259    qprintln!("  Full uninstall:       lean-ctx uninstall");
260    qprintln!("  Diagnose issues:      lean-ctx doctor");
261    qprintln!("  Preview changes:      lean-ctx init --global --dry-run");
262    qprintln!();
263    if is_powershell {
264        qprintln!("  Restart PowerShell or run: . {rc}");
265    } else {
266        qprintln!("  Restart your shell or run: source ~/{rc}");
267    }
268    qprintln!();
269    qprintln!("For AI tool integration: lean-ctx init --agent <tool> [--mode <mode>]");
270    qprintln!("  Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
271    qprintln!(
272        "    claude, cline, codewhale, codex, commandcode, continue, copilot, crush, cursor, emacs, gemini, goose,"
273    );
274    qprintln!("    grok, hermes, jetbrains, kiro, muse, neovim, omp, openclaw, opencode, pi,");
275    qprintln!("    qoder, qodercli, qoderwork, qwen, roo, sublime, trae, verdent, vscode,");
276    qprintln!("    windsurf, zed");
277    qprintln!("  Modes: mcp, hybrid, replace  (auto-detected per agent, override with --mode)");
278    qprintln!("  New Claude Code installs get governor-mcp; existing setups keep their mode");
279}
280
281pub fn cmd_init_quiet(args: &[String]) {
282    let _quiet_guard = lean_ctx::core::runtime_flags::scoped_quiet();
283    cmd_init(args);
284}
285
286/// `--flag` → enable, `--flag off` / `--flag=off` → disable, absent → `None`.
287fn opt_in_flag(args: &[String], flag: &str) -> Option<bool> {
288    let pos = args
289        .iter()
290        .position(|a| a == flag || a.starts_with(&format!("{flag}=")))?;
291    let value = args[pos]
292        .strip_prefix(&format!("{flag}="))
293        .or_else(|| args.get(pos + 1).map(String::as_str));
294    Some(!matches!(value, Some("off" | "false" | "0")))
295}
296
297fn is_claude_agent(agent: &str) -> bool {
298    matches!(
299        agent.to_ascii_lowercase().as_str(),
300        "claude" | "claude-code"
301    )
302}
303
304/// `init --agent <host> --mode governor|governor-mcp`: the zero-overhead
305/// governor profile (`governor-mcp` is Claude Code only).
306fn init_governor(
307    agents: &[&str],
308    arm: lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm,
309) {
310    let Some(home) = lean_ctx::core::home::resolve_home_dir() else {
311        eprintln!("  ✗ cannot resolve the home directory");
312        std::process::exit(1);
313    };
314    if agents.is_empty() {
315        eprintln!("  ✗ --mode governor needs --agent <host>");
316        std::process::exit(1);
317    }
318    for agent in agents {
319        if !is_claude_agent(agent) {
320            init_host_governor(agent, arm, &home);
321            continue;
322        }
323        lean_ctx_hooks::hooks::agents::claude_governor::install(&home, arm);
324        if let Some(host) = lean_ctx_hooks::hooks::governor_default::host(agent) {
325            // A chosen governor is pinned like a chosen standard mode: no
326            // update or repair of the 3.12.1 migration switches it back.
327            lean_ctx_hooks::hooks::governor_default::pin(host, Some(arm.label()));
328        }
329        qprintln!("  ✓ Claude Code governor setup installed (revert: --mode hybrid)");
330        if arm == lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm::McpDeferred {
331            disable_claude_mod_for_governor();
332        }
333        if let Err(e) = crate::setup::agent_selection::remember_connected_agent(agent) {
334            eprintln!("  ✗ {agent}: {e}");
335        }
336    }
337}
338
339/// governor-mcp keeps lean-ctx tool schemas deferred; an enabled LeanCTX
340/// plugin would front-load them again. Only this explicit init disables it
341/// (never uninstalls), once: setup and the post-update rewire leave a plugin
342/// the user re-enabled alone.
343fn disable_claude_mod_for_governor() {
344    use lean_ctx_hooks::hooks::agents::claude_mod::{self, ModStatus};
345    // Ran once already: skip `claude --version` / `plugin list` entirely.
346    if claude_mod::governor_disabled_marker().is_ok_and(|m| m.exists()) {
347        return;
348    }
349    if !matches!(
350        claude_mod::status(),
351        ModStatus::Current(_) | ModStatus::Stale(_)
352    ) {
353        return;
354    }
355    let outcome = claude_mod::disable_for_governor();
356    // Printed under --quiet too: it changes a setting outside lean-ctx.
357    if !outcome.disabled.is_empty() {
358        println!(
359            "  ✓ Disabled {} in your user settings — it would front-load lean-ctx tool schemas (undo: claude plugin enable {} --scope user; stays as you set it)",
360            claude_mod::PLUGIN_ID,
361            claude_mod::PLUGIN_ID
362        );
363    }
364    if let Some(e) = &outcome.error {
365        eprintln!("  ✗ disabling the LeanCTX Claude plugin failed: {e}");
366    }
367    if !outcome.left.is_empty() {
368        // A failed user-scope disable is retried in the user scope; a local or
369        // checked-in project enable is overridden for this user in local.
370        let scope = if outcome.left.iter().any(|s| s == "user") {
371            "user"
372        } else {
373            "local"
374        };
375        eprintln!(
376            "  ! {} stays enabled in {} settings — it front-loads lean-ctx tool schemas under governor-mcp (disable for you only: claude plugin disable {} --scope {scope})",
377            claude_mod::PLUGIN_ID,
378            outcome.left.join(" and "),
379            claude_mod::PLUGIN_ID
380        );
381    }
382}
383
384/// Leaving governor-mcp does not re-enable the plugin it disabled: that was
385/// a settings change outside lean-ctx, and the user may have kept it. Say so.
386fn note_claude_mod_left_disabled() {
387    use lean_ctx_hooks::hooks::agents::claude_mod;
388    if claude_mod::governor_disabled_marker().is_ok_and(|m| m.exists()) {
389        qprintln!(
390            "  · {} stays as governor-mcp left it in your user settings (enable: claude plugin enable {} --scope user)",
391            claude_mod::PLUGIN_ID,
392            claude_mod::PLUGIN_ID
393        );
394    }
395}
396
397/// `init --agent <host>` without `--mode` on a host with a governor: apply the
398/// default (a new Claude Code install gets governor-mcp; an automatic 3.12.1
399/// migration is switched back). Returns whether the host is handled; `false`
400/// runs the standard setup (in the mode `recommend_hook_mode` reads, which
401/// includes the host's pin).
402fn init_governor_default(agent: &str) -> bool {
403    use lean_ctx_hooks::hooks::governor_default::{Outcome, apply_default, host};
404    let (Some(host), Some(home)) = (host(agent), lean_ctx::core::home::resolve_home_dir()) else {
405        return false;
406    };
407    let outcome = apply_default(host, &home);
408    if outcome.ran_steps() {
409        let _ = crate::setup::agent_selection::remember_connected_agent(host.key);
410    }
411    if let Some(notice) = outcome.notice(host) {
412        qprintln!("  ✓ {notice}");
413    } else if outcome == Outcome::AlreadyGovernor {
414        (host.refresh)(&home);
415        qprintln!("  ✓ {} governor setup up to date", host.name);
416    }
417    !outcome.standard_setup_runs()
418}
419
420/// `init --agent <host> --mode governor` for a host other than Claude Code.
421fn init_host_governor(
422    agent: &str,
423    arm: lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm,
424    home: &std::path::Path,
425) {
426    use lean_ctx_hooks::hooks::agents::{claude_governor::GovernorArm, governor_hosts};
427    let Some(spec) = governor_hosts::governor_available(agent) else {
428        eprintln!("  • {agent}: no tool hooks LeanCTX can govern; keeps the MCP setup");
429        return;
430    };
431    if arm == GovernorArm::McpDeferred {
432        eprintln!("  • {agent}: governor-mcp is Claude Code only; use --mode governor");
433        return;
434    }
435    governor_hosts::install(spec, home);
436    // A chosen governor is pinned, so the repair of 3.12.1's automatic
437    // migration never switches it back.
438    if let Some(host) = lean_ctx_hooks::hooks::governor_default::host(agent) {
439        lean_ctx_hooks::hooks::governor_default::pin(host, Some(arm.label()));
440    }
441    qprintln!(
442        "  ✓ {} {} setup installed (switch back: {})",
443        spec.name,
444        spec.class.label(),
445        spec.switch_back
446    );
447    if let Err(e) = crate::setup::agent_selection::remember_connected_agent(agent) {
448        eprintln!("  ✗ {agent}: {e}");
449    }
450}
451
452/// Help for `lean-ctx init`. Printed for `--help`/`-h`, whatever else is on
453/// the line, and never followed by an init.
454fn print_init_help() {
455    println!("Usage: lean-ctx init [options]");
456    println!("       lean-ctx init <bash|zsh|fish|powershell|pwsh>");
457    println!();
458    println!("Installs the shell aliases, or connects an AI tool with --agent.");
459    println!("The second form prints the shell hook to stdout for `eval` and writes nothing.");
460    println!();
461    println!("Options:");
462    println!("  --global, -g        Install the shell aliases into your shell profile");
463    println!("  --agent <tool>      Configure an AI tool: MCP, hooks and rules (repeatable)");
464    println!("  --mode <mode>       Hook mode for --agent: mcp, hybrid or replace");
465    println!("                      (auto-detected per agent when omitted). A new Claude");
466    println!("                      Code install gets governor-mcp (governor hooks + MCP");
467    println!("                      server); existing setups keep their mode. Claude Code,");
468    println!("                      CodeBuddy, Cursor, Codex, Gemini and Copilot CLI also");
469    println!("                      take governor; an explicit mode is kept by later updates");
470    println!("  --project           With --agent: also install project-local hooks");
471    println!("  --no-shell-hook     Skip the shell aliases; MCP tools stay active");
472    println!("  --dry-run           Show what the shell setup would change, change nothing");
473    println!("  --prompt [off]      Show what lean-ctx did in your shell prompt (zsh, bash,");
474    println!("                      fish; prints a module for Starship). `off` removes it");
475    println!("  --git-trailer [off] Add a `lean-ctx:` trailer to this repo's commit messages.");
476    println!("                      `off` removes the hook");
477    println!("  --help, -h          Show this help (never runs init)");
478    println!();
479    println!("Examples:");
480    println!("  lean-ctx init --global --dry-run");
481    println!("  lean-ctx init --global");
482    println!("  lean-ctx init --prompt");
483    println!("  lean-ctx init --agent claude");
484    println!("  lean-ctx init --agent codex --mode hybrid");
485}
486
487#[cfg(test)]
488mod tests {
489    use super::opt_in_flag;
490
491    fn args(a: &[&str]) -> Vec<String> {
492        a.iter().map(ToString::to_string).collect()
493    }
494
495    #[test]
496    fn opt_in_flags_parse_on_and_off() {
497        assert_eq!(opt_in_flag(&args(&["--prompt"]), "--prompt"), Some(true));
498        assert_eq!(
499            opt_in_flag(&args(&["--prompt", "off"]), "--prompt"),
500            Some(false)
501        );
502        assert_eq!(
503            opt_in_flag(&args(&["--prompt=false"]), "--prompt"),
504            Some(false)
505        );
506        assert_eq!(
507            opt_in_flag(&args(&["--git-trailer", "0"]), "--git-trailer"),
508            Some(false)
509        );
510        assert_eq!(opt_in_flag(&args(&["--global"]), "--prompt"), None);
511        // `--prompt-foo` is not `--prompt`.
512        assert_eq!(opt_in_flag(&args(&["--prompt-foo"]), "--prompt"), None);
513    }
514
515    /// `init --agent claude` after an automatic 3.12.1 governor migration
516    /// (backups next to the files, governor hooks, no MCP entry) restores the
517    /// standard setup and pins it, so the next update leaves it alone.
518    #[test]
519    fn init_restores_an_automatically_migrated_setup_pinned() {
520        use lean_ctx::test_env;
521        use lean_ctx_hooks::hooks::agents::claude_governor;
522        use lean_ctx_hooks::hooks::governor_default::{Outcome, apply_default, host, pinned_mode};
523
524        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
525        let home = tempfile::tempdir().unwrap();
526        let prev_home = std::env::var_os("HOME");
527        test_env::set_var("HOME", home.path());
528        test_env::set_var("LEAN_CTX_HOOK_BINARY", "lean-ctx");
529        for var in ["CLAUDE_CONFIG_DIR", "LEAN_CTX_HOOK_MODE", "LEAN_CTX_QUIET"] {
530            test_env::remove_var(var);
531        }
532        let h = home.path();
533        let read = |p: &str| std::fs::read_to_string(h.join(p)).unwrap_or_default();
534        let mcp = || serde_json::from_str::<serde_json::Value>(&read(".claude.json")).unwrap();
535        // The standard install the migration found, backed up as 3.12.1 did.
536        std::fs::create_dir_all(h.join(".claude")).unwrap();
537        std::fs::write(
538            h.join(".claude/settings.json"),
539            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"]}}"#,
540        )
541        .unwrap();
542        std::fs::write(
543            h.join(".claude.json"),
544            r#"{"projects":{"/x":{}},"mcpServers":{"lean-ctx":{"command":"lean-ctx","alwaysLoad":true},"other":{"command":"o"}}}"#,
545        )
546        .unwrap();
547        std::fs::write(
548            h.join(".claude/CLAUDE.md"),
549            "# My notes\nkeep me\n\n<!-- lean-ctx -->\nstandard block: use ctx_read\n<!-- /lean-ctx -->\n",
550        )
551        .unwrap();
552        for f in [".claude/settings.json", ".claude.json", ".claude/CLAUDE.md"] {
553            std::fs::copy(h.join(f), h.join(format!("{f}.pre-governor-3.12.1.bak"))).unwrap();
554        }
555        claude_governor::install(h, claude_governor::GovernorArm::NoMcp);
556        assert!(mcp().pointer("/mcpServers/lean-ctx").is_none(), "migrated");
557
558        super::cmd_init_quiet(&args(&["--agent", "claude", "--global"]));
559
560        assert!(!claude_governor::is_installed(h));
561        let settings = read(".claude/settings.json");
562        assert!(settings.contains("lean-ctx hook rewrite"), "{settings}");
563        assert!(!settings.contains("hook govern"), "{settings}");
564        assert!(mcp().pointer("/mcpServers/lean-ctx").is_some(), "MCP back");
565        assert!(mcp().pointer("/mcpServers/other").is_some(), "foreign kept");
566        assert!(
567            settings.contains("\"Grep\""),
568            "the deny returns with the MCP entry: {settings}"
569        );
570        assert!(read(".claude/CLAUDE.md").starts_with("# My notes\nkeep me\n"));
571        assert_eq!(
572            pinned_mode(host("claude").unwrap()).as_deref(),
573            Some("hybrid")
574        );
575        // The next update leaves the pinned choice alone.
576        let before = (read(".claude/settings.json"), read(".claude/CLAUDE.md"));
577        assert_eq!(
578            apply_default(host("claude").unwrap(), h),
579            Outcome::Pinned("hybrid".into())
580        );
581        assert_eq!(
582            (read(".claude/settings.json"), read(".claude/CLAUDE.md")),
583            before
584        );
585
586        test_env::remove_var("LEAN_CTX_HOOK_BINARY");
587        match prev_home {
588            Some(p) => test_env::set_var("HOME", p),
589            None => test_env::remove_var("HOME"),
590        }
591    }
592
593    /// `init --agent claude` on a new home installs governor-mcp: governor
594    /// hooks plus the lean-ctx MCP server with deferred tools.
595    #[test]
596    fn a_new_claude_install_gets_governor_mcp() {
597        use lean_ctx::test_env;
598        use lean_ctx_hooks::hooks::agents::claude_governor;
599
600        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
601        let home = tempfile::tempdir().unwrap();
602        let prev_home = std::env::var_os("HOME");
603        test_env::set_var("HOME", home.path());
604        test_env::set_var("LEAN_CTX_HOOK_BINARY", "lean-ctx");
605        for var in ["CLAUDE_CONFIG_DIR", "LEAN_CTX_HOOK_MODE", "LEAN_CTX_QUIET"] {
606            test_env::remove_var(var);
607        }
608        let h = home.path();
609        std::fs::create_dir_all(h.join(".claude")).unwrap();
610
611        super::cmd_init_quiet(&args(&["--agent", "claude", "--global"]));
612
613        assert_eq!(
614            claude_governor::installed_arm(h),
615            Some(claude_governor::GovernorArm::McpDeferred)
616        );
617        let mcp: serde_json::Value =
618            serde_json::from_str(&std::fs::read_to_string(h.join(".claude.json")).unwrap())
619                .unwrap();
620        assert_eq!(mcp["mcpServers"]["lean-ctx"]["alwaysLoad"], false);
621
622        test_env::remove_var("LEAN_CTX_HOOK_BINARY");
623        match prev_home {
624            Some(p) => test_env::set_var("HOME", p),
625            None => test_env::remove_var("HOME"),
626        }
627    }
628}