Skip to main content

lean_ctx_cli/setup/
interactive.rs

1// SPDX-License-Identifier: Apache-2.0
2use lean_ctx::core::editor_registry::{WriteAction, WriteOptions};
3use lean_ctx::core::portable_binary::resolve_agent_binary;
4use lean_ctx_hooks::hooks::{HookMode, recommend_hook_mode};
5
6use super::first_run::{first_run_setup_level, persist_setup_choice};
7use super::helpers::{
8    configure_plan_mode_settings, configure_premium_features, configure_tool_profile, shorten_path,
9};
10use super::index_build::spawn_index_build_background;
11use super::options::SetupOptions;
12use super::with_options::run_setup_with_options;
13
14pub fn run_setup() {
15    run_setup_with_agents(None);
16}
17
18/// Which detected tools this setup connects: `--agents`, else the answer to
19/// the selection prompt. The choice is recorded so updates refresh exactly
20/// these tools; nothing is recorded while no tool is installed yet.
21fn choose_agents(
22    home: &std::path::Path,
23    targets: &[lean_ctx::core::editor_registry::EditorTarget],
24    explicit: Option<std::collections::BTreeSet<String>>,
25) -> std::collections::BTreeSet<String> {
26    use super::agent_selection as sel;
27
28    let detected = sel::detected_agents(home, targets);
29    let selection = match explicit {
30        Some(keys) => keys,
31        None if detected.is_empty() => return std::collections::BTreeSet::new(),
32        None => {
33            let saved = lean_ctx::core::config::Config::load_global().setup.agents;
34            let default = sel::prompt_default(&detected, saved.as_deref());
35            sel::prompt_agent_selection(&detected, &default)
36        }
37    };
38    if let Err(e) = sel::save_selection(&selection) {
39        lean_ctx::terminal_ui::print_status_warn(&e);
40    }
41    selection
42}
43
44/// Guided setup. `agents` (from `--agents`) skips the selection prompt.
45pub fn run_setup_with_agents(agents: Option<std::collections::BTreeSet<String>>) {
46    use lean_ctx::terminal_ui;
47
48    if lean_ctx::shell::is_non_interactive() {
49        eprintln!("Non-interactive terminal detected (no TTY on stdin).");
50        eprintln!(
51            "Running in non-interactive mode (equivalent to: lean-ctx setup --non-interactive --yes)"
52        );
53        if agents.is_none() {
54            eprintln!(
55                "Connecting all detected tools (or the recorded choice); use --agents to choose."
56            );
57        }
58        eprintln!();
59        let opts = SetupOptions {
60            non_interactive: true,
61            yes: true,
62            agents,
63            ..Default::default()
64        };
65        match run_setup_with_options(&opts) {
66            // Plain lines, not log records: the CLI logs only errors by
67            // default, and these are for the person reading the output.
68            Ok(report) => {
69                for w in &report.warnings {
70                    eprintln!("Warning: {w}");
71                }
72            }
73            Err(e) => eprintln!("Setup error: {e}"),
74        }
75        return;
76    }
77
78    let Some(home) = lean_ctx::core::home::resolve_home_dir() else {
79        tracing::error!("Cannot determine home directory");
80        std::process::exit(1);
81    };
82
83    let binary = resolve_agent_binary();
84
85    let home_str = home.to_string_lossy().to_string();
86
87    terminal_ui::print_setup_header();
88
89    let (inject_rules, inject_skills) = first_run_setup_level();
90    persist_setup_choice(inject_rules, inject_skills);
91
92    let allow_rule_steering =
93        inject_rules && !lean_ctx::core::config::Config::load().declines_rule_steering();
94
95    terminal_ui::print_step_header(1, 14, "Shell Hook");
96    crate::cli::cmd_init(&["--global".to_string()]);
97    lean_ctx::shell_hook::install_all(false);
98
99    terminal_ui::print_step_header(2, 14, "Daemon");
100    if lean_ctx::daemon::is_daemon_running() {
101        terminal_ui::print_status_ok("Daemon running — restarting with current binary…");
102        let _ = lean_ctx::daemon::stop_daemon();
103        std::thread::sleep(std::time::Duration::from_millis(500));
104        if let Err(e) = lean_ctx::daemon::start_daemon(&[]) {
105            terminal_ui::print_status_warn(&format!("Daemon restart failed: {e}"));
106        }
107    } else if let Err(e) = lean_ctx::daemon::start_daemon(&[]) {
108        terminal_ui::print_status_warn(&format!("Daemon start failed: {e}"));
109    }
110
111    terminal_ui::print_step_header(3, 14, "AI Tool Detection");
112
113    let targets = lean_ctx::core::editor_registry::build_targets(&home);
114    let selection = choose_agents(&home, &targets, agents);
115    let allows = |key: &str| selection.contains(key);
116    let mut deselected: Vec<&str> = Vec::new();
117    // #281: in MCP-disabled environments (`auto_update_mcp = false`) editors are
118    // still detected and hooks/rules still install, but the MCP server is never
119    // written into their configs.
120    let update_mcp = lean_ctx::core::config::Config::load()
121        .setup
122        .should_update_mcp();
123    let mut newly_configured: Vec<&str> = Vec::new();
124    let mut already_configured: Vec<&str> = Vec::new();
125    let mut not_installed: Vec<&str> = Vec::new();
126    let mut mcp_skipped: Vec<&str> = Vec::new();
127    let mut errors: Vec<&str> = Vec::new();
128    let mut configured_integration_ids = Vec::new();
129
130    // The governor default first (a new Claude Code install gets governor-mcp,
131    // an automatic 3.12.1 migration is switched back; existing and pinned
132    // setups untouched): the MCP/rules/hook steps below then render the rest.
133    lean_ctx_hooks::hooks::setup_writer::record();
134    for (host, outcome) in
135        lean_ctx_hooks::hooks::governor_default::apply_for_targets(&home, &targets, &allows)
136    {
137        if outcome.ran_steps() {
138            let _ = super::agent_selection::remember_connected_agent(host.key);
139        }
140        if let Some(notice) = outcome.notice(host) {
141            terminal_ui::print_status_new(&notice);
142        }
143    }
144
145    for target in &targets {
146        let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
147
148        if !target.detect_path.exists() {
149            not_installed.push(target.name);
150            continue;
151        }
152
153        if !allows(&target.agent_key) {
154            if !deselected.contains(&target.name) {
155                deselected.push(target.name);
156            }
157            continue;
158        }
159
160        if !update_mcp {
161            terminal_ui::print_status_ok(&format!(
162                "{:<20} \x1b[2mMCP registration skipped (auto_update_mcp=false)\x1b[0m",
163                target.name
164            ));
165            mcp_skipped.push(target.name);
166            continue;
167        }
168
169        let mode = lean_ctx_hooks::hooks::governor_default::display_mode(
170            &target.agent_key,
171            &home,
172            if target.agent_key.is_empty() {
173                HookMode::Mcp
174            } else {
175                recommend_hook_mode(&target.agent_key)
176            },
177        );
178
179        match lean_ctx::core::editor_registry::write_config_with_options_and_rule_steering(
180            target,
181            &binary,
182            WriteOptions {
183                overwrite_invalid: false,
184            },
185            allow_rule_steering,
186        ) {
187            Ok(res) if res.action == WriteAction::Already => {
188                terminal_ui::print_status_ok(&format!(
189                    "{:<20} \x1b[36m{mode}\x1b[0m  \x1b[2m{short_path}\x1b[0m",
190                    target.name
191                ));
192                already_configured.push(target.name);
193                configured_integration_ids.push(target.agent_key.clone());
194            }
195            Ok(_) => {
196                terminal_ui::print_status_new(&format!(
197                    "{:<20} \x1b[36m{mode}\x1b[0m  \x1b[2m{short_path}\x1b[0m",
198                    target.name
199                ));
200                newly_configured.push(target.name);
201                configured_integration_ids.push(target.agent_key.clone());
202            }
203            Err(e) => {
204                terminal_ui::print_status_warn(&format!("{}: {e}", target.name));
205                errors.push(target.name);
206            }
207        }
208    }
209
210    let total_ok = newly_configured.len() + already_configured.len();
211    if total_ok == 0 && errors.is_empty() && mcp_skipped.is_empty() && deselected.is_empty() {
212        terminal_ui::print_status_warn(
213            "No AI tools detected. Install one and re-run: lean-ctx setup",
214        );
215    }
216
217    if !deselected.is_empty() {
218        println!(
219            "  \x1b[2m○ {} left untouched (not selected): {}\x1b[0m",
220            deselected.len(),
221            deselected.join(", ")
222        );
223    }
224    if !not_installed.is_empty() {
225        println!(
226            "  \x1b[2m○ {} not detected: {}\x1b[0m",
227            not_installed.len(),
228            not_installed.join(", ")
229        );
230    }
231
232    configure_plan_mode_settings(&newly_configured, &already_configured);
233
234    terminal_ui::print_step_header(4, 14, "Agent Rules");
235    let rules_result = if inject_rules {
236        let r = lean_ctx::rules_inject::inject_rules_where(&home, &allows);
237        for name in &r.injected {
238            terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules injected\x1b[0m"));
239        }
240        for name in &r.updated {
241            terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules updated\x1b[0m"));
242        }
243        for name in &r.already {
244            terminal_ui::print_status_ok(&format!("{name:<20} \x1b[2mrules up-to-date\x1b[0m"));
245        }
246        for err in &r.errors {
247            terminal_ui::print_status_warn(err);
248        }
249        if !r.backed_up.is_empty() {
250            for bak in &r.backed_up {
251                println!("  \x1b[2m  ↳ backup: {bak}\x1b[0m");
252            }
253        }
254        if r.injected.is_empty()
255            && r.updated.is_empty()
256            && r.already.is_empty()
257            && r.errors.is_empty()
258        {
259            terminal_ui::print_status_skip("No agent rules needed");
260        }
261        r
262    } else {
263        terminal_ui::print_status_skip(
264            "Skipped (run `lean-ctx setup` or set auto_inject_rules = true in config)",
265        );
266        lean_ctx::rules_inject::InjectResult::default()
267    };
268
269    for target in &targets {
270        if !target.detect_path.exists() || target.agent_key.is_empty() || !allows(&target.agent_key)
271        {
272            continue;
273        }
274
275        let mode = recommend_hook_mode(&target.agent_key);
276
277        if allow_rule_steering {
278            lean_ctx_hooks::hooks::install_agent_hook_with_mode(&target.agent_key, true, mode);
279        } else {
280            lean_ctx_hooks::hooks::install_agent_runtime_hook_with_mode(
281                &target.agent_key,
282                true,
283                mode,
284            );
285        }
286    }
287
288    terminal_ui::print_step_header(5, 14, "API Proxy (optional)");
289    {
290        let cfg = lean_ctx::core::config::Config::load();
291        let proxy_port = crate::proxy_setup::default_port();
292
293        match cfg.proxy_enabled {
294            Some(true) => {
295                lean_ctx::proxy_autostart::install(proxy_port, false);
296                std::thread::sleep(std::time::Duration::from_millis(500));
297                crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
298                terminal_ui::print_status_ok("Proxy active (opted in)");
299            }
300            Some(false) => {
301                terminal_ui::print_status_skip(
302                    "Proxy disabled (run `lean-ctx proxy enable` to change)",
303                );
304            }
305            None => {
306                println!(
307                    "  \x1b[2mThe API proxy routes LLM requests through lean-ctx for additional\x1b[0m"
308                );
309                println!(
310                    "  \x1b[2mtool-result compression and precise token analytics in the dashboard.\x1b[0m"
311                );
312                println!();
313                println!(
314                    "  \x1b[2mWithout it: MCP tools, shell hooks, gain tracking, and memory\x1b[0m"
315                );
316                println!(
317                    "  \x1b[2mall work normally. The proxy compresses API traffic on top.\x1b[0m"
318                );
319                println!();
320                print!("  Enable the API proxy? [y/N] ");
321                let _ = std::io::Write::flush(&mut std::io::stdout());
322                let mut input = String::new();
323                let _ = std::io::stdin().read_line(&mut input);
324                let answer = matches!(input.trim().to_lowercase().as_str(), "y" | "yes");
325                if let Err(e) = lean_ctx::core::config::Config::update_global(|c| {
326                    c.proxy_enabled = Some(answer);
327                }) {
328                    terminal_ui::print_status_warn(&format!(
329                        "could not save the proxy choice: {e}"
330                    ));
331                }
332                if answer {
333                    lean_ctx::proxy_autostart::install(proxy_port, false);
334                    std::thread::sleep(std::time::Duration::from_millis(500));
335                    crate::proxy_setup::install_proxy_env(&home, proxy_port, false);
336                    terminal_ui::print_status_new("Proxy enabled");
337                } else {
338                    terminal_ui::print_status_skip(
339                        "Proxy skipped (run `lean-ctx proxy enable` anytime)",
340                    );
341                }
342            }
343        }
344    }
345
346    terminal_ui::print_step_header(6, 14, "IDE Config Access (optional)");
347    {
348        let cfg = lean_ctx::core::config::Config::load();
349        match cfg.allow_ide_config_dirs {
350            Some(true) => {
351                terminal_ui::print_status_ok(
352                    "Enabled — the agent can read your editors' config dirs",
353                );
354            }
355            Some(false) => {
356                terminal_ui::print_status_skip(
357                    "Off (enable: lean-ctx config set allow_ide_config_dirs true)",
358                );
359            }
360            None => {
361                println!(
362                    "  \x1b[2mlean-ctx tools are jailed to the current project. Enabling this lets\x1b[0m"
363                );
364                println!(
365                    "  \x1b[2mthe agent read every supported editor's config dir (~/.cursor, VS Code,\x1b[0m"
366                );
367                println!(
368                    "  \x1b[2mCline/Roo, JetBrains, …) to manage MCP setup across editors.\x1b[0m"
369                );
370                println!();
371                println!(
372                    "  \x1b[33mTrade-off:\x1b[0m \x1b[2mthose dirs can hold other agents' sessions & credentials.\x1b[0m"
373                );
374                println!();
375                print!("  Allow the agent to read IDE config dirs? [y/N] ");
376                let _ = std::io::Write::flush(&mut std::io::stdout());
377                let mut input = String::new();
378                let _ = std::io::stdin().read_line(&mut input);
379                let answer = matches!(input.trim().to_lowercase().as_str(), "y" | "yes");
380                if let Err(e) = lean_ctx::core::config::Config::update_global(|c| {
381                    c.allow_ide_config_dirs = Some(answer);
382                }) {
383                    terminal_ui::print_status_warn(&format!(
384                        "could not save the IDE-config-access choice: {e}"
385                    ));
386                }
387                if answer {
388                    terminal_ui::print_status_new("IDE config access enabled");
389                } else {
390                    terminal_ui::print_status_skip(
391                        "Skipped (enable later: lean-ctx config set allow_ide_config_dirs true)",
392                    );
393                }
394            }
395        }
396    }
397
398    terminal_ui::print_step_header(7, 14, "Skill Files");
399    if inject_skills {
400        let skill_result = lean_ctx::rules_inject::install_skills_where(&home, &allows);
401        for (name, installed) in &skill_result {
402            if *installed {
403                terminal_ui::print_status_new(&format!(
404                    "{name:<20} \x1b[2mSKILL.md installed\x1b[0m"
405                ));
406            } else {
407                terminal_ui::print_status_ok(&format!(
408                    "{name:<20} \x1b[2mSKILL.md up-to-date\x1b[0m"
409                ));
410            }
411        }
412        if skill_result.is_empty() {
413            terminal_ui::print_status_skip("No skill directories to install");
414        }
415    } else {
416        terminal_ui::print_status_skip(
417            "Skipped (skill files install with the rules opt-in; choose Standard/Full in `lean-ctx setup`)",
418        );
419    }
420
421    terminal_ui::print_step_header(8, 14, "Environment Check");
422    let lean_dir = lean_ctx::core::data_dir::lean_ctx_data_dir()
423        .unwrap_or_else(|_| home.join(".config/lean-ctx"));
424    if lean_dir.exists() {
425        terminal_ui::print_status_ok(&format!("{} ready", lean_dir.display()));
426    } else {
427        let _ = std::fs::create_dir_all(&lean_dir);
428        terminal_ui::print_status_new(&format!("Created {}", lean_dir.display()));
429    }
430    if let Some(report) = lean_ctx::core::data_consolidate::consolidate()
431        && report.files_moved > 0
432    {
433        terminal_ui::print_status_new(&format!(
434            "Consolidated {} file(s) from a split data dir into {}",
435            report.files_moved,
436            report.canonical.display()
437        ));
438    }
439    // #594: relocate a `config.toml` that an old MCP env (LEAN_CTX_DATA_DIR)
440    // stranded in the data dir, so CLI and MCP read the same config from now on.
441    if let Some(report) = lean_ctx::core::config_heal::heal() {
442        match report.action {
443            lean_ctx::core::config_heal::HealAction::Adopted => {
444                terminal_ui::print_status_new(&format!(
445                    "Recovered your config into {}",
446                    report.to.display()
447                ));
448            }
449            lean_ctx::core::config_heal::HealAction::Superseded => {
450                terminal_ui::print_status_ok("Unified config (archived a stale data-dir copy)");
451            }
452        }
453    }
454    crate::doctor::run_compact();
455
456    // Commit to the XDG layout (and drain any residual ~/.lean-ctx) so a stray
457    // marker can never re-collapse config/data/state/cache later (GL #623).
458    lean_ctx::core::layout_pin::heal();
459
460    terminal_ui::print_step_header(9, 14, "Help Improve lean-ctx");
461    // No question: telemetry stays on by default and setup only says how to
462    // change it. An earlier explicit `telemetry off` is left untouched.
463    if lean_ctx::core::telemetry_consent::telemetry_would_send() {
464        for line in lean_ctx::core::telemetry_consent::hint_lines() {
465            println!("  \x1b[2m{line}\x1b[0m");
466        }
467    } else {
468        terminal_ui::print_status_skip(
469            "Telemetry is off — nothing is sent. Turn on: lean-ctx telemetry on",
470        );
471    }
472    lean_ctx::core::telemetry_consent::mark_notice_seen();
473
474    terminal_ui::print_step_header(10, 14, "Auto-Updates");
475    println!("  Keep lean-ctx up to date automatically.");
476    println!("  \x1b[1mChecks GitHub every 6h, installs only when a new release exists.\x1b[0m");
477    println!(
478        "  \x1b[2mNo restarts mid-session. Change anytime: lean-ctx update --schedule off\x1b[0m"
479    );
480    println!();
481    print!("  Enable automatic updates? \x1b[1m[y/N]\x1b[0m ");
482    use std::io::Write;
483    std::io::stdout().flush().ok();
484
485    let mut auto_input = String::new();
486    let auto_update = if std::io::stdin().read_line(&mut auto_input).is_ok() {
487        let answer = auto_input.trim().to_lowercase();
488        answer == "y" || answer == "yes"
489    } else {
490        false
491    };
492
493    if auto_update {
494        let cfg = lean_ctx::core::config::Config::load();
495        let hours = cfg.updates.check_interval_hours;
496        match lean_ctx::core::update_scheduler::install_schedule(hours) {
497            Ok(info) => {
498                lean_ctx::core::update_scheduler::set_auto_update(true, false, hours);
499                terminal_ui::print_status_ok(&format!("Enabled — {info}"));
500            }
501            Err(e) => {
502                terminal_ui::print_status_warn(&format!("Scheduler setup failed: {e}"));
503                terminal_ui::print_status_skip("Enable later: lean-ctx update --schedule");
504            }
505        }
506    } else {
507        lean_ctx::core::update_scheduler::set_auto_update(false, false, 6);
508        terminal_ui::print_status_skip("Skipped — enable later: lean-ctx update --schedule");
509    }
510
511    terminal_ui::print_step_header(11, 14, "Tool Profile");
512    configure_tool_profile();
513
514    terminal_ui::print_step_header(12, 14, "Advanced Tuning (optional)");
515    configure_premium_features(&home);
516
517    terminal_ui::print_step_header(13, 14, "Code Intelligence");
518    let cwd = std::env::current_dir().ok();
519    let cwd_is_home = cwd
520        .as_ref()
521        .is_some_and(|d| dirs::home_dir().is_some_and(|h| d.as_path() == h.as_path()));
522    if cwd_is_home {
523        terminal_ui::print_status_warn(
524            "Running from $HOME — graph build skipped to avoid scanning your entire home directory.",
525        );
526        println!();
527        println!("  \x1b[1mSet a default project root to avoid this:\x1b[0m");
528        println!("  \x1b[2mEnter your main project path (or press Enter to skip):\x1b[0m");
529        print!("  \x1b[1m>\x1b[0m ");
530        use std::io::Write;
531        std::io::stdout().flush().ok();
532        let mut root_input = String::new();
533        if std::io::stdin().read_line(&mut root_input).is_ok() {
534            let root_trimmed = root_input.trim();
535            if root_trimmed.is_empty() {
536                terminal_ui::print_status_skip(
537                    "No project root set. Set later: lean-ctx config set project_root /path/to/project",
538                );
539            } else {
540                let root_path = std::path::Path::new(root_trimmed);
541                if root_path.exists() && root_path.is_dir() {
542                    let config_path = lean_ctx::core::config::Config::path()
543                        .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
544                    let mut content = std::fs::read_to_string(&config_path).unwrap_or_default();
545                    if content.contains("project_root") {
546                        if let Ok(re) = regex::Regex::new(r#"(?m)^project_root\s*=\s*"[^"]*""#) {
547                            content = re
548                                .replace(&content, &format!("project_root = \"{root_trimmed}\""))
549                                .to_string();
550                        }
551                    } else {
552                        if !content.is_empty() && !content.ends_with('\n') {
553                            content.push('\n');
554                        }
555                        content.push_str(&format!("project_root = \"{root_trimmed}\"\n"));
556                    }
557                    let _ = lean_ctx::config_io::write_atomic_with_backup(&config_path, &content);
558                    terminal_ui::print_status_ok(&format!("Project root set: {root_trimmed}"));
559                    if lean_ctx::core::pathutil::has_project_marker(root_path) {
560                        spawn_index_build_background(root_path);
561                        terminal_ui::print_status_ok("Graph build started (background)");
562                    }
563                } else {
564                    terminal_ui::print_status_warn(&format!(
565                        "Path not found: {root_trimmed} — skipped"
566                    ));
567                }
568            }
569        }
570    } else {
571        let is_project = cwd
572            .as_ref()
573            .is_some_and(|d| lean_ctx::core::pathutil::has_project_marker(d));
574        if is_project {
575            println!("  \x1b[2mBuilding code graph for graph-aware reads, impact analysis,\x1b[0m");
576            println!("  \x1b[2mand smart search fusion in the background...\x1b[0m");
577            if let Some(ref root) = cwd {
578                spawn_index_build_background(root);
579            }
580            terminal_ui::print_status_ok("Graph build started (background)");
581        } else {
582            println!("  \x1b[2mRun `lean-ctx graph build` inside any git project to enable\x1b[0m");
583            println!(
584                "  \x1b[2mgraph-aware reads, impact analysis, and smart search fusion.\x1b[0m"
585            );
586        }
587    }
588    println!();
589
590    {
591        let tools = lean_ctx::core::editor_registry::writers::auto_approve_tools();
592        println!();
593        println!(
594            "  \x1b[33m⚡ Auto-approved tools ({} total):\x1b[0m",
595            tools.len()
596        );
597        for chunk in tools.chunks(6) {
598            let names: Vec<_> = chunk.iter().map(|t| format!("\x1b[2m{t}\x1b[0m")).collect();
599            println!("    {}", names.join(", "));
600        }
601    }
602
603    terminal_ui::print_step_header(14, 14, "Intelligence Runtime");
604    super::intelligence::configure_runtime();
605
606    println!();
607    println!(
608        "  \x1b[1;32m✓ Setup complete!\x1b[0m  \x1b[1m{}\x1b[0m configured, \x1b[2m{} already set, {} skipped\x1b[0m",
609        newly_configured.len(),
610        already_configured.len(),
611        not_installed.len()
612    );
613
614    if !errors.is_empty() {
615        println!(
616            "  \x1b[33m⚠ {} error{}: {}\x1b[0m",
617            errors.len(),
618            if errors.len() == 1 { "" } else { "s" },
619            errors.join(", ")
620        );
621    }
622
623    let source_cmd = lean_ctx::shell_hook::shell_source_command().unwrap_or("Restart your shell");
624
625    let dim = "\x1b[2m";
626    let bold = "\x1b[1m";
627    let cyan = "\x1b[36m";
628    let yellow = "\x1b[33m";
629    let rst = "\x1b[0m";
630
631    println!();
632    println!("  {bold}Next steps:{rst}");
633    println!();
634    println!("  {cyan}1.{rst} Reload your shell:");
635    println!("     {bold}{source_cmd}{rst}");
636    println!();
637
638    let mut tools_to_restart: Vec<String> = newly_configured
639        .iter()
640        .map(std::string::ToString::to_string)
641        .collect();
642    for name in rules_result
643        .injected
644        .iter()
645        .chain(rules_result.updated.iter())
646    {
647        if !tools_to_restart.contains(name) {
648            tools_to_restart.push(name.clone());
649        }
650    }
651
652    if !tools_to_restart.is_empty() {
653        println!("  {cyan}2.{rst} {yellow}{bold}Restart your IDE / AI tool:{rst}");
654        println!("     {bold}{}{rst}", tools_to_restart.join(", "));
655        println!(
656            "     {dim}Changes take effect after a full restart (MCP may be enabled or disabled depending on mode).{rst}"
657        );
658        println!("     {dim}Close and re-open the application completely.{rst}");
659    } else if !already_configured.is_empty() {
660        println!(
661            "  {cyan}2.{rst} {dim}Your tools are already configured — no restart needed.{rst}"
662        );
663    }
664
665    println!();
666    println!(
667        "  {dim}After restart, lean-ctx will automatically optimize every AI interaction.{rst}"
668    );
669    println!("  {dim}Verify with:{rst} {bold}lean-ctx cockpit{rst}");
670
671    println!();
672    terminal_ui::print_logo_animated();
673    terminal_ui::print_command_box();
674
675    if errors.is_empty() {
676        if let Err(error) =
677            lean_ctx::core::telemetry_aggregate::record_setup_completion(configured_integration_ids)
678        {
679            tracing::debug!("telemetry setup aggregate unavailable: {error}");
680        }
681    }
682
683    crate::cli::show_first_run_wow();
684}