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