Skip to main content

lean_ctx/cli/
init_cmd.rs

1use crate::hooks::to_bash_compatible_path;
2
3pub(crate) fn quiet_enabled() -> bool {
4    crate::core::runtime_flags::quiet_enabled()
5}
6
7macro_rules! qprintln {
8    ($($t:tt)*) => {
9        if !quiet_enabled() {
10            println!($($t)*);
11        }
12    };
13}
14
15pub fn cmd_init(args: &[String]) {
16    // Safety (#476 class, #1849): asking about init must never *run* it —
17    // `init --agent claude --help` used to write the agent's rules file. The
18    // guard sits here rather than in the dispatcher so every entry point
19    // (`cmd_init_quiet`, `doctor --fix`) inherits it.
20    if args.iter().any(|a| a == "--help" || a == "-h") {
21        print_init_help();
22        return;
23    }
24    // Opt-in value surfaces: each is its own step, never part of the alias setup.
25    if let Some(enable) = opt_in_flag(args, "--prompt") {
26        let binary = crate::core::portable_binary::stable_shell_binary(
27            &crate::core::portable_binary::resolve_portable_binary(),
28        );
29        super::prompt_init::cmd_init_prompt(enable, &binary);
30        return;
31    }
32    if let Some(enable) = opt_in_flag(args, "--git-trailer") {
33        super::git_trailer::cmd_init_git_trailer(enable);
34        return;
35    }
36    let global = args.iter().any(|a| a == "--global" || a == "-g");
37    let project = args.iter().any(|a| a == "--project");
38    let dry_run = args.iter().any(|a| a == "--dry-run");
39    let no_hook = args.iter().any(|a| a == "--no-shell-hook")
40        || crate::core::config::Config::load().shell_hook_disabled_effective();
41
42    let explicit_mode = args
43        .windows(2)
44        .find(|w| w[0] == "--mode")
45        .and_then(|w| crate::hooks::HookMode::from_str_loose(&w[1]));
46
47    if args.windows(2).any(|w| w[0] == "--mode")
48        && !args
49            .windows(2)
50            .any(|w| w[0] == "--mode" && crate::hooks::HookMode::from_str_loose(&w[1]).is_some())
51    {
52        let bad = args
53            .windows(2)
54            .find(|w| w[0] == "--mode")
55            .map_or("?", |w| w[1].as_str());
56        eprintln!("Unknown hook mode: '{bad}'. Valid: mcp, hybrid, replace");
57        std::process::exit(1);
58    }
59
60    let agents: Vec<&str> = args
61        .windows(2)
62        .filter(|w| w[0] == "--agent")
63        .map(|w| w[1].as_str())
64        .collect();
65
66    if !agents.is_empty() {
67        let cwd = std::env::current_dir().unwrap_or_default();
68        for agent_name in &agents {
69            let mode =
70                explicit_mode.unwrap_or_else(|| crate::hooks::recommend_hook_mode(agent_name));
71            let result = crate::setup::setup_single_agent(agent_name, global, mode);
72            for name in &result.rules.injected {
73                qprintln!("  ✓ {name} rules injected");
74            }
75            for name in &result.rules.updated {
76                qprintln!("  ✓ {name} rules updated");
77            }
78            for name in &result.rules.already {
79                qprintln!("  ✓ {name} rules up-to-date");
80            }
81            if result.skill_installed {
82                qprintln!("  ✓ SKILL.md installed for {agent_name}");
83            }
84            if result.mcp_skipped {
85                qprintln!("  • MCP registration skipped for {agent_name} (auto_update_mcp=false)");
86            }
87            for e in &result.errors {
88                eprintln!("  ✗ {agent_name}: {e}");
89            }
90            if result.errors.is_empty()
91                && let Err(e) = crate::setup::agent_selection::remember_connected_agent(agent_name)
92            {
93                eprintln!("  ✗ {agent_name}: {e}");
94            }
95            if agent_name.eq_ignore_ascii_case("hermes") {
96                qprintln!("\n  Beyond MCP, lean-ctx can be Hermes' active context engine");
97                qprintln!("  (replaces the built-in ContextCompressor). Install the plugin from");
98                qprintln!("  integrations/hermes-lean-ctx (scripts/install.sh), then set");
99                qprintln!("  context.engine: \"lean-ctx\" in ~/.hermes/config.yaml.");
100            }
101            if project {
102                crate::hooks::install_agent_project_hooks(agent_name, &cwd);
103            }
104        }
105        if !global {
106            crate::hooks::install_project_rules_for_agents(&agents);
107        }
108        qprintln!("\nRun 'lean-ctx cockpit' after using some commands to see your savings.");
109        return;
110    }
111
112    let eval_shell = args
113        .iter()
114        .find(|a| matches!(a.as_str(), "bash" | "zsh" | "fish" | "powershell" | "pwsh"));
115    if let Some(shell) = eval_shell
116        && !global
117    {
118        super::shell_init::print_hook_stdout(shell);
119        return;
120    }
121
122    let shell_name = std::env::var("SHELL").unwrap_or_default();
123    let is_zsh = shell_name.contains("zsh");
124    let is_fish = shell_name.contains("fish");
125    let is_powershell = cfg!(windows) && shell_name.is_empty();
126
127    // Shell hooks outlive the build that wrote them: embed the stable PATH
128    // entry, not a versioned package-manager directory (#1851).
129    let binary = crate::core::portable_binary::stable_shell_binary(
130        &crate::core::portable_binary::resolve_portable_binary(),
131    );
132
133    if dry_run {
134        let rc = if is_powershell {
135            dirs::home_dir().map_or_else(
136                || "PowerShell profile".to_string(),
137                |h| {
138                    crate::shell::platform::resolve_powershell_profile_path(&h)
139                        .to_string_lossy()
140                        .into_owned()
141                },
142            )
143        } else if is_fish {
144            "~/.config/fish/config.fish".to_string()
145        } else if is_zsh {
146            "~/.zshrc".to_string()
147        } else {
148            "~/.bashrc".to_string()
149        };
150        qprintln!("\nlean-ctx init --dry-run\n");
151        qprintln!("  Would modify:  {rc}");
152        qprintln!("  Would backup:  {rc}.lean-ctx.bak");
153        qprintln!("  Would alias:   git npm pnpm yarn cargo docker docker-compose kubectl");
154        qprintln!("                 gh pip pip3 ruff go golangci-lint eslint prettier tsc");
155        qprintln!("                 curl wget php composer (24 commands + k)");
156        let data_dir = crate::core::data_dir::lean_ctx_data_dir().map_or_else(
157            |_| "~/.config/lean-ctx/".to_string(),
158            |p| p.to_string_lossy().to_string(),
159        );
160        qprintln!("  Would create:  {data_dir}");
161        qprintln!("  Binary:        {binary}");
162        qprintln!("\n  Safety: aliases auto-fallback to original command if lean-ctx is removed.");
163        qprintln!("\n  Run without --dry-run to apply.");
164        return;
165    }
166
167    if no_hook {
168        qprintln!("Shell hook disabled (--no-shell-hook or shell_hook_disabled config).");
169        qprintln!("MCP tools remain active. Set LEAN_CTX_NO_HOOK=1 to disable at runtime.");
170    } else if is_powershell {
171        super::shell_init::init_powershell(&binary);
172    } else {
173        let bash_binary = to_bash_compatible_path(&binary);
174        if is_fish {
175            super::shell_init::init_fish(&bash_binary);
176        } else {
177            super::shell_init::init_posix(is_zsh, &bash_binary);
178        }
179    }
180
181    if let Ok(lean_dir) = crate::core::data_dir::lean_ctx_data_dir()
182        && !lean_dir.exists()
183    {
184        let _ = std::fs::create_dir_all(&lean_dir);
185        qprintln!("Created {}", lean_dir.display());
186    }
187
188    let rc = if is_powershell {
189        "$PROFILE"
190    } else if is_fish {
191        "config.fish"
192    } else if is_zsh {
193        ".zshrc"
194    } else {
195        ".bashrc"
196    };
197
198    qprintln!("\nlean-ctx init complete (24 aliases installed)");
199    qprintln!();
200    qprintln!("  Disable temporarily:  lean-ctx-off");
201    qprintln!("  Re-enable:            lean-ctx-on");
202    qprintln!("  Check status:         lean-ctx-status");
203    qprintln!("  Full uninstall:       lean-ctx uninstall");
204    qprintln!("  Diagnose issues:      lean-ctx doctor");
205    qprintln!("  Preview changes:      lean-ctx init --global --dry-run");
206    qprintln!();
207    if is_powershell {
208        qprintln!("  Restart PowerShell or run: . {rc}");
209    } else {
210        qprintln!("  Restart your shell or run: source ~/{rc}");
211    }
212    qprintln!();
213    qprintln!("For AI tool integration: lean-ctx init --agent <tool> [--mode <mode>]");
214    qprintln!("  Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
215    qprintln!(
216        "    claude, cline, codewhale, codex, commandcode, continue, copilot, crush, cursor, emacs, gemini,"
217    );
218    qprintln!("    grok, hermes, jetbrains, kiro, neovim, omp, openclaw, opencode, pi,");
219    qprintln!("    qoder, qodercli, qoderwork, qwen, roo, sublime, trae, verdent, vscode,");
220    qprintln!("    windsurf, zed");
221    qprintln!("  Modes: mcp, hybrid, replace  (auto-detected per agent, override with --mode)");
222}
223
224pub fn cmd_init_quiet(args: &[String]) {
225    let _quiet_guard = crate::core::runtime_flags::scoped_quiet();
226    cmd_init(args);
227}
228
229/// `--flag` → enable, `--flag off` / `--flag=off` → disable, absent → `None`.
230fn opt_in_flag(args: &[String], flag: &str) -> Option<bool> {
231    let pos = args
232        .iter()
233        .position(|a| a == flag || a.starts_with(&format!("{flag}=")))?;
234    let value = args[pos]
235        .strip_prefix(&format!("{flag}="))
236        .or_else(|| args.get(pos + 1).map(String::as_str));
237    Some(!matches!(value, Some("off" | "false" | "0")))
238}
239
240/// Help for `lean-ctx init`. Printed for `--help`/`-h`, whatever else is on
241/// the line, and never followed by an init.
242fn print_init_help() {
243    println!("Usage: lean-ctx init [options]");
244    println!("       lean-ctx init <bash|zsh|fish|powershell|pwsh>");
245    println!();
246    println!("Installs the shell aliases, or connects an AI tool with --agent.");
247    println!("The second form prints the shell hook to stdout for `eval` and writes nothing.");
248    println!();
249    println!("Options:");
250    println!("  --global, -g        Install the shell aliases into your shell profile");
251    println!("  --agent <tool>      Configure an AI tool: MCP, hooks and rules (repeatable)");
252    println!("  --mode <mode>       Hook mode for --agent: mcp, hybrid or replace");
253    println!("                      (auto-detected per agent when omitted)");
254    println!("  --project           With --agent: also install project-local hooks");
255    println!("  --no-shell-hook     Skip the shell aliases; MCP tools stay active");
256    println!("  --dry-run           Show what the shell setup would change, change nothing");
257    println!("  --prompt [off]      Show what lean-ctx did in your shell prompt (zsh, bash,");
258    println!("                      fish; prints a module for Starship). `off` removes it");
259    println!("  --git-trailer [off] Add a `lean-ctx:` trailer to this repo's commit messages.");
260    println!("                      `off` removes the hook");
261    println!("  --help, -h          Show this help (never runs init)");
262    println!();
263    println!("Examples:");
264    println!("  lean-ctx init --global --dry-run");
265    println!("  lean-ctx init --global");
266    println!("  lean-ctx init --prompt");
267    println!("  lean-ctx init --agent claude");
268    println!("  lean-ctx init --agent codex --mode hybrid");
269}
270
271#[cfg(test)]
272mod tests {
273    use super::opt_in_flag;
274
275    fn args(a: &[&str]) -> Vec<String> {
276        a.iter().map(ToString::to_string).collect()
277    }
278
279    #[test]
280    fn opt_in_flags_parse_on_and_off() {
281        assert_eq!(opt_in_flag(&args(&["--prompt"]), "--prompt"), Some(true));
282        assert_eq!(
283            opt_in_flag(&args(&["--prompt", "off"]), "--prompt"),
284            Some(false)
285        );
286        assert_eq!(
287            opt_in_flag(&args(&["--prompt=false"]), "--prompt"),
288            Some(false)
289        );
290        assert_eq!(
291            opt_in_flag(&args(&["--git-trailer", "0"]), "--git-trailer"),
292            Some(false)
293        );
294        assert_eq!(opt_in_flag(&args(&["--global"]), "--prompt"), None);
295        // `--prompt-foo` is not `--prompt`.
296        assert_eq!(opt_in_flag(&args(&["--prompt-foo"]), "--prompt"), None);
297    }
298}