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(tokens) = crate::core::data_dir::migrate_if_split() {
350        terminal_ui::print_status_new(&format!(
351            "Migrated stats from split data dir ({tokens} tokens recovered)"
352        ));
353    }
354    crate::doctor::run_compact();
355
356    // Step 8: Data sharing
357    terminal_ui::print_step_header(8, 12, "Help Improve lean-ctx");
358    println!("  Share anonymous compression stats to make lean-ctx better.");
359    println!("  \x1b[1mNo code, no file names, no personal data — ever.\x1b[0m");
360    println!();
361    print!("  Enable anonymous data sharing? \x1b[1m[y/N]\x1b[0m ");
362    use std::io::Write;
363    std::io::stdout().flush().ok();
364
365    let mut input = String::new();
366    let contribute = if std::io::stdin().read_line(&mut input).is_ok() {
367        let answer = input.trim().to_lowercase();
368        answer == "y" || answer == "yes"
369    } else {
370        false
371    };
372
373    if contribute {
374        let config_path = crate::core::config::Config::path()
375            .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
376        if let Some(dir) = config_path.parent() {
377            let _ = std::fs::create_dir_all(dir);
378        }
379        let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
380        if !config_content.contains("[cloud]") {
381            if !config_content.is_empty() && !config_content.ends_with('\n') {
382                config_content.push('\n');
383            }
384            config_content.push_str("\n[cloud]\ncontribute_enabled = true\n");
385            let _ = crate::config_io::write_atomic_with_backup(&config_path, &config_content);
386        }
387        terminal_ui::print_status_ok("Enabled — thank you!");
388    } else {
389        terminal_ui::print_status_skip("Skipped — enable later with: lean-ctx config");
390    }
391
392    // Step 9: Auto-Update opt-in
393    terminal_ui::print_step_header(9, 12, "Auto-Updates");
394    println!("  Keep lean-ctx up to date automatically.");
395    println!("  \x1b[1mChecks GitHub every 6h, installs only when a new release exists.\x1b[0m");
396    println!(
397        "  \x1b[2mNo restarts mid-session. Change anytime: lean-ctx update --schedule off\x1b[0m"
398    );
399    println!();
400    print!("  Enable automatic updates? \x1b[1m[y/N]\x1b[0m ");
401    std::io::stdout().flush().ok();
402
403    let mut auto_input = String::new();
404    let auto_update = if std::io::stdin().read_line(&mut auto_input).is_ok() {
405        let answer = auto_input.trim().to_lowercase();
406        answer == "y" || answer == "yes"
407    } else {
408        false
409    };
410
411    if auto_update {
412        let cfg = crate::core::config::Config::load();
413        let hours = cfg.updates.check_interval_hours;
414        match crate::core::update_scheduler::install_schedule(hours) {
415            Ok(info) => {
416                crate::core::update_scheduler::set_auto_update(true, false, hours);
417                terminal_ui::print_status_ok(&format!("Enabled — {info}"));
418            }
419            Err(e) => {
420                terminal_ui::print_status_warn(&format!("Scheduler setup failed: {e}"));
421                terminal_ui::print_status_skip("Enable later: lean-ctx update --schedule");
422            }
423        }
424    } else {
425        crate::core::update_scheduler::set_auto_update(false, false, 6);
426        terminal_ui::print_status_skip("Skipped — enable later: lean-ctx update --schedule");
427    }
428
429    // Step 10: Tool Profile selection
430    terminal_ui::print_step_header(10, 12, "Tool Profile");
431    configure_tool_profile();
432
433    // Step 11: Advanced tuning (optional power-user options)
434    terminal_ui::print_step_header(11, 12, "Advanced Tuning (optional)");
435    configure_premium_features(&home);
436
437    // Step 12: Code Intelligence — build graph in background
438    terminal_ui::print_step_header(12, 12, "Code Intelligence");
439    let cwd = std::env::current_dir().ok();
440    let cwd_is_home = cwd
441        .as_ref()
442        .is_some_and(|d| dirs::home_dir().is_some_and(|h| d.as_path() == h.as_path()));
443    if cwd_is_home {
444        terminal_ui::print_status_warn(
445            "Running from $HOME — graph build skipped to avoid scanning your entire home directory.",
446        );
447        println!();
448        println!("  \x1b[1mSet a default project root to avoid this:\x1b[0m");
449        println!("  \x1b[2mEnter your main project path (or press Enter to skip):\x1b[0m");
450        print!("  \x1b[1m>\x1b[0m ");
451        use std::io::Write;
452        std::io::stdout().flush().ok();
453        let mut root_input = String::new();
454        if std::io::stdin().read_line(&mut root_input).is_ok() {
455            let root_trimmed = root_input.trim();
456            if root_trimmed.is_empty() {
457                terminal_ui::print_status_skip("No project root set. Set later: lean-ctx config set project_root /path/to/project");
458            } else {
459                let root_path = std::path::Path::new(root_trimmed);
460                if root_path.exists() && root_path.is_dir() {
461                    let config_path = crate::core::config::Config::path()
462                        .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
463                    let mut content = std::fs::read_to_string(&config_path).unwrap_or_default();
464                    if content.contains("project_root") {
465                        if let Ok(re) = regex::Regex::new(r#"(?m)^project_root\s*=\s*"[^"]*""#) {
466                            content = re
467                                .replace(&content, &format!("project_root = \"{root_trimmed}\""))
468                                .to_string();
469                        }
470                    } else {
471                        if !content.is_empty() && !content.ends_with('\n') {
472                            content.push('\n');
473                        }
474                        content.push_str(&format!("project_root = \"{root_trimmed}\"\n"));
475                    }
476                    let _ = crate::config_io::write_atomic_with_backup(&config_path, &content);
477                    terminal_ui::print_status_ok(&format!("Project root set: {root_trimmed}"));
478                    if root_path.join(".git").exists()
479                        || root_path.join("Cargo.toml").exists()
480                        || root_path.join("package.json").exists()
481                    {
482                        spawn_index_build_background(root_path);
483                        terminal_ui::print_status_ok("Graph build started (background)");
484                    }
485                } else {
486                    terminal_ui::print_status_warn(&format!(
487                        "Path not found: {root_trimmed} — skipped"
488                    ));
489                }
490            }
491        }
492    } else {
493        let is_project = cwd.as_ref().is_some_and(|d| {
494            d.join(".git").exists()
495                || d.join("Cargo.toml").exists()
496                || d.join("package.json").exists()
497                || d.join("go.mod").exists()
498        });
499        if is_project {
500            println!("  \x1b[2mBuilding code graph for graph-aware reads, impact analysis,\x1b[0m");
501            println!("  \x1b[2mand smart search fusion in the background...\x1b[0m");
502            if let Some(ref root) = cwd {
503                spawn_index_build_background(root);
504            }
505            terminal_ui::print_status_ok("Graph build started (background)");
506        } else {
507            println!("  \x1b[2mRun `lean-ctx graph build` inside any git project to enable\x1b[0m");
508            println!(
509                "  \x1b[2mgraph-aware reads, impact analysis, and smart search fusion.\x1b[0m"
510            );
511        }
512    }
513    println!();
514
515    // Auto-approve transparency banner
516    {
517        let tools = crate::core::editor_registry::writers::auto_approve_tools();
518        println!();
519        println!(
520            "  \x1b[33m⚡ Auto-approved tools ({} total):\x1b[0m",
521            tools.len()
522        );
523        for chunk in tools.chunks(6) {
524            let names: Vec<_> = chunk.iter().map(|t| format!("\x1b[2m{t}\x1b[0m")).collect();
525            println!("    {}", names.join(", "));
526        }
527        println!("  \x1b[2mDisable with: lean-ctx setup --no-auto-approve\x1b[0m");
528    }
529
530    // Summary
531    println!();
532    println!(
533        "  \x1b[1;32m✓ Setup complete!\x1b[0m  \x1b[1m{}\x1b[0m configured, \x1b[2m{} already set, {} skipped\x1b[0m",
534        newly_configured.len(),
535        already_configured.len(),
536        not_installed.len()
537    );
538
539    if !errors.is_empty() {
540        println!(
541            "  \x1b[33m⚠ {} error{}: {}\x1b[0m",
542            errors.len(),
543            if errors.len() == 1 { "" } else { "s" },
544            errors.join(", ")
545        );
546    }
547
548    // Next steps
549    let source_cmd = crate::shell_hook::shell_source_command().unwrap_or("Restart your shell");
550
551    let dim = "\x1b[2m";
552    let bold = "\x1b[1m";
553    let cyan = "\x1b[36m";
554    let yellow = "\x1b[33m";
555    let rst = "\x1b[0m";
556
557    println!();
558    println!("  {bold}Next steps:{rst}");
559    println!();
560    println!("  {cyan}1.{rst} Reload your shell:");
561    println!("     {bold}{source_cmd}{rst}");
562    println!();
563
564    let mut tools_to_restart: Vec<String> = newly_configured
565        .iter()
566        .map(std::string::ToString::to_string)
567        .collect();
568    for name in rules_result
569        .injected
570        .iter()
571        .chain(rules_result.updated.iter())
572    {
573        if !tools_to_restart.iter().any(|t| t == name) {
574            tools_to_restart.push(name.clone());
575        }
576    }
577
578    if !tools_to_restart.is_empty() {
579        println!("  {cyan}2.{rst} {yellow}{bold}Restart your IDE / AI tool:{rst}");
580        println!("     {bold}{}{rst}", tools_to_restart.join(", "));
581        println!(
582            "     {dim}Changes take effect after a full restart (MCP may be enabled or disabled depending on mode).{rst}"
583        );
584        println!("     {dim}Close and re-open the application completely.{rst}");
585    } else if !already_configured.is_empty() {
586        println!(
587            "  {cyan}2.{rst} {dim}Your tools are already configured — no restart needed.{rst}"
588        );
589    }
590
591    println!();
592    println!(
593        "  {dim}After restart, lean-ctx will automatically optimize every AI interaction.{rst}"
594    );
595    println!("  {dim}Verify with:{rst} {bold}lean-ctx gain{rst}");
596
597    // Logo + commands
598    println!();
599    terminal_ui::print_logo_animated();
600    terminal_ui::print_command_box();
601
602    // First-run "aha": show the savings lean-ctx just started capturing (once).
603    crate::cli::show_first_run_wow();
604}
605
606/// Friendly, non-interactive "golden path" onboarding.
607///
608/// Unlike `run_setup` (the full 12-step interactive wizard), `onboard` makes
609/// every decision for the user with sensible defaults — connect detected AI
610/// tools, install the shell hook, set the `standard` tool profile — then prints
611/// one clear "you're all set" message with a single obvious next step. This is
612/// the recommended first-run path: time-to-value in seconds, zero prompts.
613pub fn run_onboard() {
614    use crate::terminal_ui;
615
616    let dim = "\x1b[2m";
617    let bold = "\x1b[1m";
618    let cyan = "\x1b[36m";
619    let green = "\x1b[1;32m";
620    let yellow = "\x1b[33m";
621    let rst = "\x1b[0m";
622
623    println!();
624    println!("  {bold}Connecting lean-ctx to your AI tools…{rst}");
625    println!("  {dim}No questions — using recommended defaults. Run `lean-ctx setup` for full control.{rst}");
626    println!();
627
628    let opts = SetupOptions {
629        non_interactive: true,
630        yes: true,
631        fix: true,
632        ..Default::default()
633    };
634
635    let report = match run_setup_with_options(opts) {
636        Ok(r) => r,
637        Err(e) => {
638            eprintln!("  {yellow}Onboarding could not complete: {e}{rst}");
639            eprintln!("  {dim}Try the guided setup instead: lean-ctx setup{rst}");
640            std::process::exit(1);
641        }
642    };
643
644    // Which AI tools did we actually wire up?
645    let connected: Vec<String> = report
646        .steps
647        .iter()
648        .find(|s| s.name == "editors")
649        .map(|s| {
650            s.items
651                .iter()
652                .filter(|i| matches!(i.status.as_str(), "created" | "updated" | "already"))
653                .map(|i| i.name.clone())
654                .collect()
655        })
656        .unwrap_or_default();
657
658    let data_dir = crate::core::data_dir::lean_ctx_data_dir()
659        .map_or_else(|_| "~/.lean-ctx".to_string(), |p| p.display().to_string());
660
661    println!();
662    if connected.is_empty() {
663        println!("  {yellow}No AI tools detected yet.{rst}");
664        println!(
665            "  {dim}Install Cursor, Claude Code, VS Code, etc., then re-run: lean-ctx onboard{rst}"
666        );
667    } else {
668        println!("  {green}✓ lean-ctx is connected.{rst}");
669        println!();
670        println!("  {bold}Connected:{rst} {}", connected.join(", "));
671    }
672    println!("  {dim}Data dir:{rst}  {data_dir}");
673
674    let source_cmd = crate::shell_hook::shell_source_command().unwrap_or("Restart your shell");
675    println!();
676    println!("  {bold}One last step:{rst}");
677    println!("  {cyan}1.{rst} Reload your shell:  {bold}{source_cmd}{rst}");
678    if !connected.is_empty() {
679        println!(
680            "  {cyan}2.{rst} {yellow}Fully restart your AI tool{rst} {dim}(so it reconnects to lean-ctx){rst}"
681        );
682        println!(
683            "  {cyan}3.{rst} Ask your AI to read a file — lean-ctx optimizes it automatically."
684        );
685    }
686    println!();
687    println!("  {dim}Check anytime:{rst}  {bold}lean-ctx doctor{rst}  {dim}·{rst}  {bold}lean-ctx gain{rst}");
688    println!();
689    terminal_ui::print_command_box();
690
691    // First-run "aha": show the savings lean-ctx just started capturing (once).
692    crate::cli::show_first_run_wow();
693}
694
695#[derive(Debug, Clone, Copy, Default)]
696pub struct SetupOptions {
697    pub non_interactive: bool,
698    pub yes: bool,
699    pub fix: bool,
700    pub json: bool,
701    pub no_auto_approve: bool,
702    pub skip_proxy: bool,
703    pub skip_rules: bool,
704    /// Explicitly request rules injection (overrides config).
705    pub force_inject_rules: bool,
706}
707
708pub fn run_setup_with_options(opts: SetupOptions) -> Result<SetupReport, String> {
709    let _quiet_guard = opts.json.then(|| EnvVarGuard::set("LEAN_CTX_QUIET", "1"));
710    let started_at = Utc::now();
711    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
712    let binary = resolve_portable_binary();
713    let home_str = home.to_string_lossy().to_string();
714
715    let mut steps: Vec<SetupStepReport> = Vec::new();
716
717    // Step: Shell Hook
718    let mut shell_step = SetupStepReport {
719        name: "shell_hook".to_string(),
720        ok: true,
721        items: Vec::new(),
722        warnings: Vec::new(),
723        errors: Vec::new(),
724    };
725    if !opts.non_interactive || opts.yes {
726        if opts.json {
727            crate::cli::cmd_init_quiet(&["--global".to_string()]);
728        } else {
729            crate::cli::cmd_init(&["--global".to_string()]);
730        }
731        crate::shell_hook::install_all(opts.json);
732        #[cfg(not(windows))]
733        {
734            let hook_content = crate::cli::generate_hook_posix(&binary);
735            if crate::shell::is_container() {
736                crate::cli::write_env_sh_for_containers(&hook_content);
737                shell_step.items.push(SetupItem {
738                    name: "env_sh".to_string(),
739                    status: "created".to_string(),
740                    path: Some(crate::core::paths::config_dir().map_or_else(
741                        |_| "~/.config/lean-ctx/env.sh".to_string(),
742                        |d| d.join("env.sh").to_string_lossy().to_string(),
743                    )),
744                    note: Some("Docker/CI helper (BASH_ENV / CLAUDE_ENV_FILE)".to_string()),
745                });
746            } else {
747                shell_step.items.push(SetupItem {
748                    name: "env_sh".to_string(),
749                    status: "skipped".to_string(),
750                    path: None,
751                    note: Some("not a container environment".to_string()),
752                });
753            }
754        }
755        shell_step.items.push(SetupItem {
756            name: "init --global".to_string(),
757            status: "ran".to_string(),
758            path: None,
759            note: None,
760        });
761        shell_step.items.push(SetupItem {
762            name: "universal_shell_hook".to_string(),
763            status: "installed".to_string(),
764            path: None,
765            note: Some("~/.zshenv, ~/.bashenv, agent aliases".to_string()),
766        });
767    } else {
768        shell_step
769            .warnings
770            .push("non_interactive_without_yes: shell hook not installed (use --yes)".to_string());
771        shell_step.ok = false;
772        shell_step.items.push(SetupItem {
773            name: "init --global".to_string(),
774            status: "skipped".to_string(),
775            path: None,
776            note: Some("requires --yes in --non-interactive mode".to_string()),
777        });
778    }
779    steps.push(shell_step);
780
781    // Step: Daemon (optional acceleration for CLI routing)
782    let mut daemon_step = SetupStepReport {
783        name: "daemon".to_string(),
784        ok: true,
785        items: Vec::new(),
786        warnings: Vec::new(),
787        errors: Vec::new(),
788    };
789    {
790        let was_running = crate::daemon::is_daemon_running();
791        if was_running {
792            let _ = crate::daemon::stop_daemon();
793            std::thread::sleep(std::time::Duration::from_millis(500));
794        }
795        match crate::daemon::start_daemon(&[]) {
796            Ok(()) => {
797                let action = if was_running { "restarted" } else { "started" };
798                daemon_step.items.push(SetupItem {
799                    name: "serve --daemon".to_string(),
800                    status: action.to_string(),
801                    path: Some(crate::daemon::daemon_addr().display()),
802                    note: Some("CLI commands can route via IPC when running".to_string()),
803                });
804            }
805            Err(e) => {
806                daemon_step
807                    .warnings
808                    .push(format!("daemon start failed (non-fatal): {e}"));
809                daemon_step.items.push(SetupItem {
810                    name: "serve --daemon".to_string(),
811                    status: "skipped".to_string(),
812                    path: None,
813                    note: Some(format!("optional — {e}")),
814                });
815            }
816        }
817    }
818    steps.push(daemon_step);
819
820    // Step: Editor MCP config
821    let mut editor_step = SetupStepReport {
822        name: "editors".to_string(),
823        ok: true,
824        items: Vec::new(),
825        warnings: Vec::new(),
826        errors: Vec::new(),
827    };
828
829    let targets = crate::core::editor_registry::build_targets(&home);
830    for target in &targets {
831        let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
832        if !target.detect_path.exists() {
833            editor_step.items.push(SetupItem {
834                name: target.name.to_string(),
835                status: "not_detected".to_string(),
836                path: Some(short_path),
837                note: None,
838            });
839            continue;
840        }
841
842        let mode = if target.agent_key.is_empty() {
843            HookMode::Mcp
844        } else {
845            recommend_hook_mode(&target.agent_key)
846        };
847
848        let res = crate::core::editor_registry::write_config_with_options(
849            target,
850            &binary,
851            WriteOptions {
852                overwrite_invalid: opts.fix,
853            },
854        );
855        match res {
856            Ok(w) => {
857                let note_parts: Vec<String> = [Some(format!("mode={mode}")), w.note]
858                    .into_iter()
859                    .flatten()
860                    .collect();
861                editor_step.items.push(SetupItem {
862                    name: target.name.to_string(),
863                    status: match w.action {
864                        WriteAction::Created => "created".to_string(),
865                        WriteAction::Updated => "updated".to_string(),
866                        WriteAction::Already => "already".to_string(),
867                    },
868                    path: Some(short_path),
869                    note: Some(note_parts.join("; ")),
870                });
871            }
872            Err(e) => {
873                editor_step.ok = false;
874                editor_step.items.push(SetupItem {
875                    name: target.name.to_string(),
876                    status: "error".to_string(),
877                    path: Some(short_path),
878                    note: Some(e),
879                });
880            }
881        }
882    }
883    steps.push(editor_step);
884
885    // Step: Agent rules — respect config unless explicitly forced or skipped
886    let mut rules_step = SetupStepReport {
887        name: "agent_rules".to_string(),
888        ok: true,
889        items: Vec::new(),
890        warnings: Vec::new(),
891        errors: Vec::new(),
892    };
893    let setup_cfg = crate::core::config::Config::load().setup;
894    let should_inject = if opts.skip_rules {
895        false
896    } else if opts.force_inject_rules {
897        true
898    } else if opts.yes && opts.non_interactive {
899        setup_cfg.should_inject_rules()
900    } else {
901        !opts.skip_rules
902    };
903
904    if should_inject {
905        let rules_result = crate::rules_inject::inject_all_rules(&home);
906        for n in rules_result.injected {
907            rules_step.items.push(SetupItem {
908                name: n,
909                status: "injected".to_string(),
910                path: None,
911                note: None,
912            });
913        }
914        for n in rules_result.updated {
915            rules_step.items.push(SetupItem {
916                name: n,
917                status: "updated".to_string(),
918                path: None,
919                note: None,
920            });
921        }
922        for n in rules_result.already {
923            rules_step.items.push(SetupItem {
924                name: n,
925                status: "already".to_string(),
926                path: None,
927                note: None,
928            });
929        }
930        if !rules_result.backed_up.is_empty() {
931            for bak in &rules_result.backed_up {
932                rules_step.items.push(SetupItem {
933                    name: "backup".to_string(),
934                    status: "created".to_string(),
935                    path: Some(bak.clone()),
936                    note: Some("previous version backed up".to_string()),
937                });
938            }
939        }
940        for e in rules_result.errors {
941            rules_step.ok = false;
942            rules_step.errors.push(e);
943        }
944    } else {
945        let reason = if opts.skip_rules {
946            "--skip-rules flag set"
947        } else {
948            "auto_inject_rules not enabled (run `lean-ctx setup --inject-rules`)"
949        };
950        rules_step.items.push(SetupItem {
951            name: "agent_rules".to_string(),
952            status: "skipped".to_string(),
953            path: None,
954            note: Some(reason.to_string()),
955        });
956    }
957    steps.push(rules_step);
958
959    // Step: Skill files — respect config
960    let mut skill_step = SetupStepReport {
961        name: "skill_files".to_string(),
962        ok: true,
963        items: Vec::new(),
964        warnings: Vec::new(),
965        errors: Vec::new(),
966    };
967    let should_install_skills = if opts.skip_rules {
968        false
969    } else if opts.force_inject_rules {
970        true
971    } else if opts.yes && opts.non_interactive {
972        setup_cfg.should_inject_skills()
973    } else {
974        !opts.skip_rules
975    };
976    if should_install_skills {
977        let skill_results = crate::rules_inject::install_all_skills(&home);
978        for (name, is_new) in &skill_results {
979            skill_step.items.push(SetupItem {
980                name: name.clone(),
981                status: if *is_new { "installed" } else { "already" }.to_string(),
982                path: None,
983                note: Some("SKILL.md".to_string()),
984            });
985        }
986    } else {
987        skill_step.items.push(SetupItem {
988            name: "skill_files".to_string(),
989            status: "skipped".to_string(),
990            path: None,
991            note: Some("auto_inject_skills not enabled".to_string()),
992        });
993    }
994    if !skill_step.items.is_empty() {
995        steps.push(skill_step);
996    }
997
998    // Step: Agent-specific hooks (all detected agents)
999    let mut hooks_step = SetupStepReport {
1000        name: "agent_hooks".to_string(),
1001        ok: true,
1002        items: Vec::new(),
1003        warnings: Vec::new(),
1004        errors: Vec::new(),
1005    };
1006    for target in &targets {
1007        if !target.detect_path.exists() || target.agent_key.is_empty() {
1008            continue;
1009        }
1010        let mode = recommend_hook_mode(&target.agent_key);
1011        crate::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
1012        // #281: honor `[setup] auto_update_mcp = false` — register MCP only when
1013        // enabled; hooks above always install.
1014        let mcp_note = if setup_cfg.should_update_mcp() {
1015            match configure_agent_mcp(&target.agent_key) {
1016                Ok(()) => "; MCP config updated".to_string(),
1017                Err(e) => format!("; MCP config skipped: {e}"),
1018            }
1019        } else {
1020            "; MCP registration skipped (auto_update_mcp=false)".to_string()
1021        };
1022        hooks_step.items.push(SetupItem {
1023            name: format!("{} hooks", target.name),
1024            status: "installed".to_string(),
1025            path: Some(target.detect_path.to_string_lossy().to_string()),
1026            note: Some(format!(
1027                "mode={mode}; merge-based install/repair (preserves other hooks/plugins){mcp_note}"
1028            )),
1029        });
1030    }
1031    if !hooks_step.items.is_empty() {
1032        steps.push(hooks_step);
1033    }
1034
1035    // Step: Tool profile. Deliberately does NOT write a default profile:
1036    // writing `tool_profile = "standard"` made every install "explicit", which
1037    // disables the lazy-core advertisement (13 tools) and ships the full
1038    // profile schema set (~5-15k tokens) to every session (#575). The lean
1039    // default needs no config key — all tools stay reachable via ctx_call.
1040    let mut tool_profile_step = SetupStepReport {
1041        name: "tool_profile".to_string(),
1042        ok: true,
1043        items: Vec::new(),
1044        warnings: Vec::new(),
1045        errors: Vec::new(),
1046    };
1047    {
1048        let cfg = crate::core::config::Config::load();
1049        if cfg.tool_profile.is_none() && std::env::var("LEAN_CTX_TOOL_PROFILE").is_err() {
1050            tool_profile_step.items.push(SetupItem {
1051                name: "tool_profile".to_string(),
1052                status: "lean default".to_string(),
1053                path: None,
1054                note: Some(
1055                    "13 tools advertised, all reachable via ctx_call \
1056                     (pin more with: lean-ctx tools standard|power)"
1057                        .to_string(),
1058                ),
1059            });
1060        } else {
1061            let profile = cfg.tool_profile_effective();
1062            let overhead_hint = match profile {
1063                crate::core::tool_profiles::ToolProfile::Power => {
1064                    "; advertises ALL tool schemas — `lean-ctx tools lean` cuts this to 13"
1065                }
1066                _ => "",
1067            };
1068            tool_profile_step.items.push(SetupItem {
1069                name: "tool_profile".to_string(),
1070                status: "already".to_string(),
1071                path: None,
1072                note: Some(format!("profile={}{overhead_hint}", profile.as_str())),
1073            });
1074        }
1075    }
1076    steps.push(tool_profile_step);
1077
1078    // Step: Proxy autostart + env vars (respects opt-in)
1079    let mut proxy_step = SetupStepReport {
1080        name: "proxy".to_string(),
1081        ok: true,
1082        items: Vec::new(),
1083        warnings: Vec::new(),
1084        errors: Vec::new(),
1085    };
1086    if opts.skip_proxy {
1087        proxy_step.items.push(SetupItem {
1088            name: "proxy".to_string(),
1089            status: "skipped".to_string(),
1090            path: None,
1091            note: Some("Proxy not enabled (run `lean-ctx proxy enable`)".to_string()),
1092        });
1093    } else {
1094        let proxy_cfg = crate::core::config::Config::load();
1095        if proxy_cfg.proxy_enabled == Some(true) {
1096            let proxy_port = crate::proxy_setup::default_port();
1097            crate::proxy_autostart::install(proxy_port, true);
1098            std::thread::sleep(std::time::Duration::from_millis(500));
1099            crate::proxy_setup::install_proxy_env(&home, proxy_port, opts.json);
1100            proxy_step.items.push(SetupItem {
1101                name: "proxy_autostart".to_string(),
1102                status: "installed".to_string(),
1103                path: None,
1104                note: Some("LaunchAgent/systemd auto-start on login".to_string()),
1105            });
1106            proxy_step.items.push(SetupItem {
1107                name: "proxy_env".to_string(),
1108                status: "configured".to_string(),
1109                path: None,
1110                note: Some("ANTHROPIC_BASE_URL, OPENAI_BASE_URL, GEMINI_API_BASE_URL".to_string()),
1111            });
1112        } else {
1113            proxy_step.items.push(SetupItem {
1114                name: "proxy".to_string(),
1115                status: "skipped".to_string(),
1116                path: None,
1117                note: Some(
1118                    "Proxy not opted-in (run `lean-ctx proxy enable` to activate)".to_string(),
1119                ),
1120            });
1121        }
1122    }
1123    steps.push(proxy_step);
1124
1125    // Step: Environment / doctor (compact)
1126    let mut env_step = SetupStepReport {
1127        name: "doctor_compact".to_string(),
1128        ok: true,
1129        items: Vec::new(),
1130        warnings: Vec::new(),
1131        errors: Vec::new(),
1132    };
1133    let (passed, total) = crate::doctor::compact_score();
1134    env_step.items.push(SetupItem {
1135        name: "doctor".to_string(),
1136        status: format!("{passed}/{total}"),
1137        path: None,
1138        note: None,
1139    });
1140    if passed != total {
1141        env_step.warnings.push(format!(
1142            "doctor compact not fully passing: {passed}/{total}"
1143        ));
1144    }
1145    steps.push(env_step);
1146
1147    // Project root validation: warn if no root is configured and cwd is broad
1148    {
1149        let has_env_root = std::env::var("LEAN_CTX_PROJECT_ROOT")
1150            .ok()
1151            .is_some_and(|v| !v.is_empty());
1152        let cfg = crate::core::config::Config::load();
1153        let has_cfg_root = cfg.project_root.as_ref().is_some_and(|v| !v.is_empty());
1154        if !has_env_root && !has_cfg_root {
1155            if let Ok(cwd) = std::env::current_dir() {
1156                let is_home = dirs::home_dir().is_some_and(|h| cwd == h);
1157                if is_home {
1158                    let mut root_step = SetupStepReport {
1159                        name: "project_root".to_string(),
1160                        ok: true,
1161                        items: Vec::new(),
1162                        warnings: vec![
1163                            "No project_root configured. Running from $HOME can cause excessive scanning. \
1164                             Set via: lean-ctx config set project_root /path/to/project".to_string()
1165                        ],
1166                        errors: Vec::new(),
1167                    };
1168                    root_step.items.push(SetupItem {
1169                        name: "project_root".to_string(),
1170                        status: "unconfigured".to_string(),
1171                        path: None,
1172                        note: Some(
1173                            "Set LEAN_CTX_PROJECT_ROOT or add project_root to config.toml"
1174                                .to_string(),
1175                        ),
1176                    });
1177                    steps.push(root_step);
1178                }
1179            }
1180        }
1181    }
1182
1183    // Auto-build property graph if inside any recognized project
1184    if let Ok(cwd) = std::env::current_dir() {
1185        let is_project = cwd.join(".git").exists()
1186            || cwd.join("Cargo.toml").exists()
1187            || cwd.join("package.json").exists()
1188            || cwd.join("go.mod").exists();
1189        if is_project {
1190            spawn_index_build_background(&cwd);
1191        }
1192    }
1193
1194    let finished_at = Utc::now();
1195    let success = steps.iter().all(|s| s.ok);
1196    let report = SetupReport {
1197        schema_version: 1,
1198        started_at,
1199        finished_at,
1200        success,
1201        platform: PlatformInfo {
1202            os: std::env::consts::OS.to_string(),
1203            arch: std::env::consts::ARCH.to_string(),
1204        },
1205        steps,
1206        warnings: Vec::new(),
1207        errors: Vec::new(),
1208    };
1209
1210    let path = SetupReport::default_path()?;
1211    let mut content =
1212        serde_json::to_string_pretty(&report).map_err(|e| format!("serialize report: {e}"))?;
1213    content.push('\n');
1214    crate::config_io::write_atomic(&path, &content)?;
1215
1216    Ok(report)
1217}
1218
1219fn spawn_index_build_background(root: &std::path::Path) {
1220    if std::env::var("LEAN_CTX_DISABLED").is_ok()
1221        || matches!(std::env::var("LEAN_CTX_QUIET"), Ok(v) if v.trim() == "1")
1222    {
1223        return;
1224    }
1225    let root_str = crate::core::graph_index::normalize_project_root(&root.to_string_lossy());
1226    if !crate::core::graph_index::is_safe_scan_root_public(&root_str) {
1227        tracing::info!("[setup: skipping background graph build for unsafe root {root_str}]");
1228        return;
1229    }
1230
1231    let binary = resolve_portable_binary();
1232
1233    #[cfg(unix)]
1234    {
1235        let mut cmd = std::process::Command::new("nice");
1236        cmd.args(["-n", "19"]);
1237        if which_ionice_available() {
1238            cmd.arg("ionice").args(["-c", "3"]);
1239        }
1240        cmd.arg(&binary)
1241            .args(["index", "build", "--root"])
1242            .arg(root)
1243            .stdout(std::process::Stdio::null())
1244            .stderr(std::process::Stdio::null())
1245            .stdin(std::process::Stdio::null());
1246        let _ = cmd.spawn();
1247    }
1248
1249    #[cfg(windows)]
1250    {
1251        use std::os::windows::process::CommandExt;
1252        const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
1253        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
1254        let _ = std::process::Command::new(&binary)
1255            .args(["index", "build", "--root"])
1256            .arg(root)
1257            .stdout(std::process::Stdio::null())
1258            .stderr(std::process::Stdio::null())
1259            .stdin(std::process::Stdio::null())
1260            .creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW)
1261            .spawn();
1262    }
1263}
1264
1265#[cfg(unix)]
1266fn which_ionice_available() -> bool {
1267    std::process::Command::new("ionice")
1268        .arg("--version")
1269        .stdout(std::process::Stdio::null())
1270        .stderr(std::process::Stdio::null())
1271        .status()
1272        .is_ok()
1273}
1274
1275#[cfg(all(test, target_os = "macos"))]
1276mod tests {
1277    use super::*;
1278
1279    #[test]
1280    #[cfg(target_os = "macos")]
1281    fn qoder_agent_targets_include_all_macos_mcp_locations() {
1282        let home = std::path::Path::new("/Users/tester");
1283        let targets = agent_mcp_targets("qoder", home).unwrap();
1284        let paths: Vec<_> = targets.iter().map(|t| t.config_path.as_path()).collect();
1285
1286        assert_eq!(
1287            paths,
1288            vec![
1289                home.join(".qoder/mcp.json").as_path(),
1290                home.join("Library/Application Support/Qoder/User/mcp.json")
1291                    .as_path(),
1292                home.join("Library/Application Support/Qoder/SharedClientCache/mcp.json")
1293                    .as_path(),
1294            ]
1295        );
1296        assert!(targets
1297            .iter()
1298            .all(|t| t.config_type == ConfigType::QoderSettings));
1299    }
1300}