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 let Some(arm) = governor_arm {
86        init_governor(&agents, arm);
87        return;
88    }
89    // An explicit standard mode is a pinned choice (no later update switches
90    // it to the governor) and switches a governor install back first.
91    if let Some(mode) = explicit_mode
92        && let Some(home) = lean_ctx::core::home::resolve_home_dir()
93    {
94        let mode = mode.to_string().to_ascii_lowercase();
95        for agent in &agents {
96            let Some(host) = lean_ctx_hooks::hooks::governor_default::host(agent) else {
97                continue;
98            };
99            lean_ctx_hooks::hooks::governor_default::pin(host, Some(&mode));
100            let reverted = if host.key == "claude" {
101                lean_ctx_hooks::hooks::agents::claude_governor::revert(&home)
102            } else {
103                lean_ctx_hooks::hooks::agents::governor_hosts::governor_available(agent)
104                    .is_some_and(|spec| (spec.revert)(&home))
105            };
106            if reverted {
107                qprintln!("  ✓ governor setup reverted for {}", host.name);
108            }
109        }
110    }
111
112    if !agents.is_empty() {
113        let cwd = std::env::current_dir().unwrap_or_default();
114        for agent_name in &agents {
115            if explicit_mode.is_none() && init_governor_default(agent_name) {
116                continue;
117            }
118            let mode = explicit_mode
119                .unwrap_or_else(|| lean_ctx_hooks::hooks::recommend_hook_mode(agent_name));
120            let result = crate::setup::setup_single_agent(agent_name, global, mode);
121            for name in &result.rules.injected {
122                qprintln!("  ✓ {name} rules injected");
123            }
124            for name in &result.rules.updated {
125                qprintln!("  ✓ {name} rules updated");
126            }
127            for name in &result.rules.already {
128                qprintln!("  ✓ {name} rules up-to-date");
129            }
130            if result.skill_installed {
131                qprintln!("  ✓ SKILL.md installed for {agent_name}");
132            }
133            if result.mcp_skipped {
134                qprintln!("  • MCP registration skipped for {agent_name} (auto_update_mcp=false)");
135            }
136            for e in &result.errors {
137                eprintln!("  ✗ {agent_name}: {e}");
138            }
139            if result.errors.is_empty()
140                && let Err(e) = crate::setup::agent_selection::remember_connected_agent(agent_name)
141            {
142                eprintln!("  ✗ {agent_name}: {e}");
143            }
144            if agent_name.eq_ignore_ascii_case("hermes") {
145                qprintln!("\n  Beyond MCP, lean-ctx can be Hermes' active context engine");
146                qprintln!("  (replaces the built-in ContextCompressor). Install the plugin from");
147                qprintln!("  integrations/hermes-lean-ctx (scripts/install.sh), then set");
148                qprintln!("  context.engine: \"lean-ctx\" in ~/.hermes/config.yaml.");
149            }
150            if project {
151                lean_ctx_hooks::hooks::install_agent_project_hooks(agent_name, &cwd);
152            }
153        }
154        if !global {
155            lean_ctx_hooks::hooks::install_project_rules_for_agents(&agents);
156        }
157        qprintln!("\nRun 'lean-ctx cockpit' after using some commands to see your savings.");
158        return;
159    }
160
161    let eval_shell = args
162        .iter()
163        .find(|a| matches!(a.as_str(), "bash" | "zsh" | "fish" | "powershell" | "pwsh"));
164    if let Some(shell) = eval_shell
165        && !global
166    {
167        super::shell_init::print_hook_stdout(shell);
168        return;
169    }
170
171    let shell_name = std::env::var("SHELL").unwrap_or_default();
172    let is_zsh = shell_name.contains("zsh");
173    let is_fish = shell_name.contains("fish");
174    let is_powershell = cfg!(windows) && shell_name.is_empty();
175
176    // Shell hooks outlive the build that wrote them: embed the stable PATH
177    // entry, not a versioned package-manager directory (#1851).
178    let binary = lean_ctx::core::portable_binary::stable_shell_binary(
179        &lean_ctx::core::portable_binary::resolve_portable_binary(),
180    );
181
182    if dry_run {
183        let rc = if is_powershell {
184            dirs::home_dir().map_or_else(
185                || "PowerShell profile".to_string(),
186                |h| {
187                    lean_ctx::shell::platform::resolve_powershell_profile_path(&h)
188                        .to_string_lossy()
189                        .into_owned()
190                },
191            )
192        } else if is_fish {
193            "~/.config/fish/config.fish".to_string()
194        } else if is_zsh {
195            "~/.zshrc".to_string()
196        } else {
197            "~/.bashrc".to_string()
198        };
199        qprintln!("\nlean-ctx init --dry-run\n");
200        qprintln!("  Would modify:  {rc}");
201        qprintln!("  Would backup:  {rc}.lean-ctx.bak");
202        qprintln!("  Would alias:   git npm pnpm yarn cargo docker docker-compose kubectl");
203        qprintln!("                 gh pip pip3 ruff go golangci-lint eslint prettier tsc");
204        qprintln!("                 curl wget php composer (24 commands + k)");
205        let data_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().map_or_else(
206            |_| "~/.config/lean-ctx/".to_string(),
207            |p| p.to_string_lossy().to_string(),
208        );
209        qprintln!("  Would create:  {data_dir}");
210        qprintln!("  Binary:        {binary}");
211        qprintln!("\n  Safety: aliases auto-fallback to original command if lean-ctx is removed.");
212        qprintln!("\n  Run without --dry-run to apply.");
213        return;
214    }
215
216    if no_hook {
217        qprintln!("Shell hook disabled (--no-shell-hook or shell_hook_disabled config).");
218        qprintln!("MCP tools remain active. Set LEAN_CTX_NO_HOOK=1 to disable at runtime.");
219    } else if is_powershell {
220        super::shell_init::init_powershell(&binary);
221    } else {
222        let bash_binary = to_bash_compatible_path(&binary);
223        if is_fish {
224            super::shell_init::init_fish(&bash_binary);
225        } else {
226            super::shell_init::init_posix(is_zsh, &bash_binary);
227        }
228    }
229
230    if let Ok(lean_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir()
231        && !lean_dir.exists()
232    {
233        let _ = std::fs::create_dir_all(&lean_dir);
234        qprintln!("Created {}", lean_dir.display());
235    }
236
237    let rc = if is_powershell {
238        "$PROFILE"
239    } else if is_fish {
240        "config.fish"
241    } else if is_zsh {
242        ".zshrc"
243    } else {
244        ".bashrc"
245    };
246
247    qprintln!("\nlean-ctx init complete (24 aliases installed)");
248    qprintln!();
249    qprintln!("  Disable temporarily:  lean-ctx-off");
250    qprintln!("  Re-enable:            lean-ctx-on");
251    qprintln!("  Check status:         lean-ctx-status");
252    qprintln!("  Full uninstall:       lean-ctx uninstall");
253    qprintln!("  Diagnose issues:      lean-ctx doctor");
254    qprintln!("  Preview changes:      lean-ctx init --global --dry-run");
255    qprintln!();
256    if is_powershell {
257        qprintln!("  Restart PowerShell or run: . {rc}");
258    } else {
259        qprintln!("  Restart your shell or run: source ~/{rc}");
260    }
261    qprintln!();
262    qprintln!("For AI tool integration: lean-ctx init --agent <tool> [--mode <mode>]");
263    qprintln!("  Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
264    qprintln!(
265        "    claude, cline, codewhale, codex, commandcode, continue, copilot, crush, cursor, emacs, gemini,"
266    );
267    qprintln!("    grok, hermes, jetbrains, kiro, neovim, omp, openclaw, opencode, pi,");
268    qprintln!("    qoder, qodercli, qoderwork, qwen, roo, sublime, trae, verdent, vscode,");
269    qprintln!("    windsurf, zed");
270    qprintln!("  Modes: mcp, hybrid, replace  (auto-detected per agent, override with --mode)");
271    qprintln!("  Claude Code defaults to governor (no MCP server); MCP tools: --mode hybrid");
272}
273
274pub fn cmd_init_quiet(args: &[String]) {
275    let _quiet_guard = lean_ctx::core::runtime_flags::scoped_quiet();
276    cmd_init(args);
277}
278
279/// `--flag` → enable, `--flag off` / `--flag=off` → disable, absent → `None`.
280fn opt_in_flag(args: &[String], flag: &str) -> Option<bool> {
281    let pos = args
282        .iter()
283        .position(|a| a == flag || a.starts_with(&format!("{flag}=")))?;
284    let value = args[pos]
285        .strip_prefix(&format!("{flag}="))
286        .or_else(|| args.get(pos + 1).map(String::as_str));
287    Some(!matches!(value, Some("off" | "false" | "0")))
288}
289
290fn is_claude_agent(agent: &str) -> bool {
291    matches!(
292        agent.to_ascii_lowercase().as_str(),
293        "claude" | "claude-code"
294    )
295}
296
297/// `init --agent <host> --mode governor|governor-mcp`: the zero-overhead
298/// governor profile (`governor-mcp` is Claude Code only).
299fn init_governor(
300    agents: &[&str],
301    arm: lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm,
302) {
303    let Some(home) = lean_ctx::core::home::resolve_home_dir() else {
304        eprintln!("  ✗ cannot resolve the home directory");
305        std::process::exit(1);
306    };
307    if agents.is_empty() {
308        eprintln!("  ✗ --mode governor needs --agent <host>");
309        std::process::exit(1);
310    }
311    for agent in agents {
312        if !is_claude_agent(agent) {
313            init_host_governor(agent, arm, &home);
314            continue;
315        }
316        lean_ctx_hooks::hooks::agents::claude_governor::install(&home, arm);
317        if let Some(host) = lean_ctx_hooks::hooks::governor_default::host(agent) {
318            lean_ctx_hooks::hooks::governor_default::pin(host, None);
319        }
320        qprintln!("  ✓ Claude Code governor setup installed (revert: --mode hybrid)");
321        if let Err(e) = crate::setup::agent_selection::remember_connected_agent(agent) {
322            eprintln!("  ✗ {agent}: {e}");
323        }
324    }
325}
326
327/// `init --agent <host>` without `--mode` on a host with a governor: apply the
328/// default (new install or once-per-version migration). Returns whether the
329/// host is handled; `false` (pinned, or switched back this version) runs the
330/// standard setup.
331fn init_governor_default(agent: &str) -> bool {
332    use lean_ctx_hooks::hooks::governor_default::{Outcome, apply_default, host};
333    let (Some(host), Some(home)) = (host(agent), lean_ctx::core::home::resolve_home_dir()) else {
334        return false;
335    };
336    let outcome = apply_default(host, &home);
337    if outcome.ran_steps() {
338        let _ = crate::setup::agent_selection::remember_connected_agent(host.key);
339    }
340    if let Some(notice) = outcome.notice(host) {
341        qprintln!("  ✓ {notice}");
342    } else if outcome == Outcome::AlreadyGovernor {
343        (host.refresh)(&home);
344        qprintln!("  ✓ {} governor setup up to date", host.name);
345    }
346    !matches!(outcome, Outcome::Pinned(_) | Outcome::SkippedThisVersion)
347}
348
349/// `init --agent <host> --mode governor` for a host other than Claude Code.
350fn init_host_governor(
351    agent: &str,
352    arm: lean_ctx_hooks::hooks::agents::claude_governor::GovernorArm,
353    home: &std::path::Path,
354) {
355    use lean_ctx_hooks::hooks::agents::{claude_governor::GovernorArm, governor_hosts};
356    let Some(spec) = governor_hosts::governor_available(agent) else {
357        eprintln!("  • {agent}: no tool hooks LeanCTX can govern; keeps the MCP setup");
358        return;
359    };
360    if arm == GovernorArm::McpDeferred {
361        eprintln!("  • {agent}: governor-mcp is Claude Code only; use --mode governor");
362        return;
363    }
364    governor_hosts::install(spec, home);
365    qprintln!(
366        "  ✓ {} {} setup installed (switch back: {})",
367        spec.name,
368        spec.class.label(),
369        spec.switch_back
370    );
371    if let Err(e) = crate::setup::agent_selection::remember_connected_agent(agent) {
372        eprintln!("  ✗ {agent}: {e}");
373    }
374}
375
376/// Help for `lean-ctx init`. Printed for `--help`/`-h`, whatever else is on
377/// the line, and never followed by an init.
378fn print_init_help() {
379    println!("Usage: lean-ctx init [options]");
380    println!("       lean-ctx init <bash|zsh|fish|powershell|pwsh>");
381    println!();
382    println!("Installs the shell aliases, or connects an AI tool with --agent.");
383    println!("The second form prints the shell hook to stdout for `eval` and writes nothing.");
384    println!();
385    println!("Options:");
386    println!("  --global, -g        Install the shell aliases into your shell profile");
387    println!("  --agent <tool>      Configure an AI tool: MCP, hooks and rules (repeatable)");
388    println!("  --mode <mode>       Hook mode for --agent: mcp, hybrid or replace");
389    println!("                      (auto-detected per agent when omitted). Claude Code,");
390    println!("                      CodeBuddy, Cursor, Codex, Gemini and Copilot CLI default");
391    println!("                      to governor (native tools + hooks, no MCP); an explicit");
392    println!("                      mode there is kept by later updates (Claude Code also:");
393    println!("                      governor-mcp)");
394    println!("  --project           With --agent: also install project-local hooks");
395    println!("  --no-shell-hook     Skip the shell aliases; MCP tools stay active");
396    println!("  --dry-run           Show what the shell setup would change, change nothing");
397    println!("  --prompt [off]      Show what lean-ctx did in your shell prompt (zsh, bash,");
398    println!("                      fish; prints a module for Starship). `off` removes it");
399    println!("  --git-trailer [off] Add a `lean-ctx:` trailer to this repo's commit messages.");
400    println!("                      `off` removes the hook");
401    println!("  --help, -h          Show this help (never runs init)");
402    println!();
403    println!("Examples:");
404    println!("  lean-ctx init --global --dry-run");
405    println!("  lean-ctx init --global");
406    println!("  lean-ctx init --prompt");
407    println!("  lean-ctx init --agent claude");
408    println!("  lean-ctx init --agent codex --mode hybrid");
409}
410
411#[cfg(test)]
412mod tests {
413    use super::opt_in_flag;
414
415    fn args(a: &[&str]) -> Vec<String> {
416        a.iter().map(ToString::to_string).collect()
417    }
418
419    #[test]
420    fn opt_in_flags_parse_on_and_off() {
421        assert_eq!(opt_in_flag(&args(&["--prompt"]), "--prompt"), Some(true));
422        assert_eq!(
423            opt_in_flag(&args(&["--prompt", "off"]), "--prompt"),
424            Some(false)
425        );
426        assert_eq!(
427            opt_in_flag(&args(&["--prompt=false"]), "--prompt"),
428            Some(false)
429        );
430        assert_eq!(
431            opt_in_flag(&args(&["--git-trailer", "0"]), "--git-trailer"),
432            Some(false)
433        );
434        assert_eq!(opt_in_flag(&args(&["--global"]), "--prompt"), None);
435        // `--prompt-foo` is not `--prompt`.
436        assert_eq!(opt_in_flag(&args(&["--prompt-foo"]), "--prompt"), None);
437    }
438
439    /// `init --mode hybrid` after a governor migration restores the standard
440    /// setup and pins it, so the next update leaves it alone.
441    #[test]
442    fn revert_restores_the_standard_setup_pinned() {
443        use lean_ctx::test_env;
444        use lean_ctx_hooks::hooks::agents::claude_governor;
445        use lean_ctx_hooks::hooks::governor_default::{Outcome, apply_default, host, pinned_mode};
446
447        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
448        let home = tempfile::tempdir().unwrap();
449        let prev_home = std::env::var_os("HOME");
450        test_env::set_var("HOME", home.path());
451        test_env::set_var("LEAN_CTX_HOOK_BINARY", "lean-ctx");
452        for var in ["CLAUDE_CONFIG_DIR", "LEAN_CTX_HOOK_MODE", "LEAN_CTX_QUIET"] {
453            test_env::remove_var(var);
454        }
455        let h = home.path();
456        let read = |p: &str| std::fs::read_to_string(h.join(p)).unwrap_or_default();
457        let mcp = || serde_json::from_str::<serde_json::Value>(&read(".claude.json")).unwrap();
458        // A pre-governor standard install: MCP entry and rules block below
459        // the user's own text.
460        std::fs::create_dir_all(h.join(".claude")).unwrap();
461        std::fs::write(
462            h.join(".claude.json"),
463            r#"{"projects":{"/x":{}},"mcpServers":{"lean-ctx":{"command":"lean-ctx","alwaysLoad":true},"other":{"command":"o"}}}"#,
464        )
465        .unwrap();
466        std::fs::write(
467            h.join(".claude/CLAUDE.md"),
468            "# My notes\nkeep me\n\n<!-- lean-ctx -->\nstandard block: use ctx_read\n<!-- /lean-ctx -->\n",
469        )
470        .unwrap();
471
472        let claude = host("claude").unwrap();
473        assert!(matches!(apply_default(claude, h), Outcome::Migrated(_)));
474        super::cmd_init_quiet(&args(&[
475            "--agent", "claude", "--mode", "hybrid", "--global",
476        ]));
477
478        assert!(!claude_governor::is_installed(h));
479        let settings = read(".claude/settings.json");
480        assert!(settings.contains("lean-ctx hook rewrite"), "{settings}");
481        assert!(!settings.contains("hook govern"), "{settings}");
482        assert!(mcp().pointer("/mcpServers/lean-ctx").is_some(), "MCP back");
483        assert!(read(".claude/CLAUDE.md").starts_with("# My notes\nkeep me\n"));
484        assert_eq!(pinned_mode(claude).as_deref(), Some("hybrid"));
485        // The next update leaves the pinned choice alone.
486        let before = (read(".claude/settings.json"), read(".claude/CLAUDE.md"));
487        assert_eq!(apply_default(claude, h), Outcome::Pinned("hybrid".into()));
488        assert_eq!(
489            (read(".claude/settings.json"), read(".claude/CLAUDE.md")),
490            before
491        );
492
493        test_env::remove_var("LEAN_CTX_HOOK_BINARY");
494        match prev_home {
495            Some(p) => test_env::set_var("HOME", p),
496            None => test_env::remove_var("HOME"),
497        }
498    }
499}