Skip to main content

lean_ctx/setup/
mod.rs

1use std::path::PathBuf;
2
3use crate::core::editor_registry::{ConfigType, EditorTarget, WriteAction, WriteOptions};
4use crate::core::portable_binary::resolve_portable_binary;
5use crate::core::setup_report::{PlatformInfo, SetupItem, SetupReport, SetupStepReport};
6use crate::hooks::{recommend_hook_mode, HookMode};
7use chrono::Utc;
8use std::ffi::OsString;
9mod mcp;
10pub use mcp::*;
11mod helpers;
12pub use helpers::*;
13
14pub fn claude_config_json_path(home: &std::path::Path) -> PathBuf {
15    crate::core::editor_registry::claude_mcp_json_path(home)
16}
17
18pub fn claude_config_dir(home: &std::path::Path) -> PathBuf {
19    crate::core::editor_registry::claude_state_dir(home)
20}
21
22pub(crate) struct EnvVarGuard {
23    key: &'static str,
24    previous: Option<OsString>,
25}
26
27impl EnvVarGuard {
28    pub(crate) fn set(key: &'static str, value: &str) -> Self {
29        let previous = std::env::var_os(key);
30        std::env::set_var(key, value);
31        Self { key, previous }
32    }
33}
34
35impl Drop for EnvVarGuard {
36    fn drop(&mut self) {
37        if let Some(previous) = &self.previous {
38            std::env::set_var(self.key, previous);
39        } else {
40            std::env::remove_var(self.key);
41        }
42    }
43}
44
45/// Determine the setup level from a first-run interactive menu.
46/// Returns (inject_rules, inject_skills).
47fn first_run_setup_level() -> (bool, bool) {
48    use std::io::Write;
49
50    let cfg = crate::core::config::Config::load();
51    if cfg.setup.auto_inject_rules.is_some() {
52        return (
53            cfg.setup.should_inject_rules(),
54            cfg.setup.should_inject_skills(),
55        );
56    }
57
58    println!();
59    println!("  \x1b[1mWelcome to lean-ctx!\x1b[0m");
60    println!();
61    println!("  lean-ctx compresses AI context by 60-99%, saving tokens and money.");
62    println!();
63    println!("  Choose your setup level:");
64    println!("    \x1b[36m[1]\x1b[0m Minimal  \x1b[2m— Just MCP tools, no config file changes (recommended)\x1b[0m");
65    println!("    \x1b[36m[2]\x1b[0m Standard \x1b[2m— MCP tools + agent instructions for optimal mode selection\x1b[0m");
66    println!("    \x1b[36m[3]\x1b[0m Full     \x1b[2m— Everything (tools + rules + skills + shell hooks)\x1b[0m");
67    println!();
68    print!("  Your choice \x1b[1m[1]\x1b[0m: ");
69    std::io::stdout().flush().ok();
70
71    let mut input = String::new();
72    let choice = if std::io::stdin().read_line(&mut input).is_ok() {
73        input.trim().parse::<u8>().unwrap_or(1)
74    } else {
75        1
76    };
77
78    match choice {
79        3 => (true, true),
80        2 => (true, false),
81        _ => (false, false),
82    }
83}
84
85/// Persist the user's setup level choice to config.toml.
86fn persist_setup_choice(inject_rules: bool, inject_skills: bool) {
87    let mut cfg = crate::core::config::Config::load();
88    cfg.setup.auto_inject_rules = Some(inject_rules);
89    cfg.setup.auto_inject_skills = Some(inject_skills);
90    let _ = cfg.save();
91}
92
93pub fn run_setup() {
94    use crate::terminal_ui;
95
96    if crate::shell::is_non_interactive() {
97        eprintln!("Non-interactive terminal detected (no TTY on stdin).");
98        eprintln!("Running in non-interactive mode (equivalent to: lean-ctx setup --non-interactive --yes)");
99        eprintln!();
100        let opts = SetupOptions {
101            non_interactive: true,
102            yes: true,
103            ..Default::default()
104        };
105        match run_setup_with_options(opts) {
106            Ok(report) => {
107                if !report.warnings.is_empty() {
108                    for w in &report.warnings {
109                        tracing::warn!("{w}");
110                    }
111                }
112            }
113            Err(e) => tracing::error!("Setup error: {e}"),
114        }
115        return;
116    }
117
118    let Some(home) = dirs::home_dir() else {
119        tracing::error!("Cannot determine home directory");
120        std::process::exit(1);
121    };
122
123    let binary = resolve_portable_binary();
124
125    let home_str = home.to_string_lossy().to_string();
126
127    terminal_ui::print_setup_header();
128
129    let (inject_rules, inject_skills) = first_run_setup_level();
130    persist_setup_choice(inject_rules, inject_skills);
131
132    // Step 1: Shell hook (legacy aliases + universal shell hook)
133    terminal_ui::print_step_header(1, 12, "Shell Hook");
134    crate::cli::cmd_init(&["--global".to_string()]);
135    crate::shell_hook::install_all(false);
136
137    // Step 2: Daemon (optional acceleration for CLI routing)
138    terminal_ui::print_step_header(2, 12, "Daemon");
139    if crate::daemon::is_daemon_running() {
140        terminal_ui::print_status_ok("Daemon running — restarting with current binary…");
141        let _ = crate::daemon::stop_daemon();
142        std::thread::sleep(std::time::Duration::from_millis(500));
143        if let Err(e) = crate::daemon::start_daemon(&[]) {
144            terminal_ui::print_status_warn(&format!("Daemon restart failed: {e}"));
145        }
146    } else if let Err(e) = crate::daemon::start_daemon(&[]) {
147        terminal_ui::print_status_warn(&format!("Daemon start failed: {e}"));
148    }
149
150    // Step 3: Editor auto-detection + configuration
151    terminal_ui::print_step_header(3, 12, "AI Tool Detection");
152
153    let targets = crate::core::editor_registry::build_targets(&home);
154    let mut newly_configured: Vec<&str> = Vec::new();
155    let mut already_configured: Vec<&str> = Vec::new();
156    let mut not_installed: Vec<&str> = Vec::new();
157    let mut errors: Vec<&str> = Vec::new();
158
159    for target in &targets {
160        let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
161
162        if !target.detect_path.exists() {
163            not_installed.push(target.name);
164            continue;
165        }
166
167        let mode = if target.agent_key.is_empty() {
168            HookMode::Mcp
169        } else {
170            recommend_hook_mode(&target.agent_key)
171        };
172
173        match crate::core::editor_registry::write_config_with_options(
174            target,
175            &binary,
176            WriteOptions {
177                overwrite_invalid: false,
178            },
179        ) {
180            Ok(res) if res.action == WriteAction::Already => {
181                terminal_ui::print_status_ok(&format!(
182                    "{:<20} \x1b[36m{mode}\x1b[0m  \x1b[2m{short_path}\x1b[0m",
183                    target.name
184                ));
185                already_configured.push(target.name);
186            }
187            Ok(_) => {
188                terminal_ui::print_status_new(&format!(
189                    "{:<20} \x1b[36m{mode}\x1b[0m  \x1b[2m{short_path}\x1b[0m",
190                    target.name
191                ));
192                newly_configured.push(target.name);
193            }
194            Err(e) => {
195                terminal_ui::print_status_warn(&format!("{}: {e}", target.name));
196                errors.push(target.name);
197            }
198        }
199    }
200
201    let total_ok = newly_configured.len() + already_configured.len();
202    if total_ok == 0 && errors.is_empty() {
203        terminal_ui::print_status_warn(
204            "No AI tools detected. Install one and re-run: lean-ctx setup",
205        );
206    }
207
208    if !not_installed.is_empty() {
209        println!(
210            "  \x1b[2m○ {} not detected: {}\x1b[0m",
211            not_installed.len(),
212            not_installed.join(", ")
213        );
214    }
215
216    configure_plan_mode_settings(&newly_configured, &already_configured);
217
218    // Step 4: Agent rules injection (only if user opted in)
219    terminal_ui::print_step_header(4, 12, "Agent Rules");
220    let rules_result = if inject_rules {
221        let r = crate::rules_inject::inject_all_rules(&home);
222        for name in &r.injected {
223            terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules injected\x1b[0m"));
224        }
225        for name in &r.updated {
226            terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules updated\x1b[0m"));
227        }
228        for name in &r.already {
229            terminal_ui::print_status_ok(&format!("{name:<20} \x1b[2mrules up-to-date\x1b[0m"));
230        }
231        for err in &r.errors {
232            terminal_ui::print_status_warn(err);
233        }
234        if !r.backed_up.is_empty() {
235            for bak in &r.backed_up {
236                println!("  \x1b[2m  ↳ backup: {bak}\x1b[0m");
237            }
238        }
239        if r.injected.is_empty()
240            && r.updated.is_empty()
241            && r.already.is_empty()
242            && r.errors.is_empty()
243        {
244            terminal_ui::print_status_skip("No agent rules needed");
245        }
246        r
247    } else {
248        terminal_ui::print_status_skip("Skipped (run `lean-ctx setup --inject-rules` to enable)");
249        crate::rules_inject::InjectResult::default()
250    };
251
252    // Agent hooks (mode-aware)
253    for target in &targets {
254        if !target.detect_path.exists() || target.agent_key.is_empty() {
255            continue;
256        }
257        let mode = recommend_hook_mode(&target.agent_key);
258        crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
259    }
260
261    // Step 5: API Proxy (opt-in)
262    terminal_ui::print_step_header(5, 12, "API Proxy (optional)");
263    {
264        let mut cfg = crate::core::config::Config::load();
265        let proxy_port = crate::proxy_setup::default_port();
266
267        match cfg.proxy_enabled {
268            Some(true) => {
269                crate::proxy_autostart::install(proxy_port, false);
270                std::thread::sleep(std::time::Duration::from_millis(500));
271                crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
272                terminal_ui::print_status_ok("Proxy active (opted in)");
273            }
274            Some(false) => {
275                terminal_ui::print_status_skip(
276                    "Proxy disabled (run `lean-ctx proxy enable` to change)",
277                );
278            }
279            None => {
280                println!(
281                    "  \x1b[2mThe API proxy routes LLM requests through lean-ctx for additional\x1b[0m"
282                );
283                println!(
284                    "  \x1b[2mtool-result compression and precise token analytics in the dashboard.\x1b[0m"
285                );
286                println!();
287                println!(
288                    "  \x1b[2mWithout it: MCP tools, shell hooks, gain tracking, and memory\x1b[0m"
289                );
290                println!(
291                    "  \x1b[2mall work normally. The proxy adds ~5-15% extra savings on top.\x1b[0m"
292                );
293                println!();
294                print!("  Enable the API proxy? [y/N] ");
295                let _ = std::io::Write::flush(&mut std::io::stdout());
296                let mut input = String::new();
297                let _ = std::io::stdin().read_line(&mut input);
298                let answer = matches!(input.trim().to_lowercase().as_str(), "y" | "yes");
299                cfg.proxy_enabled = Some(answer);
300                let _ = cfg.save();
301                if answer {
302                    crate::proxy_autostart::install(proxy_port, false);
303                    std::thread::sleep(std::time::Duration::from_millis(500));
304                    crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
305                    terminal_ui::print_status_new("Proxy enabled");
306                } else {
307                    terminal_ui::print_status_skip(
308                        "Proxy skipped (run `lean-ctx proxy enable` anytime)",
309                    );
310                }
311            }
312        }
313    }
314
315    // Step 6: SKILL.md installation (only if user opted in)
316    terminal_ui::print_step_header(6, 12, "Skill Files");
317    if inject_skills {
318        let skill_result = install_skill_files(&home);
319        for (name, installed) in &skill_result {
320            if *installed {
321                terminal_ui::print_status_new(&format!(
322                    "{name:<20} \x1b[2mSKILL.md installed\x1b[0m"
323                ));
324            } else {
325                terminal_ui::print_status_ok(&format!(
326                    "{name:<20} \x1b[2mSKILL.md up-to-date\x1b[0m"
327                ));
328            }
329        }
330        if skill_result.is_empty() {
331            terminal_ui::print_status_skip("No skill directories to install");
332        }
333    } else {
334        terminal_ui::print_status_skip(
335            "Skipped (skill files install with the rules opt-in; choose Standard/Full in `lean-ctx setup`)",
336        );
337    }
338
339    // Step 7: Data directory + diagnostics
340    terminal_ui::print_step_header(7, 12, "Environment Check");
341    let lean_dir = crate::core::data_dir::lean_ctx_data_dir()
342        .unwrap_or_else(|_| home.join(".config/lean-ctx"));
343    if lean_dir.exists() {
344        terminal_ui::print_status_ok(&format!("{} ready", lean_dir.display()));
345    } else {
346        let _ = std::fs::create_dir_all(&lean_dir);
347        terminal_ui::print_status_new(&format!("Created {}", lean_dir.display()));
348    }
349    if let Some(report) = crate::core::data_consolidate::consolidate() {
350        if report.files_moved > 0 {
351            terminal_ui::print_status_new(&format!(
352                "Consolidated {} file(s) from a split data dir into {}",
353                report.files_moved,
354                report.canonical.display()
355            ));
356        }
357    }
358    crate::doctor::run_compact();
359
360    // Step 8: Data sharing
361    terminal_ui::print_step_header(8, 12, "Help Improve lean-ctx");
362    println!("  Share anonymous compression stats to make lean-ctx better.");
363    println!("  \x1b[1mNo code, no file names, no personal data — ever.\x1b[0m");
364    println!();
365    print!("  Enable anonymous data sharing? \x1b[1m[y/N]\x1b[0m ");
366    use std::io::Write;
367    std::io::stdout().flush().ok();
368
369    let mut input = String::new();
370    let contribute = if std::io::stdin().read_line(&mut input).is_ok() {
371        let answer = input.trim().to_lowercase();
372        answer == "y" || answer == "yes"
373    } else {
374        false
375    };
376
377    if contribute {
378        let config_path = crate::core::config::Config::path()
379            .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
380        if let Some(dir) = config_path.parent() {
381            let _ = std::fs::create_dir_all(dir);
382        }
383        let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
384        if !config_content.contains("[cloud]") {
385            if !config_content.is_empty() && !config_content.ends_with('\n') {
386                config_content.push('\n');
387            }
388            config_content.push_str("\n[cloud]\ncontribute_enabled = true\n");
389            let _ = crate::config_io::write_atomic_with_backup(&config_path, &config_content);
390        }
391        terminal_ui::print_status_ok("Enabled — thank you!");
392    } else {
393        terminal_ui::print_status_skip("Skipped — enable later with: lean-ctx config");
394    }
395
396    // Step 9: Auto-Update opt-in
397    terminal_ui::print_step_header(9, 12, "Auto-Updates");
398    println!("  Keep lean-ctx up to date automatically.");
399    println!("  \x1b[1mChecks GitHub every 6h, installs only when a new release exists.\x1b[0m");
400    println!(
401        "  \x1b[2mNo restarts mid-session. Change anytime: lean-ctx update --schedule off\x1b[0m"
402    );
403    println!();
404    print!("  Enable automatic updates? \x1b[1m[y/N]\x1b[0m ");
405    std::io::stdout().flush().ok();
406
407    let mut auto_input = String::new();
408    let auto_update = if std::io::stdin().read_line(&mut auto_input).is_ok() {
409        let answer = auto_input.trim().to_lowercase();
410        answer == "y" || answer == "yes"
411    } else {
412        false
413    };
414
415    if auto_update {
416        let cfg = crate::core::config::Config::load();
417        let hours = cfg.updates.check_interval_hours;
418        match crate::core::update_scheduler::install_schedule(hours) {
419            Ok(info) => {
420                crate::core::update_scheduler::set_auto_update(true, false, hours);
421                terminal_ui::print_status_ok(&format!("Enabled — {info}"));
422            }
423            Err(e) => {
424                terminal_ui::print_status_warn(&format!("Scheduler setup failed: {e}"));
425                terminal_ui::print_status_skip("Enable later: lean-ctx update --schedule");
426            }
427        }
428    } else {
429        crate::core::update_scheduler::set_auto_update(false, false, 6);
430        terminal_ui::print_status_skip("Skipped — enable later: lean-ctx update --schedule");
431    }
432
433    // Step 10: Tool Profile selection
434    terminal_ui::print_step_header(10, 12, "Tool Profile");
435    configure_tool_profile();
436
437    // Step 11: Advanced tuning (optional power-user options)
438    terminal_ui::print_step_header(11, 12, "Advanced Tuning (optional)");
439    configure_premium_features(&home);
440
441    // Step 12: Code Intelligence — build graph in background
442    terminal_ui::print_step_header(12, 12, "Code Intelligence");
443    let cwd = std::env::current_dir().ok();
444    let cwd_is_home = cwd
445        .as_ref()
446        .is_some_and(|d| dirs::home_dir().is_some_and(|h| d.as_path() == h.as_path()));
447    if cwd_is_home {
448        terminal_ui::print_status_warn(
449            "Running from $HOME — graph build skipped to avoid scanning your entire home directory.",
450        );
451        println!();
452        println!("  \x1b[1mSet a default project root to avoid this:\x1b[0m");
453        println!("  \x1b[2mEnter your main project path (or press Enter to skip):\x1b[0m");
454        print!("  \x1b[1m>\x1b[0m ");
455        use std::io::Write;
456        std::io::stdout().flush().ok();
457        let mut root_input = String::new();
458        if std::io::stdin().read_line(&mut root_input).is_ok() {
459            let root_trimmed = root_input.trim();
460            if root_trimmed.is_empty() {
461                terminal_ui::print_status_skip("No project root set. Set later: lean-ctx config set project_root /path/to/project");
462            } else {
463                let root_path = std::path::Path::new(root_trimmed);
464                if root_path.exists() && root_path.is_dir() {
465                    let config_path = crate::core::config::Config::path()
466                        .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
467                    let mut content = std::fs::read_to_string(&config_path).unwrap_or_default();
468                    if content.contains("project_root") {
469                        if let Ok(re) = regex::Regex::new(r#"(?m)^project_root\s*=\s*"[^"]*""#) {
470                            content = re
471                                .replace(&content, &format!("project_root = \"{root_trimmed}\""))
472                                .to_string();
473                        }
474                    } else {
475                        if !content.is_empty() && !content.ends_with('\n') {
476                            content.push('\n');
477                        }
478                        content.push_str(&format!("project_root = \"{root_trimmed}\"\n"));
479                    }
480                    let _ = crate::config_io::write_atomic_with_backup(&config_path, &content);
481                    terminal_ui::print_status_ok(&format!("Project root set: {root_trimmed}"));
482                    if root_path.join(".git").exists()
483                        || root_path.join("Cargo.toml").exists()
484                        || root_path.join("package.json").exists()
485                    {
486                        spawn_index_build_background(root_path);
487                        terminal_ui::print_status_ok("Graph build started (background)");
488                    }
489                } else {
490                    terminal_ui::print_status_warn(&format!(
491                        "Path not found: {root_trimmed} — skipped"
492                    ));
493                }
494            }
495        }
496    } else {
497        let is_project = cwd.as_ref().is_some_and(|d| {
498            d.join(".git").exists()
499                || d.join("Cargo.toml").exists()
500                || d.join("package.json").exists()
501                || d.join("go.mod").exists()
502        });
503        if is_project {
504            println!("  \x1b[2mBuilding code graph for graph-aware reads, impact analysis,\x1b[0m");
505            println!("  \x1b[2mand smart search fusion in the background...\x1b[0m");
506            if let Some(ref root) = cwd {
507                spawn_index_build_background(root);
508            }
509            terminal_ui::print_status_ok("Graph build started (background)");
510        } else {
511            println!("  \x1b[2mRun `lean-ctx graph build` inside any git project to enable\x1b[0m");
512            println!(
513                "  \x1b[2mgraph-aware reads, impact analysis, and smart search fusion.\x1b[0m"
514            );
515        }
516    }
517    println!();
518
519    // Auto-approve transparency banner
520    {
521        let tools = crate::core::editor_registry::writers::auto_approve_tools();
522        println!();
523        println!(
524            "  \x1b[33m⚡ Auto-approved tools ({} total):\x1b[0m",
525            tools.len()
526        );
527        for chunk in tools.chunks(6) {
528            let names: Vec<_> = chunk.iter().map(|t| format!("\x1b[2m{t}\x1b[0m")).collect();
529            println!("    {}", names.join(", "));
530        }
531        println!("  \x1b[2mDisable with: lean-ctx setup --no-auto-approve\x1b[0m");
532    }
533
534    // Summary
535    println!();
536    println!(
537        "  \x1b[1;32m✓ Setup complete!\x1b[0m  \x1b[1m{}\x1b[0m configured, \x1b[2m{} already set, {} skipped\x1b[0m",
538        newly_configured.len(),
539        already_configured.len(),
540        not_installed.len()
541    );
542
543    if !errors.is_empty() {
544        println!(
545            "  \x1b[33m⚠ {} error{}: {}\x1b[0m",
546            errors.len(),
547            if errors.len() == 1 { "" } else { "s" },
548            errors.join(", ")
549        );
550    }
551
552    // Next steps
553    let source_cmd = crate::shell_hook::shell_source_command().unwrap_or("Restart your shell");
554
555    let dim = "\x1b[2m";
556    let bold = "\x1b[1m";
557    let cyan = "\x1b[36m";
558    let yellow = "\x1b[33m";
559    let rst = "\x1b[0m";
560
561    println!();
562    println!("  {bold}Next steps:{rst}");
563    println!();
564    println!("  {cyan}1.{rst} Reload your shell:");
565    println!("     {bold}{source_cmd}{rst}");
566    println!();
567
568    let mut tools_to_restart: Vec<String> = newly_configured
569        .iter()
570        .map(std::string::ToString::to_string)
571        .collect();
572    for name in rules_result
573        .injected
574        .iter()
575        .chain(rules_result.updated.iter())
576    {
577        if !tools_to_restart.iter().any(|t| t == name) {
578            tools_to_restart.push(name.clone());
579        }
580    }
581
582    if !tools_to_restart.is_empty() {
583        println!("  {cyan}2.{rst} {yellow}{bold}Restart your IDE / AI tool:{rst}");
584        println!("     {bold}{}{rst}", tools_to_restart.join(", "));
585        println!(
586            "     {dim}Changes take effect after a full restart (MCP may be enabled or disabled depending on mode).{rst}"
587        );
588        println!("     {dim}Close and re-open the application completely.{rst}");
589    } else if !already_configured.is_empty() {
590        println!(
591            "  {cyan}2.{rst} {dim}Your tools are already configured — no restart needed.{rst}"
592        );
593    }
594
595    println!();
596    println!(
597        "  {dim}After restart, lean-ctx will automatically optimize every AI interaction.{rst}"
598    );
599    println!("  {dim}Verify with:{rst} {bold}lean-ctx gain{rst}");
600
601    // Logo + commands
602    println!();
603    terminal_ui::print_logo_animated();
604    terminal_ui::print_command_box();
605
606    // First-run "aha": show the savings lean-ctx just started capturing (once).
607    crate::cli::show_first_run_wow();
608}
609
610/// Friendly, non-interactive "golden path" onboarding.
611///
612/// Unlike `run_setup` (the full 12-step interactive wizard), `onboard` makes
613/// every decision for the user with sensible defaults — connect detected AI
614/// tools, install the shell hook, set the `standard` tool profile — then prints
615/// one clear "you're all set" message with a single obvious next step. This is
616/// the recommended first-run path: time-to-value in seconds, zero prompts.
617pub fn run_onboard() {
618    use crate::terminal_ui;
619
620    let dim = "\x1b[2m";
621    let bold = "\x1b[1m";
622    let cyan = "\x1b[36m";
623    let green = "\x1b[1;32m";
624    let yellow = "\x1b[33m";
625    let rst = "\x1b[0m";
626
627    println!();
628    println!("  {bold}Connecting lean-ctx to your AI tools…{rst}");
629    println!("  {dim}No questions — using recommended defaults. Run `lean-ctx setup` for full control.{rst}");
630    println!();
631
632    let opts = SetupOptions {
633        non_interactive: true,
634        yes: true,
635        fix: true,
636        ..Default::default()
637    };
638
639    let report = match run_setup_with_options(opts) {
640        Ok(r) => r,
641        Err(e) => {
642            eprintln!("  {yellow}Onboarding could not complete: {e}{rst}");
643            eprintln!("  {dim}Try the guided setup instead: lean-ctx setup{rst}");
644            std::process::exit(1);
645        }
646    };
647
648    // Which AI tools did we actually wire up?
649    let connected: Vec<String> = report
650        .steps
651        .iter()
652        .find(|s| s.name == "editors")
653        .map(|s| {
654            s.items
655                .iter()
656                .filter(|i| matches!(i.status.as_str(), "created" | "updated" | "already"))
657                .map(|i| i.name.clone())
658                .collect()
659        })
660        .unwrap_or_default();
661
662    let data_dir = crate::core::data_dir::lean_ctx_data_dir()
663        .map_or_else(|_| "~/.lean-ctx".to_string(), |p| p.display().to_string());
664
665    println!();
666    if connected.is_empty() {
667        println!("  {yellow}No AI tools detected yet.{rst}");
668        println!(
669            "  {dim}Install Cursor, Claude Code, VS Code, etc., then re-run: lean-ctx onboard{rst}"
670        );
671    } else {
672        println!("  {green}✓ lean-ctx is connected.{rst}");
673        println!();
674        println!("  {bold}Connected:{rst} {}", connected.join(", "));
675    }
676    println!("  {dim}Data dir:{rst}  {data_dir}");
677
678    let source_cmd = crate::shell_hook::shell_source_command().unwrap_or("Restart your shell");
679    println!();
680    println!("  {bold}One last step:{rst}");
681    println!("  {cyan}1.{rst} Reload your shell:  {bold}{source_cmd}{rst}");
682    if !connected.is_empty() {
683        println!(
684            "  {cyan}2.{rst} {yellow}Fully restart your AI tool{rst} {dim}(so it reconnects to lean-ctx){rst}"
685        );
686        println!(
687            "  {cyan}3.{rst} Ask your AI to read a file — lean-ctx optimizes it automatically."
688        );
689    }
690    println!();
691    println!("  {dim}Check anytime:{rst}  {bold}lean-ctx doctor{rst}  {dim}·{rst}  {bold}lean-ctx gain{rst}");
692    println!();
693    terminal_ui::print_command_box();
694
695    // First-run "aha": show the savings lean-ctx just started capturing (once).
696    crate::cli::show_first_run_wow();
697}
698
699#[derive(Debug, Clone, Copy, Default)]
700pub struct SetupOptions {
701    pub non_interactive: bool,
702    pub yes: bool,
703    pub fix: bool,
704    pub json: bool,
705    pub no_auto_approve: bool,
706    pub skip_proxy: bool,
707    pub skip_rules: bool,
708    /// Explicitly request rules injection (overrides config).
709    pub force_inject_rules: bool,
710}
711
712pub fn run_setup_with_options(opts: SetupOptions) -> Result<SetupReport, String> {
713    let _quiet_guard = opts.json.then(|| EnvVarGuard::set("LEAN_CTX_QUIET", "1"));
714    let started_at = Utc::now();
715    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
716    let binary = resolve_portable_binary();
717    let home_str = home.to_string_lossy().to_string();
718
719    let mut steps: Vec<SetupStepReport> = Vec::new();
720
721    // Step: Shell Hook
722    let mut shell_step = SetupStepReport {
723        name: "shell_hook".to_string(),
724        ok: true,
725        items: Vec::new(),
726        warnings: Vec::new(),
727        errors: Vec::new(),
728    };
729    if !opts.non_interactive || opts.yes {
730        if opts.json {
731            crate::cli::cmd_init_quiet(&["--global".to_string()]);
732        } else {
733            crate::cli::cmd_init(&["--global".to_string()]);
734        }
735        crate::shell_hook::install_all(opts.json);
736        #[cfg(not(windows))]
737        {
738            let hook_content = crate::cli::generate_hook_posix(&binary);
739            if crate::shell::is_container() {
740                crate::cli::write_env_sh_for_containers(&hook_content);
741                shell_step.items.push(SetupItem {
742                    name: "env_sh".to_string(),
743                    status: "created".to_string(),
744                    path: Some(crate::core::paths::config_dir().map_or_else(
745                        |_| "~/.config/lean-ctx/env.sh".to_string(),
746                        |d| d.join("env.sh").to_string_lossy().to_string(),
747                    )),
748                    note: Some("Docker/CI helper (BASH_ENV / CLAUDE_ENV_FILE)".to_string()),
749                });
750            } else {
751                shell_step.items.push(SetupItem {
752                    name: "env_sh".to_string(),
753                    status: "skipped".to_string(),
754                    path: None,
755                    note: Some("not a container environment".to_string()),
756                });
757            }
758        }
759        shell_step.items.push(SetupItem {
760            name: "init --global".to_string(),
761            status: "ran".to_string(),
762            path: None,
763            note: None,
764        });
765        shell_step.items.push(SetupItem {
766            name: "universal_shell_hook".to_string(),
767            status: "installed".to_string(),
768            path: None,
769            note: Some("~/.zshenv, ~/.bashenv, agent aliases".to_string()),
770        });
771    } else {
772        shell_step
773            .warnings
774            .push("non_interactive_without_yes: shell hook not installed (use --yes)".to_string());
775        shell_step.ok = false;
776        shell_step.items.push(SetupItem {
777            name: "init --global".to_string(),
778            status: "skipped".to_string(),
779            path: None,
780            note: Some("requires --yes in --non-interactive mode".to_string()),
781        });
782    }
783    steps.push(shell_step);
784
785    // Step: Daemon (optional acceleration for CLI routing)
786    let mut daemon_step = SetupStepReport {
787        name: "daemon".to_string(),
788        ok: true,
789        items: Vec::new(),
790        warnings: Vec::new(),
791        errors: Vec::new(),
792    };
793    {
794        let was_running = crate::daemon::is_daemon_running();
795        if was_running {
796            let _ = crate::daemon::stop_daemon();
797            std::thread::sleep(std::time::Duration::from_millis(500));
798        }
799        match crate::daemon::start_daemon(&[]) {
800            Ok(()) => {
801                let action = if was_running { "restarted" } else { "started" };
802                daemon_step.items.push(SetupItem {
803                    name: "serve --daemon".to_string(),
804                    status: action.to_string(),
805                    path: Some(crate::daemon::daemon_addr().display()),
806                    note: Some("CLI commands can route via IPC when running".to_string()),
807                });
808            }
809            Err(e) => {
810                daemon_step
811                    .warnings
812                    .push(format!("daemon start failed (non-fatal): {e}"));
813                daemon_step.items.push(SetupItem {
814                    name: "serve --daemon".to_string(),
815                    status: "skipped".to_string(),
816                    path: None,
817                    note: Some(format!("optional — {e}")),
818                });
819            }
820        }
821    }
822    steps.push(daemon_step);
823
824    // Step: Editor MCP config
825    let mut editor_step = SetupStepReport {
826        name: "editors".to_string(),
827        ok: true,
828        items: Vec::new(),
829        warnings: Vec::new(),
830        errors: Vec::new(),
831    };
832
833    let targets = crate::core::editor_registry::build_targets(&home);
834    for target in &targets {
835        let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
836        if !target.detect_path.exists() {
837            editor_step.items.push(SetupItem {
838                name: target.name.to_string(),
839                status: "not_detected".to_string(),
840                path: Some(short_path),
841                note: None,
842            });
843            continue;
844        }
845
846        let mode = if target.agent_key.is_empty() {
847            HookMode::Mcp
848        } else {
849            recommend_hook_mode(&target.agent_key)
850        };
851
852        let res = crate::core::editor_registry::write_config_with_options(
853            target,
854            &binary,
855            WriteOptions {
856                overwrite_invalid: opts.fix,
857            },
858        );
859        match res {
860            Ok(w) => {
861                let note_parts: Vec<String> = [Some(format!("mode={mode}")), w.note]
862                    .into_iter()
863                    .flatten()
864                    .collect();
865                editor_step.items.push(SetupItem {
866                    name: target.name.to_string(),
867                    status: match w.action {
868                        WriteAction::Created => "created".to_string(),
869                        WriteAction::Updated => "updated".to_string(),
870                        WriteAction::Already => "already".to_string(),
871                    },
872                    path: Some(short_path),
873                    note: Some(note_parts.join("; ")),
874                });
875            }
876            Err(e) => {
877                editor_step.ok = false;
878                editor_step.items.push(SetupItem {
879                    name: target.name.to_string(),
880                    status: "error".to_string(),
881                    path: Some(short_path),
882                    note: Some(e),
883                });
884            }
885        }
886    }
887    steps.push(editor_step);
888
889    // Step: Agent rules — respect config unless explicitly forced or skipped
890    let mut rules_step = SetupStepReport {
891        name: "agent_rules".to_string(),
892        ok: true,
893        items: Vec::new(),
894        warnings: Vec::new(),
895        errors: Vec::new(),
896    };
897    let setup_cfg = crate::core::config::Config::load().setup;
898    let should_inject = if opts.skip_rules {
899        false
900    } else if opts.force_inject_rules {
901        true
902    } else if opts.yes && opts.non_interactive {
903        setup_cfg.should_inject_rules()
904    } else {
905        !opts.skip_rules
906    };
907
908    if should_inject {
909        let rules_result = crate::rules_inject::inject_all_rules(&home);
910        for n in rules_result.injected {
911            rules_step.items.push(SetupItem {
912                name: n,
913                status: "injected".to_string(),
914                path: None,
915                note: None,
916            });
917        }
918        for n in rules_result.updated {
919            rules_step.items.push(SetupItem {
920                name: n,
921                status: "updated".to_string(),
922                path: None,
923                note: None,
924            });
925        }
926        for n in rules_result.already {
927            rules_step.items.push(SetupItem {
928                name: n,
929                status: "already".to_string(),
930                path: None,
931                note: None,
932            });
933        }
934        if !rules_result.backed_up.is_empty() {
935            for bak in &rules_result.backed_up {
936                rules_step.items.push(SetupItem {
937                    name: "backup".to_string(),
938                    status: "created".to_string(),
939                    path: Some(bak.clone()),
940                    note: Some("previous version backed up".to_string()),
941                });
942            }
943        }
944        for e in rules_result.errors {
945            rules_step.ok = false;
946            rules_step.errors.push(e);
947        }
948    } else {
949        let reason = if opts.skip_rules {
950            "--skip-rules flag set"
951        } else {
952            "auto_inject_rules not enabled (run `lean-ctx setup --inject-rules`)"
953        };
954        rules_step.items.push(SetupItem {
955            name: "agent_rules".to_string(),
956            status: "skipped".to_string(),
957            path: None,
958            note: Some(reason.to_string()),
959        });
960    }
961    steps.push(rules_step);
962
963    // Step: Skill files — respect config
964    let mut skill_step = SetupStepReport {
965        name: "skill_files".to_string(),
966        ok: true,
967        items: Vec::new(),
968        warnings: Vec::new(),
969        errors: Vec::new(),
970    };
971    let should_install_skills = if opts.skip_rules {
972        false
973    } else if opts.force_inject_rules {
974        true
975    } else if opts.yes && opts.non_interactive {
976        setup_cfg.should_inject_skills()
977    } else {
978        !opts.skip_rules
979    };
980    if should_install_skills {
981        let skill_results = crate::rules_inject::install_all_skills(&home);
982        for (name, is_new) in &skill_results {
983            skill_step.items.push(SetupItem {
984                name: name.clone(),
985                status: if *is_new { "installed" } else { "already" }.to_string(),
986                path: None,
987                note: Some("SKILL.md".to_string()),
988            });
989        }
990    } else {
991        skill_step.items.push(SetupItem {
992            name: "skill_files".to_string(),
993            status: "skipped".to_string(),
994            path: None,
995            note: Some("auto_inject_skills not enabled".to_string()),
996        });
997    }
998    if !skill_step.items.is_empty() {
999        steps.push(skill_step);
1000    }
1001
1002    // Step: Agent-specific hooks (all detected agents)
1003    let mut hooks_step = SetupStepReport {
1004        name: "agent_hooks".to_string(),
1005        ok: true,
1006        items: Vec::new(),
1007        warnings: Vec::new(),
1008        errors: Vec::new(),
1009    };
1010    for target in &targets {
1011        if !target.detect_path.exists() || target.agent_key.is_empty() {
1012            continue;
1013        }
1014        let mode = recommend_hook_mode(&target.agent_key);
1015        crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
1016        // #281: honor `[setup] auto_update_mcp = false` — register MCP only when
1017        // enabled; hooks above always install.
1018        let mcp_note = if setup_cfg.should_update_mcp() {
1019            match configure_agent_mcp(&target.agent_key) {
1020                Ok(()) => "; MCP config updated".to_string(),
1021                Err(e) => format!("; MCP config skipped: {e}"),
1022            }
1023        } else {
1024            "; MCP registration skipped (auto_update_mcp=false)".to_string()
1025        };
1026        hooks_step.items.push(SetupItem {
1027            name: format!("{} hooks", target.name),
1028            status: "installed".to_string(),
1029            path: Some(target.detect_path.to_string_lossy().to_string()),
1030            note: Some(format!(
1031                "mode={mode}; merge-based install/repair (preserves other hooks/plugins){mcp_note}"
1032            )),
1033        });
1034    }
1035    if !hooks_step.items.is_empty() {
1036        steps.push(hooks_step);
1037    }
1038
1039    // Step: Tool profile. Deliberately does NOT write a default profile:
1040    // writing `tool_profile = "standard"` made every install "explicit", which
1041    // disables the lazy-core advertisement (the lazy core) and ships the full
1042    // profile schema set (~5-15k tokens) to every session (#575). The lean
1043    // default needs no config key — all tools stay reachable via ctx_call.
1044    let mut tool_profile_step = SetupStepReport {
1045        name: "tool_profile".to_string(),
1046        ok: true,
1047        items: Vec::new(),
1048        warnings: Vec::new(),
1049        errors: Vec::new(),
1050    };
1051    {
1052        let cfg = crate::core::config::Config::load();
1053        if cfg.tool_profile.is_none() && std::env::var("LEAN_CTX_TOOL_PROFILE").is_err() {
1054            let lazy_count = crate::tool_defs::core_tool_names().len();
1055            tool_profile_step.items.push(SetupItem {
1056                name: "tool_profile".to_string(),
1057                status: "lean default".to_string(),
1058                path: None,
1059                note: Some(format!(
1060                    "{lazy_count} tools advertised, all reachable via ctx_call \
1061                     (pin more with: lean-ctx tools standard|power)"
1062                )),
1063            });
1064        } else {
1065            let profile = cfg.tool_profile_effective();
1066            let overhead_hint = match profile {
1067                crate::core::tool_profiles::ToolProfile::Power => {
1068                    "; advertises ALL tool schemas — `lean-ctx tools lean` cuts this to the lazy core"
1069                }
1070                _ => "",
1071            };
1072            tool_profile_step.items.push(SetupItem {
1073                name: "tool_profile".to_string(),
1074                status: "already".to_string(),
1075                path: None,
1076                note: Some(format!("profile={}{overhead_hint}", profile.as_str())),
1077            });
1078        }
1079    }
1080    steps.push(tool_profile_step);
1081
1082    // Step: Proxy autostart + env vars (respects opt-in)
1083    let mut proxy_step = SetupStepReport {
1084        name: "proxy".to_string(),
1085        ok: true,
1086        items: Vec::new(),
1087        warnings: Vec::new(),
1088        errors: Vec::new(),
1089    };
1090    if opts.skip_proxy {
1091        proxy_step.items.push(SetupItem {
1092            name: "proxy".to_string(),
1093            status: "skipped".to_string(),
1094            path: None,
1095            note: Some("Proxy not enabled (run `lean-ctx proxy enable`)".to_string()),
1096        });
1097    } else {
1098        let proxy_cfg = crate::core::config::Config::load();
1099        if proxy_cfg.proxy_enabled == Some(true) {
1100            let proxy_port = crate::proxy_setup::default_port();
1101            crate::proxy_autostart::install(proxy_port, true);
1102            std::thread::sleep(std::time::Duration::from_millis(500));
1103            crate::proxy_setup::install_proxy_env(&home, proxy_port, opts.json);
1104            proxy_step.items.push(SetupItem {
1105                name: "proxy_autostart".to_string(),
1106                status: "installed".to_string(),
1107                path: None,
1108                note: Some("LaunchAgent/systemd auto-start on login".to_string()),
1109            });
1110            proxy_step.items.push(SetupItem {
1111                name: "proxy_env".to_string(),
1112                status: "configured".to_string(),
1113                path: None,
1114                note: Some("ANTHROPIC_BASE_URL, OPENAI_BASE_URL, GEMINI_API_BASE_URL".to_string()),
1115            });
1116        } else {
1117            proxy_step.items.push(SetupItem {
1118                name: "proxy".to_string(),
1119                status: "skipped".to_string(),
1120                path: None,
1121                note: Some(
1122                    "Proxy not opted-in (run `lean-ctx proxy enable` to activate)".to_string(),
1123                ),
1124            });
1125        }
1126    }
1127    steps.push(proxy_step);
1128
1129    // Step: Environment / doctor (compact)
1130    let mut env_step = SetupStepReport {
1131        name: "doctor_compact".to_string(),
1132        ok: true,
1133        items: Vec::new(),
1134        warnings: Vec::new(),
1135        errors: Vec::new(),
1136    };
1137    let (passed, total) = crate::doctor::compact_score();
1138    env_step.items.push(SetupItem {
1139        name: "doctor".to_string(),
1140        status: format!("{passed}/{total}"),
1141        path: None,
1142        note: None,
1143    });
1144    if passed != total {
1145        env_step.warnings.push(format!(
1146            "doctor compact not fully passing: {passed}/{total}"
1147        ));
1148    }
1149    steps.push(env_step);
1150
1151    // Project root validation: warn if no root is configured and cwd is broad
1152    {
1153        let has_env_root = std::env::var("LEAN_CTX_PROJECT_ROOT")
1154            .ok()
1155            .is_some_and(|v| !v.is_empty());
1156        let cfg = crate::core::config::Config::load();
1157        let has_cfg_root = cfg.project_root.as_ref().is_some_and(|v| !v.is_empty());
1158        if !has_env_root && !has_cfg_root {
1159            if let Ok(cwd) = std::env::current_dir() {
1160                let is_home = dirs::home_dir().is_some_and(|h| cwd == h);
1161                if is_home {
1162                    let mut root_step = SetupStepReport {
1163                        name: "project_root".to_string(),
1164                        ok: true,
1165                        items: Vec::new(),
1166                        warnings: vec![
1167                            "No project_root configured. Running from $HOME can cause excessive scanning. \
1168                             Set via: lean-ctx config set project_root /path/to/project".to_string()
1169                        ],
1170                        errors: Vec::new(),
1171                    };
1172                    root_step.items.push(SetupItem {
1173                        name: "project_root".to_string(),
1174                        status: "unconfigured".to_string(),
1175                        path: None,
1176                        note: Some(
1177                            "Set LEAN_CTX_PROJECT_ROOT or add project_root to config.toml"
1178                                .to_string(),
1179                        ),
1180                    });
1181                    steps.push(root_step);
1182                }
1183            }
1184        }
1185    }
1186
1187    // Auto-build property graph if inside any recognized project
1188    if let Ok(cwd) = std::env::current_dir() {
1189        let is_project = cwd.join(".git").exists()
1190            || cwd.join("Cargo.toml").exists()
1191            || cwd.join("package.json").exists()
1192            || cwd.join("go.mod").exists();
1193        if is_project {
1194            spawn_index_build_background(&cwd);
1195        }
1196    }
1197
1198    let finished_at = Utc::now();
1199    let success = steps.iter().all(|s| s.ok);
1200    let report = SetupReport {
1201        schema_version: 1,
1202        started_at,
1203        finished_at,
1204        success,
1205        platform: PlatformInfo {
1206            os: std::env::consts::OS.to_string(),
1207            arch: std::env::consts::ARCH.to_string(),
1208        },
1209        steps,
1210        warnings: Vec::new(),
1211        errors: Vec::new(),
1212    };
1213
1214    let path = SetupReport::default_path()?;
1215    let mut content =
1216        serde_json::to_string_pretty(&report).map_err(|e| format!("serialize report: {e}"))?;
1217    content.push('\n');
1218    crate::config_io::write_atomic(&path, &content)?;
1219
1220    Ok(report)
1221}
1222
1223fn spawn_index_build_background(root: &std::path::Path) {
1224    if std::env::var("LEAN_CTX_DISABLED").is_ok()
1225        || matches!(std::env::var("LEAN_CTX_QUIET"), Ok(v) if v.trim() == "1")
1226    {
1227        return;
1228    }
1229    let root_str = crate::core::graph_index::normalize_project_root(&root.to_string_lossy());
1230    if !crate::core::graph_index::is_safe_scan_root_public(&root_str) {
1231        tracing::info!("[setup: skipping background graph build for unsafe root {root_str}]");
1232        return;
1233    }
1234
1235    let binary = resolve_portable_binary();
1236
1237    #[cfg(unix)]
1238    {
1239        let mut cmd = std::process::Command::new("nice");
1240        cmd.args(["-n", "19"]);
1241        if which_ionice_available() {
1242            cmd.arg("ionice").args(["-c", "3"]);
1243        }
1244        cmd.arg(&binary)
1245            .args(["index", "build", "--root"])
1246            .arg(root)
1247            .stdout(std::process::Stdio::null())
1248            .stderr(std::process::Stdio::null())
1249            .stdin(std::process::Stdio::null());
1250        let _ = cmd.spawn();
1251    }
1252
1253    #[cfg(windows)]
1254    {
1255        use std::os::windows::process::CommandExt;
1256        const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
1257        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
1258        let _ = std::process::Command::new(&binary)
1259            .args(["index", "build", "--root"])
1260            .arg(root)
1261            .stdout(std::process::Stdio::null())
1262            .stderr(std::process::Stdio::null())
1263            .stdin(std::process::Stdio::null())
1264            .creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW)
1265            .spawn();
1266    }
1267}
1268
1269#[cfg(unix)]
1270fn which_ionice_available() -> bool {
1271    std::process::Command::new("ionice")
1272        .arg("--version")
1273        .stdout(std::process::Stdio::null())
1274        .stderr(std::process::Stdio::null())
1275        .status()
1276        .is_ok()
1277}
1278
1279#[cfg(all(test, target_os = "macos"))]
1280mod tests {
1281    use super::*;
1282
1283    #[test]
1284    #[cfg(target_os = "macos")]
1285    fn qoder_agent_targets_include_all_macos_mcp_locations() {
1286        let home = std::path::Path::new("/Users/tester");
1287        let targets = agent_mcp_targets("qoder", home).unwrap();
1288        let paths: Vec<_> = targets.iter().map(|t| t.config_path.as_path()).collect();
1289
1290        assert_eq!(
1291            paths,
1292            vec![
1293                home.join(".qoder/mcp.json").as_path(),
1294                home.join("Library/Application Support/Qoder/User/mcp.json")
1295                    .as_path(),
1296                home.join("Library/Application Support/Qoder/SharedClientCache/mcp.json")
1297                    .as_path(),
1298            ]
1299        );
1300        assert!(targets
1301            .iter()
1302            .all(|t| t.config_type == ConfigType::QoderSettings));
1303    }
1304}