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