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