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 if args.iter().any(|a| a == "--help" || a == "-h") {
21 print_init_help();
22 return;
23 }
24 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 agent_name.eq_ignore_ascii_case("hermes") {
91 qprintln!("\n Beyond MCP, lean-ctx can be Hermes' active context engine");
92 qprintln!(" (replaces the built-in ContextCompressor). Install the plugin from");
93 qprintln!(" integrations/hermes-lean-ctx (scripts/install.sh), then set");
94 qprintln!(" context.engine: \"lean-ctx\" in ~/.hermes/config.yaml.");
95 }
96 if project {
97 crate::hooks::install_agent_project_hooks(agent_name, &cwd);
98 }
99 }
100 if !global {
101 crate::hooks::install_project_rules_for_agents(&agents);
102 }
103 qprintln!("\nRun 'lean-ctx gain' after using some commands to see your savings.");
104 return;
105 }
106
107 let eval_shell = args
108 .iter()
109 .find(|a| matches!(a.as_str(), "bash" | "zsh" | "fish" | "powershell" | "pwsh"));
110 if let Some(shell) = eval_shell
111 && !global
112 {
113 super::shell_init::print_hook_stdout(shell);
114 return;
115 }
116
117 let shell_name = std::env::var("SHELL").unwrap_or_default();
118 let is_zsh = shell_name.contains("zsh");
119 let is_fish = shell_name.contains("fish");
120 let is_powershell = cfg!(windows) && shell_name.is_empty();
121
122 let binary = crate::core::portable_binary::stable_shell_binary(
125 &crate::core::portable_binary::resolve_portable_binary(),
126 );
127
128 if dry_run {
129 let rc = if is_powershell {
130 dirs::home_dir().map_or_else(
131 || "PowerShell profile".to_string(),
132 |h| {
133 crate::shell::platform::resolve_powershell_profile_path(&h)
134 .to_string_lossy()
135 .into_owned()
136 },
137 )
138 } else if is_fish {
139 "~/.config/fish/config.fish".to_string()
140 } else if is_zsh {
141 "~/.zshrc".to_string()
142 } else {
143 "~/.bashrc".to_string()
144 };
145 qprintln!("\nlean-ctx init --dry-run\n");
146 qprintln!(" Would modify: {rc}");
147 qprintln!(" Would backup: {rc}.lean-ctx.bak");
148 qprintln!(" Would alias: git npm pnpm yarn cargo docker docker-compose kubectl");
149 qprintln!(" gh pip pip3 ruff go golangci-lint eslint prettier tsc");
150 qprintln!(" curl wget php composer (24 commands + k)");
151 let data_dir = crate::core::data_dir::lean_ctx_data_dir().map_or_else(
152 |_| "~/.config/lean-ctx/".to_string(),
153 |p| p.to_string_lossy().to_string(),
154 );
155 qprintln!(" Would create: {data_dir}");
156 qprintln!(" Binary: {binary}");
157 qprintln!("\n Safety: aliases auto-fallback to original command if lean-ctx is removed.");
158 qprintln!("\n Run without --dry-run to apply.");
159 return;
160 }
161
162 if no_hook {
163 qprintln!("Shell hook disabled (--no-shell-hook or shell_hook_disabled config).");
164 qprintln!("MCP tools remain active. Set LEAN_CTX_NO_HOOK=1 to disable at runtime.");
165 } else if is_powershell {
166 super::shell_init::init_powershell(&binary);
167 } else {
168 let bash_binary = to_bash_compatible_path(&binary);
169 if is_fish {
170 super::shell_init::init_fish(&bash_binary);
171 } else {
172 super::shell_init::init_posix(is_zsh, &bash_binary);
173 }
174 }
175
176 if let Ok(lean_dir) = crate::core::data_dir::lean_ctx_data_dir()
177 && !lean_dir.exists()
178 {
179 let _ = std::fs::create_dir_all(&lean_dir);
180 qprintln!("Created {}", lean_dir.display());
181 }
182
183 let rc = if is_powershell {
184 "$PROFILE"
185 } else if is_fish {
186 "config.fish"
187 } else if is_zsh {
188 ".zshrc"
189 } else {
190 ".bashrc"
191 };
192
193 qprintln!("\nlean-ctx init complete (24 aliases installed)");
194 qprintln!();
195 qprintln!(" Disable temporarily: lean-ctx-off");
196 qprintln!(" Re-enable: lean-ctx-on");
197 qprintln!(" Check status: lean-ctx-status");
198 qprintln!(" Full uninstall: lean-ctx uninstall");
199 qprintln!(" Diagnose issues: lean-ctx doctor");
200 qprintln!(" Preview changes: lean-ctx init --global --dry-run");
201 qprintln!();
202 if is_powershell {
203 qprintln!(" Restart PowerShell or run: . {rc}");
204 } else {
205 qprintln!(" Restart your shell or run: source ~/{rc}");
206 }
207 qprintln!();
208 qprintln!("For AI tool integration: lean-ctx init --agent <tool> [--mode <mode>]");
209 qprintln!(" Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
210 qprintln!(
211 " claude, cline, codewhale, codex, commandcode, continue, copilot, crush, cursor, emacs, gemini,"
212 );
213 qprintln!(" grok, hermes, jetbrains, kiro, neovim, omp, openclaw, opencode, pi,");
214 qprintln!(" qoder, qodercli, qoderwork, qwen, roo, sublime, trae, verdent, vscode,");
215 qprintln!(" windsurf, zed");
216 qprintln!(" Modes: mcp, hybrid, replace (auto-detected per agent, override with --mode)");
217}
218
219pub fn cmd_init_quiet(args: &[String]) {
220 let _quiet_guard = crate::core::runtime_flags::scoped_quiet();
221 cmd_init(args);
222}
223
224fn opt_in_flag(args: &[String], flag: &str) -> Option<bool> {
226 let pos = args
227 .iter()
228 .position(|a| a == flag || a.starts_with(&format!("{flag}=")))?;
229 let value = args[pos]
230 .strip_prefix(&format!("{flag}="))
231 .or_else(|| args.get(pos + 1).map(String::as_str));
232 Some(!matches!(value, Some("off" | "false" | "0")))
233}
234
235fn print_init_help() {
238 println!("Usage: lean-ctx init [options]");
239 println!(" lean-ctx init <bash|zsh|fish|powershell|pwsh>");
240 println!();
241 println!("Installs the shell aliases, or connects an AI tool with --agent.");
242 println!("The second form prints the shell hook to stdout for `eval` and writes nothing.");
243 println!();
244 println!("Options:");
245 println!(" --global, -g Install the shell aliases into your shell profile");
246 println!(" --agent <tool> Configure an AI tool: MCP, hooks and rules (repeatable)");
247 println!(" --mode <mode> Hook mode for --agent: mcp, hybrid or replace");
248 println!(" (auto-detected per agent when omitted)");
249 println!(" --project With --agent: also install project-local hooks");
250 println!(" --no-shell-hook Skip the shell aliases; MCP tools stay active");
251 println!(" --dry-run Show what the shell setup would change, change nothing");
252 println!(" --prompt [off] Show what lean-ctx did in your shell prompt (zsh, bash,");
253 println!(" fish; prints a module for Starship). `off` removes it");
254 println!(" --git-trailer [off] Add a `lean-ctx:` trailer to this repo's commit messages.");
255 println!(" `off` removes the hook");
256 println!(" --help, -h Show this help (never runs init)");
257 println!();
258 println!("Examples:");
259 println!(" lean-ctx init --global --dry-run");
260 println!(" lean-ctx init --global");
261 println!(" lean-ctx init --prompt");
262 println!(" lean-ctx init --agent claude");
263 println!(" lean-ctx init --agent codex --mode hybrid");
264}
265
266#[cfg(test)]
267mod tests {
268 use super::opt_in_flag;
269
270 fn args(a: &[&str]) -> Vec<String> {
271 a.iter().map(ToString::to_string).collect()
272 }
273
274 #[test]
275 fn opt_in_flags_parse_on_and_off() {
276 assert_eq!(opt_in_flag(&args(&["--prompt"]), "--prompt"), Some(true));
277 assert_eq!(
278 opt_in_flag(&args(&["--prompt", "off"]), "--prompt"),
279 Some(false)
280 );
281 assert_eq!(
282 opt_in_flag(&args(&["--prompt=false"]), "--prompt"),
283 Some(false)
284 );
285 assert_eq!(
286 opt_in_flag(&args(&["--git-trailer", "0"]), "--git-trailer"),
287 Some(false)
288 );
289 assert_eq!(opt_in_flag(&args(&["--global"]), "--prompt"), None);
290 assert_eq!(opt_in_flag(&args(&["--prompt-foo"]), "--prompt"), None);
292 }
293}